285d90ba09927765f09dc5839b854a0cee5de647
[rust-lightning] / lightning-c-bindings / src / chain / keysinterface.rs
1 //! keysinterface provides keys into rust-lightning and defines some useful enums which describe
2 //! spendable on-chain outputs which the user owns and is responsible for using just as any other
3 //! on-chain output which is theirs.
4
5 use std::ffi::c_void;
6 use bitcoin::hashes::Hash;
7 use crate::c_types::*;
8
9 /// When on-chain outputs are created by rust-lightning (which our counterparty is not able to
10 /// claim at any point in the future) an event is generated which you must track and be able to
11 /// spend on-chain. The information needed to do this is provided in this enum, including the
12 /// outpoint describing which txid and output index is available, the full output which exists at
13 /// that txid/index, and any keys or other information required to sign.
14 #[must_use]
15 #[derive(Clone)]
16 #[repr(C)]
17 pub enum SpendableOutputDescriptor {
18         /// An output to a script which was provided via KeysInterface, thus you should already know
19         /// how to spend it. No keys are provided as rust-lightning was never given any keys - only the
20         /// script_pubkey as it appears in the output.
21         /// These may include outputs from a transaction punishing our counterparty or claiming an HTLC
22         /// on-chain using the payment preimage or after it has timed out.
23         StaticOutput {
24                 outpoint: crate::chain::transaction::OutPoint,
25                 output: crate::c_types::TxOut,
26         },
27         /// An output to a P2WSH script which can be spent with a single signature after a CSV delay.
28         ///
29         /// The witness in the spending input should be:
30         /// <BIP 143 signature> <empty vector> (MINIMALIF standard rule) <provided witnessScript>
31         ///
32         /// Note that the nSequence field in the spending input must be set to to_self_delay
33         /// (which means the transaction is not broadcastable until at least to_self_delay
34         /// blocks after the outpoint confirms).
35         ///
36         /// These are generally the result of a \"revocable\" output to us, spendable only by us unless
37         /// it is an output from an old state which we broadcast (which should never happen).
38         ///
39         /// To derive the delayed_payment key which is used to sign for this input, you must pass the
40         /// holder delayed_payment_base_key (ie the private key which corresponds to the pubkey in
41         /// ChannelKeys::pubkeys().delayed_payment_basepoint) and the provided per_commitment_point to
42         /// chan_utils::derive_private_key. The public key can be generated without the secret key
43         /// using chan_utils::derive_public_key and only the delayed_payment_basepoint which appears in
44         /// ChannelKeys::pubkeys().
45         ///
46         /// To derive the revocation_pubkey provided here (which is used in the witness
47         /// script generation), you must pass the counterparty revocation_basepoint (which appears in the
48         /// call to ChannelKeys::ready_channel) and the provided per_commitment point
49         /// to chan_utils::derive_public_revocation_key.
50         ///
51         /// The witness script which is hashed and included in the output script_pubkey may be
52         /// regenerated by passing the revocation_pubkey (derived as above), our delayed_payment pubkey
53         /// (derived as above), and the to_self_delay contained here to
54         /// chan_utils::get_revokeable_redeemscript.
55         DynamicOutputP2WSH {
56                 outpoint: crate::chain::transaction::OutPoint,
57                 per_commitment_point: crate::c_types::PublicKey,
58                 to_self_delay: u16,
59                 output: crate::c_types::TxOut,
60                 key_derivation_params: crate::c_types::derived::C2Tuple_u64u64Z,
61                 revocation_pubkey: crate::c_types::PublicKey,
62         },
63         /// An output to a P2WPKH, spendable exclusively by our payment key (ie the private key which
64         /// corresponds to the public key in ChannelKeys::pubkeys().payment_point).
65         /// The witness in the spending input, is, thus, simply:
66         /// <BIP 143 signature> <payment key>
67         ///
68         /// These are generally the result of our counterparty having broadcast the current state,
69         /// allowing us to claim the non-HTLC-encumbered outputs immediately.
70         StaticOutputCounterpartyPayment {
71                 outpoint: crate::chain::transaction::OutPoint,
72                 output: crate::c_types::TxOut,
73                 key_derivation_params: crate::c_types::derived::C2Tuple_u64u64Z,
74         },
75 }
76 use lightning::chain::keysinterface::SpendableOutputDescriptor as nativeSpendableOutputDescriptor;
77 impl SpendableOutputDescriptor {
78         #[allow(unused)]
79         pub(crate) fn to_native(&self) -> nativeSpendableOutputDescriptor {
80                 match self {
81                         SpendableOutputDescriptor::StaticOutput {ref outpoint, ref output, } => {
82                                 let mut outpoint_nonref = (*outpoint).clone();
83                                 let mut output_nonref = (*output).clone();
84                                 nativeSpendableOutputDescriptor::StaticOutput {
85                                         outpoint: *unsafe { Box::from_raw(outpoint_nonref.take_inner()) },
86                                         output: output_nonref.into_rust(),
87                                 }
88                         },
89                         SpendableOutputDescriptor::DynamicOutputP2WSH {ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref revocation_pubkey, } => {
90                                 let mut outpoint_nonref = (*outpoint).clone();
91                                 let mut per_commitment_point_nonref = (*per_commitment_point).clone();
92                                 let mut to_self_delay_nonref = (*to_self_delay).clone();
93                                 let mut output_nonref = (*output).clone();
94                                 let mut key_derivation_params_nonref = (*key_derivation_params).clone();
95                                 let (mut orig_key_derivation_params_nonref_0, mut orig_key_derivation_params_nonref_1) = key_derivation_params_nonref.to_rust(); let mut local_key_derivation_params_nonref = (orig_key_derivation_params_nonref_0, orig_key_derivation_params_nonref_1);
96                                 let mut revocation_pubkey_nonref = (*revocation_pubkey).clone();
97                                 nativeSpendableOutputDescriptor::DynamicOutputP2WSH {
98                                         outpoint: *unsafe { Box::from_raw(outpoint_nonref.take_inner()) },
99                                         per_commitment_point: per_commitment_point_nonref.into_rust(),
100                                         to_self_delay: to_self_delay_nonref,
101                                         output: output_nonref.into_rust(),
102                                         key_derivation_params: local_key_derivation_params_nonref,
103                                         revocation_pubkey: revocation_pubkey_nonref.into_rust(),
104                                 }
105                         },
106                         SpendableOutputDescriptor::StaticOutputCounterpartyPayment {ref outpoint, ref output, ref key_derivation_params, } => {
107                                 let mut outpoint_nonref = (*outpoint).clone();
108                                 let mut output_nonref = (*output).clone();
109                                 let mut key_derivation_params_nonref = (*key_derivation_params).clone();
110                                 let (mut orig_key_derivation_params_nonref_0, mut orig_key_derivation_params_nonref_1) = key_derivation_params_nonref.to_rust(); let mut local_key_derivation_params_nonref = (orig_key_derivation_params_nonref_0, orig_key_derivation_params_nonref_1);
111                                 nativeSpendableOutputDescriptor::StaticOutputCounterpartyPayment {
112                                         outpoint: *unsafe { Box::from_raw(outpoint_nonref.take_inner()) },
113                                         output: output_nonref.into_rust(),
114                                         key_derivation_params: local_key_derivation_params_nonref,
115                                 }
116                         },
117                 }
118         }
119         #[allow(unused)]
120         pub(crate) fn into_native(self) -> nativeSpendableOutputDescriptor {
121                 match self {
122                         SpendableOutputDescriptor::StaticOutput {mut outpoint, mut output, } => {
123                                 nativeSpendableOutputDescriptor::StaticOutput {
124                                         outpoint: *unsafe { Box::from_raw(outpoint.take_inner()) },
125                                         output: output.into_rust(),
126                                 }
127                         },
128                         SpendableOutputDescriptor::DynamicOutputP2WSH {mut outpoint, mut per_commitment_point, mut to_self_delay, mut output, mut key_derivation_params, mut revocation_pubkey, } => {
129                                 let (mut orig_key_derivation_params_0, mut orig_key_derivation_params_1) = key_derivation_params.to_rust(); let mut local_key_derivation_params = (orig_key_derivation_params_0, orig_key_derivation_params_1);
130                                 nativeSpendableOutputDescriptor::DynamicOutputP2WSH {
131                                         outpoint: *unsafe { Box::from_raw(outpoint.take_inner()) },
132                                         per_commitment_point: per_commitment_point.into_rust(),
133                                         to_self_delay: to_self_delay,
134                                         output: output.into_rust(),
135                                         key_derivation_params: local_key_derivation_params,
136                                         revocation_pubkey: revocation_pubkey.into_rust(),
137                                 }
138                         },
139                         SpendableOutputDescriptor::StaticOutputCounterpartyPayment {mut outpoint, mut output, mut key_derivation_params, } => {
140                                 let (mut orig_key_derivation_params_0, mut orig_key_derivation_params_1) = key_derivation_params.to_rust(); let mut local_key_derivation_params = (orig_key_derivation_params_0, orig_key_derivation_params_1);
141                                 nativeSpendableOutputDescriptor::StaticOutputCounterpartyPayment {
142                                         outpoint: *unsafe { Box::from_raw(outpoint.take_inner()) },
143                                         output: output.into_rust(),
144                                         key_derivation_params: local_key_derivation_params,
145                                 }
146                         },
147                 }
148         }
149         #[allow(unused)]
150         pub(crate) fn from_native(native: &nativeSpendableOutputDescriptor) -> Self {
151                 match native {
152                         nativeSpendableOutputDescriptor::StaticOutput {ref outpoint, ref output, } => {
153                                 let mut outpoint_nonref = (*outpoint).clone();
154                                 let mut output_nonref = (*output).clone();
155                                 SpendableOutputDescriptor::StaticOutput {
156                                         outpoint: crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(outpoint_nonref)), is_owned: true },
157                                         output: crate::c_types::TxOut::from_rust(output_nonref),
158                                 }
159                         },
160                         nativeSpendableOutputDescriptor::DynamicOutputP2WSH {ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref revocation_pubkey, } => {
161                                 let mut outpoint_nonref = (*outpoint).clone();
162                                 let mut per_commitment_point_nonref = (*per_commitment_point).clone();
163                                 let mut to_self_delay_nonref = (*to_self_delay).clone();
164                                 let mut output_nonref = (*output).clone();
165                                 let mut key_derivation_params_nonref = (*key_derivation_params).clone();
166                                 let (mut orig_key_derivation_params_nonref_0, mut orig_key_derivation_params_nonref_1) = key_derivation_params_nonref; let mut local_key_derivation_params_nonref = (orig_key_derivation_params_nonref_0, orig_key_derivation_params_nonref_1).into();
167                                 let mut revocation_pubkey_nonref = (*revocation_pubkey).clone();
168                                 SpendableOutputDescriptor::DynamicOutputP2WSH {
169                                         outpoint: crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(outpoint_nonref)), is_owned: true },
170                                         per_commitment_point: crate::c_types::PublicKey::from_rust(&per_commitment_point_nonref),
171                                         to_self_delay: to_self_delay_nonref,
172                                         output: crate::c_types::TxOut::from_rust(output_nonref),
173                                         key_derivation_params: local_key_derivation_params_nonref,
174                                         revocation_pubkey: crate::c_types::PublicKey::from_rust(&revocation_pubkey_nonref),
175                                 }
176                         },
177                         nativeSpendableOutputDescriptor::StaticOutputCounterpartyPayment {ref outpoint, ref output, ref key_derivation_params, } => {
178                                 let mut outpoint_nonref = (*outpoint).clone();
179                                 let mut output_nonref = (*output).clone();
180                                 let mut key_derivation_params_nonref = (*key_derivation_params).clone();
181                                 let (mut orig_key_derivation_params_nonref_0, mut orig_key_derivation_params_nonref_1) = key_derivation_params_nonref; let mut local_key_derivation_params_nonref = (orig_key_derivation_params_nonref_0, orig_key_derivation_params_nonref_1).into();
182                                 SpendableOutputDescriptor::StaticOutputCounterpartyPayment {
183                                         outpoint: crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(outpoint_nonref)), is_owned: true },
184                                         output: crate::c_types::TxOut::from_rust(output_nonref),
185                                         key_derivation_params: local_key_derivation_params_nonref,
186                                 }
187                         },
188                 }
189         }
190         #[allow(unused)]
191         pub(crate) fn native_into(native: nativeSpendableOutputDescriptor) -> Self {
192                 match native {
193                         nativeSpendableOutputDescriptor::StaticOutput {mut outpoint, mut output, } => {
194                                 SpendableOutputDescriptor::StaticOutput {
195                                         outpoint: crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(outpoint)), is_owned: true },
196                                         output: crate::c_types::TxOut::from_rust(output),
197                                 }
198                         },
199                         nativeSpendableOutputDescriptor::DynamicOutputP2WSH {mut outpoint, mut per_commitment_point, mut to_self_delay, mut output, mut key_derivation_params, mut revocation_pubkey, } => {
200                                 let (mut orig_key_derivation_params_0, mut orig_key_derivation_params_1) = key_derivation_params; let mut local_key_derivation_params = (orig_key_derivation_params_0, orig_key_derivation_params_1).into();
201                                 SpendableOutputDescriptor::DynamicOutputP2WSH {
202                                         outpoint: crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(outpoint)), is_owned: true },
203                                         per_commitment_point: crate::c_types::PublicKey::from_rust(&per_commitment_point),
204                                         to_self_delay: to_self_delay,
205                                         output: crate::c_types::TxOut::from_rust(output),
206                                         key_derivation_params: local_key_derivation_params,
207                                         revocation_pubkey: crate::c_types::PublicKey::from_rust(&revocation_pubkey),
208                                 }
209                         },
210                         nativeSpendableOutputDescriptor::StaticOutputCounterpartyPayment {mut outpoint, mut output, mut key_derivation_params, } => {
211                                 let (mut orig_key_derivation_params_0, mut orig_key_derivation_params_1) = key_derivation_params; let mut local_key_derivation_params = (orig_key_derivation_params_0, orig_key_derivation_params_1).into();
212                                 SpendableOutputDescriptor::StaticOutputCounterpartyPayment {
213                                         outpoint: crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(outpoint)), is_owned: true },
214                                         output: crate::c_types::TxOut::from_rust(output),
215                                         key_derivation_params: local_key_derivation_params,
216                                 }
217                         },
218                 }
219         }
220 }
221 #[no_mangle]
222 pub extern "C" fn SpendableOutputDescriptor_free(this_ptr: SpendableOutputDescriptor) { }
223 #[no_mangle]
224 pub extern "C" fn SpendableOutputDescriptor_clone(orig: &SpendableOutputDescriptor) -> SpendableOutputDescriptor {
225         orig.clone()
226 }
227 /// Set of lightning keys needed to operate a channel as described in BOLT 3.
228 ///
229 /// Signing services could be implemented on a hardware wallet. In this case,
230 /// the current ChannelKeys would be a front-end on top of a communication
231 /// channel connected to your secure device and lightning key material wouldn't
232 /// reside on a hot server. Nevertheless, a this deployment would still need
233 /// to trust the ChannelManager to avoid loss of funds as this latest component
234 /// could ask to sign commitment transaction with HTLCs paying to attacker pubkeys.
235 ///
236 /// A more secure iteration would be to use hashlock (or payment points) to pair
237 /// invoice/incoming HTLCs with outgoing HTLCs to implement a no-trust-ChannelManager
238 /// at the price of more state and computation on the hardware wallet side. In the future,
239 /// we are looking forward to design such interface.
240 ///
241 /// In any case, ChannelMonitor or fallback watchtowers are always going to be trusted
242 /// to act, as liveness and breach reply correctness are always going to be hard requirements
243 /// of LN security model, orthogonal of key management issues.
244 ///
245 /// If you're implementing a custom signer, you almost certainly want to implement
246 /// Readable/Writable to serialize out a unique reference to this set of keys so
247 /// that you can serialize the full ChannelManager object.
248 ///
249 #[repr(C)]
250 pub struct ChannelKeys {
251         pub this_arg: *mut c_void,
252         /// Gets the per-commitment point for a specific commitment number
253         ///
254         /// Note that the commitment number starts at (1 << 48) - 1 and counts backwards.
255         #[must_use]
256         pub get_per_commitment_point: extern "C" fn (this_arg: *const c_void, idx: u64) -> crate::c_types::PublicKey,
257         /// Gets the commitment secret for a specific commitment number as part of the revocation process
258         ///
259         /// An external signer implementation should error here if the commitment was already signed
260         /// and should refuse to sign it in the future.
261         ///
262         /// May be called more than once for the same index.
263         ///
264         /// Note that the commitment number starts at (1 << 48) - 1 and counts backwards.
265         /// TODO: return a Result so we can signal a validation error
266         #[must_use]
267         pub release_commitment_secret: extern "C" fn (this_arg: *const c_void, idx: u64) -> crate::c_types::ThirtyTwoBytes,
268         /// Gets the holder's channel public keys and basepoints
269         pub pubkeys: crate::ln::chan_utils::ChannelPublicKeys,
270         /// Fill in the pubkeys field as a reference to it will be given to Rust after this returns
271         /// Note that this takes a pointer to this object, not the this_ptr like other methods do
272         /// This function pointer may be NULL if pubkeys is filled in when this object is created and never needs updating.
273         pub set_pubkeys: Option<extern "C" fn(&ChannelKeys)>,
274         /// Gets arbitrary identifiers describing the set of keys which are provided back to you in
275         /// some SpendableOutputDescriptor types. These should be sufficient to identify this
276         /// ChannelKeys object uniquely and lookup or re-derive its keys.
277         #[must_use]
278         pub key_derivation_params: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::C2Tuple_u64u64Z,
279         /// Create a signature for a counterparty's commitment transaction and associated HTLC transactions.
280         ///
281         /// Note that if signing fails or is rejected, the channel will be force-closed.
282         #[must_use]
283         pub sign_counterparty_commitment: extern "C" fn (this_arg: *const c_void, commitment_tx: &crate::ln::chan_utils::CommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ,
284         /// Create a signatures for a holder's commitment transaction and its claiming HTLC transactions.
285         /// This will only ever be called with a non-revoked commitment_tx.  This will be called with the
286         /// latest commitment_tx when we initiate a force-close.
287         /// This will be called with the previous latest, just to get claiming HTLC signatures, if we are
288         /// reacting to a ChannelMonitor replica that decided to broadcast before it had been updated to
289         /// the latest.
290         /// This may be called multiple times for the same transaction.
291         ///
292         /// An external signer implementation should check that the commitment has not been revoked.
293         ///
294         /// May return Err if key derivation fails.  Callers, such as ChannelMonitor, will panic in such a case.
295         #[must_use]
296         pub sign_holder_commitment_and_htlcs: extern "C" fn (this_arg: *const c_void, commitment_tx: &crate::ln::chan_utils::HolderCommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ,
297         /// Create a signature for the given input in a transaction spending an HTLC or commitment
298         /// transaction output when our counterparty broadcasts an old state.
299         ///
300         /// A justice transaction may claim multiples outputs at the same time if timelocks are
301         /// similar, but only a signature for the input at index `input` should be signed for here.
302         /// It may be called multiples time for same output(s) if a fee-bump is needed with regards
303         /// to an upcoming timelock expiration.
304         ///
305         /// Amount is value of the output spent by this input, committed to in the BIP 143 signature.
306         ///
307         /// per_commitment_key is revocation secret which was provided by our counterparty when they
308         /// revoked the state which they eventually broadcast. It's not a _holder_ secret key and does
309         /// not allow the spending of any funds by itself (you need our holder revocation_secret to do
310         /// so).
311         ///
312         /// htlc holds HTLC elements (hash, timelock) if the output being spent is a HTLC output, thus
313         /// changing the format of the witness script (which is committed to in the BIP 143
314         /// signatures).
315         #[must_use]
316         pub sign_justice_transaction: extern "C" fn (this_arg: *const c_void, justice_tx: crate::c_types::Transaction, input: usize, amount: u64, per_commitment_key: *const [u8; 32], htlc: &crate::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ,
317         /// Create a signature for a claiming transaction for a HTLC output on a counterparty's commitment
318         /// transaction, either offered or received.
319         ///
320         /// Such a transaction may claim multiples offered outputs at same time if we know the
321         /// preimage for each when we create it, but only the input at index `input` should be
322         /// signed for here. It may be called multiple times for same output(s) if a fee-bump is
323         /// needed with regards to an upcoming timelock expiration.
324         ///
325         /// Witness_script is either a offered or received script as defined in BOLT3 for HTLC
326         /// outputs.
327         ///
328         /// Amount is value of the output spent by this input, committed to in the BIP 143 signature.
329         ///
330         /// Per_commitment_point is the dynamic point corresponding to the channel state
331         /// detected onchain. It has been generated by our counterparty and is used to derive
332         /// channel state keys, which are then included in the witness script and committed to in the
333         /// BIP 143 signature.
334         #[must_use]
335         pub sign_counterparty_htlc_transaction: extern "C" fn (this_arg: *const c_void, htlc_tx: crate::c_types::Transaction, input: usize, amount: u64, per_commitment_point: crate::c_types::PublicKey, htlc: &crate::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ,
336         /// Create a signature for a (proposed) closing transaction.
337         ///
338         /// Note that, due to rounding, there may be one \"missing\" satoshi, and either party may have
339         /// chosen to forgo their output as dust.
340         #[must_use]
341         pub sign_closing_transaction: extern "C" fn (this_arg: *const c_void, closing_tx: crate::c_types::Transaction) -> crate::c_types::derived::CResult_SignatureNoneZ,
342         /// Signs a channel announcement message with our funding key, proving it comes from one
343         /// of the channel participants.
344         ///
345         /// Note that if this fails or is rejected, the channel will not be publicly announced and
346         /// our counterparty may (though likely will not) close the channel on us for violating the
347         /// protocol.
348         #[must_use]
349         pub sign_channel_announcement: extern "C" fn (this_arg: *const c_void, msg: &crate::ln::msgs::UnsignedChannelAnnouncement) -> crate::c_types::derived::CResult_SignatureNoneZ,
350         /// Set the counterparty static channel data, including basepoints,
351         /// counterparty_selected/holder_selected_contest_delay and funding outpoint.
352         /// This is done as soon as the funding outpoint is known.  Since these are static channel data,
353         /// they MUST NOT be allowed to change to different values once set.
354         ///
355         /// channel_parameters.is_populated() MUST be true.
356         ///
357         /// We bind holder_selected_contest_delay late here for API convenience.
358         ///
359         /// Will be called before any signatures are applied.
360         pub ready_channel: extern "C" fn (this_arg: *mut c_void, channel_parameters: &crate::ln::chan_utils::ChannelTransactionParameters),
361         pub clone: Option<extern "C" fn (this_arg: *const c_void) -> *mut c_void>,
362         pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
363         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
364 }
365 unsafe impl Send for ChannelKeys {}
366 #[no_mangle]
367 pub extern "C" fn ChannelKeys_clone(orig: &ChannelKeys) -> ChannelKeys {
368         ChannelKeys {
369                 this_arg: if let Some(f) = orig.clone { (f)(orig.this_arg) } else { orig.this_arg },
370                 get_per_commitment_point: orig.get_per_commitment_point.clone(),
371                 release_commitment_secret: orig.release_commitment_secret.clone(),
372                 pubkeys: orig.pubkeys.clone(),
373                 set_pubkeys: orig.set_pubkeys.clone(),
374                 key_derivation_params: orig.key_derivation_params.clone(),
375                 sign_counterparty_commitment: orig.sign_counterparty_commitment.clone(),
376                 sign_holder_commitment_and_htlcs: orig.sign_holder_commitment_and_htlcs.clone(),
377                 sign_justice_transaction: orig.sign_justice_transaction.clone(),
378                 sign_counterparty_htlc_transaction: orig.sign_counterparty_htlc_transaction.clone(),
379                 sign_closing_transaction: orig.sign_closing_transaction.clone(),
380                 sign_channel_announcement: orig.sign_channel_announcement.clone(),
381                 ready_channel: orig.ready_channel.clone(),
382                 clone: orig.clone.clone(),
383                 write: orig.write.clone(),
384                 free: orig.free.clone(),
385         }
386 }
387 impl Clone for ChannelKeys {
388         fn clone(&self) -> Self {
389                 ChannelKeys_clone(self)
390         }
391 }
392 impl lightning::util::ser::Writeable for ChannelKeys {
393         fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
394                 let vec = (self.write)(self.this_arg);
395                 w.write_all(vec.as_slice())
396         }
397 }
398
399 use lightning::chain::keysinterface::ChannelKeys as rustChannelKeys;
400 impl rustChannelKeys for ChannelKeys {
401         fn get_per_commitment_point<T:bitcoin::secp256k1::Signing + bitcoin::secp256k1::Verification>(&self, idx: u64, _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> bitcoin::secp256k1::key::PublicKey {
402                 let mut ret = (self.get_per_commitment_point)(self.this_arg, idx);
403                 ret.into_rust()
404         }
405         fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
406                 let mut ret = (self.release_commitment_secret)(self.this_arg, idx);
407                 ret.data
408         }
409         fn pubkeys(&self) -> &lightning::ln::chan_utils::ChannelPublicKeys {
410                 if let Some(f) = self.set_pubkeys {
411                         (f)(self);
412                 }
413                 unsafe { &*self.pubkeys.inner }
414         }
415         fn key_derivation_params(&self) -> (u64, u64) {
416                 let mut ret = (self.key_derivation_params)(self.this_arg);
417                 let (mut orig_ret_0, mut orig_ret_1) = ret.to_rust(); let mut local_ret = (orig_ret_0, orig_ret_1);
418                 local_ret
419         }
420         fn sign_counterparty_commitment<T:bitcoin::secp256k1::Signing + bitcoin::secp256k1::Verification>(&self, commitment_tx: &lightning::ln::chan_utils::CommitmentTransaction, _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> Result<(bitcoin::secp256k1::Signature, Vec<bitcoin::secp256k1::Signature>), ()> {
421                 let mut ret = (self.sign_counterparty_commitment)(self.this_arg, &crate::ln::chan_utils::CommitmentTransaction { inner: unsafe { (commitment_tx as *const _) as *mut _ }, is_owned: false });
422                 let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_rust() }); }; let mut local_ret_0 = (orig_ret_0_0.into_rust(), local_orig_ret_0_1); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
423                 local_ret
424         }
425         fn sign_holder_commitment_and_htlcs<T:bitcoin::secp256k1::Signing + bitcoin::secp256k1::Verification>(&self, commitment_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> Result<(bitcoin::secp256k1::Signature, Vec<bitcoin::secp256k1::Signature>), ()> {
426                 let mut ret = (self.sign_holder_commitment_and_htlcs)(self.this_arg, &crate::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { (commitment_tx as *const _) as *mut _ }, is_owned: false });
427                 let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_rust() }); }; let mut local_ret_0 = (orig_ret_0_0.into_rust(), local_orig_ret_0_1); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
428                 local_ret
429         }
430         fn sign_justice_transaction<T:bitcoin::secp256k1::Signing + bitcoin::secp256k1::Verification>(&self, justice_tx: &bitcoin::blockdata::transaction::Transaction, input: usize, amount: u64, per_commitment_key: &bitcoin::secp256k1::key::SecretKey, htlc: &Option<lightning::ln::chan_utils::HTLCOutputInCommitment>, _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> Result<bitcoin::secp256k1::Signature, ()> {
431                 let mut local_justice_tx = ::bitcoin::consensus::encode::serialize(justice_tx);
432                 let mut local_htlc = &crate::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (if htlc.is_none() { std::ptr::null() } else {  { (htlc.as_ref().unwrap()) } } as *const _) as *mut _ }, is_owned: false };
433                 let mut ret = (self.sign_justice_transaction)(self.this_arg, crate::c_types::Transaction::from_vec(local_justice_tx), input, amount, per_commitment_key.as_ref(), local_htlc);
434                 let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
435                 local_ret
436         }
437         fn sign_counterparty_htlc_transaction<T:bitcoin::secp256k1::Signing + bitcoin::secp256k1::Verification>(&self, htlc_tx: &bitcoin::blockdata::transaction::Transaction, input: usize, amount: u64, per_commitment_point: &bitcoin::secp256k1::key::PublicKey, htlc: &lightning::ln::chan_utils::HTLCOutputInCommitment, _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> Result<bitcoin::secp256k1::Signature, ()> {
438                 let mut local_htlc_tx = ::bitcoin::consensus::encode::serialize(htlc_tx);
439                 let mut ret = (self.sign_counterparty_htlc_transaction)(self.this_arg, crate::c_types::Transaction::from_vec(local_htlc_tx), input, amount, crate::c_types::PublicKey::from_rust(&per_commitment_point), &crate::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (htlc as *const _) as *mut _ }, is_owned: false });
440                 let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
441                 local_ret
442         }
443         fn sign_closing_transaction<T:bitcoin::secp256k1::Signing>(&self, closing_tx: &bitcoin::blockdata::transaction::Transaction, _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> Result<bitcoin::secp256k1::Signature, ()> {
444                 let mut local_closing_tx = ::bitcoin::consensus::encode::serialize(closing_tx);
445                 let mut ret = (self.sign_closing_transaction)(self.this_arg, crate::c_types::Transaction::from_vec(local_closing_tx));
446                 let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
447                 local_ret
448         }
449         fn sign_channel_announcement<T:bitcoin::secp256k1::Signing>(&self, msg: &lightning::ln::msgs::UnsignedChannelAnnouncement, _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> Result<bitcoin::secp256k1::Signature, ()> {
450                 let mut ret = (self.sign_channel_announcement)(self.this_arg, &crate::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false });
451                 let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
452                 local_ret
453         }
454         fn ready_channel(&mut self, channel_parameters: &lightning::ln::chan_utils::ChannelTransactionParameters) {
455                 (self.ready_channel)(self.this_arg, &crate::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { (channel_parameters as *const _) as *mut _ }, is_owned: false })
456         }
457 }
458
459 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
460 // directly as a Deref trait in higher-level structs:
461 impl std::ops::Deref for ChannelKeys {
462         type Target = Self;
463         fn deref(&self) -> &Self {
464                 self
465         }
466 }
467 /// Calls the free function if one is set
468 #[no_mangle]
469 pub extern "C" fn ChannelKeys_free(this_ptr: ChannelKeys) { }
470 impl Drop for ChannelKeys {
471         fn drop(&mut self) {
472                 if let Some(f) = self.free {
473                         f(self.this_arg);
474                 }
475         }
476 }
477 /// A trait to describe an object which can get user secrets and key material.
478 #[repr(C)]
479 pub struct KeysInterface {
480         pub this_arg: *mut c_void,
481         /// Get node secret key (aka node_id or network_key)
482         #[must_use]
483         pub get_node_secret: extern "C" fn (this_arg: *const c_void) -> crate::c_types::SecretKey,
484         /// Get destination redeemScript to encumber static protocol exit points.
485         #[must_use]
486         pub get_destination_script: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
487         /// Get shutdown_pubkey to use as PublicKey at channel closure
488         #[must_use]
489         pub get_shutdown_pubkey: extern "C" fn (this_arg: *const c_void) -> crate::c_types::PublicKey,
490         /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
491         /// restarted with some stale data!
492         #[must_use]
493         pub get_channel_keys: extern "C" fn (this_arg: *const c_void, inbound: bool, channel_value_satoshis: u64) -> crate::chain::keysinterface::ChannelKeys,
494         /// Gets a unique, cryptographically-secure, random 32 byte value. This is used for encrypting
495         /// onion packets and for temporary channel IDs. There is no requirement that these be
496         /// persisted anywhere, though they must be unique across restarts.
497         #[must_use]
498         pub get_secure_random_bytes: extern "C" fn (this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes,
499         /// Reads a `ChanKeySigner` for this `KeysInterface` from the given input stream.
500         /// This is only called during deserialization of other objects which contain
501         /// `ChannelKeys`-implementing objects (ie `ChannelMonitor`s and `ChannelManager`s).
502         /// The bytes are exactly those which `<Self::ChanKeySigner as Writeable>::write()` writes, and
503         /// contain no versioning scheme. You may wish to include your own version prefix and ensure
504         /// you've read all of the provided bytes to ensure no corruption occurred.
505         #[must_use]
506         pub read_chan_signer: extern "C" fn (this_arg: *const c_void, reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChanKeySignerDecodeErrorZ,
507         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
508 }
509 unsafe impl Send for KeysInterface {}
510 unsafe impl Sync for KeysInterface {}
511
512 use lightning::chain::keysinterface::KeysInterface as rustKeysInterface;
513 impl rustKeysInterface for KeysInterface {
514         type ChanKeySigner = crate::chain::keysinterface::ChannelKeys;
515         fn get_node_secret(&self) -> bitcoin::secp256k1::key::SecretKey {
516                 let mut ret = (self.get_node_secret)(self.this_arg);
517                 ret.into_rust()
518         }
519         fn get_destination_script(&self) -> bitcoin::blockdata::script::Script {
520                 let mut ret = (self.get_destination_script)(self.this_arg);
521                 ::bitcoin::blockdata::script::Script::from(ret.into_rust())
522         }
523         fn get_shutdown_pubkey(&self) -> bitcoin::secp256k1::key::PublicKey {
524                 let mut ret = (self.get_shutdown_pubkey)(self.this_arg);
525                 ret.into_rust()
526         }
527         fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> crate::chain::keysinterface::ChannelKeys {
528                 let mut ret = (self.get_channel_keys)(self.this_arg, inbound, channel_value_satoshis);
529                 ret
530         }
531         fn get_secure_random_bytes(&self) -> [u8; 32] {
532                 let mut ret = (self.get_secure_random_bytes)(self.this_arg);
533                 ret.data
534         }
535         fn read_chan_signer(&self, reader: &[u8]) -> Result<crate::chain::keysinterface::ChannelKeys, lightning::ln::msgs::DecodeError> {
536                 let mut local_reader = crate::c_types::u8slice::from_slice(reader);
537                 let mut ret = (self.read_chan_signer)(self.this_arg, local_reader);
538                 let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }) }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })};
539                 local_ret
540         }
541 }
542
543 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
544 // directly as a Deref trait in higher-level structs:
545 impl std::ops::Deref for KeysInterface {
546         type Target = Self;
547         fn deref(&self) -> &Self {
548                 self
549         }
550 }
551 /// Calls the free function if one is set
552 #[no_mangle]
553 pub extern "C" fn KeysInterface_free(this_ptr: KeysInterface) { }
554 impl Drop for KeysInterface {
555         fn drop(&mut self) {
556                 if let Some(f) = self.free {
557                         f(self.this_arg);
558                 }
559         }
560 }
561
562 use lightning::chain::keysinterface::InMemoryChannelKeys as nativeInMemoryChannelKeysImport;
563 type nativeInMemoryChannelKeys = nativeInMemoryChannelKeysImport;
564
565 /// A simple implementation of ChannelKeys that just keeps the private keys in memory.
566 ///
567 /// This implementation performs no policy checks and is insufficient by itself as
568 /// a secure external signer.
569 #[must_use]
570 #[repr(C)]
571 pub struct InMemoryChannelKeys {
572         /// Nearly everywhere, inner must be non-null, however in places where
573         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
574         pub inner: *mut nativeInMemoryChannelKeys,
575         pub is_owned: bool,
576 }
577
578 impl Drop for InMemoryChannelKeys {
579         fn drop(&mut self) {
580                 if self.is_owned && !self.inner.is_null() {
581                         let _ = unsafe { Box::from_raw(self.inner) };
582                 }
583         }
584 }
585 #[no_mangle]
586 pub extern "C" fn InMemoryChannelKeys_free(this_ptr: InMemoryChannelKeys) { }
587 #[allow(unused)]
588 /// Used only if an object of this type is returned as a trait impl by a method
589 extern "C" fn InMemoryChannelKeys_free_void(this_ptr: *mut c_void) {
590         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInMemoryChannelKeys); }
591 }
592 #[allow(unused)]
593 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
594 impl InMemoryChannelKeys {
595         pub(crate) fn take_inner(mut self) -> *mut nativeInMemoryChannelKeys {
596                 assert!(self.is_owned);
597                 let ret = self.inner;
598                 self.inner = std::ptr::null_mut();
599                 ret
600         }
601 }
602 impl Clone for InMemoryChannelKeys {
603         fn clone(&self) -> Self {
604                 Self {
605                         inner: Box::into_raw(Box::new(unsafe { &*self.inner }.clone())),
606                         is_owned: true,
607                 }
608         }
609 }
610 #[allow(unused)]
611 /// Used only if an object of this type is returned as a trait impl by a method
612 pub(crate) extern "C" fn InMemoryChannelKeys_clone_void(this_ptr: *const c_void) -> *mut c_void {
613         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeInMemoryChannelKeys)).clone() })) as *mut c_void
614 }
615 #[no_mangle]
616 pub extern "C" fn InMemoryChannelKeys_clone(orig: &InMemoryChannelKeys) -> InMemoryChannelKeys {
617         InMemoryChannelKeys { inner: Box::into_raw(Box::new(unsafe { &*orig.inner }.clone())), is_owned: true }
618 }
619 /// Private key of anchor tx
620 #[no_mangle]
621 pub extern "C" fn InMemoryChannelKeys_get_funding_key(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
622         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_key;
623         (*inner_val).as_ref()
624 }
625 /// Private key of anchor tx
626 #[no_mangle]
627 pub extern "C" fn InMemoryChannelKeys_set_funding_key(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::SecretKey) {
628         unsafe { &mut *this_ptr.inner }.funding_key = val.into_rust();
629 }
630 /// Holder secret key for blinded revocation pubkey
631 #[no_mangle]
632 pub extern "C" fn InMemoryChannelKeys_get_revocation_base_key(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
633         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.revocation_base_key;
634         (*inner_val).as_ref()
635 }
636 /// Holder secret key for blinded revocation pubkey
637 #[no_mangle]
638 pub extern "C" fn InMemoryChannelKeys_set_revocation_base_key(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::SecretKey) {
639         unsafe { &mut *this_ptr.inner }.revocation_base_key = val.into_rust();
640 }
641 /// Holder secret key used for our balance in counterparty-broadcasted commitment transactions
642 #[no_mangle]
643 pub extern "C" fn InMemoryChannelKeys_get_payment_key(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
644         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.payment_key;
645         (*inner_val).as_ref()
646 }
647 /// Holder secret key used for our balance in counterparty-broadcasted commitment transactions
648 #[no_mangle]
649 pub extern "C" fn InMemoryChannelKeys_set_payment_key(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::SecretKey) {
650         unsafe { &mut *this_ptr.inner }.payment_key = val.into_rust();
651 }
652 /// Holder secret key used in HTLC tx
653 #[no_mangle]
654 pub extern "C" fn InMemoryChannelKeys_get_delayed_payment_base_key(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
655         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.delayed_payment_base_key;
656         (*inner_val).as_ref()
657 }
658 /// Holder secret key used in HTLC tx
659 #[no_mangle]
660 pub extern "C" fn InMemoryChannelKeys_set_delayed_payment_base_key(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::SecretKey) {
661         unsafe { &mut *this_ptr.inner }.delayed_payment_base_key = val.into_rust();
662 }
663 /// Holder htlc secret key used in commitment tx htlc outputs
664 #[no_mangle]
665 pub extern "C" fn InMemoryChannelKeys_get_htlc_base_key(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
666         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_base_key;
667         (*inner_val).as_ref()
668 }
669 /// Holder htlc secret key used in commitment tx htlc outputs
670 #[no_mangle]
671 pub extern "C" fn InMemoryChannelKeys_set_htlc_base_key(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::SecretKey) {
672         unsafe { &mut *this_ptr.inner }.htlc_base_key = val.into_rust();
673 }
674 /// Commitment seed
675 #[no_mangle]
676 pub extern "C" fn InMemoryChannelKeys_get_commitment_seed(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
677         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.commitment_seed;
678         &(*inner_val)
679 }
680 /// Commitment seed
681 #[no_mangle]
682 pub extern "C" fn InMemoryChannelKeys_set_commitment_seed(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::ThirtyTwoBytes) {
683         unsafe { &mut *this_ptr.inner }.commitment_seed = val.data;
684 }
685 /// Create a new InMemoryChannelKeys
686 #[must_use]
687 #[no_mangle]
688 pub extern "C" fn InMemoryChannelKeys_new(mut funding_key: crate::c_types::SecretKey, mut revocation_base_key: crate::c_types::SecretKey, mut payment_key: crate::c_types::SecretKey, mut delayed_payment_base_key: crate::c_types::SecretKey, mut htlc_base_key: crate::c_types::SecretKey, mut commitment_seed: crate::c_types::ThirtyTwoBytes, mut channel_value_satoshis: u64, mut key_derivation_params: crate::c_types::derived::C2Tuple_u64u64Z) -> crate::chain::keysinterface::InMemoryChannelKeys {
689         let (mut orig_key_derivation_params_0, mut orig_key_derivation_params_1) = key_derivation_params.to_rust(); let mut local_key_derivation_params = (orig_key_derivation_params_0, orig_key_derivation_params_1);
690         let mut ret = lightning::chain::keysinterface::InMemoryChannelKeys::new(&bitcoin::secp256k1::Secp256k1::new(), funding_key.into_rust(), revocation_base_key.into_rust(), payment_key.into_rust(), delayed_payment_base_key.into_rust(), htlc_base_key.into_rust(), commitment_seed.data, channel_value_satoshis, local_key_derivation_params);
691         crate::chain::keysinterface::InMemoryChannelKeys { inner: Box::into_raw(Box::new(ret)), is_owned: true }
692 }
693
694 /// Counterparty pubkeys.
695 /// Will panic if ready_channel wasn't called.
696 #[must_use]
697 #[no_mangle]
698 pub extern "C" fn InMemoryChannelKeys_counterparty_pubkeys(this_arg: &InMemoryChannelKeys) -> crate::ln::chan_utils::ChannelPublicKeys {
699         let mut ret = unsafe { &*this_arg.inner }.counterparty_pubkeys();
700         crate::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
701 }
702
703 /// The contest_delay value specified by our counterparty and applied on holder-broadcastable
704 /// transactions, ie the amount of time that we have to wait to recover our funds if we
705 /// broadcast a transaction.
706 /// Will panic if ready_channel wasn't called.
707 #[must_use]
708 #[no_mangle]
709 pub extern "C" fn InMemoryChannelKeys_counterparty_selected_contest_delay(this_arg: &InMemoryChannelKeys) -> u16 {
710         let mut ret = unsafe { &*this_arg.inner }.counterparty_selected_contest_delay();
711         ret
712 }
713
714 /// The contest_delay value specified by us and applied on transactions broadcastable
715 /// by our counterparty, ie the amount of time that they have to wait to recover their funds
716 /// if they broadcast a transaction.
717 /// Will panic if ready_channel wasn't called.
718 #[must_use]
719 #[no_mangle]
720 pub extern "C" fn InMemoryChannelKeys_holder_selected_contest_delay(this_arg: &InMemoryChannelKeys) -> u16 {
721         let mut ret = unsafe { &*this_arg.inner }.holder_selected_contest_delay();
722         ret
723 }
724
725 /// Whether the holder is the initiator
726 /// Will panic if ready_channel wasn't called.
727 #[must_use]
728 #[no_mangle]
729 pub extern "C" fn InMemoryChannelKeys_is_outbound(this_arg: &InMemoryChannelKeys) -> bool {
730         let mut ret = unsafe { &*this_arg.inner }.is_outbound();
731         ret
732 }
733
734 /// Funding outpoint
735 /// Will panic if ready_channel wasn't called.
736 #[must_use]
737 #[no_mangle]
738 pub extern "C" fn InMemoryChannelKeys_funding_outpoint(this_arg: &InMemoryChannelKeys) -> crate::chain::transaction::OutPoint {
739         let mut ret = unsafe { &*this_arg.inner }.funding_outpoint();
740         crate::chain::transaction::OutPoint { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
741 }
742
743 /// Obtain a ChannelTransactionParameters for this channel, to be used when verifying or
744 /// building transactions.
745 ///
746 /// Will panic if ready_channel wasn't called.
747 #[must_use]
748 #[no_mangle]
749 pub extern "C" fn InMemoryChannelKeys_get_channel_parameters(this_arg: &InMemoryChannelKeys) -> crate::ln::chan_utils::ChannelTransactionParameters {
750         let mut ret = unsafe { &*this_arg.inner }.get_channel_parameters();
751         crate::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
752 }
753
754 impl From<nativeInMemoryChannelKeys> for crate::chain::keysinterface::ChannelKeys {
755         fn from(obj: nativeInMemoryChannelKeys) -> Self {
756                 let mut rust_obj = InMemoryChannelKeys { inner: Box::into_raw(Box::new(obj)), is_owned: true };
757                 let mut ret = InMemoryChannelKeys_as_ChannelKeys(&rust_obj);
758                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
759                 rust_obj.inner = std::ptr::null_mut();
760                 ret.free = Some(InMemoryChannelKeys_free_void);
761                 ret
762         }
763 }
764 #[no_mangle]
765 pub extern "C" fn InMemoryChannelKeys_as_ChannelKeys(this_arg: *const InMemoryChannelKeys) -> crate::chain::keysinterface::ChannelKeys {
766         crate::chain::keysinterface::ChannelKeys {
767                 this_arg: unsafe { (*this_arg).inner as *mut c_void },
768                 free: None,
769                 get_per_commitment_point: InMemoryChannelKeys_ChannelKeys_get_per_commitment_point,
770                 release_commitment_secret: InMemoryChannelKeys_ChannelKeys_release_commitment_secret,
771
772                 pubkeys: crate::ln::chan_utils::ChannelPublicKeys { inner: std::ptr::null_mut(), is_owned: true },
773                 set_pubkeys: Some(InMemoryChannelKeys_ChannelKeys_set_pubkeys),
774                 key_derivation_params: InMemoryChannelKeys_ChannelKeys_key_derivation_params,
775                 sign_counterparty_commitment: InMemoryChannelKeys_ChannelKeys_sign_counterparty_commitment,
776                 sign_holder_commitment_and_htlcs: InMemoryChannelKeys_ChannelKeys_sign_holder_commitment_and_htlcs,
777                 sign_justice_transaction: InMemoryChannelKeys_ChannelKeys_sign_justice_transaction,
778                 sign_counterparty_htlc_transaction: InMemoryChannelKeys_ChannelKeys_sign_counterparty_htlc_transaction,
779                 sign_closing_transaction: InMemoryChannelKeys_ChannelKeys_sign_closing_transaction,
780                 sign_channel_announcement: InMemoryChannelKeys_ChannelKeys_sign_channel_announcement,
781                 ready_channel: InMemoryChannelKeys_ChannelKeys_ready_channel,
782                 clone: Some(InMemoryChannelKeys_clone_void),
783                 write: InMemoryChannelKeys_write_void,
784         }
785 }
786 use lightning::chain::keysinterface::ChannelKeys as ChannelKeysTraitImport;
787 #[must_use]
788 extern "C" fn InMemoryChannelKeys_ChannelKeys_get_per_commitment_point(this_arg: *const c_void, mut idx: u64) -> crate::c_types::PublicKey {
789         let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.get_per_commitment_point(idx, &bitcoin::secp256k1::Secp256k1::new());
790         crate::c_types::PublicKey::from_rust(&ret)
791 }
792 #[must_use]
793 extern "C" fn InMemoryChannelKeys_ChannelKeys_release_commitment_secret(this_arg: *const c_void, mut idx: u64) -> crate::c_types::ThirtyTwoBytes {
794         let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.release_commitment_secret(idx);
795         crate::c_types::ThirtyTwoBytes { data: ret }
796 }
797 #[must_use]
798 extern "C" fn InMemoryChannelKeys_ChannelKeys_pubkeys(this_arg: *const c_void) -> crate::ln::chan_utils::ChannelPublicKeys {
799         let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.pubkeys();
800         crate::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
801 }
802 extern "C" fn InMemoryChannelKeys_ChannelKeys_set_pubkeys(trait_self_arg: &ChannelKeys) {
803         // This is a bit race-y in the general case, but for our specific use-cases today, we're safe
804         // Specifically, we must ensure that the first time we're called it can never be in parallel
805         if trait_self_arg.pubkeys.inner.is_null() {
806                 unsafe { &mut *(trait_self_arg as *const ChannelKeys  as *mut ChannelKeys) }.pubkeys = InMemoryChannelKeys_ChannelKeys_pubkeys(trait_self_arg.this_arg);
807         }
808 }
809 #[must_use]
810 extern "C" fn InMemoryChannelKeys_ChannelKeys_key_derivation_params(this_arg: *const c_void) -> crate::c_types::derived::C2Tuple_u64u64Z {
811         let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.key_derivation_params();
812         let (mut orig_ret_0, mut orig_ret_1) = ret; let mut local_ret = (orig_ret_0, orig_ret_1).into();
813         local_ret
814 }
815 #[must_use]
816 extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_counterparty_commitment(this_arg: *const c_void, commitment_tx: &crate::ln::chan_utils::CommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
817         let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_counterparty_commitment(unsafe { &*commitment_tx.inner }, &bitcoin::secp256k1::Secp256k1::new());
818         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_orig_ret_0_1 = Vec::new(); for item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::c_types::Signature::from_rust(&item) }); }; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }) };
819         local_ret
820 }
821 #[must_use]
822 extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_holder_commitment_and_htlcs(this_arg: *const c_void, commitment_tx: &crate::ln::chan_utils::HolderCommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
823         let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_holder_commitment_and_htlcs(unsafe { &*commitment_tx.inner }, &bitcoin::secp256k1::Secp256k1::new());
824         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_orig_ret_0_1 = Vec::new(); for item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::c_types::Signature::from_rust(&item) }); }; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }) };
825         local_ret
826 }
827 #[must_use]
828 extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_justice_transaction(this_arg: *const c_void, mut justice_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, per_commitment_key: *const [u8; 32], htlc: &crate::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ {
829         let mut local_htlc = if htlc.inner.is_null() { None } else { Some((* { unsafe { &*htlc.inner } }).clone()) };
830         let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_justice_transaction(&justice_tx.into_bitcoin(), input, amount, &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *per_commitment_key}[..]).unwrap(), &local_htlc, &bitcoin::secp256k1::Secp256k1::new());
831         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }) };
832         local_ret
833 }
834 #[must_use]
835 extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_counterparty_htlc_transaction(this_arg: *const c_void, mut htlc_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, mut per_commitment_point: crate::c_types::PublicKey, htlc: &crate::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ {
836         let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_counterparty_htlc_transaction(&htlc_tx.into_bitcoin(), input, amount, &per_commitment_point.into_rust(), unsafe { &*htlc.inner }, &bitcoin::secp256k1::Secp256k1::new());
837         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }) };
838         local_ret
839 }
840 #[must_use]
841 extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_closing_transaction(this_arg: *const c_void, mut closing_tx: crate::c_types::Transaction) -> crate::c_types::derived::CResult_SignatureNoneZ {
842         let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_closing_transaction(&closing_tx.into_bitcoin(), &bitcoin::secp256k1::Secp256k1::new());
843         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }) };
844         local_ret
845 }
846 #[must_use]
847 extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_channel_announcement(this_arg: *const c_void, msg: &crate::ln::msgs::UnsignedChannelAnnouncement) -> crate::c_types::derived::CResult_SignatureNoneZ {
848         let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_channel_announcement(unsafe { &*msg.inner }, &bitcoin::secp256k1::Secp256k1::new());
849         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }) };
850         local_ret
851 }
852 extern "C" fn InMemoryChannelKeys_ChannelKeys_ready_channel(this_arg: *mut c_void, channel_parameters: &crate::ln::chan_utils::ChannelTransactionParameters) {
853         unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.ready_channel(unsafe { &*channel_parameters.inner })
854 }
855
856 #[no_mangle]
857 pub extern "C" fn InMemoryChannelKeys_write(obj: *const InMemoryChannelKeys) -> crate::c_types::derived::CVec_u8Z {
858         crate::c_types::serialize_obj(unsafe { &(*(*obj).inner) })
859 }
860 #[no_mangle]
861 pub(crate) extern "C" fn InMemoryChannelKeys_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
862         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeInMemoryChannelKeys) })
863 }
864 #[no_mangle]
865 pub extern "C" fn InMemoryChannelKeys_read(ser: crate::c_types::u8slice) -> InMemoryChannelKeys {
866         if let Ok(res) = crate::c_types::deserialize_obj(ser) {
867                 InMemoryChannelKeys { inner: Box::into_raw(Box::new(res)), is_owned: true }
868         } else {
869                 InMemoryChannelKeys { inner: std::ptr::null_mut(), is_owned: true }
870         }
871 }
872
873 use lightning::chain::keysinterface::KeysManager as nativeKeysManagerImport;
874 type nativeKeysManager = nativeKeysManagerImport;
875
876 /// Simple KeysInterface implementor that takes a 32-byte seed for use as a BIP 32 extended key
877 /// and derives keys from that.
878 ///
879 /// Your node_id is seed/0'
880 /// ChannelMonitor closes may use seed/1'
881 /// Cooperative closes may use seed/2'
882 /// The two close keys may be needed to claim on-chain funds!
883 #[must_use]
884 #[repr(C)]
885 pub struct KeysManager {
886         /// Nearly everywhere, inner must be non-null, however in places where
887         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
888         pub inner: *mut nativeKeysManager,
889         pub is_owned: bool,
890 }
891
892 impl Drop for KeysManager {
893         fn drop(&mut self) {
894                 if self.is_owned && !self.inner.is_null() {
895                         let _ = unsafe { Box::from_raw(self.inner) };
896                 }
897         }
898 }
899 #[no_mangle]
900 pub extern "C" fn KeysManager_free(this_ptr: KeysManager) { }
901 #[allow(unused)]
902 /// Used only if an object of this type is returned as a trait impl by a method
903 extern "C" fn KeysManager_free_void(this_ptr: *mut c_void) {
904         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeKeysManager); }
905 }
906 #[allow(unused)]
907 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
908 impl KeysManager {
909         pub(crate) fn take_inner(mut self) -> *mut nativeKeysManager {
910                 assert!(self.is_owned);
911                 let ret = self.inner;
912                 self.inner = std::ptr::null_mut();
913                 ret
914         }
915 }
916 /// Constructs a KeysManager from a 32-byte seed. If the seed is in some way biased (eg your
917 /// CSRNG is busted) this may panic (but more importantly, you will possibly lose funds).
918 /// starting_time isn't strictly required to actually be a time, but it must absolutely,
919 /// without a doubt, be unique to this instance. ie if you start multiple times with the same
920 /// seed, starting_time must be unique to each run. Thus, the easiest way to achieve this is to
921 /// simply use the current time (with very high precision).
922 ///
923 /// The seed MUST be backed up safely prior to use so that the keys can be re-created, however,
924 /// obviously, starting_time should be unique every time you reload the library - it is only
925 /// used to generate new ephemeral key data (which will be stored by the individual channel if
926 /// necessary).
927 ///
928 /// Note that the seed is required to recover certain on-chain funds independent of
929 /// ChannelMonitor data, though a current copy of ChannelMonitor data is also required for any
930 /// channel, and some on-chain during-closing funds.
931 ///
932 /// Note that until the 0.1 release there is no guarantee of backward compatibility between
933 /// versions. Once the library is more fully supported, the docs will be updated to include a
934 /// detailed description of the guarantee.
935 #[must_use]
936 #[no_mangle]
937 pub extern "C" fn KeysManager_new(seed: *const [u8; 32], mut network: crate::bitcoin::network::Network, mut starting_time_secs: u64, mut starting_time_nanos: u32) -> KeysManager {
938         let mut ret = lightning::chain::keysinterface::KeysManager::new(unsafe { &*seed}, network.into_bitcoin(), starting_time_secs, starting_time_nanos);
939         KeysManager { inner: Box::into_raw(Box::new(ret)), is_owned: true }
940 }
941
942 /// Derive an old set of ChannelKeys for per-channel secrets based on a key derivation
943 /// parameters.
944 /// Key derivation parameters are accessible through a per-channel secrets
945 /// ChannelKeys::key_derivation_params and is provided inside DynamicOuputP2WSH in case of
946 /// onchain output detection for which a corresponding delayed_payment_key must be derived.
947 #[must_use]
948 #[no_mangle]
949 pub extern "C" fn KeysManager_derive_channel_keys(this_arg: &KeysManager, mut channel_value_satoshis: u64, mut params_1: u64, mut params_2: u64) -> crate::chain::keysinterface::InMemoryChannelKeys {
950         let mut ret = unsafe { &*this_arg.inner }.derive_channel_keys(channel_value_satoshis, params_1, params_2);
951         crate::chain::keysinterface::InMemoryChannelKeys { inner: Box::into_raw(Box::new(ret)), is_owned: true }
952 }
953
954 impl From<nativeKeysManager> for crate::chain::keysinterface::KeysInterface {
955         fn from(obj: nativeKeysManager) -> Self {
956                 let mut rust_obj = KeysManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
957                 let mut ret = KeysManager_as_KeysInterface(&rust_obj);
958                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
959                 rust_obj.inner = std::ptr::null_mut();
960                 ret.free = Some(KeysManager_free_void);
961                 ret
962         }
963 }
964 #[no_mangle]
965 pub extern "C" fn KeysManager_as_KeysInterface(this_arg: *const KeysManager) -> crate::chain::keysinterface::KeysInterface {
966         crate::chain::keysinterface::KeysInterface {
967                 this_arg: unsafe { (*this_arg).inner as *mut c_void },
968                 free: None,
969                 get_node_secret: KeysManager_KeysInterface_get_node_secret,
970                 get_destination_script: KeysManager_KeysInterface_get_destination_script,
971                 get_shutdown_pubkey: KeysManager_KeysInterface_get_shutdown_pubkey,
972                 get_channel_keys: KeysManager_KeysInterface_get_channel_keys,
973                 get_secure_random_bytes: KeysManager_KeysInterface_get_secure_random_bytes,
974                 read_chan_signer: KeysManager_KeysInterface_read_chan_signer,
975         }
976 }
977 use lightning::chain::keysinterface::KeysInterface as KeysInterfaceTraitImport;
978 #[must_use]
979 extern "C" fn KeysManager_KeysInterface_get_node_secret(this_arg: *const c_void) -> crate::c_types::SecretKey {
980         let mut ret = unsafe { &mut *(this_arg as *mut nativeKeysManager) }.get_node_secret();
981         crate::c_types::SecretKey::from_rust(ret)
982 }
983 #[must_use]
984 extern "C" fn KeysManager_KeysInterface_get_destination_script(this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z {
985         let mut ret = unsafe { &mut *(this_arg as *mut nativeKeysManager) }.get_destination_script();
986         ret.into_bytes().into()
987 }
988 #[must_use]
989 extern "C" fn KeysManager_KeysInterface_get_shutdown_pubkey(this_arg: *const c_void) -> crate::c_types::PublicKey {
990         let mut ret = unsafe { &mut *(this_arg as *mut nativeKeysManager) }.get_shutdown_pubkey();
991         crate::c_types::PublicKey::from_rust(&ret)
992 }
993 #[must_use]
994 extern "C" fn KeysManager_KeysInterface_get_channel_keys(this_arg: *const c_void, mut _inbound: bool, mut channel_value_satoshis: u64) -> crate::chain::keysinterface::ChannelKeys {
995         let mut ret = unsafe { &mut *(this_arg as *mut nativeKeysManager) }.get_channel_keys(_inbound, channel_value_satoshis);
996         ret.into()
997 }
998 #[must_use]
999 extern "C" fn KeysManager_KeysInterface_get_secure_random_bytes(this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes {
1000         let mut ret = unsafe { &mut *(this_arg as *mut nativeKeysManager) }.get_secure_random_bytes();
1001         crate::c_types::ThirtyTwoBytes { data: ret }
1002 }
1003 #[must_use]
1004 extern "C" fn KeysManager_KeysInterface_read_chan_signer(this_arg: *const c_void, mut reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChanKeySignerDecodeErrorZ {
1005         let mut ret = unsafe { &mut *(this_arg as *mut nativeKeysManager) }.read_chan_signer(reader.to_slice());
1006         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o.into() }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
1007         local_ret
1008 }
1009