1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Provides keys to LDK and defines some useful objects describing spendable on-chain outputs.
12 //! The provided output descriptors follow a custom LDK data format and are currently not fully
13 //! compatible with Bitcoin Core output descriptors.
15 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, EcdsaSighashType};
16 use bitcoin::blockdata::script::{Script, Builder};
17 use bitcoin::blockdata::opcodes;
18 use bitcoin::network::constants::Network;
19 use bitcoin::psbt::PartiallySignedTransaction;
20 use bitcoin::util::bip32::{ExtendedPrivKey, ExtendedPubKey, ChildNumber};
21 use bitcoin::util::sighash;
23 use bitcoin::bech32::u5;
24 use bitcoin::hashes::{Hash, HashEngine};
25 use bitcoin::hashes::sha256::Hash as Sha256;
26 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
27 use bitcoin::hash_types::WPubkeyHash;
29 use bitcoin::secp256k1::{KeyPair, PublicKey, Scalar, Secp256k1, SecretKey, Signing};
30 use bitcoin::secp256k1::ecdh::SharedSecret;
31 use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
32 use bitcoin::secp256k1::schnorr;
33 use bitcoin::{PackedLockTime, secp256k1, Sequence, Witness};
35 use crate::util::transaction_utils;
36 use crate::util::crypto::{hkdf_extract_expand_twice, sign, sign_with_aux_rand};
37 use crate::util::ser::{Writeable, Writer, Readable, ReadableArgs};
38 use crate::chain::transaction::OutPoint;
39 use crate::events::bump_transaction::HTLCDescriptor;
40 use crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI;
41 use crate::ln::{chan_utils, PaymentPreimage};
42 use crate::ln::chan_utils::{HTLCOutputInCommitment, make_funding_redeemscript, ChannelPublicKeys, HolderCommitmentTransaction, ChannelTransactionParameters, CommitmentTransaction, ClosingTransaction};
43 use crate::ln::msgs::{UnsignedChannelAnnouncement, UnsignedGossipMessage};
44 use crate::ln::script::ShutdownScript;
45 use crate::offers::invoice::UnsignedBolt12Invoice;
46 use crate::offers::invoice_request::UnsignedInvoiceRequest;
48 use crate::prelude::*;
49 use core::convert::TryInto;
51 use core::sync::atomic::{AtomicUsize, Ordering};
52 use crate::io::{self, Error};
53 use crate::ln::features::ChannelTypeFeatures;
54 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
55 use crate::util::atomic_counter::AtomicCounter;
56 use crate::util::chacha20::ChaCha20;
57 use crate::util::invoice::construct_invoice_preimage;
59 pub(crate) mod type_resolver;
61 /// Used as initial key material, to be expanded into multiple secret keys (but not to be used
62 /// directly). This is used within LDK to encrypt/decrypt inbound payment data.
64 /// This is not exported to bindings users as we just use `[u8; 32]` directly
65 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
66 pub struct KeyMaterial(pub [u8; 32]);
68 /// Information about a spendable output to a P2WSH script.
70 /// See [`SpendableOutputDescriptor::DelayedPaymentOutput`] for more details on how to spend this.
71 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
72 pub struct DelayedPaymentOutputDescriptor {
73 /// The outpoint which is spendable.
74 pub outpoint: OutPoint,
75 /// Per commitment point to derive the delayed payment key by key holder.
76 pub per_commitment_point: PublicKey,
77 /// The `nSequence` value which must be set in the spending input to satisfy the `OP_CSV` in
78 /// the witness_script.
79 pub to_self_delay: u16,
80 /// The output which is referenced by the given outpoint.
82 /// The revocation point specific to the commitment transaction which was broadcast. Used to
83 /// derive the witnessScript for this output.
84 pub revocation_pubkey: PublicKey,
85 /// Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`].
86 /// This may be useful in re-deriving keys used in the channel to spend the output.
87 pub channel_keys_id: [u8; 32],
88 /// The value of the channel which this output originated from, possibly indirectly.
89 pub channel_value_satoshis: u64,
91 impl DelayedPaymentOutputDescriptor {
92 /// The maximum length a well-formed witness spending one of these should have.
93 /// Note: If you have the grind_signatures feature enabled, this will be at least 1 byte
95 // Calculated as 1 byte length + 73 byte signature, 1 byte empty vec push, 1 byte length plus
96 // redeemscript push length.
97 pub const MAX_WITNESS_LENGTH: usize = 1 + 73 + 1 + chan_utils::REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH + 1;
100 impl_writeable_tlv_based!(DelayedPaymentOutputDescriptor, {
101 (0, outpoint, required),
102 (2, per_commitment_point, required),
103 (4, to_self_delay, required),
104 (6, output, required),
105 (8, revocation_pubkey, required),
106 (10, channel_keys_id, required),
107 (12, channel_value_satoshis, required),
110 pub(crate) const P2WPKH_WITNESS_WEIGHT: u64 = 1 /* num stack items */ +
112 73 /* sig including sighash flag */ +
113 1 /* pubkey length */ +
116 /// Information about a spendable output to our "payment key".
118 /// See [`SpendableOutputDescriptor::StaticPaymentOutput`] for more details on how to spend this.
119 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
120 pub struct StaticPaymentOutputDescriptor {
121 /// The outpoint which is spendable.
122 pub outpoint: OutPoint,
123 /// The output which is referenced by the given outpoint.
125 /// Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`].
126 /// This may be useful in re-deriving keys used in the channel to spend the output.
127 pub channel_keys_id: [u8; 32],
128 /// The value of the channel which this transactions spends.
129 pub channel_value_satoshis: u64,
130 /// The necessary channel parameters that need to be provided to the re-derived signer through
131 /// [`ChannelSigner::provide_channel_parameters`].
133 /// Added as optional, but always `Some` if the descriptor was produced in v0.0.117 or later.
134 pub channel_transaction_parameters: Option<ChannelTransactionParameters>,
136 impl StaticPaymentOutputDescriptor {
137 /// The maximum length a well-formed witness spending one of these should have.
138 /// Note: If you have the grind_signatures feature enabled, this will be at least 1 byte
140 pub fn max_witness_length(&self) -> usize {
141 if self.channel_transaction_parameters.as_ref()
142 .map(|channel_params| channel_params.channel_type_features.supports_anchors_zero_fee_htlc_tx())
145 let witness_script_weight = 1 /* pubkey push */ + 33 /* pubkey */ +
146 1 /* OP_CHECKSIGVERIFY */ + 1 /* OP_1 */ + 1 /* OP_CHECKSEQUENCEVERIFY */;
147 1 /* num witness items */ + 1 /* sig push */ + 73 /* sig including sighash flag */ +
148 1 /* witness script push */ + witness_script_weight
150 P2WPKH_WITNESS_WEIGHT as usize
154 impl_writeable_tlv_based!(StaticPaymentOutputDescriptor, {
155 (0, outpoint, required),
156 (2, output, required),
157 (4, channel_keys_id, required),
158 (6, channel_value_satoshis, required),
159 (7, channel_transaction_parameters, option),
162 /// Describes the necessary information to spend a spendable output.
164 /// When on-chain outputs are created by LDK (which our counterparty is not able to claim at any
165 /// point in the future) a [`SpendableOutputs`] event is generated which you must track and be able
166 /// to spend on-chain. The information needed to do this is provided in this enum, including the
167 /// outpoint describing which `txid` and output `index` is available, the full output which exists
168 /// at that `txid`/`index`, and any keys or other information required to sign.
170 /// [`SpendableOutputs`]: crate::events::Event::SpendableOutputs
171 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
172 pub enum SpendableOutputDescriptor {
173 /// An output to a script which was provided via [`SignerProvider`] directly, either from
174 /// [`get_destination_script`] or [`get_shutdown_scriptpubkey`], thus you should already
175 /// know how to spend it. No secret keys are provided as LDK was never given any key.
176 /// These may include outputs from a transaction punishing our counterparty or claiming an HTLC
177 /// on-chain using the payment preimage or after it has timed out.
179 /// [`get_shutdown_scriptpubkey`]: SignerProvider::get_shutdown_scriptpubkey
180 /// [`get_destination_script`]: SignerProvider::get_shutdown_scriptpubkey
182 /// The outpoint which is spendable.
184 /// The output which is referenced by the given outpoint.
187 /// An output to a P2WSH script which can be spent with a single signature after an `OP_CSV`
190 /// The witness in the spending input should be:
192 /// <BIP 143 signature> <empty vector> (MINIMALIF standard rule) <provided witnessScript>
195 /// Note that the `nSequence` field in the spending input must be set to
196 /// [`DelayedPaymentOutputDescriptor::to_self_delay`] (which means the transaction is not
197 /// broadcastable until at least [`DelayedPaymentOutputDescriptor::to_self_delay`] blocks after
198 /// the outpoint confirms, see [BIP
199 /// 68](https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki)). Also note that LDK
200 /// won't generate a [`SpendableOutputDescriptor`] until the corresponding block height
203 /// These are generally the result of a "revocable" output to us, spendable only by us unless
204 /// it is an output from an old state which we broadcast (which should never happen).
206 /// To derive the delayed payment key which is used to sign this input, you must pass the
207 /// holder [`InMemorySigner::delayed_payment_base_key`] (i.e., the private key which corresponds to the
208 /// [`ChannelPublicKeys::delayed_payment_basepoint`] in [`ChannelSigner::pubkeys`]) and the provided
209 /// [`DelayedPaymentOutputDescriptor::per_commitment_point`] to [`chan_utils::derive_private_key`]. The public key can be
210 /// generated without the secret key using [`chan_utils::derive_public_key`] and only the
211 /// [`ChannelPublicKeys::delayed_payment_basepoint`] which appears in [`ChannelSigner::pubkeys`].
213 /// To derive the [`DelayedPaymentOutputDescriptor::revocation_pubkey`] provided here (which is
214 /// used in the witness script generation), you must pass the counterparty
215 /// [`ChannelPublicKeys::revocation_basepoint`] (which appears in the call to
216 /// [`ChannelSigner::provide_channel_parameters`]) and the provided
217 /// [`DelayedPaymentOutputDescriptor::per_commitment_point`] to
218 /// [`chan_utils::derive_public_revocation_key`].
220 /// The witness script which is hashed and included in the output `script_pubkey` may be
221 /// regenerated by passing the [`DelayedPaymentOutputDescriptor::revocation_pubkey`] (derived
222 /// as explained above), our delayed payment pubkey (derived as explained above), and the
223 /// [`DelayedPaymentOutputDescriptor::to_self_delay`] contained here to
224 /// [`chan_utils::get_revokeable_redeemscript`].
225 DelayedPaymentOutput(DelayedPaymentOutputDescriptor),
226 /// An output spendable exclusively by our payment key (i.e., the private key that corresponds
227 /// to the `payment_point` in [`ChannelSigner::pubkeys`]). The output type depends on the
228 /// channel type negotiated.
230 /// On an anchor outputs channel, the witness in the spending input is:
232 /// <BIP 143 signature> <witness script>
235 /// Otherwise, it is:
237 /// <BIP 143 signature> <payment key>
240 /// These are generally the result of our counterparty having broadcast the current state,
241 /// allowing us to claim the non-HTLC-encumbered outputs immediately, or after one confirmation
242 /// in the case of anchor outputs channels.
243 StaticPaymentOutput(StaticPaymentOutputDescriptor),
246 impl_writeable_tlv_based_enum!(SpendableOutputDescriptor,
247 (0, StaticOutput) => {
248 (0, outpoint, required),
249 (2, output, required),
252 (1, DelayedPaymentOutput),
253 (2, StaticPaymentOutput),
256 impl SpendableOutputDescriptor {
257 /// Turns this into a [`bitcoin::psbt::Input`] which can be used to create a
258 /// [`PartiallySignedTransaction`] which spends the given descriptor.
260 /// Note that this does not include any signatures, just the information required to
261 /// construct the transaction and sign it.
262 pub fn to_psbt_input(&self) -> bitcoin::psbt::Input {
264 SpendableOutputDescriptor::StaticOutput { output, .. } => {
265 // Is a standard P2WPKH, no need for witness script
266 bitcoin::psbt::Input {
267 witness_utxo: Some(output.clone()),
271 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
272 // TODO we could add the witness script as well
273 bitcoin::psbt::Input {
274 witness_utxo: Some(descriptor.output.clone()),
278 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
279 // TODO we could add the witness script as well
280 bitcoin::psbt::Input {
281 witness_utxo: Some(descriptor.output.clone()),
288 /// Creates an unsigned [`PartiallySignedTransaction`] which spends the given descriptors to
289 /// the given outputs, plus an output to the given change destination (if sufficient
290 /// change value remains). The PSBT will have a feerate, at least, of the given value.
292 /// The `locktime` argument is used to set the transaction's locktime. If `None`, the
293 /// transaction will have a locktime of 0. It it recommended to set this to the current block
294 /// height to avoid fee sniping, unless you have some specific reason to use a different
297 /// Returns the PSBT and expected max transaction weight.
299 /// Returns `Err(())` if the output value is greater than the input value minus required fee,
300 /// if a descriptor was duplicated, or if an output descriptor `script_pubkey`
301 /// does not match the one we can spend.
303 /// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
304 pub fn create_spendable_outputs_psbt(descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>, change_destination_script: Script, feerate_sat_per_1000_weight: u32, locktime: Option<PackedLockTime>) -> Result<(PartiallySignedTransaction, usize), ()> {
305 let mut input = Vec::with_capacity(descriptors.len());
306 let mut input_value = 0;
307 let mut witness_weight = 0;
308 let mut output_set = HashSet::with_capacity(descriptors.len());
309 for outp in descriptors {
311 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
312 if !output_set.insert(descriptor.outpoint) { return Err(()); }
314 if descriptor.channel_transaction_parameters.as_ref()
315 .map(|channel_params| channel_params.channel_type_features.supports_anchors_zero_fee_htlc_tx())
318 Sequence::from_consensus(1)
323 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
324 script_sig: Script::new(),
326 witness: Witness::new(),
328 witness_weight += descriptor.max_witness_length();
329 #[cfg(feature = "grind_signatures")]
330 { witness_weight -= 1; } // Guarantees a low R signature
331 input_value += descriptor.output.value;
333 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
334 if !output_set.insert(descriptor.outpoint) { return Err(()); }
336 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
337 script_sig: Script::new(),
338 sequence: Sequence(descriptor.to_self_delay as u32),
339 witness: Witness::new(),
341 witness_weight += DelayedPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
342 #[cfg(feature = "grind_signatures")]
343 { witness_weight -= 1; } // Guarantees a low R signature
344 input_value += descriptor.output.value;
346 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
347 if !output_set.insert(*outpoint) { return Err(()); }
349 previous_output: outpoint.into_bitcoin_outpoint(),
350 script_sig: Script::new(),
351 sequence: Sequence::ZERO,
352 witness: Witness::new(),
354 witness_weight += 1 + 73 + 34;
355 #[cfg(feature = "grind_signatures")]
356 { witness_weight -= 1; } // Guarantees a low R signature
357 input_value += output.value;
360 if input_value > MAX_VALUE_MSAT / 1000 { return Err(()); }
362 let mut tx = Transaction {
364 lock_time: locktime.unwrap_or(PackedLockTime::ZERO),
368 let expected_max_weight =
369 transaction_utils::maybe_add_change_output(&mut tx, input_value, witness_weight, feerate_sat_per_1000_weight, change_destination_script)?;
371 let psbt_inputs = descriptors.iter().map(|d| d.to_psbt_input()).collect::<Vec<_>>();
372 let psbt = PartiallySignedTransaction {
374 outputs: vec![Default::default(); tx.output.len()],
376 xpub: Default::default(),
378 proprietary: Default::default(),
379 unknown: Default::default(),
381 Ok((psbt, expected_max_weight))
385 /// A trait to handle Lightning channel key material without concretizing the channel type or
386 /// the signature mechanism.
387 pub trait ChannelSigner {
388 /// Gets the per-commitment point for a specific commitment number
390 /// Note that the commitment number starts at `(1 << 48) - 1` and counts backwards.
391 fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>) -> PublicKey;
393 /// Gets the commitment secret for a specific commitment number as part of the revocation process
395 /// An external signer implementation should error here if the commitment was already signed
396 /// and should refuse to sign it in the future.
398 /// May be called more than once for the same index.
400 /// Note that the commitment number starts at `(1 << 48) - 1` and counts backwards.
401 // TODO: return a Result so we can signal a validation error
402 fn release_commitment_secret(&self, idx: u64) -> [u8; 32];
404 /// Validate the counterparty's signatures on the holder commitment transaction and HTLCs.
406 /// This is required in order for the signer to make sure that releasing a commitment
407 /// secret won't leave us without a broadcastable holder transaction.
408 /// Policy checks should be implemented in this function, including checking the amount
409 /// sent to us and checking the HTLCs.
411 /// The preimages of outgoing HTLCs that were fulfilled since the last commitment are provided.
412 /// A validating signer should ensure that an HTLC output is removed only when the matching
413 /// preimage is provided, or when the value to holder is restored.
415 /// Note that all the relevant preimages will be provided, but there may also be additional
416 /// irrelevant or duplicate preimages.
417 fn validate_holder_commitment(&self, holder_tx: &HolderCommitmentTransaction,
418 preimages: Vec<PaymentPreimage>) -> Result<(), ()>;
420 /// Returns the holder's channel public keys and basepoints.
421 fn pubkeys(&self) -> &ChannelPublicKeys;
423 /// Returns an arbitrary identifier describing the set of keys which are provided back to you in
424 /// some [`SpendableOutputDescriptor`] types. This should be sufficient to identify this
425 /// [`EcdsaChannelSigner`] object uniquely and lookup or re-derive its keys.
426 fn channel_keys_id(&self) -> [u8; 32];
428 /// Set the counterparty static channel data, including basepoints,
429 /// `counterparty_selected`/`holder_selected_contest_delay` and funding outpoint.
431 /// This data is static, and will never change for a channel once set. For a given [`ChannelSigner`]
432 /// instance, LDK will call this method exactly once - either immediately after construction
433 /// (not including if done via [`SignerProvider::read_chan_signer`]) or when the funding
434 /// information has been generated.
436 /// channel_parameters.is_populated() MUST be true.
437 fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters);
440 /// A trait to sign Lightning channel transactions as described in
441 /// [BOLT 3](https://github.com/lightning/bolts/blob/master/03-transactions.md).
443 /// Signing services could be implemented on a hardware wallet and should implement signing
444 /// policies in order to be secure. Please refer to the [VLS Policy
445 /// Controls](https://gitlab.com/lightning-signer/validating-lightning-signer/-/blob/main/docs/policy-controls.md)
446 /// for an example of such policies.
447 pub trait EcdsaChannelSigner: ChannelSigner {
448 /// Create a signature for a counterparty's commitment transaction and associated HTLC transactions.
450 /// Note that if signing fails or is rejected, the channel will be force-closed.
452 /// Policy checks should be implemented in this function, including checking the amount
453 /// sent to us and checking the HTLCs.
455 /// The preimages of outgoing HTLCs that were fulfilled since the last commitment are provided.
456 /// A validating signer should ensure that an HTLC output is removed only when the matching
457 /// preimage is provided, or when the value to holder is restored.
459 /// Note that all the relevant preimages will be provided, but there may also be additional
460 /// irrelevant or duplicate preimages.
462 // TODO: Document the things someone using this interface should enforce before signing.
463 fn sign_counterparty_commitment(&self, commitment_tx: &CommitmentTransaction,
464 preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<secp256k1::All>
465 ) -> Result<(Signature, Vec<Signature>), ()>;
466 /// Validate the counterparty's revocation.
468 /// This is required in order for the signer to make sure that the state has moved
469 /// forward and it is safe to sign the next counterparty commitment.
470 fn validate_counterparty_revocation(&self, idx: u64, secret: &SecretKey) -> Result<(), ()>;
471 /// Creates a signature for a holder's commitment transaction and its claiming HTLC transactions.
473 /// This will be called
474 /// - with a non-revoked `commitment_tx`.
475 /// - with the latest `commitment_tx` when we initiate a force-close.
476 /// - with the previous `commitment_tx`, just to get claiming HTLC
477 /// signatures, if we are reacting to a [`ChannelMonitor`]
478 /// [replica](https://github.com/lightningdevkit/rust-lightning/blob/main/GLOSSARY.md#monitor-replicas)
479 /// that decided to broadcast before it had been updated to the latest `commitment_tx`.
481 /// This may be called multiple times for the same transaction.
483 /// An external signer implementation should check that the commitment has not been revoked.
485 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
486 // TODO: Document the things someone using this interface should enforce before signing.
487 fn sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction,
488 secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()>;
489 /// Same as [`sign_holder_commitment_and_htlcs`], but exists only for tests to get access to
490 /// holder commitment transactions which will be broadcasted later, after the channel has moved
491 /// on to a newer state. Thus, needs its own method as [`sign_holder_commitment_and_htlcs`] may
492 /// enforce that we only ever get called once.
493 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
494 fn unsafe_sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction,
495 secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()>;
496 /// Create a signature for the given input in a transaction spending an HTLC transaction output
497 /// or a commitment transaction `to_local` output when our counterparty broadcasts an old state.
499 /// A justice transaction may claim multiple outputs at the same time if timelocks are
500 /// similar, but only a signature for the input at index `input` should be signed for here.
501 /// It may be called multiple times for same output(s) if a fee-bump is needed with regards
502 /// to an upcoming timelock expiration.
504 /// Amount is value of the output spent by this input, committed to in the BIP 143 signature.
506 /// `per_commitment_key` is revocation secret which was provided by our counterparty when they
507 /// revoked the state which they eventually broadcast. It's not a _holder_ secret key and does
508 /// not allow the spending of any funds by itself (you need our holder `revocation_secret` to do
510 fn sign_justice_revoked_output(&self, justice_tx: &Transaction, input: usize, amount: u64,
511 per_commitment_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>
512 ) -> Result<Signature, ()>;
513 /// Create a signature for the given input in a transaction spending a commitment transaction
514 /// HTLC output when our counterparty broadcasts an old state.
516 /// A justice transaction may claim multiple outputs at the same time if timelocks are
517 /// similar, but only a signature for the input at index `input` should be signed for here.
518 /// It may be called multiple times for same output(s) if a fee-bump is needed with regards
519 /// to an upcoming timelock expiration.
521 /// `amount` is the value of the output spent by this input, committed to in the BIP 143
524 /// `per_commitment_key` is revocation secret which was provided by our counterparty when they
525 /// revoked the state which they eventually broadcast. It's not a _holder_ secret key and does
526 /// not allow the spending of any funds by itself (you need our holder revocation_secret to do
529 /// `htlc` holds HTLC elements (hash, timelock), thus changing the format of the witness script
530 /// (which is committed to in the BIP 143 signatures).
531 fn sign_justice_revoked_htlc(&self, justice_tx: &Transaction, input: usize, amount: u64,
532 per_commitment_key: &SecretKey, htlc: &HTLCOutputInCommitment,
533 secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()>;
534 /// Computes the signature for a commitment transaction's HTLC output used as an input within
535 /// `htlc_tx`, which spends the commitment transaction at index `input`. The signature returned
536 /// must be be computed using [`EcdsaSighashType::All`]. Note that this should only be used to
537 /// sign HTLC transactions from channels supporting anchor outputs after all additional
538 /// inputs/outputs have been added to the transaction.
540 /// [`EcdsaSighashType::All`]: bitcoin::blockdata::transaction::EcdsaSighashType::All
541 fn sign_holder_htlc_transaction(&self, htlc_tx: &Transaction, input: usize,
542 htlc_descriptor: &HTLCDescriptor, secp_ctx: &Secp256k1<secp256k1::All>
543 ) -> Result<Signature, ()>;
544 /// Create a signature for a claiming transaction for a HTLC output on a counterparty's commitment
545 /// transaction, either offered or received.
547 /// Such a transaction may claim multiples offered outputs at same time if we know the
548 /// preimage for each when we create it, but only the input at index `input` should be
549 /// signed for here. It may be called multiple times for same output(s) if a fee-bump is
550 /// needed with regards to an upcoming timelock expiration.
552 /// `witness_script` is either an offered or received script as defined in BOLT3 for HTLC
555 /// `amount` is value of the output spent by this input, committed to in the BIP 143 signature.
557 /// `per_commitment_point` is the dynamic point corresponding to the channel state
558 /// detected onchain. It has been generated by our counterparty and is used to derive
559 /// channel state keys, which are then included in the witness script and committed to in the
560 /// BIP 143 signature.
561 fn sign_counterparty_htlc_transaction(&self, htlc_tx: &Transaction, input: usize, amount: u64,
562 per_commitment_point: &PublicKey, htlc: &HTLCOutputInCommitment,
563 secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()>;
564 /// Create a signature for a (proposed) closing transaction.
566 /// Note that, due to rounding, there may be one "missing" satoshi, and either party may have
567 /// chosen to forgo their output as dust.
568 fn sign_closing_transaction(&self, closing_tx: &ClosingTransaction,
569 secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()>;
570 /// Computes the signature for a commitment transaction's anchor output used as an
571 /// input within `anchor_tx`, which spends the commitment transaction, at index `input`.
572 fn sign_holder_anchor_input(
573 &self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<secp256k1::All>,
574 ) -> Result<Signature, ()>;
575 /// Signs a channel announcement message with our funding key proving it comes from one of the
576 /// channel participants.
578 /// Channel announcements also require a signature from each node's network key. Our node
579 /// signature is computed through [`NodeSigner::sign_gossip_message`].
581 /// Note that if this fails or is rejected, the channel will not be publicly announced and
582 /// our counterparty may (though likely will not) close the channel on us for violating the
584 fn sign_channel_announcement_with_funding_key(
585 &self, msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>
586 ) -> Result<Signature, ()>;
589 /// A writeable signer.
591 /// There will always be two instances of a signer per channel, one occupied by the
592 /// [`ChannelManager`] and another by the channel's [`ChannelMonitor`].
594 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
595 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
596 pub trait WriteableEcdsaChannelSigner: EcdsaChannelSigner + Writeable {}
598 /// Specifies the recipient of an invoice.
600 /// This indicates to [`NodeSigner::sign_invoice`] what node secret key should be used to sign
603 /// The invoice should be signed with the local node secret key.
605 /// The invoice should be signed with the phantom node secret key. This secret key must be the
606 /// same for all nodes participating in the [phantom node payment].
608 /// [phantom node payment]: PhantomKeysManager
612 /// A trait that describes a source of entropy.
613 pub trait EntropySource {
614 /// Gets a unique, cryptographically-secure, random 32-byte value. This method must return a
615 /// different value each time it is called.
616 fn get_secure_random_bytes(&self) -> [u8; 32];
619 /// A trait that can handle cryptographic operations at the scope level of a node.
620 pub trait NodeSigner {
621 /// Get secret key material as bytes for use in encrypting and decrypting inbound payment data.
623 /// If the implementor of this trait supports [phantom node payments], then every node that is
624 /// intended to be included in the phantom invoice route hints must return the same value from
626 // This is because LDK avoids storing inbound payment data by encrypting payment data in the
627 // payment hash and/or payment secret, therefore for a payment to be receivable by multiple
628 // nodes, they must share the key that encrypts this payment data.
630 /// This method must return the same value each time it is called.
632 /// [phantom node payments]: PhantomKeysManager
633 fn get_inbound_payment_key_material(&self) -> KeyMaterial;
635 /// Get node id based on the provided [`Recipient`].
637 /// This method must return the same value each time it is called with a given [`Recipient`]
640 /// Errors if the [`Recipient`] variant is not supported by the implementation.
641 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()>;
643 /// Gets the ECDH shared secret of our node secret and `other_key`, multiplying by `tweak` if
644 /// one is provided. Note that this tweak can be applied to `other_key` instead of our node
645 /// secret, though this is less efficient.
647 /// Note that if this fails while attempting to forward an HTLC, LDK will panic. The error
648 /// should be resolved to allow LDK to resume forwarding HTLCs.
650 /// Errors if the [`Recipient`] variant is not supported by the implementation.
651 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()>;
655 /// By parameterizing by the raw invoice bytes instead of the hash, we allow implementors of
656 /// this trait to parse the invoice and make sure they're signing what they expect, rather than
657 /// blindly signing the hash.
659 /// The `hrp_bytes` are ASCII bytes, while the `invoice_data` is base32.
661 /// The secret key used to sign the invoice is dependent on the [`Recipient`].
663 /// Errors if the [`Recipient`] variant is not supported by the implementation.
664 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()>;
666 /// Signs the [`TaggedHash`] of a BOLT 12 invoice request.
668 /// May be called by a function passed to [`UnsignedInvoiceRequest::sign`] where
669 /// `invoice_request` is the callee.
671 /// Implementors may check that the `invoice_request` is expected rather than blindly signing
672 /// the tagged hash. An `Ok` result should sign `invoice_request.tagged_hash().as_digest()` with
673 /// the node's signing key or an ephemeral key to preserve privacy, whichever is associated with
674 /// [`UnsignedInvoiceRequest::payer_id`].
676 /// [`TaggedHash`]: crate::offers::merkle::TaggedHash
677 fn sign_bolt12_invoice_request(
678 &self, invoice_request: &UnsignedInvoiceRequest
679 ) -> Result<schnorr::Signature, ()>;
681 /// Signs the [`TaggedHash`] of a BOLT 12 invoice.
683 /// May be called by a function passed to [`UnsignedBolt12Invoice::sign`] where `invoice` is the
686 /// Implementors may check that the `invoice` is expected rather than blindly signing the tagged
687 /// hash. An `Ok` result should sign `invoice.tagged_hash().as_digest()` with the node's signing
688 /// key or an ephemeral key to preserve privacy, whichever is associated with
689 /// [`UnsignedBolt12Invoice::signing_pubkey`].
691 /// [`TaggedHash`]: crate::offers::merkle::TaggedHash
692 fn sign_bolt12_invoice(
693 &self, invoice: &UnsignedBolt12Invoice
694 ) -> Result<schnorr::Signature, ()>;
696 /// Sign a gossip message.
698 /// Note that if this fails, LDK may panic and the message will not be broadcast to the network
699 /// or a possible channel counterparty. If LDK panics, the error should be resolved to allow the
700 /// message to be broadcast, as otherwise it may prevent one from receiving funds over the
701 /// corresponding channel.
702 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()>;
705 /// A trait that can return signer instances for individual channels.
706 pub trait SignerProvider {
707 /// A type which implements [`WriteableEcdsaChannelSigner`] which will be returned by [`Self::derive_channel_signer`].
708 type Signer : WriteableEcdsaChannelSigner;
710 /// Generates a unique `channel_keys_id` that can be used to obtain a [`Self::Signer`] through
711 /// [`SignerProvider::derive_channel_signer`]. The `user_channel_id` is provided to allow
712 /// implementations of [`SignerProvider`] to maintain a mapping between itself and the generated
713 /// `channel_keys_id`.
715 /// This method must return a different value each time it is called.
716 fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32];
718 /// Derives the private key material backing a `Signer`.
720 /// To derive a new `Signer`, a fresh `channel_keys_id` should be obtained through
721 /// [`SignerProvider::generate_channel_keys_id`]. Otherwise, an existing `Signer` can be
722 /// re-derived from its `channel_keys_id`, which can be obtained through its trait method
723 /// [`ChannelSigner::channel_keys_id`].
724 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::Signer;
726 /// Reads a [`Signer`] for this [`SignerProvider`] from the given input stream.
727 /// This is only called during deserialization of other objects which contain
728 /// [`WriteableEcdsaChannelSigner`]-implementing objects (i.e., [`ChannelMonitor`]s and [`ChannelManager`]s).
729 /// The bytes are exactly those which `<Self::Signer as Writeable>::write()` writes, and
730 /// contain no versioning scheme. You may wish to include your own version prefix and ensure
731 /// you've read all of the provided bytes to ensure no corruption occurred.
733 /// This method is slowly being phased out -- it will only be called when reading objects
734 /// written by LDK versions prior to 0.0.113.
736 /// [`Signer`]: Self::Signer
737 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
738 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
739 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, DecodeError>;
741 /// Get a script pubkey which we send funds to when claiming on-chain contestable outputs.
743 /// If this function returns an error, this will result in a channel failing to open.
745 /// This method should return a different value each time it is called, to avoid linking
746 /// on-chain funds across channels as controlled to the same user.
747 fn get_destination_script(&self) -> Result<Script, ()>;
749 /// Get a script pubkey which we will send funds to when closing a channel.
751 /// If this function returns an error, this will result in a channel failing to open or close.
752 /// In the event of a failure when the counterparty is initiating a close, this can result in a
753 /// channel force close.
755 /// This method should return a different value each time it is called, to avoid linking
756 /// on-chain funds across channels as controlled to the same user.
757 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()>;
760 /// A simple implementation of [`WriteableEcdsaChannelSigner`] that just keeps the private keys in memory.
762 /// This implementation performs no policy checks and is insufficient by itself as
763 /// a secure external signer.
765 pub struct InMemorySigner {
766 /// Holder secret key in the 2-of-2 multisig script of a channel. This key also backs the
767 /// holder's anchor output in a commitment transaction, if one is present.
768 pub funding_key: SecretKey,
769 /// Holder secret key for blinded revocation pubkey.
770 pub revocation_base_key: SecretKey,
771 /// Holder secret key used for our balance in counterparty-broadcasted commitment transactions.
772 pub payment_key: SecretKey,
773 /// Holder secret key used in an HTLC transaction.
774 pub delayed_payment_base_key: SecretKey,
775 /// Holder HTLC secret key used in commitment transaction HTLC outputs.
776 pub htlc_base_key: SecretKey,
778 pub commitment_seed: [u8; 32],
779 /// Holder public keys and basepoints.
780 pub(crate) holder_channel_pubkeys: ChannelPublicKeys,
781 /// Counterparty public keys and counterparty/holder `selected_contest_delay`, populated on channel acceptance.
782 channel_parameters: Option<ChannelTransactionParameters>,
783 /// The total value of this channel.
784 channel_value_satoshis: u64,
785 /// Key derivation parameters.
786 channel_keys_id: [u8; 32],
787 /// Seed from which all randomness produced is derived from.
788 rand_bytes_unique_start: [u8; 32],
789 /// Tracks the number of times we've produced randomness to ensure we don't return the same
791 rand_bytes_index: AtomicCounter,
794 impl PartialEq for InMemorySigner {
795 fn eq(&self, other: &Self) -> bool {
796 self.funding_key == other.funding_key &&
797 self.revocation_base_key == other.revocation_base_key &&
798 self.payment_key == other.payment_key &&
799 self.delayed_payment_base_key == other.delayed_payment_base_key &&
800 self.htlc_base_key == other.htlc_base_key &&
801 self.commitment_seed == other.commitment_seed &&
802 self.holder_channel_pubkeys == other.holder_channel_pubkeys &&
803 self.channel_parameters == other.channel_parameters &&
804 self.channel_value_satoshis == other.channel_value_satoshis &&
805 self.channel_keys_id == other.channel_keys_id
809 impl Clone for InMemorySigner {
810 fn clone(&self) -> Self {
812 funding_key: self.funding_key.clone(),
813 revocation_base_key: self.revocation_base_key.clone(),
814 payment_key: self.payment_key.clone(),
815 delayed_payment_base_key: self.delayed_payment_base_key.clone(),
816 htlc_base_key: self.htlc_base_key.clone(),
817 commitment_seed: self.commitment_seed.clone(),
818 holder_channel_pubkeys: self.holder_channel_pubkeys.clone(),
819 channel_parameters: self.channel_parameters.clone(),
820 channel_value_satoshis: self.channel_value_satoshis,
821 channel_keys_id: self.channel_keys_id,
822 rand_bytes_unique_start: self.get_secure_random_bytes(),
823 rand_bytes_index: AtomicCounter::new(),
828 impl InMemorySigner {
829 /// Creates a new [`InMemorySigner`].
830 pub fn new<C: Signing>(
831 secp_ctx: &Secp256k1<C>,
832 funding_key: SecretKey,
833 revocation_base_key: SecretKey,
834 payment_key: SecretKey,
835 delayed_payment_base_key: SecretKey,
836 htlc_base_key: SecretKey,
837 commitment_seed: [u8; 32],
838 channel_value_satoshis: u64,
839 channel_keys_id: [u8; 32],
840 rand_bytes_unique_start: [u8; 32],
841 ) -> InMemorySigner {
842 let holder_channel_pubkeys =
843 InMemorySigner::make_holder_keys(secp_ctx, &funding_key, &revocation_base_key,
844 &payment_key, &delayed_payment_base_key,
850 delayed_payment_base_key,
853 channel_value_satoshis,
854 holder_channel_pubkeys,
855 channel_parameters: None,
857 rand_bytes_unique_start,
858 rand_bytes_index: AtomicCounter::new(),
862 fn make_holder_keys<C: Signing>(secp_ctx: &Secp256k1<C>,
863 funding_key: &SecretKey,
864 revocation_base_key: &SecretKey,
865 payment_key: &SecretKey,
866 delayed_payment_base_key: &SecretKey,
867 htlc_base_key: &SecretKey) -> ChannelPublicKeys {
868 let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
870 funding_pubkey: from_secret(&funding_key),
871 revocation_basepoint: from_secret(&revocation_base_key),
872 payment_point: from_secret(&payment_key),
873 delayed_payment_basepoint: from_secret(&delayed_payment_base_key),
874 htlc_basepoint: from_secret(&htlc_base_key),
878 /// Returns the counterparty's pubkeys.
880 /// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before.
881 pub fn counterparty_pubkeys(&self) -> &ChannelPublicKeys { &self.get_channel_parameters().counterparty_parameters.as_ref().unwrap().pubkeys }
882 /// Returns the `contest_delay` value specified by our counterparty and applied on holder-broadcastable
883 /// transactions, i.e., the amount of time that we have to wait to recover our funds if we
884 /// broadcast a transaction.
886 /// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before.
887 pub fn counterparty_selected_contest_delay(&self) -> u16 { self.get_channel_parameters().counterparty_parameters.as_ref().unwrap().selected_contest_delay }
888 /// Returns the `contest_delay` value specified by us and applied on transactions broadcastable
889 /// by our counterparty, i.e., the amount of time that they have to wait to recover their funds
890 /// if they broadcast a transaction.
892 /// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before.
893 pub fn holder_selected_contest_delay(&self) -> u16 { self.get_channel_parameters().holder_selected_contest_delay }
894 /// Returns whether the holder is the initiator.
896 /// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before.
897 pub fn is_outbound(&self) -> bool { self.get_channel_parameters().is_outbound_from_holder }
900 /// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before.
901 pub fn funding_outpoint(&self) -> &OutPoint { self.get_channel_parameters().funding_outpoint.as_ref().unwrap() }
902 /// Returns a [`ChannelTransactionParameters`] for this channel, to be used when verifying or
903 /// building transactions.
905 /// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before.
906 pub fn get_channel_parameters(&self) -> &ChannelTransactionParameters {
907 self.channel_parameters.as_ref().unwrap()
909 /// Returns the channel type features of the channel parameters. Should be helpful for
910 /// determining a channel's category, i. e. legacy/anchors/taproot/etc.
912 /// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before.
913 pub fn channel_type_features(&self) -> &ChannelTypeFeatures {
914 &self.get_channel_parameters().channel_type_features
916 /// Sign the single input of `spend_tx` at index `input_idx`, which spends the output described
917 /// by `descriptor`, returning the witness stack for the input.
919 /// Returns an error if the input at `input_idx` does not exist, has a non-empty `script_sig`,
920 /// is not spending the outpoint described by [`descriptor.outpoint`],
921 /// or if an output descriptor `script_pubkey` does not match the one we can spend.
923 /// [`descriptor.outpoint`]: StaticPaymentOutputDescriptor::outpoint
924 pub fn sign_counterparty_payment_input<C: Signing>(&self, spend_tx: &Transaction, input_idx: usize, descriptor: &StaticPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>) -> Result<Vec<Vec<u8>>, ()> {
925 // TODO: We really should be taking the SigHashCache as a parameter here instead of
926 // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
927 // so that we can check them. This requires upstream rust-bitcoin changes (as well as
928 // bindings updates to support SigHashCache objects).
929 if spend_tx.input.len() <= input_idx { return Err(()); }
930 if !spend_tx.input[input_idx].script_sig.is_empty() { return Err(()); }
931 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint() { return Err(()); }
933 let remotepubkey = bitcoin::PublicKey::new(self.pubkeys().payment_point);
934 let witness_script = if self.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
935 chan_utils::get_to_countersignatory_with_anchors_redeemscript(&remotepubkey.inner)
937 Script::new_p2pkh(&remotepubkey.pubkey_hash())
939 let sighash = hash_to_message!(&sighash::SighashCache::new(spend_tx).segwit_signature_hash(input_idx, &witness_script, descriptor.output.value, EcdsaSighashType::All).unwrap()[..]);
940 let remotesig = sign_with_aux_rand(secp_ctx, &sighash, &self.payment_key, &self);
941 let payment_script = if self.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
942 witness_script.to_v0_p2wsh()
944 Script::new_v0_p2wpkh(&remotepubkey.wpubkey_hash().unwrap())
947 if payment_script != descriptor.output.script_pubkey { return Err(()); }
949 let mut witness = Vec::with_capacity(2);
950 witness.push(remotesig.serialize_der().to_vec());
951 witness[0].push(EcdsaSighashType::All as u8);
952 if self.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
953 witness.push(witness_script.to_bytes());
955 witness.push(remotepubkey.to_bytes());
960 /// Sign the single input of `spend_tx` at index `input_idx` which spends the output
961 /// described by `descriptor`, returning the witness stack for the input.
963 /// Returns an error if the input at `input_idx` does not exist, has a non-empty `script_sig`,
964 /// is not spending the outpoint described by [`descriptor.outpoint`], does not have a
965 /// sequence set to [`descriptor.to_self_delay`], or if an output descriptor
966 /// `script_pubkey` does not match the one we can spend.
968 /// [`descriptor.outpoint`]: DelayedPaymentOutputDescriptor::outpoint
969 /// [`descriptor.to_self_delay`]: DelayedPaymentOutputDescriptor::to_self_delay
970 pub fn sign_dynamic_p2wsh_input<C: Signing>(&self, spend_tx: &Transaction, input_idx: usize, descriptor: &DelayedPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>) -> Result<Vec<Vec<u8>>, ()> {
971 // TODO: We really should be taking the SigHashCache as a parameter here instead of
972 // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
973 // so that we can check them. This requires upstream rust-bitcoin changes (as well as
974 // bindings updates to support SigHashCache objects).
975 if spend_tx.input.len() <= input_idx { return Err(()); }
976 if !spend_tx.input[input_idx].script_sig.is_empty() { return Err(()); }
977 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint() { return Err(()); }
978 if spend_tx.input[input_idx].sequence.0 != descriptor.to_self_delay as u32 { return Err(()); }
980 let delayed_payment_key = chan_utils::derive_private_key(&secp_ctx, &descriptor.per_commitment_point, &self.delayed_payment_base_key);
981 let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
982 let witness_script = chan_utils::get_revokeable_redeemscript(&descriptor.revocation_pubkey, descriptor.to_self_delay, &delayed_payment_pubkey);
983 let sighash = hash_to_message!(&sighash::SighashCache::new(spend_tx).segwit_signature_hash(input_idx, &witness_script, descriptor.output.value, EcdsaSighashType::All).unwrap()[..]);
984 let local_delayedsig = sign_with_aux_rand(secp_ctx, &sighash, &delayed_payment_key, &self);
985 let payment_script = bitcoin::Address::p2wsh(&witness_script, Network::Bitcoin).script_pubkey();
987 if descriptor.output.script_pubkey != payment_script { return Err(()); }
989 let mut witness = Vec::with_capacity(3);
990 witness.push(local_delayedsig.serialize_der().to_vec());
991 witness[0].push(EcdsaSighashType::All as u8);
992 witness.push(vec!()); //MINIMALIF
993 witness.push(witness_script.clone().into_bytes());
998 impl EntropySource for InMemorySigner {
999 fn get_secure_random_bytes(&self) -> [u8; 32] {
1000 let index = self.rand_bytes_index.get_increment();
1001 let mut nonce = [0u8; 16];
1002 nonce[..8].copy_from_slice(&index.to_be_bytes());
1003 ChaCha20::get_single_block(&self.rand_bytes_unique_start, &nonce)
1007 impl ChannelSigner for InMemorySigner {
1008 fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>) -> PublicKey {
1009 let commitment_secret = SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx)).unwrap();
1010 PublicKey::from_secret_key(secp_ctx, &commitment_secret)
1013 fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
1014 chan_utils::build_commitment_secret(&self.commitment_seed, idx)
1017 fn validate_holder_commitment(&self, _holder_tx: &HolderCommitmentTransaction, _preimages: Vec<PaymentPreimage>) -> Result<(), ()> {
1021 fn pubkeys(&self) -> &ChannelPublicKeys { &self.holder_channel_pubkeys }
1023 fn channel_keys_id(&self) -> [u8; 32] { self.channel_keys_id }
1025 fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters) {
1026 assert!(self.channel_parameters.is_none() || self.channel_parameters.as_ref().unwrap() == channel_parameters);
1027 if self.channel_parameters.is_some() {
1028 // The channel parameters were already set and they match, return early.
1031 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1032 self.channel_parameters = Some(channel_parameters.clone());
1036 impl EcdsaChannelSigner for InMemorySigner {
1037 fn sign_counterparty_commitment(&self, commitment_tx: &CommitmentTransaction, _preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
1038 let trusted_tx = commitment_tx.trust();
1039 let keys = trusted_tx.keys();
1041 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1042 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
1044 let built_tx = trusted_tx.built_transaction();
1045 let commitment_sig = built_tx.sign_counterparty_commitment(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx);
1046 let commitment_txid = built_tx.txid;
1048 let mut htlc_sigs = Vec::with_capacity(commitment_tx.htlcs().len());
1049 for htlc in commitment_tx.htlcs() {
1050 let channel_parameters = self.get_channel_parameters();
1051 let htlc_tx = chan_utils::build_htlc_transaction(&commitment_txid, commitment_tx.feerate_per_kw(), self.holder_selected_contest_delay(), htlc, &channel_parameters.channel_type_features, &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1052 let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, self.channel_type_features(), &keys);
1053 let htlc_sighashtype = if self.channel_type_features().supports_anchors_zero_fee_htlc_tx() { EcdsaSighashType::SinglePlusAnyoneCanPay } else { EcdsaSighashType::All };
1054 let htlc_sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, htlc.amount_msat / 1000, htlc_sighashtype).unwrap()[..]);
1055 let holder_htlc_key = chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key);
1056 htlc_sigs.push(sign(secp_ctx, &htlc_sighash, &holder_htlc_key));
1059 Ok((commitment_sig, htlc_sigs))
1062 fn validate_counterparty_revocation(&self, _idx: u64, _secret: &SecretKey) -> Result<(), ()> {
1066 fn sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
1067 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1068 let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
1069 let trusted_tx = commitment_tx.trust();
1070 let sig = trusted_tx.built_transaction().sign_holder_commitment(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, &self, secp_ctx);
1071 let channel_parameters = self.get_channel_parameters();
1072 let htlc_sigs = trusted_tx.get_htlc_sigs(&self.htlc_base_key, &channel_parameters.as_holder_broadcastable(), &self, secp_ctx)?;
1073 Ok((sig, htlc_sigs))
1076 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
1077 fn unsafe_sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
1078 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1079 let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
1080 let trusted_tx = commitment_tx.trust();
1081 let sig = trusted_tx.built_transaction().sign_holder_commitment(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, &self, secp_ctx);
1082 let channel_parameters = self.get_channel_parameters();
1083 let htlc_sigs = trusted_tx.get_htlc_sigs(&self.htlc_base_key, &channel_parameters.as_holder_broadcastable(), &self, secp_ctx)?;
1084 Ok((sig, htlc_sigs))
1087 fn sign_justice_revoked_output(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
1088 let revocation_key = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key);
1089 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
1090 let revocation_pubkey = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint);
1091 let witness_script = {
1092 let counterparty_delayedpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().delayed_payment_basepoint);
1093 chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.holder_selected_contest_delay(), &counterparty_delayedpubkey)
1095 let mut sighash_parts = sighash::SighashCache::new(justice_tx);
1096 let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
1097 return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self))
1100 fn sign_justice_revoked_htlc(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
1101 let revocation_key = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key);
1102 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
1103 let revocation_pubkey = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint);
1104 let witness_script = {
1105 let counterparty_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().htlc_basepoint);
1106 let holder_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint);
1107 chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, self.channel_type_features(), &counterparty_htlcpubkey, &holder_htlcpubkey, &revocation_pubkey)
1109 let mut sighash_parts = sighash::SighashCache::new(justice_tx);
1110 let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
1111 return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self))
1114 fn sign_holder_htlc_transaction(
1115 &self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
1116 secp_ctx: &Secp256k1<secp256k1::All>
1117 ) -> Result<Signature, ()> {
1118 let witness_script = htlc_descriptor.witness_script(secp_ctx);
1119 let sighash = &sighash::SighashCache::new(&*htlc_tx).segwit_signature_hash(
1120 input, &witness_script, htlc_descriptor.htlc.amount_msat / 1000, EcdsaSighashType::All
1122 let our_htlc_private_key = chan_utils::derive_private_key(
1123 &secp_ctx, &htlc_descriptor.per_commitment_point, &self.htlc_base_key
1125 Ok(sign_with_aux_rand(&secp_ctx, &hash_to_message!(sighash), &our_htlc_private_key, &self))
1128 fn sign_counterparty_htlc_transaction(&self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
1129 let htlc_key = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key);
1130 let revocation_pubkey = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint);
1131 let counterparty_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().htlc_basepoint);
1132 let htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint);
1133 let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, self.channel_type_features(), &counterparty_htlcpubkey, &htlcpubkey, &revocation_pubkey);
1134 let mut sighash_parts = sighash::SighashCache::new(htlc_tx);
1135 let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
1136 Ok(sign_with_aux_rand(secp_ctx, &sighash, &htlc_key, &self))
1139 fn sign_closing_transaction(&self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
1140 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1141 let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
1142 Ok(closing_tx.trust().sign(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
1145 fn sign_holder_anchor_input(
1146 &self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<secp256k1::All>,
1147 ) -> Result<Signature, ()> {
1148 let witness_script = chan_utils::get_anchor_redeemscript(&self.holder_channel_pubkeys.funding_pubkey);
1149 let sighash = sighash::SighashCache::new(&*anchor_tx).segwit_signature_hash(
1150 input, &witness_script, ANCHOR_OUTPUT_VALUE_SATOSHI, EcdsaSighashType::All,
1152 Ok(sign_with_aux_rand(secp_ctx, &hash_to_message!(&sighash[..]), &self.funding_key, &self))
1155 fn sign_channel_announcement_with_funding_key(
1156 &self, msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>
1157 ) -> Result<Signature, ()> {
1158 let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1159 Ok(secp_ctx.sign_ecdsa(&msghash, &self.funding_key))
1163 const SERIALIZATION_VERSION: u8 = 1;
1165 const MIN_SERIALIZATION_VERSION: u8 = 1;
1167 impl WriteableEcdsaChannelSigner for InMemorySigner {}
1169 impl Writeable for InMemorySigner {
1170 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
1171 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
1173 self.funding_key.write(writer)?;
1174 self.revocation_base_key.write(writer)?;
1175 self.payment_key.write(writer)?;
1176 self.delayed_payment_base_key.write(writer)?;
1177 self.htlc_base_key.write(writer)?;
1178 self.commitment_seed.write(writer)?;
1179 self.channel_parameters.write(writer)?;
1180 self.channel_value_satoshis.write(writer)?;
1181 self.channel_keys_id.write(writer)?;
1183 write_tlv_fields!(writer, {});
1189 impl<ES: Deref> ReadableArgs<ES> for InMemorySigner where ES::Target: EntropySource {
1190 fn read<R: io::Read>(reader: &mut R, entropy_source: ES) -> Result<Self, DecodeError> {
1191 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
1193 let funding_key = Readable::read(reader)?;
1194 let revocation_base_key = Readable::read(reader)?;
1195 let payment_key = Readable::read(reader)?;
1196 let delayed_payment_base_key = Readable::read(reader)?;
1197 let htlc_base_key = Readable::read(reader)?;
1198 let commitment_seed = Readable::read(reader)?;
1199 let counterparty_channel_data = Readable::read(reader)?;
1200 let channel_value_satoshis = Readable::read(reader)?;
1201 let secp_ctx = Secp256k1::signing_only();
1202 let holder_channel_pubkeys =
1203 InMemorySigner::make_holder_keys(&secp_ctx, &funding_key, &revocation_base_key,
1204 &payment_key, &delayed_payment_base_key, &htlc_base_key);
1205 let keys_id = Readable::read(reader)?;
1207 read_tlv_fields!(reader, {});
1211 revocation_base_key,
1213 delayed_payment_base_key,
1216 channel_value_satoshis,
1217 holder_channel_pubkeys,
1218 channel_parameters: counterparty_channel_data,
1219 channel_keys_id: keys_id,
1220 rand_bytes_unique_start: entropy_source.get_secure_random_bytes(),
1221 rand_bytes_index: AtomicCounter::new(),
1226 /// Simple implementation of [`EntropySource`], [`NodeSigner`], and [`SignerProvider`] that takes a
1227 /// 32-byte seed for use as a BIP 32 extended key and derives keys from that.
1229 /// Your `node_id` is seed/0'.
1230 /// Unilateral closes may use seed/1'.
1231 /// Cooperative closes may use seed/2'.
1232 /// The two close keys may be needed to claim on-chain funds!
1234 /// This struct cannot be used for nodes that wish to support receiving phantom payments;
1235 /// [`PhantomKeysManager`] must be used instead.
1237 /// Note that switching between this struct and [`PhantomKeysManager`] will invalidate any
1238 /// previously issued invoices and attempts to pay previous invoices will fail.
1239 pub struct KeysManager {
1240 secp_ctx: Secp256k1<secp256k1::All>,
1241 node_secret: SecretKey,
1243 inbound_payment_key: KeyMaterial,
1244 destination_script: Script,
1245 shutdown_pubkey: PublicKey,
1246 channel_master_key: ExtendedPrivKey,
1247 channel_child_index: AtomicUsize,
1249 rand_bytes_unique_start: [u8; 32],
1250 rand_bytes_index: AtomicCounter,
1253 starting_time_secs: u64,
1254 starting_time_nanos: u32,
1258 /// Constructs a [`KeysManager`] from a 32-byte seed. If the seed is in some way biased (e.g.,
1259 /// your CSRNG is busted) this may panic (but more importantly, you will possibly lose funds).
1260 /// `starting_time` isn't strictly required to actually be a time, but it must absolutely,
1261 /// without a doubt, be unique to this instance. ie if you start multiple times with the same
1262 /// `seed`, `starting_time` must be unique to each run. Thus, the easiest way to achieve this
1263 /// is to simply use the current time (with very high precision).
1265 /// The `seed` MUST be backed up safely prior to use so that the keys can be re-created, however,
1266 /// obviously, `starting_time` should be unique every time you reload the library - it is only
1267 /// used to generate new ephemeral key data (which will be stored by the individual channel if
1270 /// Note that the seed is required to recover certain on-chain funds independent of
1271 /// [`ChannelMonitor`] data, though a current copy of [`ChannelMonitor`] data is also required
1272 /// for any channel, and some on-chain during-closing funds.
1274 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
1275 pub fn new(seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32) -> Self {
1276 let secp_ctx = Secp256k1::new();
1277 // Note that when we aren't serializing the key, network doesn't matter
1278 match ExtendedPrivKey::new_master(Network::Testnet, seed) {
1280 let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key;
1281 let node_id = PublicKey::from_secret_key(&secp_ctx, &node_secret);
1282 let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
1283 Ok(destination_key) => {
1284 let wpubkey_hash = WPubkeyHash::hash(&ExtendedPubKey::from_priv(&secp_ctx, &destination_key).to_pub().to_bytes());
1285 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1286 .push_slice(&wpubkey_hash.into_inner())
1289 Err(_) => panic!("Your RNG is busted"),
1291 let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
1292 Ok(shutdown_key) => ExtendedPubKey::from_priv(&secp_ctx, &shutdown_key).public_key,
1293 Err(_) => panic!("Your RNG is busted"),
1295 let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
1296 let inbound_payment_key: SecretKey = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()).expect("Your RNG is busted").private_key;
1297 let mut inbound_pmt_key_bytes = [0; 32];
1298 inbound_pmt_key_bytes.copy_from_slice(&inbound_payment_key[..]);
1300 let mut rand_bytes_engine = Sha256::engine();
1301 rand_bytes_engine.input(&starting_time_secs.to_be_bytes());
1302 rand_bytes_engine.input(&starting_time_nanos.to_be_bytes());
1303 rand_bytes_engine.input(seed);
1304 rand_bytes_engine.input(b"LDK PRNG Seed");
1305 let rand_bytes_unique_start = Sha256::from_engine(rand_bytes_engine).into_inner();
1307 let mut res = KeysManager {
1311 inbound_payment_key: KeyMaterial(inbound_pmt_key_bytes),
1317 channel_child_index: AtomicUsize::new(0),
1319 rand_bytes_unique_start,
1320 rand_bytes_index: AtomicCounter::new(),
1324 starting_time_nanos,
1326 let secp_seed = res.get_secure_random_bytes();
1327 res.secp_ctx.seeded_randomize(&secp_seed);
1330 Err(_) => panic!("Your rng is busted"),
1334 /// Gets the "node_id" secret key used to sign gossip announcements, decode onion data, etc.
1335 pub fn get_node_secret_key(&self) -> SecretKey {
1339 /// Derive an old [`WriteableEcdsaChannelSigner`] containing per-channel secrets based on a key derivation parameters.
1340 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner {
1341 let chan_id = u64::from_be_bytes(params[0..8].try_into().unwrap());
1342 let mut unique_start = Sha256::engine();
1343 unique_start.input(params);
1344 unique_start.input(&self.seed);
1346 // We only seriously intend to rely on the channel_master_key for true secure
1347 // entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
1348 // starting_time provided in the constructor) to be unique.
1349 let child_privkey = self.channel_master_key.ckd_priv(&self.secp_ctx,
1350 ChildNumber::from_hardened_idx((chan_id as u32) % (1 << 31)).expect("key space exhausted")
1351 ).expect("Your RNG is busted");
1352 unique_start.input(&child_privkey.private_key[..]);
1354 let seed = Sha256::from_engine(unique_start).into_inner();
1356 let commitment_seed = {
1357 let mut sha = Sha256::engine();
1359 sha.input(&b"commitment seed"[..]);
1360 Sha256::from_engine(sha).into_inner()
1362 macro_rules! key_step {
1363 ($info: expr, $prev_key: expr) => {{
1364 let mut sha = Sha256::engine();
1366 sha.input(&$prev_key[..]);
1367 sha.input(&$info[..]);
1368 SecretKey::from_slice(&Sha256::from_engine(sha).into_inner()).expect("SHA-256 is busted")
1371 let funding_key = key_step!(b"funding key", commitment_seed);
1372 let revocation_base_key = key_step!(b"revocation base key", funding_key);
1373 let payment_key = key_step!(b"payment key", revocation_base_key);
1374 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key);
1375 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
1376 let prng_seed = self.get_secure_random_bytes();
1378 InMemorySigner::new(
1381 revocation_base_key,
1383 delayed_payment_base_key,
1386 channel_value_satoshis,
1392 /// Signs the given [`PartiallySignedTransaction`] which spends the given [`SpendableOutputDescriptor`]s.
1393 /// The resulting inputs will be finalized and the PSBT will be ready for broadcast if there
1394 /// are no other inputs that need signing.
1396 /// Returns `Err(())` if the PSBT is missing a descriptor or if we fail to sign.
1398 /// May panic if the [`SpendableOutputDescriptor`]s were not generated by channels which used
1399 /// this [`KeysManager`] or one of the [`InMemorySigner`] created by this [`KeysManager`].
1400 pub fn sign_spendable_outputs_psbt<C: Signing>(&self, descriptors: &[&SpendableOutputDescriptor], mut psbt: PartiallySignedTransaction, secp_ctx: &Secp256k1<C>) -> Result<PartiallySignedTransaction, ()> {
1401 let mut keys_cache: Option<(InMemorySigner, [u8; 32])> = None;
1402 for outp in descriptors {
1404 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
1405 let input_idx = psbt.unsigned_tx.input.iter().position(|i| i.previous_output == descriptor.outpoint.into_bitcoin_outpoint()).ok_or(())?;
1406 if keys_cache.is_none() || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id {
1407 let mut signer = self.derive_channel_keys(descriptor.channel_value_satoshis, &descriptor.channel_keys_id);
1408 if let Some(channel_params) = descriptor.channel_transaction_parameters.as_ref() {
1409 signer.provide_channel_parameters(channel_params);
1411 keys_cache = Some((signer, descriptor.channel_keys_id));
1413 let witness = Witness::from_vec(keys_cache.as_ref().unwrap().0.sign_counterparty_payment_input(&psbt.unsigned_tx, input_idx, &descriptor, &secp_ctx)?);
1414 psbt.inputs[input_idx].final_script_witness = Some(witness);
1416 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
1417 let input_idx = psbt.unsigned_tx.input.iter().position(|i| i.previous_output == descriptor.outpoint.into_bitcoin_outpoint()).ok_or(())?;
1418 if keys_cache.is_none() || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id {
1420 self.derive_channel_keys(descriptor.channel_value_satoshis, &descriptor.channel_keys_id),
1421 descriptor.channel_keys_id));
1423 let witness = Witness::from_vec(keys_cache.as_ref().unwrap().0.sign_dynamic_p2wsh_input(&psbt.unsigned_tx, input_idx, &descriptor, &secp_ctx)?);
1424 psbt.inputs[input_idx].final_script_witness = Some(witness);
1426 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
1427 let input_idx = psbt.unsigned_tx.input.iter().position(|i| i.previous_output == outpoint.into_bitcoin_outpoint()).ok_or(())?;
1428 let derivation_idx = if output.script_pubkey == self.destination_script {
1434 // Note that when we aren't serializing the key, network doesn't matter
1435 match ExtendedPrivKey::new_master(Network::Testnet, &self.seed) {
1437 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(derivation_idx).expect("key space exhausted")) {
1439 Err(_) => panic!("Your RNG is busted"),
1442 Err(_) => panic!("Your rng is busted"),
1445 let pubkey = ExtendedPubKey::from_priv(&secp_ctx, &secret).to_pub();
1446 if derivation_idx == 2 {
1447 assert_eq!(pubkey.inner, self.shutdown_pubkey);
1449 let witness_script = bitcoin::Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
1450 let payment_script = bitcoin::Address::p2wpkh(&pubkey, Network::Testnet).expect("uncompressed key found").script_pubkey();
1452 if payment_script != output.script_pubkey { return Err(()); };
1454 let sighash = hash_to_message!(&sighash::SighashCache::new(&psbt.unsigned_tx).segwit_signature_hash(input_idx, &witness_script, output.value, EcdsaSighashType::All).unwrap()[..]);
1455 let sig = sign_with_aux_rand(secp_ctx, &sighash, &secret.private_key, &self);
1456 let mut sig_ser = sig.serialize_der().to_vec();
1457 sig_ser.push(EcdsaSighashType::All as u8);
1458 let witness = Witness::from_vec(vec![sig_ser, pubkey.inner.serialize().to_vec()]);
1459 psbt.inputs[input_idx].final_script_witness = Some(witness);
1467 /// Creates a [`Transaction`] which spends the given descriptors to the given outputs, plus an
1468 /// output to the given change destination (if sufficient change value remains). The
1469 /// transaction will have a feerate, at least, of the given value.
1471 /// The `locktime` argument is used to set the transaction's locktime. If `None`, the
1472 /// transaction will have a locktime of 0. It it recommended to set this to the current block
1473 /// height to avoid fee sniping, unless you have some specific reason to use a different
1476 /// Returns `Err(())` if the output value is greater than the input value minus required fee,
1477 /// if a descriptor was duplicated, or if an output descriptor `script_pubkey`
1478 /// does not match the one we can spend.
1480 /// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
1482 /// May panic if the [`SpendableOutputDescriptor`]s were not generated by channels which used
1483 /// this [`KeysManager`] or one of the [`InMemorySigner`] created by this [`KeysManager`].
1484 pub fn spend_spendable_outputs<C: Signing>(&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>, change_destination_script: Script, feerate_sat_per_1000_weight: u32, locktime: Option<PackedLockTime>, secp_ctx: &Secp256k1<C>) -> Result<Transaction, ()> {
1485 let (mut psbt, expected_max_weight) = SpendableOutputDescriptor::create_spendable_outputs_psbt(descriptors, outputs, change_destination_script, feerate_sat_per_1000_weight, locktime)?;
1486 psbt = self.sign_spendable_outputs_psbt(descriptors, psbt, secp_ctx)?;
1488 let spend_tx = psbt.extract_tx();
1490 debug_assert!(expected_max_weight >= spend_tx.weight());
1491 // Note that witnesses with a signature vary somewhat in size, so allow
1492 // `expected_max_weight` to overshoot by up to 3 bytes per input.
1493 debug_assert!(expected_max_weight <= spend_tx.weight() + descriptors.len() * 3);
1499 impl EntropySource for KeysManager {
1500 fn get_secure_random_bytes(&self) -> [u8; 32] {
1501 let index = self.rand_bytes_index.get_increment();
1502 let mut nonce = [0u8; 16];
1503 nonce[..8].copy_from_slice(&index.to_be_bytes());
1504 ChaCha20::get_single_block(&self.rand_bytes_unique_start, &nonce)
1508 impl NodeSigner for KeysManager {
1509 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1511 Recipient::Node => Ok(self.node_id.clone()),
1512 Recipient::PhantomNode => Err(())
1516 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
1517 let mut node_secret = match recipient {
1518 Recipient::Node => Ok(self.node_secret.clone()),
1519 Recipient::PhantomNode => Err(())
1521 if let Some(tweak) = tweak {
1522 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
1524 Ok(SharedSecret::new(other_key, &node_secret))
1527 fn get_inbound_payment_key_material(&self) -> KeyMaterial {
1528 self.inbound_payment_key.clone()
1531 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
1532 let preimage = construct_invoice_preimage(&hrp_bytes, &invoice_data);
1533 let secret = match recipient {
1534 Recipient::Node => Ok(&self.node_secret),
1535 Recipient::PhantomNode => Err(())
1537 Ok(self.secp_ctx.sign_ecdsa_recoverable(&hash_to_message!(&Sha256::hash(&preimage)), secret))
1540 fn sign_bolt12_invoice_request(
1541 &self, invoice_request: &UnsignedInvoiceRequest
1542 ) -> Result<schnorr::Signature, ()> {
1543 let message = invoice_request.tagged_hash().as_digest();
1544 let keys = KeyPair::from_secret_key(&self.secp_ctx, &self.node_secret);
1545 let aux_rand = self.get_secure_random_bytes();
1546 Ok(self.secp_ctx.sign_schnorr_with_aux_rand(message, &keys, &aux_rand))
1549 fn sign_bolt12_invoice(
1550 &self, invoice: &UnsignedBolt12Invoice
1551 ) -> Result<schnorr::Signature, ()> {
1552 let message = invoice.tagged_hash().as_digest();
1553 let keys = KeyPair::from_secret_key(&self.secp_ctx, &self.node_secret);
1554 let aux_rand = self.get_secure_random_bytes();
1555 Ok(self.secp_ctx.sign_schnorr_with_aux_rand(message, &keys, &aux_rand))
1558 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
1559 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1560 Ok(self.secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret))
1564 impl SignerProvider for KeysManager {
1565 type Signer = InMemorySigner;
1567 fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
1568 let child_idx = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
1569 // `child_idx` is the only thing guaranteed to make each channel unique without a restart
1570 // (though `user_channel_id` should help, depending on user behavior). If it manages to
1571 // roll over, we may generate duplicate keys for two different channels, which could result
1572 // in loss of funds. Because we only support 32-bit+ systems, assert that our `AtomicUsize`
1573 // doesn't reach `u32::MAX`.
1574 assert!(child_idx < core::u32::MAX as usize, "2^32 channels opened without restart");
1575 let mut id = [0; 32];
1576 id[0..4].copy_from_slice(&(child_idx as u32).to_be_bytes());
1577 id[4..8].copy_from_slice(&self.starting_time_nanos.to_be_bytes());
1578 id[8..16].copy_from_slice(&self.starting_time_secs.to_be_bytes());
1579 id[16..32].copy_from_slice(&user_channel_id.to_be_bytes());
1583 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::Signer {
1584 self.derive_channel_keys(channel_value_satoshis, &channel_keys_id)
1587 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, DecodeError> {
1588 InMemorySigner::read(&mut io::Cursor::new(reader), self)
1591 fn get_destination_script(&self) -> Result<Script, ()> {
1592 Ok(self.destination_script.clone())
1595 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
1596 Ok(ShutdownScript::new_p2wpkh_from_pubkey(self.shutdown_pubkey.clone()))
1600 /// Similar to [`KeysManager`], but allows the node using this struct to receive phantom node
1603 /// A phantom node payment is a payment made to a phantom invoice, which is an invoice that can be
1604 /// paid to one of multiple nodes. This works because we encode the invoice route hints such that
1605 /// LDK will recognize an incoming payment as destined for a phantom node, and collect the payment
1606 /// itself without ever needing to forward to this fake node.
1608 /// Phantom node payments are useful for load balancing between multiple LDK nodes. They also
1609 /// provide some fault tolerance, because payers will automatically retry paying other provided
1610 /// nodes in the case that one node goes down.
1612 /// Note that multi-path payments are not supported in phantom invoices for security reasons.
1613 // In the hypothetical case that we did support MPP phantom payments, there would be no way for
1614 // nodes to know when the full payment has been received (and the preimage can be released) without
1615 // significantly compromising on our safety guarantees. I.e., if we expose the ability for the user
1616 // to tell LDK when the preimage can be released, we open ourselves to attacks where the preimage
1617 // is released too early.
1619 /// Switching between this struct and [`KeysManager`] will invalidate any previously issued
1620 /// invoices and attempts to pay previous invoices will fail.
1621 pub struct PhantomKeysManager {
1623 inbound_payment_key: KeyMaterial,
1624 phantom_secret: SecretKey,
1625 phantom_node_id: PublicKey,
1628 impl EntropySource for PhantomKeysManager {
1629 fn get_secure_random_bytes(&self) -> [u8; 32] {
1630 self.inner.get_secure_random_bytes()
1634 impl NodeSigner for PhantomKeysManager {
1635 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1637 Recipient::Node => self.inner.get_node_id(Recipient::Node),
1638 Recipient::PhantomNode => Ok(self.phantom_node_id.clone()),
1642 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
1643 let mut node_secret = match recipient {
1644 Recipient::Node => self.inner.node_secret.clone(),
1645 Recipient::PhantomNode => self.phantom_secret.clone(),
1647 if let Some(tweak) = tweak {
1648 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
1650 Ok(SharedSecret::new(other_key, &node_secret))
1653 fn get_inbound_payment_key_material(&self) -> KeyMaterial {
1654 self.inbound_payment_key.clone()
1657 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
1658 let preimage = construct_invoice_preimage(&hrp_bytes, &invoice_data);
1659 let secret = match recipient {
1660 Recipient::Node => &self.inner.node_secret,
1661 Recipient::PhantomNode => &self.phantom_secret,
1663 Ok(self.inner.secp_ctx.sign_ecdsa_recoverable(&hash_to_message!(&Sha256::hash(&preimage)), secret))
1666 fn sign_bolt12_invoice_request(
1667 &self, invoice_request: &UnsignedInvoiceRequest
1668 ) -> Result<schnorr::Signature, ()> {
1669 self.inner.sign_bolt12_invoice_request(invoice_request)
1672 fn sign_bolt12_invoice(
1673 &self, invoice: &UnsignedBolt12Invoice
1674 ) -> Result<schnorr::Signature, ()> {
1675 self.inner.sign_bolt12_invoice(invoice)
1678 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
1679 self.inner.sign_gossip_message(msg)
1683 impl SignerProvider for PhantomKeysManager {
1684 type Signer = InMemorySigner;
1686 fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
1687 self.inner.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
1690 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::Signer {
1691 self.inner.derive_channel_signer(channel_value_satoshis, channel_keys_id)
1694 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, DecodeError> {
1695 self.inner.read_chan_signer(reader)
1698 fn get_destination_script(&self) -> Result<Script, ()> {
1699 self.inner.get_destination_script()
1702 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
1703 self.inner.get_shutdown_scriptpubkey()
1707 impl PhantomKeysManager {
1708 /// Constructs a [`PhantomKeysManager`] given a 32-byte seed and an additional `cross_node_seed`
1709 /// that is shared across all nodes that intend to participate in [phantom node payments]
1712 /// See [`KeysManager::new`] for more information on `seed`, `starting_time_secs`, and
1713 /// `starting_time_nanos`.
1715 /// `cross_node_seed` must be the same across all phantom payment-receiving nodes and also the
1716 /// same across restarts, or else inbound payments may fail.
1718 /// [phantom node payments]: PhantomKeysManager
1719 pub fn new(seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32, cross_node_seed: &[u8; 32]) -> Self {
1720 let inner = KeysManager::new(seed, starting_time_secs, starting_time_nanos);
1721 let (inbound_key, phantom_key) = hkdf_extract_expand_twice(b"LDK Inbound and Phantom Payment Key Expansion", cross_node_seed);
1722 let phantom_secret = SecretKey::from_slice(&phantom_key).unwrap();
1723 let phantom_node_id = PublicKey::from_secret_key(&inner.secp_ctx, &phantom_secret);
1726 inbound_payment_key: KeyMaterial(inbound_key),
1732 /// See [`KeysManager::spend_spendable_outputs`] for documentation on this method.
1733 pub fn spend_spendable_outputs<C: Signing>(&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>, change_destination_script: Script, feerate_sat_per_1000_weight: u32, locktime: Option<PackedLockTime>, secp_ctx: &Secp256k1<C>) -> Result<Transaction, ()> {
1734 self.inner.spend_spendable_outputs(descriptors, outputs, change_destination_script, feerate_sat_per_1000_weight, locktime, secp_ctx)
1737 /// See [`KeysManager::derive_channel_keys`] for documentation on this method.
1738 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner {
1739 self.inner.derive_channel_keys(channel_value_satoshis, params)
1742 /// Gets the "node_id" secret key used to sign gossip announcements, decode onion data, etc.
1743 pub fn get_node_secret_key(&self) -> SecretKey {
1744 self.inner.get_node_secret_key()
1747 /// Gets the "node_id" secret key of the phantom node used to sign invoices, decode the
1748 /// last-hop onion data, etc.
1749 pub fn get_phantom_node_secret_key(&self) -> SecretKey {
1754 // Ensure that EcdsaChannelSigner can have a vtable
1757 let _signer: Box<dyn EcdsaChannelSigner>;
1762 use std::sync::{Arc, mpsc};
1763 use std::sync::mpsc::TryRecvError;
1765 use std::time::Duration;
1766 use bitcoin::blockdata::constants::genesis_block;
1767 use bitcoin::Network;
1768 use crate::sign::{EntropySource, KeysManager};
1770 use criterion::Criterion;
1772 pub fn bench_get_secure_random_bytes(bench: &mut Criterion) {
1773 let seed = [0u8; 32];
1774 let now = Duration::from_secs(genesis_block(Network::Testnet).header.time as u64);
1775 let keys_manager = Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_micros()));
1777 let mut handles = Vec::new();
1778 let mut stops = Vec::new();
1780 let keys_manager_clone = Arc::clone(&keys_manager);
1781 let (stop_sender, stop_receiver) = mpsc::channel();
1782 let handle = thread::spawn(move || {
1784 keys_manager_clone.get_secure_random_bytes();
1785 match stop_receiver.try_recv() {
1786 Ok(_) | Err(TryRecvError::Disconnected) => {
1787 println!("Terminating.");
1790 Err(TryRecvError::Empty) => {}
1794 handles.push(handle);
1795 stops.push(stop_sender);
1798 bench.bench_function("get_secure_random_bytes", |b| b.iter(||
1799 keys_manager.get_secure_random_bytes()));
1802 let _ = stop.send(());
1804 for handle in handles {
1805 handle.join().unwrap();