1use bitcoin::amount::Amount;
16use bitcoin::bip32::{ChildNumber, Xpriv, Xpub};
17use bitcoin::ecdsa::Signature as EcdsaSignature;
18use bitcoin::locktime::absolute::LockTime;
19use bitcoin::network::Network;
20use bitcoin::opcodes;
21use bitcoin::script::{Builder, Script, ScriptBuf};
22use bitcoin::sighash;
23use bitcoin::sighash::EcdsaSighashType;
24use bitcoin::transaction::Version;
25use bitcoin::transaction::{Transaction, TxIn, TxOut};
26
27use bitcoin::hashes::sha256::Hash as Sha256;
28use bitcoin::hashes::sha256d::Hash as Sha256dHash;
29use bitcoin::hashes::{Hash, HashEngine};
30
31use bitcoin::secp256k1::ecdh::SharedSecret;
32use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
33use bitcoin::secp256k1::schnorr;
34use bitcoin::secp256k1::All;
35use bitcoin::secp256k1::{Keypair, PublicKey, Scalar, Secp256k1, SecretKey, Signing};
36use bitcoin::{secp256k1, Psbt, Sequence, Txid, WPubkeyHash, Witness};
37
38use lightning_invoice::RawBolt11Invoice;
39
40use crate::chain::transaction::OutPoint;
41use crate::crypto::utils::{hkdf_extract_expand_twice, sign, sign_with_aux_rand};
42use crate::ln::chan_utils;
43use crate::ln::chan_utils::{
44 get_countersigner_payment_script, get_revokeable_redeemscript, make_funding_redeemscript,
45 ChannelPublicKeys, ChannelTransactionParameters, ClosingTransaction, CommitmentTransaction,
46 HTLCOutputInCommitment, HolderCommitmentTransaction,
47};
48use crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI;
49use crate::ln::channel_keys::{
50 add_public_key_tweak, DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, HtlcKey,
51 RevocationBasepoint, RevocationKey,
52};
53use crate::ln::inbound_payment::ExpandedKey;
54#[cfg(taproot)]
55use crate::ln::msgs::PartialSignatureWithNonce;
56use crate::ln::msgs::{UnsignedChannelAnnouncement, UnsignedGossipMessage};
57use crate::ln::script::ShutdownScript;
58use crate::offers::invoice::UnsignedBolt12Invoice;
59use crate::types::features::ChannelTypeFeatures;
60use crate::types::payment::PaymentPreimage;
61use crate::util::async_poll::AsyncResult;
62use crate::util::ser::{ReadableArgs, Writeable};
63use crate::util::transaction_utils;
64
65use crate::crypto::chacha20::ChaCha20;
66use crate::prelude::*;
67use crate::sign::ecdsa::EcdsaChannelSigner;
68#[cfg(taproot)]
69use crate::sign::taproot::TaprootChannelSigner;
70use crate::util::atomic_counter::AtomicCounter;
71use core::convert::TryInto;
72use core::ops::Deref;
73use core::sync::atomic::{AtomicUsize, Ordering};
74#[cfg(taproot)]
75use musig2::types::{PartialSignature, PublicNonce};
76
77pub(crate) mod type_resolver;
78
79pub mod ecdsa;
80#[cfg(taproot)]
81pub mod taproot;
82pub mod tx_builder;
83
84pub(crate) const COMPRESSED_PUBLIC_KEY_SIZE: usize = bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
85
86pub(crate) const MAX_STANDARD_SIGNATURE_SIZE: usize =
87 bitcoin::secp256k1::constants::MAX_SIGNATURE_SIZE;
88
89#[derive(Clone, Debug, Hash, PartialEq, Eq)]
93pub struct DelayedPaymentOutputDescriptor {
94 pub outpoint: OutPoint,
96 pub per_commitment_point: PublicKey,
98 pub to_self_delay: u16,
101 pub output: TxOut,
103 pub revocation_pubkey: RevocationKey,
106 pub channel_keys_id: [u8; 32],
109 pub channel_value_satoshis: u64,
111 pub channel_transaction_parameters: Option<ChannelTransactionParameters>,
116}
117
118impl DelayedPaymentOutputDescriptor {
119 pub const MAX_WITNESS_LENGTH: u64 = (1 + 1 + MAX_STANDARD_SIGNATURE_SIZE
126 + 1 + 1 + chan_utils::REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH) as u64;
129}
130
131impl_writeable_tlv_based!(DelayedPaymentOutputDescriptor, {
132 (0, outpoint, required),
133 (2, per_commitment_point, required),
134 (4, to_self_delay, required),
135 (6, output, required),
136 (8, revocation_pubkey, required),
137 (10, channel_keys_id, required),
138 (12, channel_value_satoshis, required),
139 (13, channel_transaction_parameters, (option: ReadableArgs, Some(channel_value_satoshis.0.unwrap()))),
140});
141
142pub(crate) const P2WPKH_WITNESS_WEIGHT: u64 = (1 + 1 + MAX_STANDARD_SIGNATURE_SIZE
146 + 1 + COMPRESSED_PUBLIC_KEY_SIZE) as u64;
148
149pub(crate) const P2TR_KEY_PATH_WITNESS_WEIGHT: u64 = (1 + 1 + bitcoin::secp256k1::constants::SCHNORR_SIGNATURE_SIZE)
153 as u64;
154
155pub const STATIC_PAYMENT_KEY_COUNT: u16 = 1000;
164
165#[derive(Clone, Debug, Hash, PartialEq, Eq)]
169pub struct StaticPaymentOutputDescriptor {
170 pub outpoint: OutPoint,
172 pub output: TxOut,
174 pub channel_keys_id: [u8; 32],
177 pub channel_value_satoshis: u64,
179 pub channel_transaction_parameters: Option<ChannelTransactionParameters>,
183}
184
185impl StaticPaymentOutputDescriptor {
186 pub fn witness_script(&self) -> Option<ScriptBuf> {
191 self.channel_transaction_parameters.as_ref().and_then(|channel_params| {
192 if channel_params.channel_type_features.supports_anchors_zero_fee_htlc_tx() {
193 let payment_point = channel_params.holder_pubkeys.payment_point;
194 Some(chan_utils::get_to_countersigner_keyed_anchor_redeemscript(&payment_point))
195 } else {
196 None
197 }
198 })
199 }
200
201 pub fn max_witness_length(&self) -> u64 {
206 if self.needs_csv_1_for_spend() {
207 let witness_script_weight = 1 + COMPRESSED_PUBLIC_KEY_SIZE
209 + 1 + 1 + 1 ;
212 (1 + 1 + MAX_STANDARD_SIGNATURE_SIZE
215 + 1 + witness_script_weight) as u64
217 } else {
218 P2WPKH_WITNESS_WEIGHT
219 }
220 }
221
222 pub fn needs_csv_1_for_spend(&self) -> bool {
225 let chan_params = self.channel_transaction_parameters.as_ref();
226 chan_params.map_or(false, |p| p.channel_type_features.supports_anchors_zero_fee_htlc_tx())
227 }
228}
229impl_writeable_tlv_based!(StaticPaymentOutputDescriptor, {
230 (0, outpoint, required),
231 (2, output, required),
232 (4, channel_keys_id, required),
233 (6, channel_value_satoshis, required),
234 (7, channel_transaction_parameters, (option: ReadableArgs, Some(channel_value_satoshis.0.unwrap()))),
235});
236
237#[derive(Clone, Debug, Hash, PartialEq, Eq)]
247pub enum SpendableOutputDescriptor {
248 StaticOutput {
257 outpoint: OutPoint,
259 output: TxOut,
261 channel_keys_id: Option<[u8; 32]>,
270 },
271 DelayedPaymentOutput(DelayedPaymentOutputDescriptor),
312 StaticPaymentOutput(StaticPaymentOutputDescriptor),
330}
331
332impl_writeable_tlv_based_enum_legacy!(SpendableOutputDescriptor,
333 (0, StaticOutput) => {
334 (0, outpoint, required),
335 (1, channel_keys_id, option),
336 (2, output, required),
337 },
338;
339 (1, DelayedPaymentOutput),
340 (2, StaticPaymentOutput),
341);
342
343impl SpendableOutputDescriptor {
344 pub fn to_psbt_input<T: secp256k1::Signing>(
383 &self, secp_ctx: &Secp256k1<T>,
384 ) -> bitcoin::psbt::Input {
385 match self {
386 SpendableOutputDescriptor::StaticOutput { output, .. } => {
387 bitcoin::psbt::Input { witness_utxo: Some(output.clone()), ..Default::default() }
389 },
390 SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
391 channel_transaction_parameters,
392 per_commitment_point,
393 revocation_pubkey,
394 to_self_delay,
395 output,
396 ..
397 }) => {
398 let delayed_payment_basepoint = channel_transaction_parameters
399 .as_ref()
400 .map(|params| params.holder_pubkeys.delayed_payment_basepoint);
401
402 let (witness_script, add_tweak) =
403 if let Some(basepoint) = delayed_payment_basepoint.as_ref() {
404 let add_tweak = basepoint.derive_add_tweak(&per_commitment_point);
406 let delayed_payment_key = DelayedPaymentKey(add_public_key_tweak(
407 secp_ctx,
408 &basepoint.to_public_key(),
409 &add_tweak,
410 ));
411
412 (
413 Some(get_revokeable_redeemscript(
414 &revocation_pubkey,
415 *to_self_delay,
416 &delayed_payment_key,
417 )),
418 Some(add_tweak),
419 )
420 } else {
421 (None, None)
422 };
423
424 bitcoin::psbt::Input {
425 witness_utxo: Some(output.clone()),
426 witness_script,
427 proprietary: add_tweak
428 .map(|add_tweak| {
429 [(
430 bitcoin::psbt::raw::ProprietaryKey {
431 prefix: "LDK_spendable_output".as_bytes().to_vec(),
434 subtype: 0,
435 key: "add_tweak".as_bytes().to_vec(),
436 },
437 add_tweak.as_byte_array().to_vec(),
438 )]
439 .into_iter()
440 .collect()
441 })
442 .unwrap_or_default(),
443 ..Default::default()
444 }
445 },
446 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => bitcoin::psbt::Input {
447 witness_utxo: Some(descriptor.output.clone()),
448 witness_script: descriptor.witness_script(),
449 ..Default::default()
450 },
451 }
452 }
453
454 pub fn create_spendable_outputs_psbt<T: secp256k1::Signing>(
471 secp_ctx: &Secp256k1<T>, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
472 change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
473 locktime: Option<LockTime>,
474 ) -> Result<(Psbt, u64), ()> {
475 let mut input = Vec::with_capacity(descriptors.len());
476 let mut input_value = Amount::ZERO;
477 let mut witness_weight = 0;
478 let mut output_set = hash_set_with_capacity(descriptors.len());
479 for outp in descriptors {
480 match outp {
481 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
482 if !output_set.insert(descriptor.outpoint) {
483 return Err(());
484 }
485 let sequence = if descriptor.needs_csv_1_for_spend() {
486 Sequence::from_consensus(1)
487 } else {
488 Sequence::ZERO
489 };
490 input.push(TxIn {
491 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
492 script_sig: ScriptBuf::new(),
493 sequence,
494 witness: Witness::new(),
495 });
496 witness_weight += descriptor.max_witness_length();
497 #[cfg(feature = "grind_signatures")]
498 {
499 witness_weight -= 1;
501 }
502 input_value += descriptor.output.value;
503 },
504 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
505 if !output_set.insert(descriptor.outpoint) {
506 return Err(());
507 }
508 input.push(TxIn {
509 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
510 script_sig: ScriptBuf::new(),
511 sequence: Sequence(descriptor.to_self_delay as u32),
512 witness: Witness::new(),
513 });
514 witness_weight += DelayedPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
515 #[cfg(feature = "grind_signatures")]
516 {
517 witness_weight -= 1;
519 }
520 input_value += descriptor.output.value;
521 },
522 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => {
523 if !output_set.insert(*outpoint) {
524 return Err(());
525 }
526 input.push(TxIn {
527 previous_output: outpoint.into_bitcoin_outpoint(),
528 script_sig: ScriptBuf::new(),
529 sequence: Sequence::ZERO,
530 witness: Witness::new(),
531 });
532 witness_weight += P2WPKH_WITNESS_WEIGHT;
533 #[cfg(feature = "grind_signatures")]
534 {
535 witness_weight -= 1;
537 }
538 input_value += output.value;
539 },
540 }
541 if input_value > Amount::MAX_MONEY {
542 return Err(());
543 }
544 }
545 let mut tx = Transaction {
546 version: Version::TWO,
547 lock_time: locktime.unwrap_or(LockTime::ZERO),
548 input,
549 output: outputs,
550 };
551 let expected_max_weight = transaction_utils::maybe_add_change_output(
552 &mut tx,
553 input_value,
554 witness_weight,
555 feerate_sat_per_1000_weight,
556 change_destination_script,
557 )?;
558
559 let psbt_inputs =
560 descriptors.iter().map(|d| d.to_psbt_input(&secp_ctx)).collect::<Vec<_>>();
561 let psbt = Psbt {
562 inputs: psbt_inputs,
563 outputs: vec![Default::default(); tx.output.len()],
564 unsigned_tx: tx,
565 xpub: Default::default(),
566 version: 0,
567 proprietary: Default::default(),
568 unknown: Default::default(),
569 };
570 Ok((psbt, expected_max_weight))
571 }
572
573 pub fn spendable_outpoint(&self) -> OutPoint {
575 match self {
576 Self::StaticOutput { outpoint, .. } => *outpoint,
577 Self::StaticPaymentOutput(descriptor) => descriptor.outpoint,
578 Self::DelayedPaymentOutput(descriptor) => descriptor.outpoint,
579 }
580 }
581}
582
583#[derive(Clone, Debug, PartialEq, Eq)]
585pub struct ChannelDerivationParameters {
586 pub value_satoshis: u64,
588 pub keys_id: [u8; 32],
590 pub transaction_parameters: ChannelTransactionParameters,
592}
593
594impl_writeable_tlv_based!(ChannelDerivationParameters, {
595 (0, value_satoshis, required),
596 (2, keys_id, required),
597 (4, transaction_parameters, (required: ReadableArgs, Some(value_satoshis.0.unwrap()))),
598});
599
600#[derive(Clone, Debug, PartialEq, Eq)]
602pub struct HTLCDescriptor {
603 pub channel_derivation_parameters: ChannelDerivationParameters,
605 pub commitment_txid: Txid,
607 pub per_commitment_number: u64,
609 pub per_commitment_point: PublicKey,
615 pub feerate_per_kw: u32,
619 pub htlc: HTLCOutputInCommitment,
621 pub preimage: Option<PaymentPreimage>,
624 pub counterparty_sig: Signature,
626}
627
628impl_writeable_tlv_based!(HTLCDescriptor, {
629 (0, channel_derivation_parameters, required),
630 (1, feerate_per_kw, (default_value, 0)),
631 (2, commitment_txid, required),
632 (4, per_commitment_number, required),
633 (6, per_commitment_point, required),
634 (8, htlc, required),
635 (10, preimage, option),
636 (12, counterparty_sig, required),
637});
638
639impl HTLCDescriptor {
640 pub fn outpoint(&self) -> bitcoin::OutPoint {
643 bitcoin::OutPoint {
644 txid: self.commitment_txid,
645 vout: self.htlc.transaction_output_index.unwrap(),
646 }
647 }
648
649 pub fn previous_utxo<C: secp256k1::Signing + secp256k1::Verification>(
652 &self, secp: &Secp256k1<C>,
653 ) -> TxOut {
654 TxOut {
655 script_pubkey: self.witness_script(secp).to_p2wsh(),
656 value: self.htlc.to_bitcoin_amount(),
657 }
658 }
659
660 pub fn unsigned_tx_input(&self) -> TxIn {
663 chan_utils::build_htlc_input(
664 &self.commitment_txid,
665 &self.htlc,
666 &self.channel_derivation_parameters.transaction_parameters.channel_type_features,
667 )
668 }
669
670 pub fn tx_output<C: secp256k1::Signing + secp256k1::Verification>(
673 &self, secp: &Secp256k1<C>,
674 ) -> TxOut {
675 let channel_params =
676 self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
677 let broadcaster_keys = channel_params.broadcaster_pubkeys();
678 let counterparty_keys = channel_params.countersignatory_pubkeys();
679 let broadcaster_delayed_key = DelayedPaymentKey::from_basepoint(
680 secp,
681 &broadcaster_keys.delayed_payment_basepoint,
682 &self.per_commitment_point,
683 );
684 let counterparty_revocation_key = &RevocationKey::from_basepoint(
685 &secp,
686 &counterparty_keys.revocation_basepoint,
687 &self.per_commitment_point,
688 );
689 chan_utils::build_htlc_output(
690 self.feerate_per_kw,
691 channel_params.contest_delay(),
692 &self.htlc,
693 channel_params.channel_type_features(),
694 &broadcaster_delayed_key,
695 &counterparty_revocation_key,
696 )
697 }
698
699 pub fn witness_script<C: secp256k1::Signing + secp256k1::Verification>(
701 &self, secp: &Secp256k1<C>,
702 ) -> ScriptBuf {
703 let channel_params =
704 self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
705 let broadcaster_keys = channel_params.broadcaster_pubkeys();
706 let counterparty_keys = channel_params.countersignatory_pubkeys();
707 let broadcaster_htlc_key = HtlcKey::from_basepoint(
708 secp,
709 &broadcaster_keys.htlc_basepoint,
710 &self.per_commitment_point,
711 );
712 let counterparty_htlc_key = HtlcKey::from_basepoint(
713 secp,
714 &counterparty_keys.htlc_basepoint,
715 &self.per_commitment_point,
716 );
717 let counterparty_revocation_key = &RevocationKey::from_basepoint(
718 &secp,
719 &counterparty_keys.revocation_basepoint,
720 &self.per_commitment_point,
721 );
722 chan_utils::get_htlc_redeemscript_with_explicit_keys(
723 &self.htlc,
724 channel_params.channel_type_features(),
725 &broadcaster_htlc_key,
726 &counterparty_htlc_key,
727 &counterparty_revocation_key,
728 )
729 }
730
731 pub fn tx_input_witness(&self, signature: &Signature, witness_script: &Script) -> Witness {
734 chan_utils::build_htlc_input_witness(
735 signature,
736 &self.counterparty_sig,
737 &self.preimage,
738 witness_script,
739 &self.channel_derivation_parameters.transaction_parameters.channel_type_features,
740 )
741 }
742}
743
744pub trait ChannelSigner {
754 fn get_per_commitment_point(
762 &self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>,
763 ) -> Result<PublicKey, ()>;
764
765 fn release_commitment_secret(&self, idx: u64) -> Result<[u8; 32], ()>;
780
781 fn validate_holder_commitment(
799 &self, holder_tx: &HolderCommitmentTransaction,
800 outbound_htlc_preimages: Vec<PaymentPreimage>,
801 ) -> Result<(), ()>;
802
803 fn validate_counterparty_revocation(&self, idx: u64, secret: &SecretKey) -> Result<(), ()>;
812
813 fn pubkeys(&self, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelPublicKeys;
820
821 fn new_funding_pubkey(
830 &self, splice_parent_funding_txid: Txid, secp_ctx: &Secp256k1<secp256k1::All>,
831 ) -> PublicKey;
832
833 fn channel_keys_id(&self) -> [u8; 32];
839}
840
841#[derive(Clone, Copy, PartialEq, Eq)]
843pub struct PeerStorageKey {
844 pub inner: [u8; 32],
846}
847
848#[derive(Clone, Copy, PartialEq, Eq)]
855pub struct ReceiveAuthKey(pub [u8; 32]);
856
857#[derive(Clone, Copy)]
862pub enum Recipient {
863 Node,
865 PhantomNode,
870}
871
872pub trait EntropySource {
874 fn get_secure_random_bytes(&self) -> [u8; 32];
877}
878
879pub trait NodeSigner {
881 fn get_expanded_key(&self) -> ExpandedKey;
900
901 fn get_peer_storage_key(&self) -> PeerStorageKey;
909
910 fn get_receive_auth_key(&self) -> ReceiveAuthKey;
922
923 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()>;
930
931 fn ecdh(
940 &self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
941 ) -> Result<SharedSecret, ()>;
942
943 fn sign_invoice(
955 &self, invoice: &RawBolt11Invoice, recipient: Recipient,
956 ) -> Result<RecoverableSignature, ()>;
957
958 fn sign_bolt12_invoice(
970 &self, invoice: &UnsignedBolt12Invoice,
971 ) -> Result<schnorr::Signature, ()>;
972
973 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()>;
980
981 fn sign_message(&self, msg: &[u8]) -> Result<String, ()>;
991}
992
993pub trait OutputSpender {
996 fn spend_spendable_outputs(
1009 &self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
1010 change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
1011 locktime: Option<LockTime>, secp_ctx: &Secp256k1<All>,
1012 ) -> Result<Transaction, ()>;
1013}
1014
1015#[cfg(taproot)]
1020#[doc(hidden)]
1021#[deprecated(note = "Remove once taproot cfg is removed")]
1022pub type DynSignerProvider =
1023 dyn SignerProvider<EcdsaSigner = InMemorySigner, TaprootSigner = InMemorySigner>;
1024
1025#[cfg(not(taproot))]
1029#[doc(hidden)]
1030#[deprecated(note = "Remove once taproot cfg is removed")]
1031pub type DynSignerProvider = dyn SignerProvider<EcdsaSigner = InMemorySigner>;
1032
1033pub trait SignerProvider {
1035 type EcdsaSigner: EcdsaChannelSigner;
1037 #[cfg(taproot)]
1038 type TaprootSigner: TaprootChannelSigner;
1040
1041 fn generate_channel_keys_id(&self, inbound: bool, user_channel_id: u128) -> [u8; 32];
1048
1049 fn derive_channel_signer(&self, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner;
1056
1057 fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()>;
1065
1066 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()>;
1075}
1076
1077pub trait ChangeDestinationSource {
1082 fn get_change_destination_script<'a>(&'a self) -> AsyncResult<'a, ScriptBuf, ()>;
1088}
1089
1090pub trait ChangeDestinationSourceSync {
1092 fn get_change_destination_script(&self) -> Result<ScriptBuf, ()>;
1098}
1099
1100#[doc(hidden)]
1105pub struct ChangeDestinationSourceSyncWrapper<T: Deref>(T)
1106where
1107 T::Target: ChangeDestinationSourceSync;
1108
1109impl<T: Deref> ChangeDestinationSourceSyncWrapper<T>
1110where
1111 T::Target: ChangeDestinationSourceSync,
1112{
1113 pub fn new(source: T) -> Self {
1115 Self(source)
1116 }
1117}
1118impl<T: Deref> ChangeDestinationSource for ChangeDestinationSourceSyncWrapper<T>
1119where
1120 T::Target: ChangeDestinationSourceSync,
1121{
1122 fn get_change_destination_script<'a>(&'a self) -> AsyncResult<'a, ScriptBuf, ()> {
1123 let script = self.0.get_change_destination_script();
1124 Box::pin(async move { script })
1125 }
1126}
1127
1128impl<T: Deref> Deref for ChangeDestinationSourceSyncWrapper<T>
1129where
1130 T::Target: ChangeDestinationSourceSync,
1131{
1132 type Target = Self;
1133 fn deref(&self) -> &Self {
1134 self
1135 }
1136}
1137
1138mod sealed {
1139 use bitcoin::secp256k1::{Scalar, SecretKey};
1140
1141 #[derive(Clone, PartialEq)]
1142 pub struct MaybeTweakedSecretKey(pub(super) SecretKey);
1143
1144 impl From<SecretKey> for MaybeTweakedSecretKey {
1145 fn from(value: SecretKey) -> Self {
1146 Self(value)
1147 }
1148 }
1149
1150 impl MaybeTweakedSecretKey {
1151 pub fn with_tweak(&self, tweak: Option<Scalar>) -> SecretKey {
1152 tweak
1153 .map(|tweak| {
1154 self.0
1155 .add_tweak(&tweak)
1156 .expect("Addition only fails if the tweak is the inverse of the key")
1157 })
1158 .unwrap_or(self.0)
1159 }
1160 }
1161}
1162
1163pub fn compute_funding_key_tweak(
1180 base_funding_secret_key: &SecretKey, splice_parent_funding_txid: &Txid,
1181) -> Scalar {
1182 let mut sha = Sha256::engine();
1183 sha.input(splice_parent_funding_txid.as_byte_array());
1184 sha.input(&base_funding_secret_key.secret_bytes());
1185 Scalar::from_be_bytes(Sha256::from_engine(sha).to_byte_array()).unwrap()
1186}
1187
1188pub struct InMemorySigner {
1193 funding_key: sealed::MaybeTweakedSecretKey,
1196 pub revocation_base_key: SecretKey,
1198 payment_key_v1: SecretKey,
1201 payment_key_v2: SecretKey,
1204 v2_remote_key_derivation: bool,
1206 pub delayed_payment_base_key: SecretKey,
1208 pub htlc_base_key: SecretKey,
1210 pub commitment_seed: [u8; 32],
1212 channel_keys_id: [u8; 32],
1214 entropy_source: RandomBytes,
1216}
1217
1218impl PartialEq for InMemorySigner {
1219 fn eq(&self, other: &Self) -> bool {
1220 self.funding_key == other.funding_key
1221 && self.revocation_base_key == other.revocation_base_key
1222 && self.payment_key_v1 == other.payment_key_v1
1223 && self.payment_key_v2 == other.payment_key_v2
1224 && self.v2_remote_key_derivation == other.v2_remote_key_derivation
1225 && self.delayed_payment_base_key == other.delayed_payment_base_key
1226 && self.htlc_base_key == other.htlc_base_key
1227 && self.commitment_seed == other.commitment_seed
1228 && self.channel_keys_id == other.channel_keys_id
1229 }
1230}
1231
1232impl Clone for InMemorySigner {
1233 fn clone(&self) -> Self {
1234 Self {
1235 funding_key: self.funding_key.clone(),
1236 revocation_base_key: self.revocation_base_key.clone(),
1237 payment_key_v1: self.payment_key_v1.clone(),
1238 payment_key_v2: self.payment_key_v2.clone(),
1239 v2_remote_key_derivation: self.v2_remote_key_derivation,
1240 delayed_payment_base_key: self.delayed_payment_base_key.clone(),
1241 htlc_base_key: self.htlc_base_key.clone(),
1242 commitment_seed: self.commitment_seed.clone(),
1243 channel_keys_id: self.channel_keys_id,
1244 entropy_source: RandomBytes::new(self.get_secure_random_bytes()),
1245 }
1246 }
1247}
1248
1249impl InMemorySigner {
1250 #[cfg(any(feature = "_test_utils", test))]
1251 pub fn new(
1252 funding_key: SecretKey, revocation_base_key: SecretKey, payment_key_v1: SecretKey,
1253 payment_key_v2: SecretKey, v2_remote_key_derivation: bool,
1254 delayed_payment_base_key: SecretKey, htlc_base_key: SecretKey, commitment_seed: [u8; 32],
1255 channel_keys_id: [u8; 32], rand_bytes_unique_start: [u8; 32],
1256 ) -> InMemorySigner {
1257 InMemorySigner {
1258 funding_key: sealed::MaybeTweakedSecretKey::from(funding_key),
1259 revocation_base_key,
1260 payment_key_v1,
1261 payment_key_v2,
1262 v2_remote_key_derivation,
1263 delayed_payment_base_key,
1264 htlc_base_key,
1265 commitment_seed,
1266 channel_keys_id,
1267 entropy_source: RandomBytes::new(rand_bytes_unique_start),
1268 }
1269 }
1270
1271 #[cfg(not(any(feature = "_test_utils", test)))]
1272 fn new(
1273 funding_key: SecretKey, revocation_base_key: SecretKey, payment_key_v1: SecretKey,
1274 payment_key_v2: SecretKey, v2_remote_key_derivation: bool,
1275 delayed_payment_base_key: SecretKey, htlc_base_key: SecretKey, commitment_seed: [u8; 32],
1276 channel_keys_id: [u8; 32], rand_bytes_unique_start: [u8; 32],
1277 ) -> InMemorySigner {
1278 InMemorySigner {
1279 funding_key: sealed::MaybeTweakedSecretKey::from(funding_key),
1280 revocation_base_key,
1281 payment_key_v1,
1282 payment_key_v2,
1283 v2_remote_key_derivation,
1284 delayed_payment_base_key,
1285 htlc_base_key,
1286 commitment_seed,
1287 channel_keys_id,
1288 entropy_source: RandomBytes::new(rand_bytes_unique_start),
1289 }
1290 }
1291
1292 pub fn funding_key(&self, splice_parent_funding_txid: Option<Txid>) -> SecretKey {
1295 let tweak = splice_parent_funding_txid
1296 .map(|txid| compute_funding_key_tweak(&self.funding_key.with_tweak(None), &txid));
1297 self.funding_key.with_tweak(tweak)
1298 }
1299
1300 pub fn sign_counterparty_payment_input<C: Signing>(
1309 &self, spend_tx: &Transaction, input_idx: usize,
1310 descriptor: &StaticPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>,
1311 ) -> Result<Witness, ()> {
1312 if spend_tx.input.len() <= input_idx {
1317 return Err(());
1318 }
1319 if !spend_tx.input[input_idx].script_sig.is_empty() {
1320 return Err(());
1321 }
1322 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint()
1323 {
1324 return Err(());
1325 }
1326
1327 let legacy_default_channel_type = ChannelTypeFeatures::only_static_remote_key();
1328 let channel_type_features = descriptor
1329 .channel_transaction_parameters
1330 .as_ref()
1331 .map(|params| ¶ms.channel_type_features)
1332 .unwrap_or(&legacy_default_channel_type);
1333
1334 let payment_point_v1 = PublicKey::from_secret_key(secp_ctx, &self.payment_key_v1);
1335 let payment_point_v2 = PublicKey::from_secret_key(secp_ctx, &self.payment_key_v2);
1336 let spk_v1 = get_countersigner_payment_script(channel_type_features, &payment_point_v1);
1337 let spk_v2 = get_countersigner_payment_script(channel_type_features, &payment_point_v2);
1338
1339 let (remotepubkey, payment_key) = if spk_v1 == descriptor.output.script_pubkey {
1340 (bitcoin::PublicKey::new(payment_point_v1), &self.payment_key_v1)
1341 } else {
1342 if spk_v2 != descriptor.output.script_pubkey {
1343 return Err(());
1344 }
1345 (bitcoin::PublicKey::new(payment_point_v2), &self.payment_key_v2)
1346 };
1347
1348 let witness_script = if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
1349 chan_utils::get_to_countersigner_keyed_anchor_redeemscript(&remotepubkey.inner)
1350 } else {
1351 ScriptBuf::new_p2pkh(&remotepubkey.pubkey_hash())
1352 };
1353 let sighash = hash_to_message!(
1354 &sighash::SighashCache::new(spend_tx)
1355 .p2wsh_signature_hash(
1356 input_idx,
1357 &witness_script,
1358 descriptor.output.value,
1359 EcdsaSighashType::All
1360 )
1361 .unwrap()[..]
1362 );
1363 let remotesig = sign_with_aux_rand(secp_ctx, &sighash, payment_key, &self);
1364 let payment_script = if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
1365 witness_script.to_p2wsh()
1366 } else {
1367 ScriptBuf::new_p2wpkh(&remotepubkey.wpubkey_hash().unwrap())
1368 };
1369
1370 if payment_script != descriptor.output.script_pubkey {
1371 return Err(());
1372 }
1373
1374 let mut witness = Vec::with_capacity(2);
1375 witness.push(remotesig.serialize_der().to_vec());
1376 witness[0].push(EcdsaSighashType::All as u8);
1377 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
1378 witness.push(witness_script.to_bytes());
1379 } else {
1380 witness.push(remotepubkey.to_bytes());
1381 }
1382 Ok(witness.into())
1383 }
1384
1385 pub fn sign_dynamic_p2wsh_input<C: Signing>(
1396 &self, spend_tx: &Transaction, input_idx: usize,
1397 descriptor: &DelayedPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>,
1398 ) -> Result<Witness, ()> {
1399 if spend_tx.input.len() <= input_idx {
1404 return Err(());
1405 }
1406 if !spend_tx.input[input_idx].script_sig.is_empty() {
1407 return Err(());
1408 }
1409 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint()
1410 {
1411 return Err(());
1412 }
1413 if spend_tx.input[input_idx].sequence.0 != descriptor.to_self_delay as u32 {
1414 return Err(());
1415 }
1416
1417 let delayed_payment_key = chan_utils::derive_private_key(
1418 &secp_ctx,
1419 &descriptor.per_commitment_point,
1420 &self.delayed_payment_base_key,
1421 );
1422 let delayed_payment_pubkey =
1423 DelayedPaymentKey::from_secret_key(&secp_ctx, &delayed_payment_key);
1424 let witness_script = chan_utils::get_revokeable_redeemscript(
1425 &descriptor.revocation_pubkey,
1426 descriptor.to_self_delay,
1427 &delayed_payment_pubkey,
1428 );
1429 let sighash = hash_to_message!(
1430 &sighash::SighashCache::new(spend_tx)
1431 .p2wsh_signature_hash(
1432 input_idx,
1433 &witness_script,
1434 descriptor.output.value,
1435 EcdsaSighashType::All
1436 )
1437 .unwrap()[..]
1438 );
1439 let local_delayedsig = EcdsaSignature {
1440 signature: sign_with_aux_rand(secp_ctx, &sighash, &delayed_payment_key, &self),
1441 sighash_type: EcdsaSighashType::All,
1442 };
1443 let payment_script =
1444 bitcoin::Address::p2wsh(&witness_script, Network::Bitcoin).script_pubkey();
1445
1446 if descriptor.output.script_pubkey != payment_script {
1447 return Err(());
1448 }
1449
1450 Ok(Witness::from_slice(&[
1451 &local_delayedsig.serialize()[..],
1452 &[], witness_script.as_bytes(),
1454 ]))
1455 }
1456}
1457
1458impl EntropySource for InMemorySigner {
1459 fn get_secure_random_bytes(&self) -> [u8; 32] {
1460 self.entropy_source.get_secure_random_bytes()
1461 }
1462}
1463
1464impl ChannelSigner for InMemorySigner {
1465 fn get_per_commitment_point(
1466 &self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>,
1467 ) -> Result<PublicKey, ()> {
1468 let commitment_secret =
1469 SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx))
1470 .unwrap();
1471 Ok(PublicKey::from_secret_key(secp_ctx, &commitment_secret))
1472 }
1473
1474 fn release_commitment_secret(&self, idx: u64) -> Result<[u8; 32], ()> {
1475 Ok(chan_utils::build_commitment_secret(&self.commitment_seed, idx))
1476 }
1477
1478 fn validate_holder_commitment(
1479 &self, _holder_tx: &HolderCommitmentTransaction,
1480 _outbound_htlc_preimages: Vec<PaymentPreimage>,
1481 ) -> Result<(), ()> {
1482 Ok(())
1483 }
1484
1485 fn validate_counterparty_revocation(&self, _idx: u64, _secret: &SecretKey) -> Result<(), ()> {
1486 Ok(())
1487 }
1488
1489 fn pubkeys(&self, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelPublicKeys {
1490 let payment_key =
1493 if self.v2_remote_key_derivation { &self.payment_key_v2 } else { &self.payment_key_v1 };
1494 let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
1495 let pubkeys = ChannelPublicKeys {
1496 funding_pubkey: from_secret(&self.funding_key.0),
1497 revocation_basepoint: RevocationBasepoint::from(from_secret(&self.revocation_base_key)),
1498 payment_point: from_secret(payment_key),
1499 delayed_payment_basepoint: DelayedPaymentBasepoint::from(from_secret(
1500 &self.delayed_payment_base_key,
1501 )),
1502 htlc_basepoint: HtlcBasepoint::from(from_secret(&self.htlc_base_key)),
1503 };
1504
1505 pubkeys
1506 }
1507
1508 fn new_funding_pubkey(
1509 &self, splice_parent_funding_txid: Txid, secp_ctx: &Secp256k1<secp256k1::All>,
1510 ) -> PublicKey {
1511 self.funding_key(Some(splice_parent_funding_txid)).public_key(secp_ctx)
1512 }
1513
1514 fn channel_keys_id(&self) -> [u8; 32] {
1515 self.channel_keys_id
1516 }
1517}
1518
1519const MISSING_PARAMS_ERR: &'static str =
1520 "ChannelTransactionParameters must be populated before signing operations";
1521
1522impl EcdsaChannelSigner for InMemorySigner {
1523 fn sign_counterparty_commitment(
1524 &self, channel_parameters: &ChannelTransactionParameters,
1525 commitment_tx: &CommitmentTransaction, _inbound_htlc_preimages: Vec<PaymentPreimage>,
1526 _outbound_htlc_preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<secp256k1::All>,
1527 ) -> Result<(Signature, Vec<Signature>), ()> {
1528 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1529
1530 let trusted_tx = commitment_tx.trust();
1531 let keys = trusted_tx.keys();
1532
1533 let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
1534 let funding_pubkey = funding_key.public_key(secp_ctx);
1535 let counterparty_keys =
1536 channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1537 let channel_funding_redeemscript =
1538 make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1539
1540 let built_tx = trusted_tx.built_transaction();
1541 let commitment_sig = built_tx.sign_counterparty_commitment(
1542 &funding_key,
1543 &channel_funding_redeemscript,
1544 channel_parameters.channel_value_satoshis,
1545 secp_ctx,
1546 );
1547 let commitment_txid = built_tx.txid;
1548
1549 let mut htlc_sigs = Vec::with_capacity(commitment_tx.nondust_htlcs().len());
1550 for htlc in commitment_tx.nondust_htlcs() {
1551 let holder_selected_contest_delay = channel_parameters.holder_selected_contest_delay;
1552 let chan_type = &channel_parameters.channel_type_features;
1553 let htlc_tx = chan_utils::build_htlc_transaction(
1554 &commitment_txid,
1555 commitment_tx.negotiated_feerate_per_kw(),
1556 holder_selected_contest_delay,
1557 htlc,
1558 chan_type,
1559 &keys.broadcaster_delayed_payment_key,
1560 &keys.revocation_key,
1561 );
1562 let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, chan_type, &keys);
1563 let htlc_sighashtype = if chan_type.supports_anchors_zero_fee_htlc_tx()
1564 || chan_type.supports_anchor_zero_fee_commitments()
1565 {
1566 EcdsaSighashType::SinglePlusAnyoneCanPay
1567 } else {
1568 EcdsaSighashType::All
1569 };
1570 let htlc_sighash = hash_to_message!(
1571 &sighash::SighashCache::new(&htlc_tx)
1572 .p2wsh_signature_hash(
1573 0,
1574 &htlc_redeemscript,
1575 htlc.to_bitcoin_amount(),
1576 htlc_sighashtype
1577 )
1578 .unwrap()[..]
1579 );
1580 let holder_htlc_key = chan_utils::derive_private_key(
1581 &secp_ctx,
1582 &keys.per_commitment_point,
1583 &self.htlc_base_key,
1584 );
1585 htlc_sigs.push(sign(secp_ctx, &htlc_sighash, &holder_htlc_key));
1586 }
1587
1588 Ok((commitment_sig, htlc_sigs))
1589 }
1590
1591 fn sign_holder_commitment(
1592 &self, channel_parameters: &ChannelTransactionParameters,
1593 commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
1594 ) -> Result<Signature, ()> {
1595 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1596
1597 let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
1598 let funding_pubkey = funding_key.public_key(secp_ctx);
1599 let counterparty_keys =
1600 channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1601 let funding_redeemscript =
1602 make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1603 let trusted_tx = commitment_tx.trust();
1604 Ok(trusted_tx.built_transaction().sign_holder_commitment(
1605 &funding_key,
1606 &funding_redeemscript,
1607 channel_parameters.channel_value_satoshis,
1608 &self,
1609 secp_ctx,
1610 ))
1611 }
1612
1613 #[cfg(any(test, feature = "_test_utils", feature = "unsafe_revoked_tx_signing"))]
1614 fn unsafe_sign_holder_commitment(
1615 &self, channel_parameters: &ChannelTransactionParameters,
1616 commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
1617 ) -> Result<Signature, ()> {
1618 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1619
1620 let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
1621 let funding_pubkey = funding_key.public_key(secp_ctx);
1622 let counterparty_keys =
1623 channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1624 let funding_redeemscript =
1625 make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1626 let trusted_tx = commitment_tx.trust();
1627 Ok(trusted_tx.built_transaction().sign_holder_commitment(
1628 &funding_key,
1629 &funding_redeemscript,
1630 channel_parameters.channel_value_satoshis,
1631 &self,
1632 secp_ctx,
1633 ))
1634 }
1635
1636 fn sign_justice_revoked_output(
1637 &self, channel_parameters: &ChannelTransactionParameters, justice_tx: &Transaction,
1638 input: usize, amount: u64, per_commitment_key: &SecretKey,
1639 secp_ctx: &Secp256k1<secp256k1::All>,
1640 ) -> Result<Signature, ()> {
1641 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1642
1643 let revocation_key = chan_utils::derive_private_revocation_key(
1644 &secp_ctx,
1645 &per_commitment_key,
1646 &self.revocation_base_key,
1647 );
1648 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
1649 let revocation_pubkey = RevocationKey::from_basepoint(
1650 &secp_ctx,
1651 &channel_parameters.holder_pubkeys.revocation_basepoint,
1652 &per_commitment_point,
1653 );
1654 let witness_script = {
1655 let counterparty_keys =
1656 channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1657 let holder_selected_contest_delay = channel_parameters.holder_selected_contest_delay;
1658 let counterparty_delayedpubkey = DelayedPaymentKey::from_basepoint(
1659 &secp_ctx,
1660 &counterparty_keys.delayed_payment_basepoint,
1661 &per_commitment_point,
1662 );
1663 chan_utils::get_revokeable_redeemscript(
1664 &revocation_pubkey,
1665 holder_selected_contest_delay,
1666 &counterparty_delayedpubkey,
1667 )
1668 };
1669 let mut sighash_parts = sighash::SighashCache::new(justice_tx);
1670 let sighash = hash_to_message!(
1671 &sighash_parts
1672 .p2wsh_signature_hash(
1673 input,
1674 &witness_script,
1675 Amount::from_sat(amount),
1676 EcdsaSighashType::All
1677 )
1678 .unwrap()[..]
1679 );
1680 return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self));
1681 }
1682
1683 fn sign_justice_revoked_htlc(
1684 &self, channel_parameters: &ChannelTransactionParameters, justice_tx: &Transaction,
1685 input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &HTLCOutputInCommitment,
1686 secp_ctx: &Secp256k1<secp256k1::All>,
1687 ) -> Result<Signature, ()> {
1688 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1689
1690 let revocation_key = chan_utils::derive_private_revocation_key(
1691 &secp_ctx,
1692 &per_commitment_key,
1693 &self.revocation_base_key,
1694 );
1695 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
1696 let revocation_pubkey = RevocationKey::from_basepoint(
1697 &secp_ctx,
1698 &channel_parameters.holder_pubkeys.revocation_basepoint,
1699 &per_commitment_point,
1700 );
1701 let witness_script = {
1702 let counterparty_keys =
1703 channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1704 let counterparty_htlcpubkey = HtlcKey::from_basepoint(
1705 &secp_ctx,
1706 &counterparty_keys.htlc_basepoint,
1707 &per_commitment_point,
1708 );
1709 let holder_htlcpubkey = HtlcKey::from_basepoint(
1710 &secp_ctx,
1711 &channel_parameters.holder_pubkeys.htlc_basepoint,
1712 &per_commitment_point,
1713 );
1714 chan_utils::get_htlc_redeemscript_with_explicit_keys(
1715 &htlc,
1716 &channel_parameters.channel_type_features,
1717 &counterparty_htlcpubkey,
1718 &holder_htlcpubkey,
1719 &revocation_pubkey,
1720 )
1721 };
1722 let mut sighash_parts = sighash::SighashCache::new(justice_tx);
1723 let sighash = hash_to_message!(
1724 &sighash_parts
1725 .p2wsh_signature_hash(
1726 input,
1727 &witness_script,
1728 Amount::from_sat(amount),
1729 EcdsaSighashType::All
1730 )
1731 .unwrap()[..]
1732 );
1733 return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self));
1734 }
1735
1736 fn sign_holder_htlc_transaction(
1737 &self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
1738 secp_ctx: &Secp256k1<secp256k1::All>,
1739 ) -> Result<Signature, ()> {
1740 let channel_parameters =
1741 &htlc_descriptor.channel_derivation_parameters.transaction_parameters;
1742 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1743
1744 let witness_script = htlc_descriptor.witness_script(secp_ctx);
1745 let sighash = &sighash::SighashCache::new(&*htlc_tx)
1746 .p2wsh_signature_hash(
1747 input,
1748 &witness_script,
1749 htlc_descriptor.htlc.to_bitcoin_amount(),
1750 EcdsaSighashType::All,
1751 )
1752 .map_err(|_| ())?;
1753 let our_htlc_private_key = chan_utils::derive_private_key(
1754 &secp_ctx,
1755 &htlc_descriptor.per_commitment_point,
1756 &self.htlc_base_key,
1757 );
1758 let sighash = hash_to_message!(sighash.as_byte_array());
1759 Ok(sign_with_aux_rand(&secp_ctx, &sighash, &our_htlc_private_key, &self))
1760 }
1761
1762 fn sign_counterparty_htlc_transaction(
1763 &self, channel_parameters: &ChannelTransactionParameters, htlc_tx: &Transaction,
1764 input: usize, amount: u64, per_commitment_point: &PublicKey, htlc: &HTLCOutputInCommitment,
1765 secp_ctx: &Secp256k1<secp256k1::All>,
1766 ) -> Result<Signature, ()> {
1767 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1768
1769 let htlc_key =
1770 chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key);
1771 let revocation_pubkey = RevocationKey::from_basepoint(
1772 &secp_ctx,
1773 &channel_parameters.holder_pubkeys.revocation_basepoint,
1774 &per_commitment_point,
1775 );
1776 let counterparty_keys =
1777 channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1778 let counterparty_htlcpubkey = HtlcKey::from_basepoint(
1779 &secp_ctx,
1780 &counterparty_keys.htlc_basepoint,
1781 &per_commitment_point,
1782 );
1783 let htlc_basepoint = channel_parameters.holder_pubkeys.htlc_basepoint;
1784 let htlcpubkey = HtlcKey::from_basepoint(&secp_ctx, &htlc_basepoint, &per_commitment_point);
1785 let chan_type = &channel_parameters.channel_type_features;
1786 let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(
1787 &htlc,
1788 chan_type,
1789 &counterparty_htlcpubkey,
1790 &htlcpubkey,
1791 &revocation_pubkey,
1792 );
1793 let mut sighash_parts = sighash::SighashCache::new(htlc_tx);
1794 let sighash = hash_to_message!(
1795 &sighash_parts
1796 .p2wsh_signature_hash(
1797 input,
1798 &witness_script,
1799 Amount::from_sat(amount),
1800 EcdsaSighashType::All
1801 )
1802 .unwrap()[..]
1803 );
1804 Ok(sign_with_aux_rand(secp_ctx, &sighash, &htlc_key, &self))
1805 }
1806
1807 fn sign_closing_transaction(
1808 &self, channel_parameters: &ChannelTransactionParameters, closing_tx: &ClosingTransaction,
1809 secp_ctx: &Secp256k1<secp256k1::All>,
1810 ) -> Result<Signature, ()> {
1811 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1812
1813 let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
1814 let funding_pubkey = funding_key.public_key(secp_ctx);
1815 let counterparty_funding_key =
1816 &channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR).funding_pubkey;
1817 let channel_funding_redeemscript =
1818 make_funding_redeemscript(&funding_pubkey, counterparty_funding_key);
1819 Ok(closing_tx.trust().sign(
1820 &funding_key,
1821 &channel_funding_redeemscript,
1822 channel_parameters.channel_value_satoshis,
1823 secp_ctx,
1824 ))
1825 }
1826
1827 fn sign_holder_keyed_anchor_input(
1828 &self, chan_params: &ChannelTransactionParameters, anchor_tx: &Transaction, input: usize,
1829 secp_ctx: &Secp256k1<secp256k1::All>,
1830 ) -> Result<Signature, ()> {
1831 assert!(chan_params.is_populated(), "Channel parameters must be fully populated");
1832
1833 let witness_script =
1834 chan_utils::get_keyed_anchor_redeemscript(&chan_params.holder_pubkeys.funding_pubkey);
1835 let amt = Amount::from_sat(ANCHOR_OUTPUT_VALUE_SATOSHI);
1836 let sighash = sighash::SighashCache::new(&*anchor_tx)
1837 .p2wsh_signature_hash(input, &witness_script, amt, EcdsaSighashType::All)
1838 .unwrap();
1839 let funding_key = self.funding_key(chan_params.splice_parent_funding_txid);
1840 Ok(sign_with_aux_rand(secp_ctx, &hash_to_message!(&sighash[..]), &funding_key, &self))
1841 }
1842
1843 fn sign_channel_announcement_with_funding_key(
1844 &self, channel_parameters: &ChannelTransactionParameters,
1845 msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>,
1846 ) -> Result<Signature, ()> {
1847 let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1848 let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
1849 Ok(secp_ctx.sign_ecdsa(&msghash, &funding_key))
1850 }
1851
1852 fn sign_splice_shared_input(
1853 &self, channel_parameters: &ChannelTransactionParameters, tx: &Transaction,
1854 input_index: usize, secp_ctx: &Secp256k1<secp256k1::All>,
1855 ) -> Signature {
1856 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1857 assert_eq!(
1858 tx.input[input_index].previous_output,
1859 channel_parameters
1860 .funding_outpoint
1861 .as_ref()
1862 .expect("Funding outpoint must be known prior to signing")
1863 .into_bitcoin_outpoint()
1864 );
1865
1866 let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
1867 let funding_pubkey = funding_key.public_key(secp_ctx);
1868 let counterparty_funding_key =
1869 &channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR).funding_pubkey;
1870 let funding_redeemscript =
1871 make_funding_redeemscript(&funding_pubkey, counterparty_funding_key);
1872 let sighash = &sighash::SighashCache::new(tx)
1873 .p2wsh_signature_hash(
1874 input_index,
1875 &funding_redeemscript,
1876 Amount::from_sat(channel_parameters.channel_value_satoshis),
1877 EcdsaSighashType::All,
1878 )
1879 .unwrap()[..];
1880 let msg = hash_to_message!(sighash);
1881 sign(secp_ctx, &msg, &funding_key)
1882 }
1883}
1884
1885#[cfg(taproot)]
1886#[allow(unused)]
1887impl TaprootChannelSigner for InMemorySigner {
1888 fn generate_local_nonce_pair(
1889 &self, commitment_number: u64, secp_ctx: &Secp256k1<All>,
1890 ) -> PublicNonce {
1891 todo!()
1892 }
1893
1894 fn partially_sign_counterparty_commitment(
1895 &self, counterparty_nonce: PublicNonce, commitment_tx: &CommitmentTransaction,
1896 inbound_htlc_preimages: Vec<PaymentPreimage>,
1897 outbound_htlc_preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<All>,
1898 ) -> Result<(PartialSignatureWithNonce, Vec<schnorr::Signature>), ()> {
1899 todo!()
1900 }
1901
1902 fn finalize_holder_commitment(
1903 &self, commitment_tx: &HolderCommitmentTransaction,
1904 counterparty_partial_signature: PartialSignatureWithNonce, secp_ctx: &Secp256k1<All>,
1905 ) -> Result<PartialSignature, ()> {
1906 todo!()
1907 }
1908
1909 fn sign_justice_revoked_output(
1910 &self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
1911 secp_ctx: &Secp256k1<All>,
1912 ) -> Result<schnorr::Signature, ()> {
1913 todo!()
1914 }
1915
1916 fn sign_justice_revoked_htlc(
1917 &self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
1918 htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<All>,
1919 ) -> Result<schnorr::Signature, ()> {
1920 todo!()
1921 }
1922
1923 fn sign_holder_htlc_transaction(
1924 &self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
1925 secp_ctx: &Secp256k1<All>,
1926 ) -> Result<schnorr::Signature, ()> {
1927 todo!()
1928 }
1929
1930 fn sign_counterparty_htlc_transaction(
1931 &self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey,
1932 htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<All>,
1933 ) -> Result<schnorr::Signature, ()> {
1934 todo!()
1935 }
1936
1937 fn partially_sign_closing_transaction(
1938 &self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<All>,
1939 ) -> Result<PartialSignature, ()> {
1940 todo!()
1941 }
1942}
1943
1944pub struct KeysManager {
1958 secp_ctx: Secp256k1<secp256k1::All>,
1959 node_secret: SecretKey,
1960 node_id: PublicKey,
1961 inbound_payment_key: ExpandedKey,
1962 destination_script: ScriptBuf,
1963 shutdown_pubkey: PublicKey,
1964 channel_master_key: Xpriv,
1965 static_payment_key: Xpriv,
1966 v2_remote_key_derivation: bool,
1967 channel_child_index: AtomicUsize,
1968 peer_storage_key: PeerStorageKey,
1969 receive_auth_key: ReceiveAuthKey,
1970
1971 #[cfg(test)]
1972 pub(crate) entropy_source: RandomBytes,
1973 #[cfg(not(test))]
1974 entropy_source: RandomBytes,
1975
1976 seed: [u8; 32],
1977 starting_time_secs: u64,
1978 starting_time_nanos: u32,
1979}
1980
1981impl KeysManager {
1982 pub fn new(
2005 seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32,
2006 v2_remote_key_derivation: bool,
2007 ) -> Self {
2008 const NODE_SECRET_INDEX: ChildNumber = ChildNumber::Hardened { index: 0 };
2010 const DESTINATION_SCRIPT_INDEX: ChildNumber = ChildNumber::Hardened { index: 1 };
2011 const SHUTDOWN_PUBKEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 2 };
2012 const CHANNEL_MASTER_KEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 3 };
2013 const INBOUND_PAYMENT_KEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 5 };
2014 const PEER_STORAGE_KEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 6 };
2015 const RECEIVE_AUTH_KEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 7 };
2016 const STATIC_PAYMENT_KEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 8 };
2017
2018 let secp_ctx = Secp256k1::new();
2019 match Xpriv::new_master(Network::Testnet, seed) {
2021 Ok(master_key) => {
2022 let node_secret = master_key
2023 .derive_priv(&secp_ctx, &NODE_SECRET_INDEX)
2024 .expect("Your RNG is busted")
2025 .private_key;
2026 let node_id = PublicKey::from_secret_key(&secp_ctx, &node_secret);
2027 let destination_script =
2028 match master_key.derive_priv(&secp_ctx, &DESTINATION_SCRIPT_INDEX) {
2029 Ok(destination_key) => {
2030 let wpubkey_hash = WPubkeyHash::hash(
2031 &Xpub::from_priv(&secp_ctx, &destination_key).to_pub().to_bytes(),
2032 );
2033 Builder::new()
2034 .push_opcode(opcodes::all::OP_PUSHBYTES_0)
2035 .push_slice(&wpubkey_hash.to_byte_array())
2036 .into_script()
2037 },
2038 Err(_) => panic!("Your RNG is busted"),
2039 };
2040 let shutdown_pubkey =
2041 match master_key.derive_priv(&secp_ctx, &SHUTDOWN_PUBKEY_INDEX) {
2042 Ok(shutdown_key) => Xpub::from_priv(&secp_ctx, &shutdown_key).public_key,
2043 Err(_) => panic!("Your RNG is busted"),
2044 };
2045 let channel_master_key = master_key
2046 .derive_priv(&secp_ctx, &CHANNEL_MASTER_KEY_INDEX)
2047 .expect("Your RNG is busted");
2048 let inbound_payment_key: SecretKey = master_key
2049 .derive_priv(&secp_ctx, &INBOUND_PAYMENT_KEY_INDEX)
2050 .expect("Your RNG is busted")
2051 .private_key;
2052 let mut inbound_pmt_key_bytes = [0; 32];
2053 inbound_pmt_key_bytes.copy_from_slice(&inbound_payment_key[..]);
2054 let peer_storage_key = master_key
2055 .derive_priv(&secp_ctx, &PEER_STORAGE_KEY_INDEX)
2056 .expect("Your RNG is busted")
2057 .private_key;
2058
2059 let receive_auth_key = master_key
2060 .derive_priv(&secp_ctx, &RECEIVE_AUTH_KEY_INDEX)
2061 .expect("Your RNG is busted")
2062 .private_key;
2063
2064 let static_payment_key = master_key
2065 .derive_priv(&secp_ctx, &STATIC_PAYMENT_KEY_INDEX)
2066 .expect("Your RNG is busted");
2067
2068 let mut rand_bytes_engine = Sha256::engine();
2069 rand_bytes_engine.input(&starting_time_secs.to_be_bytes());
2070 rand_bytes_engine.input(&starting_time_nanos.to_be_bytes());
2071 rand_bytes_engine.input(seed);
2072 rand_bytes_engine.input(b"LDK PRNG Seed");
2073 let rand_bytes_unique_start =
2074 Sha256::from_engine(rand_bytes_engine).to_byte_array();
2075
2076 let mut res = KeysManager {
2077 secp_ctx,
2078 node_secret,
2079 node_id,
2080 inbound_payment_key: ExpandedKey::new(inbound_pmt_key_bytes),
2081
2082 peer_storage_key: PeerStorageKey { inner: peer_storage_key.secret_bytes() },
2083 receive_auth_key: ReceiveAuthKey(receive_auth_key.secret_bytes()),
2084
2085 destination_script,
2086 shutdown_pubkey,
2087
2088 channel_master_key,
2089 channel_child_index: AtomicUsize::new(0),
2090
2091 static_payment_key,
2092 v2_remote_key_derivation,
2093
2094 entropy_source: RandomBytes::new(rand_bytes_unique_start),
2095
2096 seed: *seed,
2097 starting_time_secs,
2098 starting_time_nanos,
2099 };
2100 let secp_seed = res.get_secure_random_bytes();
2101 res.secp_ctx.seeded_randomize(&secp_seed);
2102 res
2103 },
2104 Err(_) => panic!("Your rng is busted"),
2105 }
2106 }
2107
2108 pub fn get_node_secret_key(&self) -> SecretKey {
2110 self.node_secret
2111 }
2112
2113 pub fn possible_v2_counterparty_closed_balance_spks<C: Signing>(
2125 &self, secp_ctx: &Secp256k1<C>,
2126 ) -> Vec<ScriptBuf> {
2127 let mut res = Vec::with_capacity(usize::from(STATIC_PAYMENT_KEY_COUNT) * 2);
2128 let static_remote_key_features = ChannelTypeFeatures::only_static_remote_key();
2129 let mut zero_fee_htlc_features = ChannelTypeFeatures::only_static_remote_key();
2130 zero_fee_htlc_features.set_anchors_zero_fee_htlc_tx_required();
2131 for idx in 0..STATIC_PAYMENT_KEY_COUNT {
2132 let key = self
2133 .static_payment_key
2134 .derive_priv(
2135 &self.secp_ctx,
2136 &ChildNumber::from_hardened_idx(u32::from(idx)).expect("key space exhausted"),
2137 )
2138 .expect("Your RNG is busted")
2139 .private_key;
2140 let pubkey = PublicKey::from_secret_key(secp_ctx, &key);
2141 res.push(get_countersigner_payment_script(&static_remote_key_features, &pubkey));
2142 res.push(get_countersigner_payment_script(&zero_fee_htlc_features, &pubkey));
2143 }
2144 res
2145 }
2146
2147 fn derive_payment_key_v2(&self, key_idx: u64) -> SecretKey {
2148 let idx = key_idx % u64::from(STATIC_PAYMENT_KEY_COUNT);
2149 self.static_payment_key
2150 .derive_priv(
2151 &self.secp_ctx,
2152 &ChildNumber::from_hardened_idx(idx as u32).expect("key space exhausted"),
2153 )
2154 .expect("Your RNG is busted")
2155 .private_key
2156 }
2157
2158 pub fn derive_channel_keys(&self, params: &[u8; 32]) -> InMemorySigner {
2160 let chan_id = u64::from_be_bytes(params[0..8].try_into().unwrap());
2161 let mut unique_start = Sha256::engine();
2162 unique_start.input(params);
2163 unique_start.input(&self.seed);
2164
2165 let child_privkey = self
2169 .channel_master_key
2170 .derive_priv(
2171 &self.secp_ctx,
2172 &ChildNumber::from_hardened_idx((chan_id as u32) % (1 << 31))
2173 .expect("key space exhausted"),
2174 )
2175 .expect("Your RNG is busted");
2176 unique_start.input(&child_privkey.private_key[..]);
2177
2178 let seed = Sha256::from_engine(unique_start).to_byte_array();
2179
2180 let commitment_seed = {
2181 let mut sha = Sha256::engine();
2182 sha.input(&seed);
2183 sha.input(&b"commitment seed"[..]);
2184 Sha256::from_engine(sha).to_byte_array()
2185 };
2186 macro_rules! key_step {
2187 ($info: expr, $prev_key: expr) => {{
2188 let mut sha = Sha256::engine();
2189 sha.input(&seed);
2190 sha.input(&$prev_key[..]);
2191 sha.input(&$info[..]);
2192 SecretKey::from_slice(&Sha256::from_engine(sha).to_byte_array())
2193 .expect("SHA-256 is busted")
2194 }};
2195 }
2196 let funding_key = key_step!(b"funding key", commitment_seed);
2197 let revocation_base_key = key_step!(b"revocation base key", funding_key);
2198 let payment_key_v1 = key_step!(b"payment key", revocation_base_key);
2199 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key_v1);
2200 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
2201 let prng_seed = self.get_secure_random_bytes();
2202
2203 let payment_key_v2_idx =
2204 u64::from_le_bytes(commitment_seed[..8].try_into().expect("8 bytes"));
2205
2206 InMemorySigner::new(
2207 funding_key,
2208 revocation_base_key,
2209 payment_key_v1,
2210 self.derive_payment_key_v2(payment_key_v2_idx),
2211 self.v2_remote_key_derivation,
2212 delayed_payment_base_key,
2213 htlc_base_key,
2214 commitment_seed,
2215 params.clone(),
2216 prng_seed,
2217 )
2218 }
2219
2220 pub fn sign_spendable_outputs_psbt<C: Signing>(
2229 &self, descriptors: &[&SpendableOutputDescriptor], mut psbt: Psbt, secp_ctx: &Secp256k1<C>,
2230 ) -> Result<Psbt, ()> {
2231 let mut keys_cache: Option<(InMemorySigner, [u8; 32])> = None;
2232 for outp in descriptors {
2233 let get_input_idx = |outpoint: &OutPoint| {
2234 psbt.unsigned_tx
2235 .input
2236 .iter()
2237 .position(|i| i.previous_output == outpoint.into_bitcoin_outpoint())
2238 .ok_or(())
2239 };
2240 match outp {
2241 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
2242 let input_idx = get_input_idx(&descriptor.outpoint)?;
2243 if keys_cache.is_none()
2244 || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id
2245 {
2246 let signer = self.derive_channel_keys(&descriptor.channel_keys_id);
2247 keys_cache = Some((signer, descriptor.channel_keys_id));
2248 }
2249 #[cfg(test)]
2250 if self.v2_remote_key_derivation {
2251 let possible_spks =
2255 self.possible_v2_counterparty_closed_balance_spks(secp_ctx);
2256 assert!(possible_spks.contains(&descriptor.output.script_pubkey));
2257 }
2258 let witness = keys_cache.as_ref().unwrap().0.sign_counterparty_payment_input(
2259 &psbt.unsigned_tx,
2260 input_idx,
2261 &descriptor,
2262 &secp_ctx,
2263 )?;
2264 psbt.inputs[input_idx].final_script_witness = Some(witness);
2265 },
2266 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
2267 let input_idx = get_input_idx(&descriptor.outpoint)?;
2268 if keys_cache.is_none()
2269 || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id
2270 {
2271 keys_cache = Some((
2272 self.derive_channel_keys(&descriptor.channel_keys_id),
2273 descriptor.channel_keys_id,
2274 ));
2275 }
2276 let witness = keys_cache.as_ref().unwrap().0.sign_dynamic_p2wsh_input(
2277 &psbt.unsigned_tx,
2278 input_idx,
2279 &descriptor,
2280 &secp_ctx,
2281 )?;
2282 psbt.inputs[input_idx].final_script_witness = Some(witness);
2283 },
2284 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => {
2285 let input_idx = get_input_idx(outpoint)?;
2286 let derivation_idx =
2287 if output.script_pubkey == self.destination_script { 1 } else { 2 };
2288 let secret = {
2289 match Xpriv::new_master(Network::Testnet, &self.seed) {
2291 Ok(master_key) => {
2292 match master_key.derive_priv(
2293 &secp_ctx,
2294 &ChildNumber::from_hardened_idx(derivation_idx)
2295 .expect("key space exhausted"),
2296 ) {
2297 Ok(key) => key,
2298 Err(_) => panic!("Your RNG is busted"),
2299 }
2300 },
2301 Err(_) => panic!("Your rng is busted"),
2302 }
2303 };
2304 let pubkey = Xpub::from_priv(&secp_ctx, &secret).to_pub();
2305 if derivation_idx == 2 {
2306 assert_eq!(pubkey.0, self.shutdown_pubkey);
2307 }
2308 let witness_script =
2309 bitcoin::Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
2310 let payment_script =
2311 bitcoin::Address::p2wpkh(&pubkey, Network::Testnet).script_pubkey();
2312
2313 if payment_script != output.script_pubkey {
2314 return Err(());
2315 };
2316
2317 let sighash = hash_to_message!(
2318 &sighash::SighashCache::new(&psbt.unsigned_tx)
2319 .p2wsh_signature_hash(
2320 input_idx,
2321 &witness_script,
2322 output.value,
2323 EcdsaSighashType::All
2324 )
2325 .unwrap()[..]
2326 );
2327 let sig = sign_with_aux_rand(secp_ctx, &sighash, &secret.private_key, &self);
2328 let mut sig_ser = sig.serialize_der().to_vec();
2329 sig_ser.push(EcdsaSighashType::All as u8);
2330 let witness = Witness::from_slice(&[&sig_ser, &pubkey.0.serialize().to_vec()]);
2331 psbt.inputs[input_idx].final_script_witness = Some(witness);
2332 },
2333 }
2334 }
2335
2336 Ok(psbt)
2337 }
2338}
2339
2340impl EntropySource for KeysManager {
2341 fn get_secure_random_bytes(&self) -> [u8; 32] {
2342 self.entropy_source.get_secure_random_bytes()
2343 }
2344}
2345
2346impl NodeSigner for KeysManager {
2347 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
2348 match recipient {
2349 Recipient::Node => Ok(self.node_id.clone()),
2350 Recipient::PhantomNode => Err(()),
2351 }
2352 }
2353
2354 fn ecdh(
2355 &self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
2356 ) -> Result<SharedSecret, ()> {
2357 let mut node_secret = match recipient {
2358 Recipient::Node => Ok(self.node_secret.clone()),
2359 Recipient::PhantomNode => Err(()),
2360 }?;
2361 if let Some(tweak) = tweak {
2362 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
2363 }
2364 Ok(SharedSecret::new(other_key, &node_secret))
2365 }
2366
2367 fn get_expanded_key(&self) -> ExpandedKey {
2368 self.inbound_payment_key.clone()
2369 }
2370
2371 fn get_peer_storage_key(&self) -> PeerStorageKey {
2372 self.peer_storage_key.clone()
2373 }
2374
2375 fn get_receive_auth_key(&self) -> ReceiveAuthKey {
2376 self.receive_auth_key.clone()
2377 }
2378
2379 fn sign_invoice(
2380 &self, invoice: &RawBolt11Invoice, recipient: Recipient,
2381 ) -> Result<RecoverableSignature, ()> {
2382 let hash = invoice.signable_hash();
2383 let secret = match recipient {
2384 Recipient::Node => Ok(&self.node_secret),
2385 Recipient::PhantomNode => Err(()),
2386 }?;
2387 Ok(self.secp_ctx.sign_ecdsa_recoverable(&hash_to_message!(&hash), secret))
2388 }
2389
2390 fn sign_bolt12_invoice(
2391 &self, invoice: &UnsignedBolt12Invoice,
2392 ) -> Result<schnorr::Signature, ()> {
2393 let message = invoice.tagged_hash().as_digest();
2394 let keys = Keypair::from_secret_key(&self.secp_ctx, &self.node_secret);
2395 let aux_rand = self.get_secure_random_bytes();
2396 Ok(self.secp_ctx.sign_schnorr_with_aux_rand(message, &keys, &aux_rand))
2397 }
2398
2399 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
2400 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
2401 Ok(self.secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret))
2402 }
2403
2404 fn sign_message(&self, msg: &[u8]) -> Result<String, ()> {
2405 Ok(crate::util::message_signing::sign(msg, &self.node_secret))
2406 }
2407}
2408
2409impl OutputSpender for KeysManager {
2410 fn spend_spendable_outputs(
2420 &self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
2421 change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
2422 locktime: Option<LockTime>, secp_ctx: &Secp256k1<All>,
2423 ) -> Result<Transaction, ()> {
2424 let (mut psbt, expected_max_weight) =
2425 SpendableOutputDescriptor::create_spendable_outputs_psbt(
2426 secp_ctx,
2427 descriptors,
2428 outputs,
2429 change_destination_script,
2430 feerate_sat_per_1000_weight,
2431 locktime,
2432 )?;
2433 psbt = self.sign_spendable_outputs_psbt(descriptors, psbt, secp_ctx)?;
2434
2435 let spend_tx = psbt.extract_tx_unchecked_fee_rate();
2436
2437 debug_assert!(expected_max_weight >= spend_tx.weight().to_wu());
2438 debug_assert!(
2441 expected_max_weight <= spend_tx.weight().to_wu() + descriptors.len() as u64 * 3
2442 );
2443
2444 Ok(spend_tx)
2445 }
2446}
2447
2448impl SignerProvider for KeysManager {
2449 type EcdsaSigner = InMemorySigner;
2450 #[cfg(taproot)]
2451 type TaprootSigner = InMemorySigner;
2452
2453 fn generate_channel_keys_id(&self, _inbound: bool, user_channel_id: u128) -> [u8; 32] {
2454 let child_idx = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
2455 assert!(child_idx < core::u32::MAX as usize, "2^32 channels opened without restart");
2461 let mut id = [0; 32];
2462 id[0..4].copy_from_slice(&(child_idx as u32).to_be_bytes());
2463 id[4..8].copy_from_slice(&self.starting_time_nanos.to_be_bytes());
2464 id[8..16].copy_from_slice(&self.starting_time_secs.to_be_bytes());
2465 id[16..32].copy_from_slice(&user_channel_id.to_be_bytes());
2466 id
2467 }
2468
2469 fn derive_channel_signer(&self, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner {
2470 self.derive_channel_keys(&channel_keys_id)
2471 }
2472
2473 fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
2474 Ok(self.destination_script.clone())
2475 }
2476
2477 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
2478 Ok(ShutdownScript::new_p2wpkh_from_pubkey(self.shutdown_pubkey.clone()))
2479 }
2480}
2481
2482pub struct PhantomKeysManager {
2504 #[cfg(test)]
2505 pub(crate) inner: KeysManager,
2506 #[cfg(not(test))]
2507 inner: KeysManager,
2508 inbound_payment_key: ExpandedKey,
2509 phantom_secret: SecretKey,
2510 phantom_node_id: PublicKey,
2511}
2512
2513impl EntropySource for PhantomKeysManager {
2514 fn get_secure_random_bytes(&self) -> [u8; 32] {
2515 self.inner.get_secure_random_bytes()
2516 }
2517}
2518
2519impl NodeSigner for PhantomKeysManager {
2520 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
2521 match recipient {
2522 Recipient::Node => self.inner.get_node_id(Recipient::Node),
2523 Recipient::PhantomNode => Ok(self.phantom_node_id.clone()),
2524 }
2525 }
2526
2527 fn ecdh(
2528 &self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
2529 ) -> Result<SharedSecret, ()> {
2530 let mut node_secret = match recipient {
2531 Recipient::Node => self.inner.node_secret.clone(),
2532 Recipient::PhantomNode => self.phantom_secret.clone(),
2533 };
2534 if let Some(tweak) = tweak {
2535 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
2536 }
2537 Ok(SharedSecret::new(other_key, &node_secret))
2538 }
2539
2540 fn get_expanded_key(&self) -> ExpandedKey {
2541 self.inbound_payment_key.clone()
2542 }
2543
2544 fn get_peer_storage_key(&self) -> PeerStorageKey {
2545 self.inner.peer_storage_key.clone()
2546 }
2547
2548 fn get_receive_auth_key(&self) -> ReceiveAuthKey {
2549 self.inner.receive_auth_key.clone()
2550 }
2551
2552 fn sign_invoice(
2553 &self, invoice: &RawBolt11Invoice, recipient: Recipient,
2554 ) -> Result<RecoverableSignature, ()> {
2555 let hash = invoice.signable_hash();
2556 let secret = match recipient {
2557 Recipient::Node => &self.inner.node_secret,
2558 Recipient::PhantomNode => &self.phantom_secret,
2559 };
2560 Ok(self.inner.secp_ctx.sign_ecdsa_recoverable(&hash_to_message!(&hash), secret))
2561 }
2562
2563 fn sign_bolt12_invoice(
2564 &self, invoice: &UnsignedBolt12Invoice,
2565 ) -> Result<schnorr::Signature, ()> {
2566 self.inner.sign_bolt12_invoice(invoice)
2567 }
2568
2569 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
2570 self.inner.sign_gossip_message(msg)
2571 }
2572
2573 fn sign_message(&self, msg: &[u8]) -> Result<String, ()> {
2574 self.inner.sign_message(msg)
2575 }
2576}
2577
2578impl OutputSpender for PhantomKeysManager {
2579 fn spend_spendable_outputs(
2582 &self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
2583 change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
2584 locktime: Option<LockTime>, secp_ctx: &Secp256k1<All>,
2585 ) -> Result<Transaction, ()> {
2586 self.inner.spend_spendable_outputs(
2587 descriptors,
2588 outputs,
2589 change_destination_script,
2590 feerate_sat_per_1000_weight,
2591 locktime,
2592 secp_ctx,
2593 )
2594 }
2595}
2596
2597impl SignerProvider for PhantomKeysManager {
2598 type EcdsaSigner = InMemorySigner;
2599 #[cfg(taproot)]
2600 type TaprootSigner = InMemorySigner;
2601
2602 fn generate_channel_keys_id(&self, inbound: bool, user_channel_id: u128) -> [u8; 32] {
2603 self.inner.generate_channel_keys_id(inbound, user_channel_id)
2604 }
2605
2606 fn derive_channel_signer(&self, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner {
2607 self.inner.derive_channel_signer(channel_keys_id)
2608 }
2609
2610 fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
2611 self.inner.get_destination_script(channel_keys_id)
2612 }
2613
2614 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
2615 self.inner.get_shutdown_scriptpubkey()
2616 }
2617}
2618
2619impl PhantomKeysManager {
2620 pub fn new(
2632 seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32,
2633 cross_node_seed: &[u8; 32], v2_remote_key_derivation: bool,
2634 ) -> Self {
2635 let inner = KeysManager::new(
2636 seed,
2637 starting_time_secs,
2638 starting_time_nanos,
2639 v2_remote_key_derivation,
2640 );
2641 let (inbound_key, phantom_key) = hkdf_extract_expand_twice(
2642 b"LDK Inbound and Phantom Payment Key Expansion",
2643 cross_node_seed,
2644 );
2645 let phantom_secret = SecretKey::from_slice(&phantom_key).unwrap();
2646 let phantom_node_id = PublicKey::from_secret_key(&inner.secp_ctx, &phantom_secret);
2647 Self {
2648 inner,
2649 inbound_payment_key: ExpandedKey::new(inbound_key),
2650 phantom_secret,
2651 phantom_node_id,
2652 }
2653 }
2654
2655 pub fn derive_channel_keys(&self, params: &[u8; 32]) -> InMemorySigner {
2657 self.inner.derive_channel_keys(params)
2658 }
2659
2660 pub fn get_node_secret_key(&self) -> SecretKey {
2662 self.inner.get_node_secret_key()
2663 }
2664
2665 pub fn get_phantom_node_secret_key(&self) -> SecretKey {
2668 self.phantom_secret
2669 }
2670}
2671
2672pub struct RandomBytes {
2674 seed: [u8; 32],
2676 index: AtomicCounter,
2679}
2680
2681impl RandomBytes {
2682 pub fn new(seed: [u8; 32]) -> Self {
2684 Self { seed, index: AtomicCounter::new() }
2685 }
2686}
2687
2688impl EntropySource for RandomBytes {
2689 fn get_secure_random_bytes(&self) -> [u8; 32] {
2690 let index = self.index.next();
2691 let mut nonce = [0u8; 16];
2692 nonce[..8].copy_from_slice(&index.to_be_bytes());
2693 ChaCha20::get_single_block(&self.seed, &nonce)
2694 }
2695}
2696
2697#[test]
2699pub fn dyn_sign() {
2700 let _signer: Box<dyn EcdsaChannelSigner>;
2701}
2702
2703#[cfg(ldk_bench)]
2704pub mod benches {
2705 use crate::sign::{EntropySource, KeysManager};
2706 use bitcoin::constants::genesis_block;
2707 use bitcoin::Network;
2708 use std::sync::mpsc::TryRecvError;
2709 use std::sync::{mpsc, Arc};
2710 use std::thread;
2711 use std::time::Duration;
2712
2713 use criterion::Criterion;
2714
2715 pub fn bench_get_secure_random_bytes(bench: &mut Criterion) {
2716 let seed = [0u8; 32];
2717 let now = Duration::from_secs(genesis_block(Network::Testnet).header.time as u64);
2718 let keys_manager =
2719 Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_micros(), true));
2720
2721 let mut handles = Vec::new();
2722 let mut stops = Vec::new();
2723 for _ in 1..5 {
2724 let keys_manager_clone = Arc::clone(&keys_manager);
2725 let (stop_sender, stop_receiver) = mpsc::channel();
2726 let handle = thread::spawn(move || loop {
2727 keys_manager_clone.get_secure_random_bytes();
2728 match stop_receiver.try_recv() {
2729 Ok(_) | Err(TryRecvError::Disconnected) => {
2730 println!("Terminating.");
2731 break;
2732 },
2733 Err(TryRecvError::Empty) => {},
2734 }
2735 });
2736 handles.push(handle);
2737 stops.push(stop_sender);
2738 }
2739
2740 bench.bench_function("get_secure_random_bytes", |b| {
2741 b.iter(|| keys_manager.get_secure_random_bytes())
2742 });
2743
2744 for stop in stops {
2745 let _ = stop.send(());
2746 }
2747 for handle in handles {
2748 handle.join().unwrap();
2749 }
2750 }
2751}