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