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;
34#[cfg(taproot)]
35use bitcoin::secp256k1::All;
36use bitcoin::secp256k1::{Keypair, PublicKey, Scalar, Secp256k1, SecretKey, Signing};
37use bitcoin::{secp256k1, Psbt, Sequence, Txid, WPubkeyHash, Witness};
38
39use lightning_invoice::RawBolt11Invoice;
40
41use crate::chain::transaction::OutPoint;
42use crate::crypto::utils::{hkdf_extract_expand_twice, sign, sign_with_aux_rand};
43use crate::ln::chan_utils;
44use crate::ln::chan_utils::{
45 get_revokeable_redeemscript, make_funding_redeemscript, ChannelPublicKeys,
46 ChannelTransactionParameters, ClosingTransaction, CommitmentTransaction,
47 HTLCOutputInCommitment, HolderCommitmentTransaction,
48};
49use crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI;
50use crate::ln::channel_keys::{
51 add_public_key_tweak, DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, HtlcKey,
52 RevocationBasepoint, RevocationKey,
53};
54use crate::ln::inbound_payment::ExpandedKey;
55#[cfg(taproot)]
56use crate::ln::msgs::PartialSignatureWithNonce;
57use crate::ln::msgs::{UnsignedChannelAnnouncement, UnsignedGossipMessage};
58use crate::ln::script::ShutdownScript;
59use crate::offers::invoice::UnsignedBolt12Invoice;
60use crate::types::payment::PaymentPreimage;
61use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer};
62use crate::util::transaction_utils;
63
64use crate::crypto::chacha20::ChaCha20;
65use crate::io::{self, Error};
66use crate::ln::msgs::DecodeError;
67use crate::prelude::*;
68use crate::sign::ecdsa::EcdsaChannelSigner;
69#[cfg(taproot)]
70use crate::sign::taproot::TaprootChannelSigner;
71use crate::types::features::ChannelTypeFeatures;
72use crate::util::atomic_counter::AtomicCounter;
73use core::convert::TryInto;
74use core::ops::Deref;
75use core::sync::atomic::{AtomicUsize, Ordering};
76#[cfg(taproot)]
77use musig2::types::{PartialSignature, PublicNonce};
78
79pub(crate) mod type_resolver;
80
81pub mod ecdsa;
82#[cfg(taproot)]
83pub mod taproot;
84
85#[derive(Clone, Debug, Hash, PartialEq, Eq)]
89pub struct DelayedPaymentOutputDescriptor {
90 pub outpoint: OutPoint,
92 pub per_commitment_point: PublicKey,
94 pub to_self_delay: u16,
97 pub output: TxOut,
99 pub revocation_pubkey: RevocationKey,
102 pub channel_keys_id: [u8; 32],
105 pub channel_value_satoshis: u64,
107 pub channel_transaction_parameters: Option<ChannelTransactionParameters>,
112}
113
114impl DelayedPaymentOutputDescriptor {
115 pub const MAX_WITNESS_LENGTH: u64 =
121 1 + 73 + 1 + chan_utils::REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH as u64 + 1;
122}
123
124impl_writeable_tlv_based!(DelayedPaymentOutputDescriptor, {
125 (0, outpoint, required),
126 (2, per_commitment_point, required),
127 (4, to_self_delay, required),
128 (6, output, required),
129 (8, revocation_pubkey, required),
130 (10, channel_keys_id, required),
131 (12, channel_value_satoshis, required),
132 (13, channel_transaction_parameters, option),
133});
134
135pub(crate) const P2WPKH_WITNESS_WEIGHT: u64 = 1 +
136 1 +
137 73 +
138 1 +
139 33 ;
140
141pub(crate) const P2TR_KEY_PATH_WITNESS_WEIGHT: u64 = 1 + 1 + 64 ;
144
145#[derive(Clone, Debug, Hash, PartialEq, Eq)]
149pub struct StaticPaymentOutputDescriptor {
150 pub outpoint: OutPoint,
152 pub output: TxOut,
154 pub channel_keys_id: [u8; 32],
157 pub channel_value_satoshis: u64,
159 pub channel_transaction_parameters: Option<ChannelTransactionParameters>,
164}
165
166impl StaticPaymentOutputDescriptor {
167 pub fn witness_script(&self) -> Option<ScriptBuf> {
172 self.channel_transaction_parameters.as_ref().and_then(|channel_params| {
173 if channel_params.supports_anchors() {
174 let payment_point = channel_params.holder_pubkeys.payment_point;
175 Some(chan_utils::get_to_countersignatory_with_anchors_redeemscript(&payment_point))
176 } else {
177 None
178 }
179 })
180 }
181
182 pub fn max_witness_length(&self) -> u64 {
186 if self.channel_transaction_parameters.as_ref().map_or(false, |p| p.supports_anchors()) {
187 let witness_script_weight = 1 + 33 +
188 1 + 1 + 1 ;
189 1 + 1 + 73 +
190 1 + witness_script_weight
191 } else {
192 P2WPKH_WITNESS_WEIGHT
193 }
194 }
195}
196impl_writeable_tlv_based!(StaticPaymentOutputDescriptor, {
197 (0, outpoint, required),
198 (2, output, required),
199 (4, channel_keys_id, required),
200 (6, channel_value_satoshis, required),
201 (7, channel_transaction_parameters, option),
202});
203
204#[derive(Clone, Debug, Hash, PartialEq, Eq)]
214pub enum SpendableOutputDescriptor {
215 StaticOutput {
224 outpoint: OutPoint,
226 output: TxOut,
228 channel_keys_id: Option<[u8; 32]>,
237 },
238 DelayedPaymentOutput(DelayedPaymentOutputDescriptor),
277 StaticPaymentOutput(StaticPaymentOutputDescriptor),
295}
296
297impl_writeable_tlv_based_enum_legacy!(SpendableOutputDescriptor,
298 (0, StaticOutput) => {
299 (0, outpoint, required),
300 (1, channel_keys_id, option),
301 (2, output, required),
302 },
303;
304 (1, DelayedPaymentOutput),
305 (2, StaticPaymentOutput),
306);
307
308impl SpendableOutputDescriptor {
309 pub fn to_psbt_input<T: secp256k1::Signing>(
348 &self, secp_ctx: &Secp256k1<T>,
349 ) -> bitcoin::psbt::Input {
350 match self {
351 SpendableOutputDescriptor::StaticOutput { output, .. } => {
352 bitcoin::psbt::Input { witness_utxo: Some(output.clone()), ..Default::default() }
354 },
355 SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
356 channel_transaction_parameters,
357 per_commitment_point,
358 revocation_pubkey,
359 to_self_delay,
360 output,
361 ..
362 }) => {
363 let delayed_payment_basepoint = channel_transaction_parameters
364 .as_ref()
365 .map(|params| params.holder_pubkeys.delayed_payment_basepoint);
366
367 let (witness_script, add_tweak) =
368 if let Some(basepoint) = delayed_payment_basepoint.as_ref() {
369 let add_tweak = basepoint.derive_add_tweak(&per_commitment_point);
371 let payment_key = DelayedPaymentKey(add_public_key_tweak(
372 secp_ctx,
373 &basepoint.to_public_key(),
374 &add_tweak,
375 ));
376
377 (
378 Some(get_revokeable_redeemscript(
379 &revocation_pubkey,
380 *to_self_delay,
381 &payment_key,
382 )),
383 Some(add_tweak),
384 )
385 } else {
386 (None, None)
387 };
388
389 bitcoin::psbt::Input {
390 witness_utxo: Some(output.clone()),
391 witness_script,
392 proprietary: add_tweak
393 .map(|add_tweak| {
394 [(
395 bitcoin::psbt::raw::ProprietaryKey {
396 prefix: "LDK_spendable_output".as_bytes().to_vec(),
399 subtype: 0,
400 key: "add_tweak".as_bytes().to_vec(),
401 },
402 add_tweak.as_byte_array().to_vec(),
403 )]
404 .into_iter()
405 .collect()
406 })
407 .unwrap_or_default(),
408 ..Default::default()
409 }
410 },
411 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => bitcoin::psbt::Input {
412 witness_utxo: Some(descriptor.output.clone()),
413 witness_script: descriptor.witness_script(),
414 ..Default::default()
415 },
416 }
417 }
418
419 pub fn create_spendable_outputs_psbt<T: secp256k1::Signing>(
436 secp_ctx: &Secp256k1<T>, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
437 change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
438 locktime: Option<LockTime>,
439 ) -> Result<(Psbt, u64), ()> {
440 let mut input = Vec::with_capacity(descriptors.len());
441 let mut input_value = Amount::ZERO;
442 let mut witness_weight = 0;
443 let mut output_set = hash_set_with_capacity(descriptors.len());
444 for outp in descriptors {
445 match outp {
446 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
447 if !output_set.insert(descriptor.outpoint) {
448 return Err(());
449 }
450 let sequence = if descriptor
451 .channel_transaction_parameters
452 .as_ref()
453 .map_or(false, |p| p.supports_anchors())
454 {
455 Sequence::from_consensus(1)
456 } else {
457 Sequence::ZERO
458 };
459 input.push(TxIn {
460 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
461 script_sig: ScriptBuf::new(),
462 sequence,
463 witness: Witness::new(),
464 });
465 witness_weight += descriptor.max_witness_length();
466 #[cfg(feature = "grind_signatures")]
467 {
468 witness_weight -= 1;
470 }
471 input_value += descriptor.output.value;
472 },
473 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
474 if !output_set.insert(descriptor.outpoint) {
475 return Err(());
476 }
477 input.push(TxIn {
478 previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
479 script_sig: ScriptBuf::new(),
480 sequence: Sequence(descriptor.to_self_delay as u32),
481 witness: Witness::new(),
482 });
483 witness_weight += DelayedPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
484 #[cfg(feature = "grind_signatures")]
485 {
486 witness_weight -= 1;
488 }
489 input_value += descriptor.output.value;
490 },
491 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => {
492 if !output_set.insert(*outpoint) {
493 return Err(());
494 }
495 input.push(TxIn {
496 previous_output: outpoint.into_bitcoin_outpoint(),
497 script_sig: ScriptBuf::new(),
498 sequence: Sequence::ZERO,
499 witness: Witness::new(),
500 });
501 witness_weight += 1 + 73 + 34;
502 #[cfg(feature = "grind_signatures")]
503 {
504 witness_weight -= 1;
506 }
507 input_value += output.value;
508 },
509 }
510 if input_value > Amount::MAX_MONEY {
511 return Err(());
512 }
513 }
514 let mut tx = Transaction {
515 version: Version::TWO,
516 lock_time: locktime.unwrap_or(LockTime::ZERO),
517 input,
518 output: outputs,
519 };
520 let expected_max_weight = transaction_utils::maybe_add_change_output(
521 &mut tx,
522 input_value,
523 witness_weight,
524 feerate_sat_per_1000_weight,
525 change_destination_script,
526 )?;
527
528 let psbt_inputs =
529 descriptors.iter().map(|d| d.to_psbt_input(&secp_ctx)).collect::<Vec<_>>();
530 let psbt = Psbt {
531 inputs: psbt_inputs,
532 outputs: vec![Default::default(); tx.output.len()],
533 unsigned_tx: tx,
534 xpub: Default::default(),
535 version: 0,
536 proprietary: Default::default(),
537 unknown: Default::default(),
538 };
539 Ok((psbt, expected_max_weight))
540 }
541
542 pub fn outpoint(&self) -> OutPoint {
544 match self {
545 Self::StaticOutput { outpoint, .. } => *outpoint,
546 Self::StaticPaymentOutput(descriptor) => descriptor.outpoint,
547 Self::DelayedPaymentOutput(descriptor) => descriptor.outpoint,
548 }
549 }
550}
551
552#[derive(Clone, Debug, PartialEq, Eq)]
554pub struct ChannelDerivationParameters {
555 pub value_satoshis: u64,
557 pub keys_id: [u8; 32],
559 pub transaction_parameters: ChannelTransactionParameters,
562}
563
564impl_writeable_tlv_based!(ChannelDerivationParameters, {
565 (0, value_satoshis, required),
566 (2, keys_id, required),
567 (4, transaction_parameters, required),
568});
569
570#[derive(Clone, Debug, PartialEq, Eq)]
572pub struct HTLCDescriptor {
573 pub channel_derivation_parameters: ChannelDerivationParameters,
575 pub commitment_txid: Txid,
577 pub per_commitment_number: u64,
579 pub per_commitment_point: PublicKey,
585 pub feerate_per_kw: u32,
589 pub htlc: HTLCOutputInCommitment,
591 pub preimage: Option<PaymentPreimage>,
594 pub counterparty_sig: Signature,
596}
597
598impl_writeable_tlv_based!(HTLCDescriptor, {
599 (0, channel_derivation_parameters, required),
600 (1, feerate_per_kw, (default_value, 0)),
601 (2, commitment_txid, required),
602 (4, per_commitment_number, required),
603 (6, per_commitment_point, required),
604 (8, htlc, required),
605 (10, preimage, option),
606 (12, counterparty_sig, required),
607});
608
609impl HTLCDescriptor {
610 pub fn outpoint(&self) -> bitcoin::OutPoint {
613 bitcoin::OutPoint {
614 txid: self.commitment_txid,
615 vout: self.htlc.transaction_output_index.unwrap(),
616 }
617 }
618
619 pub fn previous_utxo<C: secp256k1::Signing + secp256k1::Verification>(
622 &self, secp: &Secp256k1<C>,
623 ) -> TxOut {
624 TxOut {
625 script_pubkey: self.witness_script(secp).to_p2wsh(),
626 value: self.htlc.to_bitcoin_amount(),
627 }
628 }
629
630 pub fn unsigned_tx_input(&self) -> TxIn {
633 chan_utils::build_htlc_input(
634 &self.commitment_txid,
635 &self.htlc,
636 &self.channel_derivation_parameters.transaction_parameters.channel_type_features,
637 )
638 }
639
640 pub fn tx_output<C: secp256k1::Signing + secp256k1::Verification>(
643 &self, secp: &Secp256k1<C>,
644 ) -> TxOut {
645 let channel_params =
646 self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
647 let broadcaster_keys = channel_params.broadcaster_pubkeys();
648 let counterparty_keys = channel_params.countersignatory_pubkeys();
649 let broadcaster_delayed_key = DelayedPaymentKey::from_basepoint(
650 secp,
651 &broadcaster_keys.delayed_payment_basepoint,
652 &self.per_commitment_point,
653 );
654 let counterparty_revocation_key = &RevocationKey::from_basepoint(
655 &secp,
656 &counterparty_keys.revocation_basepoint,
657 &self.per_commitment_point,
658 );
659 chan_utils::build_htlc_output(
660 self.feerate_per_kw,
661 channel_params.contest_delay(),
662 &self.htlc,
663 channel_params.channel_type_features(),
664 &broadcaster_delayed_key,
665 &counterparty_revocation_key,
666 )
667 }
668
669 pub fn witness_script<C: secp256k1::Signing + secp256k1::Verification>(
671 &self, secp: &Secp256k1<C>,
672 ) -> ScriptBuf {
673 let channel_params =
674 self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
675 let broadcaster_keys = channel_params.broadcaster_pubkeys();
676 let counterparty_keys = channel_params.countersignatory_pubkeys();
677 let broadcaster_htlc_key = HtlcKey::from_basepoint(
678 secp,
679 &broadcaster_keys.htlc_basepoint,
680 &self.per_commitment_point,
681 );
682 let counterparty_htlc_key = HtlcKey::from_basepoint(
683 secp,
684 &counterparty_keys.htlc_basepoint,
685 &self.per_commitment_point,
686 );
687 let counterparty_revocation_key = &RevocationKey::from_basepoint(
688 &secp,
689 &counterparty_keys.revocation_basepoint,
690 &self.per_commitment_point,
691 );
692 chan_utils::get_htlc_redeemscript_with_explicit_keys(
693 &self.htlc,
694 channel_params.channel_type_features(),
695 &broadcaster_htlc_key,
696 &counterparty_htlc_key,
697 &counterparty_revocation_key,
698 )
699 }
700
701 pub fn tx_input_witness(&self, signature: &Signature, witness_script: &Script) -> Witness {
704 chan_utils::build_htlc_input_witness(
705 signature,
706 &self.counterparty_sig,
707 &self.preimage,
708 witness_script,
709 &self.channel_derivation_parameters.transaction_parameters.channel_type_features,
710 )
711 }
712
713 pub fn derive_channel_signer<S: EcdsaChannelSigner, SP: Deref>(&self, signer_provider: &SP) -> S
715 where
716 SP::Target: SignerProvider<EcdsaSigner = S>,
717 {
718 let mut signer = signer_provider.derive_channel_signer(
719 self.channel_derivation_parameters.value_satoshis,
720 self.channel_derivation_parameters.keys_id,
721 );
722 signer
723 .provide_channel_parameters(&self.channel_derivation_parameters.transaction_parameters);
724 signer
725 }
726}
727
728pub trait ChannelSigner {
738 fn get_per_commitment_point(
746 &self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>,
747 ) -> Result<PublicKey, ()>;
748
749 fn release_commitment_secret(&self, idx: u64) -> Result<[u8; 32], ()>;
764
765 fn validate_holder_commitment(
783 &self, holder_tx: &HolderCommitmentTransaction,
784 outbound_htlc_preimages: Vec<PaymentPreimage>,
785 ) -> Result<(), ()>;
786
787 fn validate_counterparty_revocation(&self, idx: u64, secret: &SecretKey) -> Result<(), ()>;
796
797 fn pubkeys(&self) -> &ChannelPublicKeys;
801
802 fn channel_keys_id(&self) -> [u8; 32];
808
809 fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters);
819}
820
821pub enum Recipient {
826 Node,
828 PhantomNode,
833}
834
835pub trait EntropySource {
837 fn get_secure_random_bytes(&self) -> [u8; 32];
840}
841
842pub trait NodeSigner {
844 fn get_inbound_payment_key(&self) -> ExpandedKey;
857
858 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()>;
865
866 fn ecdh(
875 &self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
876 ) -> Result<SharedSecret, ()>;
877
878 fn sign_invoice(
890 &self, invoice: &RawBolt11Invoice, recipient: Recipient,
891 ) -> Result<RecoverableSignature, ()>;
892
893 fn sign_bolt12_invoice(
905 &self, invoice: &UnsignedBolt12Invoice,
906 ) -> Result<schnorr::Signature, ()>;
907
908 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()>;
915}
916
917pub trait OutputSpender {
920 fn spend_spendable_outputs<C: Signing>(
933 &self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
934 change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
935 locktime: Option<LockTime>, secp_ctx: &Secp256k1<C>,
936 ) -> Result<Transaction, ()>;
937}
938
939#[cfg(taproot)]
944#[doc(hidden)]
945#[deprecated(note = "Remove once taproot cfg is removed")]
946pub type DynSignerProvider =
947 dyn SignerProvider<EcdsaSigner = InMemorySigner, TaprootSigner = InMemorySigner>;
948
949#[cfg(not(taproot))]
953#[doc(hidden)]
954#[deprecated(note = "Remove once taproot cfg is removed")]
955pub type DynSignerProvider = dyn SignerProvider<EcdsaSigner = InMemorySigner>;
956
957pub trait SignerProvider {
959 type EcdsaSigner: EcdsaChannelSigner;
961 #[cfg(taproot)]
962 type TaprootSigner: TaprootChannelSigner;
964
965 fn generate_channel_keys_id(
972 &self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128,
973 ) -> [u8; 32];
974
975 fn derive_channel_signer(
982 &self, channel_value_satoshis: u64, channel_keys_id: [u8; 32],
983 ) -> Self::EcdsaSigner;
984
985 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError>;
999
1000 fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()>;
1008
1009 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()>;
1018}
1019
1020pub trait ChangeDestinationSource {
1023 fn get_change_destination_script(&self) -> Result<ScriptBuf, ()>;
1029}
1030
1031pub struct InMemorySigner {
1036 pub funding_key: SecretKey,
1039 pub revocation_base_key: SecretKey,
1041 pub payment_key: SecretKey,
1043 pub delayed_payment_base_key: SecretKey,
1045 pub htlc_base_key: SecretKey,
1047 pub commitment_seed: [u8; 32],
1049 pub(crate) holder_channel_pubkeys: ChannelPublicKeys,
1051 channel_parameters: Option<ChannelTransactionParameters>,
1053 channel_value_satoshis: u64,
1055 channel_keys_id: [u8; 32],
1057 entropy_source: RandomBytes,
1059}
1060
1061impl PartialEq for InMemorySigner {
1062 fn eq(&self, other: &Self) -> bool {
1063 self.funding_key == other.funding_key
1064 && self.revocation_base_key == other.revocation_base_key
1065 && self.payment_key == other.payment_key
1066 && self.delayed_payment_base_key == other.delayed_payment_base_key
1067 && self.htlc_base_key == other.htlc_base_key
1068 && self.commitment_seed == other.commitment_seed
1069 && self.holder_channel_pubkeys == other.holder_channel_pubkeys
1070 && self.channel_parameters == other.channel_parameters
1071 && self.channel_value_satoshis == other.channel_value_satoshis
1072 && self.channel_keys_id == other.channel_keys_id
1073 }
1074}
1075
1076impl Clone for InMemorySigner {
1077 fn clone(&self) -> Self {
1078 Self {
1079 funding_key: self.funding_key.clone(),
1080 revocation_base_key: self.revocation_base_key.clone(),
1081 payment_key: self.payment_key.clone(),
1082 delayed_payment_base_key: self.delayed_payment_base_key.clone(),
1083 htlc_base_key: self.htlc_base_key.clone(),
1084 commitment_seed: self.commitment_seed.clone(),
1085 holder_channel_pubkeys: self.holder_channel_pubkeys.clone(),
1086 channel_parameters: self.channel_parameters.clone(),
1087 channel_value_satoshis: self.channel_value_satoshis,
1088 channel_keys_id: self.channel_keys_id,
1089 entropy_source: RandomBytes::new(self.get_secure_random_bytes()),
1090 }
1091 }
1092}
1093
1094impl InMemorySigner {
1095 pub fn new<C: Signing>(
1097 secp_ctx: &Secp256k1<C>, funding_key: SecretKey, revocation_base_key: SecretKey,
1098 payment_key: SecretKey, delayed_payment_base_key: SecretKey, htlc_base_key: SecretKey,
1099 commitment_seed: [u8; 32], channel_value_satoshis: u64, channel_keys_id: [u8; 32],
1100 rand_bytes_unique_start: [u8; 32],
1101 ) -> InMemorySigner {
1102 let holder_channel_pubkeys = InMemorySigner::make_holder_keys(
1103 secp_ctx,
1104 &funding_key,
1105 &revocation_base_key,
1106 &payment_key,
1107 &delayed_payment_base_key,
1108 &htlc_base_key,
1109 );
1110 InMemorySigner {
1111 funding_key,
1112 revocation_base_key,
1113 payment_key,
1114 delayed_payment_base_key,
1115 htlc_base_key,
1116 commitment_seed,
1117 channel_value_satoshis,
1118 holder_channel_pubkeys,
1119 channel_parameters: None,
1120 channel_keys_id,
1121 entropy_source: RandomBytes::new(rand_bytes_unique_start),
1122 }
1123 }
1124
1125 fn make_holder_keys<C: Signing>(
1126 secp_ctx: &Secp256k1<C>, funding_key: &SecretKey, revocation_base_key: &SecretKey,
1127 payment_key: &SecretKey, delayed_payment_base_key: &SecretKey, htlc_base_key: &SecretKey,
1128 ) -> ChannelPublicKeys {
1129 let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
1130 ChannelPublicKeys {
1131 funding_pubkey: from_secret(&funding_key),
1132 revocation_basepoint: RevocationBasepoint::from(from_secret(&revocation_base_key)),
1133 payment_point: from_secret(&payment_key),
1134 delayed_payment_basepoint: DelayedPaymentBasepoint::from(from_secret(
1135 &delayed_payment_base_key,
1136 )),
1137 htlc_basepoint: HtlcBasepoint::from(from_secret(&htlc_base_key)),
1138 }
1139 }
1140
1141 pub fn counterparty_pubkeys(&self) -> Option<&ChannelPublicKeys> {
1146 self.get_channel_parameters().and_then(|params| {
1147 params.counterparty_parameters.as_ref().map(|params| ¶ms.pubkeys)
1148 })
1149 }
1150
1151 pub fn counterparty_selected_contest_delay(&self) -> Option<u16> {
1158 self.get_channel_parameters().and_then(|params| {
1159 params.counterparty_parameters.as_ref().map(|params| params.selected_contest_delay)
1160 })
1161 }
1162
1163 pub fn holder_selected_contest_delay(&self) -> Option<u16> {
1170 self.get_channel_parameters().map(|params| params.holder_selected_contest_delay)
1171 }
1172
1173 pub fn is_outbound(&self) -> Option<bool> {
1178 self.get_channel_parameters().map(|params| params.is_outbound_from_holder)
1179 }
1180
1181 pub fn funding_outpoint(&self) -> Option<&OutPoint> {
1186 self.get_channel_parameters().map(|params| params.funding_outpoint.as_ref()).flatten()
1187 }
1188
1189 pub fn get_channel_parameters(&self) -> Option<&ChannelTransactionParameters> {
1195 self.channel_parameters.as_ref()
1196 }
1197
1198 pub fn channel_type_features(&self) -> Option<&ChannelTypeFeatures> {
1204 self.get_channel_parameters().map(|params| ¶ms.channel_type_features)
1205 }
1206
1207 pub fn sign_counterparty_payment_input<C: Signing>(
1216 &self, spend_tx: &Transaction, input_idx: usize,
1217 descriptor: &StaticPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>,
1218 ) -> Result<Witness, ()> {
1219 if spend_tx.input.len() <= input_idx {
1224 return Err(());
1225 }
1226 if !spend_tx.input[input_idx].script_sig.is_empty() {
1227 return Err(());
1228 }
1229 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint()
1230 {
1231 return Err(());
1232 }
1233
1234 let remotepubkey = bitcoin::PublicKey::new(self.pubkeys().payment_point);
1235 let supports_anchors_zero_fee_htlc_tx = self
1238 .channel_type_features()
1239 .map(|features| features.supports_anchors_zero_fee_htlc_tx())
1240 .unwrap_or(false);
1241
1242 let witness_script = if supports_anchors_zero_fee_htlc_tx {
1243 chan_utils::get_to_countersignatory_with_anchors_redeemscript(&remotepubkey.inner)
1244 } else {
1245 ScriptBuf::new_p2pkh(&remotepubkey.pubkey_hash())
1246 };
1247 let sighash = hash_to_message!(
1248 &sighash::SighashCache::new(spend_tx)
1249 .p2wsh_signature_hash(
1250 input_idx,
1251 &witness_script,
1252 descriptor.output.value,
1253 EcdsaSighashType::All
1254 )
1255 .unwrap()[..]
1256 );
1257 let remotesig = sign_with_aux_rand(secp_ctx, &sighash, &self.payment_key, &self);
1258 let payment_script = if supports_anchors_zero_fee_htlc_tx {
1259 witness_script.to_p2wsh()
1260 } else {
1261 ScriptBuf::new_p2wpkh(&remotepubkey.wpubkey_hash().unwrap())
1262 };
1263
1264 if payment_script != descriptor.output.script_pubkey {
1265 return Err(());
1266 }
1267
1268 let mut witness = Vec::with_capacity(2);
1269 witness.push(remotesig.serialize_der().to_vec());
1270 witness[0].push(EcdsaSighashType::All as u8);
1271 if supports_anchors_zero_fee_htlc_tx {
1272 witness.push(witness_script.to_bytes());
1273 } else {
1274 witness.push(remotepubkey.to_bytes());
1275 }
1276 Ok(witness.into())
1277 }
1278
1279 pub fn sign_dynamic_p2wsh_input<C: Signing>(
1290 &self, spend_tx: &Transaction, input_idx: usize,
1291 descriptor: &DelayedPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>,
1292 ) -> Result<Witness, ()> {
1293 if spend_tx.input.len() <= input_idx {
1298 return Err(());
1299 }
1300 if !spend_tx.input[input_idx].script_sig.is_empty() {
1301 return Err(());
1302 }
1303 if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint()
1304 {
1305 return Err(());
1306 }
1307 if spend_tx.input[input_idx].sequence.0 != descriptor.to_self_delay as u32 {
1308 return Err(());
1309 }
1310
1311 let delayed_payment_key = chan_utils::derive_private_key(
1312 &secp_ctx,
1313 &descriptor.per_commitment_point,
1314 &self.delayed_payment_base_key,
1315 );
1316 let delayed_payment_pubkey =
1317 DelayedPaymentKey::from_secret_key(&secp_ctx, &delayed_payment_key);
1318 let witness_script = chan_utils::get_revokeable_redeemscript(
1319 &descriptor.revocation_pubkey,
1320 descriptor.to_self_delay,
1321 &delayed_payment_pubkey,
1322 );
1323 let sighash = hash_to_message!(
1324 &sighash::SighashCache::new(spend_tx)
1325 .p2wsh_signature_hash(
1326 input_idx,
1327 &witness_script,
1328 descriptor.output.value,
1329 EcdsaSighashType::All
1330 )
1331 .unwrap()[..]
1332 );
1333 let local_delayedsig = EcdsaSignature {
1334 signature: sign_with_aux_rand(secp_ctx, &sighash, &delayed_payment_key, &self),
1335 sighash_type: EcdsaSighashType::All,
1336 };
1337 let payment_script =
1338 bitcoin::Address::p2wsh(&witness_script, Network::Bitcoin).script_pubkey();
1339
1340 if descriptor.output.script_pubkey != payment_script {
1341 return Err(());
1342 }
1343
1344 Ok(Witness::from_slice(&[
1345 &local_delayedsig.serialize()[..],
1346 &[], witness_script.as_bytes(),
1348 ]))
1349 }
1350}
1351
1352impl EntropySource for InMemorySigner {
1353 fn get_secure_random_bytes(&self) -> [u8; 32] {
1354 self.entropy_source.get_secure_random_bytes()
1355 }
1356}
1357
1358impl ChannelSigner for InMemorySigner {
1359 fn get_per_commitment_point(
1360 &self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>,
1361 ) -> Result<PublicKey, ()> {
1362 let commitment_secret =
1363 SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx))
1364 .unwrap();
1365 Ok(PublicKey::from_secret_key(secp_ctx, &commitment_secret))
1366 }
1367
1368 fn release_commitment_secret(&self, idx: u64) -> Result<[u8; 32], ()> {
1369 Ok(chan_utils::build_commitment_secret(&self.commitment_seed, idx))
1370 }
1371
1372 fn validate_holder_commitment(
1373 &self, _holder_tx: &HolderCommitmentTransaction,
1374 _outbound_htlc_preimages: Vec<PaymentPreimage>,
1375 ) -> Result<(), ()> {
1376 Ok(())
1377 }
1378
1379 fn validate_counterparty_revocation(&self, _idx: u64, _secret: &SecretKey) -> Result<(), ()> {
1380 Ok(())
1381 }
1382
1383 fn pubkeys(&self) -> &ChannelPublicKeys {
1384 &self.holder_channel_pubkeys
1385 }
1386
1387 fn channel_keys_id(&self) -> [u8; 32] {
1388 self.channel_keys_id
1389 }
1390
1391 fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters) {
1392 assert!(
1393 self.channel_parameters.is_none()
1394 || self.channel_parameters.as_ref().unwrap() == channel_parameters
1395 );
1396 if self.channel_parameters.is_some() {
1397 return;
1399 }
1400 assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1401 self.channel_parameters = Some(channel_parameters.clone());
1402 }
1403}
1404
1405const MISSING_PARAMS_ERR: &'static str =
1406 "ChannelSigner::provide_channel_parameters must be called before signing operations";
1407
1408impl EcdsaChannelSigner for InMemorySigner {
1409 fn sign_counterparty_commitment(
1410 &self, commitment_tx: &CommitmentTransaction,
1411 _inbound_htlc_preimages: Vec<PaymentPreimage>,
1412 _outbound_htlc_preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<secp256k1::All>,
1413 ) -> Result<(Signature, Vec<Signature>), ()> {
1414 let trusted_tx = commitment_tx.trust();
1415 let keys = trusted_tx.keys();
1416
1417 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1418 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1419 let channel_funding_redeemscript =
1420 make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1421
1422 let built_tx = trusted_tx.built_transaction();
1423 let commitment_sig = built_tx.sign_counterparty_commitment(
1424 &self.funding_key,
1425 &channel_funding_redeemscript,
1426 self.channel_value_satoshis,
1427 secp_ctx,
1428 );
1429 let commitment_txid = built_tx.txid;
1430
1431 let mut htlc_sigs = Vec::with_capacity(commitment_tx.htlcs().len());
1432 for htlc in commitment_tx.htlcs() {
1433 let channel_parameters = self.get_channel_parameters().expect(MISSING_PARAMS_ERR);
1434 let holder_selected_contest_delay =
1435 self.holder_selected_contest_delay().expect(MISSING_PARAMS_ERR);
1436 let chan_type = &channel_parameters.channel_type_features;
1437 let htlc_tx = chan_utils::build_htlc_transaction(
1438 &commitment_txid,
1439 commitment_tx.feerate_per_kw(),
1440 holder_selected_contest_delay,
1441 htlc,
1442 chan_type,
1443 &keys.broadcaster_delayed_payment_key,
1444 &keys.revocation_key,
1445 );
1446 let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, chan_type, &keys);
1447 let htlc_sighashtype = if chan_type.supports_anchors_zero_fee_htlc_tx() {
1448 EcdsaSighashType::SinglePlusAnyoneCanPay
1449 } else {
1450 EcdsaSighashType::All
1451 };
1452 let htlc_sighash = hash_to_message!(
1453 &sighash::SighashCache::new(&htlc_tx)
1454 .p2wsh_signature_hash(
1455 0,
1456 &htlc_redeemscript,
1457 htlc.to_bitcoin_amount(),
1458 htlc_sighashtype
1459 )
1460 .unwrap()[..]
1461 );
1462 let holder_htlc_key = chan_utils::derive_private_key(
1463 &secp_ctx,
1464 &keys.per_commitment_point,
1465 &self.htlc_base_key,
1466 );
1467 htlc_sigs.push(sign(secp_ctx, &htlc_sighash, &holder_htlc_key));
1468 }
1469
1470 Ok((commitment_sig, htlc_sigs))
1471 }
1472
1473 fn sign_holder_commitment(
1474 &self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
1475 ) -> Result<Signature, ()> {
1476 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1477 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1478 let funding_redeemscript =
1479 make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1480 let trusted_tx = commitment_tx.trust();
1481 Ok(trusted_tx.built_transaction().sign_holder_commitment(
1482 &self.funding_key,
1483 &funding_redeemscript,
1484 self.channel_value_satoshis,
1485 &self,
1486 secp_ctx,
1487 ))
1488 }
1489
1490 #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
1491 fn unsafe_sign_holder_commitment(
1492 &self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
1493 ) -> Result<Signature, ()> {
1494 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1495 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1496 let funding_redeemscript =
1497 make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1498 let trusted_tx = commitment_tx.trust();
1499 Ok(trusted_tx.built_transaction().sign_holder_commitment(
1500 &self.funding_key,
1501 &funding_redeemscript,
1502 self.channel_value_satoshis,
1503 &self,
1504 secp_ctx,
1505 ))
1506 }
1507
1508 fn sign_justice_revoked_output(
1509 &self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
1510 secp_ctx: &Secp256k1<secp256k1::All>,
1511 ) -> Result<Signature, ()> {
1512 let revocation_key = chan_utils::derive_private_revocation_key(
1513 &secp_ctx,
1514 &per_commitment_key,
1515 &self.revocation_base_key,
1516 );
1517 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
1518 let revocation_pubkey = RevocationKey::from_basepoint(
1519 &secp_ctx,
1520 &self.pubkeys().revocation_basepoint,
1521 &per_commitment_point,
1522 );
1523 let witness_script = {
1524 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1525 let holder_selected_contest_delay =
1526 self.holder_selected_contest_delay().expect(MISSING_PARAMS_ERR);
1527 let counterparty_delayedpubkey = DelayedPaymentKey::from_basepoint(
1528 &secp_ctx,
1529 &counterparty_keys.delayed_payment_basepoint,
1530 &per_commitment_point,
1531 );
1532 chan_utils::get_revokeable_redeemscript(
1533 &revocation_pubkey,
1534 holder_selected_contest_delay,
1535 &counterparty_delayedpubkey,
1536 )
1537 };
1538 let mut sighash_parts = sighash::SighashCache::new(justice_tx);
1539 let sighash = hash_to_message!(
1540 &sighash_parts
1541 .p2wsh_signature_hash(
1542 input,
1543 &witness_script,
1544 Amount::from_sat(amount),
1545 EcdsaSighashType::All
1546 )
1547 .unwrap()[..]
1548 );
1549 return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self));
1550 }
1551
1552 fn sign_justice_revoked_htlc(
1553 &self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
1554 htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>,
1555 ) -> Result<Signature, ()> {
1556 let revocation_key = chan_utils::derive_private_revocation_key(
1557 &secp_ctx,
1558 &per_commitment_key,
1559 &self.revocation_base_key,
1560 );
1561 let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
1562 let revocation_pubkey = RevocationKey::from_basepoint(
1563 &secp_ctx,
1564 &self.pubkeys().revocation_basepoint,
1565 &per_commitment_point,
1566 );
1567 let witness_script = {
1568 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1569 let counterparty_htlcpubkey = HtlcKey::from_basepoint(
1570 &secp_ctx,
1571 &counterparty_keys.htlc_basepoint,
1572 &per_commitment_point,
1573 );
1574 let holder_htlcpubkey = HtlcKey::from_basepoint(
1575 &secp_ctx,
1576 &self.pubkeys().htlc_basepoint,
1577 &per_commitment_point,
1578 );
1579 let chan_type = self.channel_type_features().expect(MISSING_PARAMS_ERR);
1580 chan_utils::get_htlc_redeemscript_with_explicit_keys(
1581 &htlc,
1582 chan_type,
1583 &counterparty_htlcpubkey,
1584 &holder_htlcpubkey,
1585 &revocation_pubkey,
1586 )
1587 };
1588 let mut sighash_parts = sighash::SighashCache::new(justice_tx);
1589 let sighash = hash_to_message!(
1590 &sighash_parts
1591 .p2wsh_signature_hash(
1592 input,
1593 &witness_script,
1594 Amount::from_sat(amount),
1595 EcdsaSighashType::All
1596 )
1597 .unwrap()[..]
1598 );
1599 return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self));
1600 }
1601
1602 fn sign_holder_htlc_transaction(
1603 &self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
1604 secp_ctx: &Secp256k1<secp256k1::All>,
1605 ) -> Result<Signature, ()> {
1606 let witness_script = htlc_descriptor.witness_script(secp_ctx);
1607 let sighash = &sighash::SighashCache::new(&*htlc_tx)
1608 .p2wsh_signature_hash(
1609 input,
1610 &witness_script,
1611 htlc_descriptor.htlc.to_bitcoin_amount(),
1612 EcdsaSighashType::All,
1613 )
1614 .map_err(|_| ())?;
1615 let our_htlc_private_key = chan_utils::derive_private_key(
1616 &secp_ctx,
1617 &htlc_descriptor.per_commitment_point,
1618 &self.htlc_base_key,
1619 );
1620 let sighash = hash_to_message!(sighash.as_byte_array());
1621 Ok(sign_with_aux_rand(&secp_ctx, &sighash, &our_htlc_private_key, &self))
1622 }
1623
1624 fn sign_counterparty_htlc_transaction(
1625 &self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey,
1626 htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>,
1627 ) -> Result<Signature, ()> {
1628 let htlc_key =
1629 chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key);
1630 let revocation_pubkey = RevocationKey::from_basepoint(
1631 &secp_ctx,
1632 &self.pubkeys().revocation_basepoint,
1633 &per_commitment_point,
1634 );
1635 let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1636 let counterparty_htlcpubkey = HtlcKey::from_basepoint(
1637 &secp_ctx,
1638 &counterparty_keys.htlc_basepoint,
1639 &per_commitment_point,
1640 );
1641 let htlc_basepoint = self.pubkeys().htlc_basepoint;
1642 let htlcpubkey = HtlcKey::from_basepoint(&secp_ctx, &htlc_basepoint, &per_commitment_point);
1643 let chan_type = self.channel_type_features().expect(MISSING_PARAMS_ERR);
1644 let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(
1645 &htlc,
1646 chan_type,
1647 &counterparty_htlcpubkey,
1648 &htlcpubkey,
1649 &revocation_pubkey,
1650 );
1651 let mut sighash_parts = sighash::SighashCache::new(htlc_tx);
1652 let sighash = hash_to_message!(
1653 &sighash_parts
1654 .p2wsh_signature_hash(
1655 input,
1656 &witness_script,
1657 Amount::from_sat(amount),
1658 EcdsaSighashType::All
1659 )
1660 .unwrap()[..]
1661 );
1662 Ok(sign_with_aux_rand(secp_ctx, &sighash, &htlc_key, &self))
1663 }
1664
1665 fn sign_closing_transaction(
1666 &self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
1667 ) -> Result<Signature, ()> {
1668 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1669 let counterparty_funding_key =
1670 &self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR).funding_pubkey;
1671 let channel_funding_redeemscript =
1672 make_funding_redeemscript(&funding_pubkey, counterparty_funding_key);
1673 Ok(closing_tx.trust().sign(
1674 &self.funding_key,
1675 &channel_funding_redeemscript,
1676 self.channel_value_satoshis,
1677 secp_ctx,
1678 ))
1679 }
1680
1681 fn sign_holder_anchor_input(
1682 &self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<secp256k1::All>,
1683 ) -> Result<Signature, ()> {
1684 let witness_script =
1685 chan_utils::get_anchor_redeemscript(&self.holder_channel_pubkeys.funding_pubkey);
1686 let sighash = sighash::SighashCache::new(&*anchor_tx)
1687 .p2wsh_signature_hash(
1688 input,
1689 &witness_script,
1690 Amount::from_sat(ANCHOR_OUTPUT_VALUE_SATOSHI),
1691 EcdsaSighashType::All,
1692 )
1693 .unwrap();
1694 Ok(sign_with_aux_rand(secp_ctx, &hash_to_message!(&sighash[..]), &self.funding_key, &self))
1695 }
1696
1697 fn sign_channel_announcement_with_funding_key(
1698 &self, msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>,
1699 ) -> Result<Signature, ()> {
1700 let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1701 Ok(secp_ctx.sign_ecdsa(&msghash, &self.funding_key))
1702 }
1703
1704 fn sign_splicing_funding_input(
1705 &self, tx: &Transaction, input_index: usize, input_value: u64,
1706 secp_ctx: &Secp256k1<secp256k1::All>,
1707 ) -> Result<Signature, ()> {
1708 let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
1709 let counterparty_funding_key =
1710 &self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR).funding_pubkey;
1711 let funding_redeemscript =
1712 make_funding_redeemscript(&funding_pubkey, counterparty_funding_key);
1713 let sighash = &sighash::SighashCache::new(tx)
1714 .p2wsh_signature_hash(
1715 input_index,
1716 &funding_redeemscript,
1717 Amount::from_sat(input_value),
1718 EcdsaSighashType::All,
1719 )
1720 .unwrap()[..];
1721 let msg = hash_to_message!(sighash);
1722 Ok(sign(secp_ctx, &msg, &self.funding_key))
1723 }
1724}
1725
1726#[cfg(taproot)]
1727#[allow(unused)]
1728impl TaprootChannelSigner for InMemorySigner {
1729 fn generate_local_nonce_pair(
1730 &self, commitment_number: u64, secp_ctx: &Secp256k1<All>,
1731 ) -> PublicNonce {
1732 todo!()
1733 }
1734
1735 fn partially_sign_counterparty_commitment(
1736 &self, counterparty_nonce: PublicNonce, commitment_tx: &CommitmentTransaction,
1737 inbound_htlc_preimages: Vec<PaymentPreimage>,
1738 outbound_htlc_preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<All>,
1739 ) -> Result<(PartialSignatureWithNonce, Vec<schnorr::Signature>), ()> {
1740 todo!()
1741 }
1742
1743 fn finalize_holder_commitment(
1744 &self, commitment_tx: &HolderCommitmentTransaction,
1745 counterparty_partial_signature: PartialSignatureWithNonce, secp_ctx: &Secp256k1<All>,
1746 ) -> Result<PartialSignature, ()> {
1747 todo!()
1748 }
1749
1750 fn sign_justice_revoked_output(
1751 &self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
1752 secp_ctx: &Secp256k1<All>,
1753 ) -> Result<schnorr::Signature, ()> {
1754 todo!()
1755 }
1756
1757 fn sign_justice_revoked_htlc(
1758 &self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
1759 htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<All>,
1760 ) -> Result<schnorr::Signature, ()> {
1761 todo!()
1762 }
1763
1764 fn sign_holder_htlc_transaction(
1765 &self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
1766 secp_ctx: &Secp256k1<All>,
1767 ) -> Result<schnorr::Signature, ()> {
1768 todo!()
1769 }
1770
1771 fn sign_counterparty_htlc_transaction(
1772 &self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey,
1773 htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<All>,
1774 ) -> Result<schnorr::Signature, ()> {
1775 todo!()
1776 }
1777
1778 fn partially_sign_closing_transaction(
1779 &self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<All>,
1780 ) -> Result<PartialSignature, ()> {
1781 todo!()
1782 }
1783
1784 fn sign_holder_anchor_input(
1785 &self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<All>,
1786 ) -> Result<schnorr::Signature, ()> {
1787 todo!()
1788 }
1789}
1790
1791const SERIALIZATION_VERSION: u8 = 1;
1792
1793const MIN_SERIALIZATION_VERSION: u8 = 1;
1794
1795impl Writeable for InMemorySigner {
1796 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
1797 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
1798
1799 self.funding_key.write(writer)?;
1800 self.revocation_base_key.write(writer)?;
1801 self.payment_key.write(writer)?;
1802 self.delayed_payment_base_key.write(writer)?;
1803 self.htlc_base_key.write(writer)?;
1804 self.commitment_seed.write(writer)?;
1805 self.channel_parameters.write(writer)?;
1806 self.channel_value_satoshis.write(writer)?;
1807 self.channel_keys_id.write(writer)?;
1808
1809 write_tlv_fields!(writer, {});
1810
1811 Ok(())
1812 }
1813}
1814
1815impl<ES: Deref> ReadableArgs<ES> for InMemorySigner
1816where
1817 ES::Target: EntropySource,
1818{
1819 fn read<R: io::Read>(reader: &mut R, entropy_source: ES) -> Result<Self, DecodeError> {
1820 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
1821
1822 let funding_key = Readable::read(reader)?;
1823 let revocation_base_key = Readable::read(reader)?;
1824 let payment_key = Readable::read(reader)?;
1825 let delayed_payment_base_key = Readable::read(reader)?;
1826 let htlc_base_key = Readable::read(reader)?;
1827 let commitment_seed = Readable::read(reader)?;
1828 let counterparty_channel_data = Readable::read(reader)?;
1829 let channel_value_satoshis = Readable::read(reader)?;
1830 let secp_ctx = Secp256k1::signing_only();
1831 let holder_channel_pubkeys = InMemorySigner::make_holder_keys(
1832 &secp_ctx,
1833 &funding_key,
1834 &revocation_base_key,
1835 &payment_key,
1836 &delayed_payment_base_key,
1837 &htlc_base_key,
1838 );
1839 let keys_id = Readable::read(reader)?;
1840
1841 read_tlv_fields!(reader, {});
1842
1843 Ok(InMemorySigner {
1844 funding_key,
1845 revocation_base_key,
1846 payment_key,
1847 delayed_payment_base_key,
1848 htlc_base_key,
1849 commitment_seed,
1850 channel_value_satoshis,
1851 holder_channel_pubkeys,
1852 channel_parameters: counterparty_channel_data,
1853 channel_keys_id: keys_id,
1854 entropy_source: RandomBytes::new(entropy_source.get_secure_random_bytes()),
1855 })
1856 }
1857}
1858
1859pub struct KeysManager {
1873 secp_ctx: Secp256k1<secp256k1::All>,
1874 node_secret: SecretKey,
1875 node_id: PublicKey,
1876 inbound_payment_key: ExpandedKey,
1877 destination_script: ScriptBuf,
1878 shutdown_pubkey: PublicKey,
1879 channel_master_key: Xpriv,
1880 channel_child_index: AtomicUsize,
1881
1882 #[cfg(test)]
1883 pub(crate) entropy_source: RandomBytes,
1884 #[cfg(not(test))]
1885 entropy_source: RandomBytes,
1886
1887 seed: [u8; 32],
1888 starting_time_secs: u64,
1889 starting_time_nanos: u32,
1890}
1891
1892impl KeysManager {
1893 pub fn new(seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32) -> Self {
1911 let secp_ctx = Secp256k1::new();
1912 match Xpriv::new_master(Network::Testnet, seed) {
1914 Ok(master_key) => {
1915 let node_secret = master_key
1916 .derive_priv(&secp_ctx, &ChildNumber::from_hardened_idx(0).unwrap())
1917 .expect("Your RNG is busted")
1918 .private_key;
1919 let node_id = PublicKey::from_secret_key(&secp_ctx, &node_secret);
1920 let destination_script = match master_key
1921 .derive_priv(&secp_ctx, &ChildNumber::from_hardened_idx(1).unwrap())
1922 {
1923 Ok(destination_key) => {
1924 let wpubkey_hash = WPubkeyHash::hash(
1925 &Xpub::from_priv(&secp_ctx, &destination_key).to_pub().to_bytes(),
1926 );
1927 Builder::new()
1928 .push_opcode(opcodes::all::OP_PUSHBYTES_0)
1929 .push_slice(&wpubkey_hash.to_byte_array())
1930 .into_script()
1931 },
1932 Err(_) => panic!("Your RNG is busted"),
1933 };
1934 let shutdown_pubkey = match master_key
1935 .derive_priv(&secp_ctx, &ChildNumber::from_hardened_idx(2).unwrap())
1936 {
1937 Ok(shutdown_key) => Xpub::from_priv(&secp_ctx, &shutdown_key).public_key,
1938 Err(_) => panic!("Your RNG is busted"),
1939 };
1940 let channel_master_key = master_key
1941 .derive_priv(&secp_ctx, &ChildNumber::from_hardened_idx(3).unwrap())
1942 .expect("Your RNG is busted");
1943 let inbound_payment_key: SecretKey = master_key
1944 .derive_priv(&secp_ctx, &ChildNumber::from_hardened_idx(5).unwrap())
1945 .expect("Your RNG is busted")
1946 .private_key;
1947 let mut inbound_pmt_key_bytes = [0; 32];
1948 inbound_pmt_key_bytes.copy_from_slice(&inbound_payment_key[..]);
1949
1950 let mut rand_bytes_engine = Sha256::engine();
1951 rand_bytes_engine.input(&starting_time_secs.to_be_bytes());
1952 rand_bytes_engine.input(&starting_time_nanos.to_be_bytes());
1953 rand_bytes_engine.input(seed);
1954 rand_bytes_engine.input(b"LDK PRNG Seed");
1955 let rand_bytes_unique_start =
1956 Sha256::from_engine(rand_bytes_engine).to_byte_array();
1957
1958 let mut res = KeysManager {
1959 secp_ctx,
1960 node_secret,
1961 node_id,
1962 inbound_payment_key: ExpandedKey::new(inbound_pmt_key_bytes),
1963
1964 destination_script,
1965 shutdown_pubkey,
1966
1967 channel_master_key,
1968 channel_child_index: AtomicUsize::new(0),
1969
1970 entropy_source: RandomBytes::new(rand_bytes_unique_start),
1971
1972 seed: *seed,
1973 starting_time_secs,
1974 starting_time_nanos,
1975 };
1976 let secp_seed = res.get_secure_random_bytes();
1977 res.secp_ctx.seeded_randomize(&secp_seed);
1978 res
1979 },
1980 Err(_) => panic!("Your rng is busted"),
1981 }
1982 }
1983
1984 pub fn get_node_secret_key(&self) -> SecretKey {
1986 self.node_secret
1987 }
1988
1989 pub fn derive_channel_keys(
1991 &self, channel_value_satoshis: u64, params: &[u8; 32],
1992 ) -> InMemorySigner {
1993 let chan_id = u64::from_be_bytes(params[0..8].try_into().unwrap());
1994 let mut unique_start = Sha256::engine();
1995 unique_start.input(params);
1996 unique_start.input(&self.seed);
1997
1998 let child_privkey = self
2002 .channel_master_key
2003 .derive_priv(
2004 &self.secp_ctx,
2005 &ChildNumber::from_hardened_idx((chan_id as u32) % (1 << 31))
2006 .expect("key space exhausted"),
2007 )
2008 .expect("Your RNG is busted");
2009 unique_start.input(&child_privkey.private_key[..]);
2010
2011 let seed = Sha256::from_engine(unique_start).to_byte_array();
2012
2013 let commitment_seed = {
2014 let mut sha = Sha256::engine();
2015 sha.input(&seed);
2016 sha.input(&b"commitment seed"[..]);
2017 Sha256::from_engine(sha).to_byte_array()
2018 };
2019 macro_rules! key_step {
2020 ($info: expr, $prev_key: expr) => {{
2021 let mut sha = Sha256::engine();
2022 sha.input(&seed);
2023 sha.input(&$prev_key[..]);
2024 sha.input(&$info[..]);
2025 SecretKey::from_slice(&Sha256::from_engine(sha).to_byte_array())
2026 .expect("SHA-256 is busted")
2027 }};
2028 }
2029 let funding_key = key_step!(b"funding key", commitment_seed);
2030 let revocation_base_key = key_step!(b"revocation base key", funding_key);
2031 let payment_key = key_step!(b"payment key", revocation_base_key);
2032 let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key);
2033 let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
2034 let prng_seed = self.get_secure_random_bytes();
2035
2036 InMemorySigner::new(
2037 &self.secp_ctx,
2038 funding_key,
2039 revocation_base_key,
2040 payment_key,
2041 delayed_payment_base_key,
2042 htlc_base_key,
2043 commitment_seed,
2044 channel_value_satoshis,
2045 params.clone(),
2046 prng_seed,
2047 )
2048 }
2049
2050 pub fn sign_spendable_outputs_psbt<C: Signing>(
2059 &self, descriptors: &[&SpendableOutputDescriptor], mut psbt: Psbt, secp_ctx: &Secp256k1<C>,
2060 ) -> Result<Psbt, ()> {
2061 let mut keys_cache: Option<(InMemorySigner, [u8; 32])> = None;
2062 for outp in descriptors {
2063 let get_input_idx = |outpoint: &OutPoint| {
2064 psbt.unsigned_tx
2065 .input
2066 .iter()
2067 .position(|i| i.previous_output == outpoint.into_bitcoin_outpoint())
2068 .ok_or(())
2069 };
2070 match outp {
2071 SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
2072 let input_idx = get_input_idx(&descriptor.outpoint)?;
2073 if keys_cache.is_none()
2074 || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id
2075 {
2076 let mut signer = self.derive_channel_keys(
2077 descriptor.channel_value_satoshis,
2078 &descriptor.channel_keys_id,
2079 );
2080 if let Some(channel_params) =
2081 descriptor.channel_transaction_parameters.as_ref()
2082 {
2083 signer.provide_channel_parameters(channel_params);
2084 }
2085 keys_cache = Some((signer, descriptor.channel_keys_id));
2086 }
2087 let witness = keys_cache.as_ref().unwrap().0.sign_counterparty_payment_input(
2088 &psbt.unsigned_tx,
2089 input_idx,
2090 &descriptor,
2091 &secp_ctx,
2092 )?;
2093 psbt.inputs[input_idx].final_script_witness = Some(witness);
2094 },
2095 SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
2096 let input_idx = get_input_idx(&descriptor.outpoint)?;
2097 if keys_cache.is_none()
2098 || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id
2099 {
2100 keys_cache = Some((
2101 self.derive_channel_keys(
2102 descriptor.channel_value_satoshis,
2103 &descriptor.channel_keys_id,
2104 ),
2105 descriptor.channel_keys_id,
2106 ));
2107 }
2108 let witness = keys_cache.as_ref().unwrap().0.sign_dynamic_p2wsh_input(
2109 &psbt.unsigned_tx,
2110 input_idx,
2111 &descriptor,
2112 &secp_ctx,
2113 )?;
2114 psbt.inputs[input_idx].final_script_witness = Some(witness);
2115 },
2116 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => {
2117 let input_idx = get_input_idx(outpoint)?;
2118 let derivation_idx =
2119 if output.script_pubkey == self.destination_script { 1 } else { 2 };
2120 let secret = {
2121 match Xpriv::new_master(Network::Testnet, &self.seed) {
2123 Ok(master_key) => {
2124 match master_key.derive_priv(
2125 &secp_ctx,
2126 &ChildNumber::from_hardened_idx(derivation_idx)
2127 .expect("key space exhausted"),
2128 ) {
2129 Ok(key) => key,
2130 Err(_) => panic!("Your RNG is busted"),
2131 }
2132 },
2133 Err(_) => panic!("Your rng is busted"),
2134 }
2135 };
2136 let pubkey = Xpub::from_priv(&secp_ctx, &secret).to_pub();
2137 if derivation_idx == 2 {
2138 assert_eq!(pubkey.0, self.shutdown_pubkey);
2139 }
2140 let witness_script =
2141 bitcoin::Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
2142 let payment_script =
2143 bitcoin::Address::p2wpkh(&pubkey, Network::Testnet).script_pubkey();
2144
2145 if payment_script != output.script_pubkey {
2146 return Err(());
2147 };
2148
2149 let sighash = hash_to_message!(
2150 &sighash::SighashCache::new(&psbt.unsigned_tx)
2151 .p2wsh_signature_hash(
2152 input_idx,
2153 &witness_script,
2154 output.value,
2155 EcdsaSighashType::All
2156 )
2157 .unwrap()[..]
2158 );
2159 let sig = sign_with_aux_rand(secp_ctx, &sighash, &secret.private_key, &self);
2160 let mut sig_ser = sig.serialize_der().to_vec();
2161 sig_ser.push(EcdsaSighashType::All as u8);
2162 let witness = Witness::from_slice(&[&sig_ser, &pubkey.0.serialize().to_vec()]);
2163 psbt.inputs[input_idx].final_script_witness = Some(witness);
2164 },
2165 }
2166 }
2167
2168 Ok(psbt)
2169 }
2170}
2171
2172impl EntropySource for KeysManager {
2173 fn get_secure_random_bytes(&self) -> [u8; 32] {
2174 self.entropy_source.get_secure_random_bytes()
2175 }
2176}
2177
2178impl NodeSigner for KeysManager {
2179 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
2180 match recipient {
2181 Recipient::Node => Ok(self.node_id.clone()),
2182 Recipient::PhantomNode => Err(()),
2183 }
2184 }
2185
2186 fn ecdh(
2187 &self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
2188 ) -> Result<SharedSecret, ()> {
2189 let mut node_secret = match recipient {
2190 Recipient::Node => Ok(self.node_secret.clone()),
2191 Recipient::PhantomNode => Err(()),
2192 }?;
2193 if let Some(tweak) = tweak {
2194 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
2195 }
2196 Ok(SharedSecret::new(other_key, &node_secret))
2197 }
2198
2199 fn get_inbound_payment_key(&self) -> ExpandedKey {
2200 self.inbound_payment_key.clone()
2201 }
2202
2203 fn sign_invoice(
2204 &self, invoice: &RawBolt11Invoice, recipient: Recipient,
2205 ) -> Result<RecoverableSignature, ()> {
2206 let hash = invoice.signable_hash();
2207 let secret = match recipient {
2208 Recipient::Node => Ok(&self.node_secret),
2209 Recipient::PhantomNode => Err(()),
2210 }?;
2211 Ok(self.secp_ctx.sign_ecdsa_recoverable(&hash_to_message!(&hash), secret))
2212 }
2213
2214 fn sign_bolt12_invoice(
2215 &self, invoice: &UnsignedBolt12Invoice,
2216 ) -> Result<schnorr::Signature, ()> {
2217 let message = invoice.tagged_hash().as_digest();
2218 let keys = Keypair::from_secret_key(&self.secp_ctx, &self.node_secret);
2219 let aux_rand = self.get_secure_random_bytes();
2220 Ok(self.secp_ctx.sign_schnorr_with_aux_rand(message, &keys, &aux_rand))
2221 }
2222
2223 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
2224 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
2225 Ok(self.secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret))
2226 }
2227}
2228
2229impl OutputSpender for KeysManager {
2230 fn spend_spendable_outputs<C: Signing>(
2240 &self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
2241 change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
2242 locktime: Option<LockTime>, secp_ctx: &Secp256k1<C>,
2243 ) -> Result<Transaction, ()> {
2244 let (mut psbt, expected_max_weight) =
2245 SpendableOutputDescriptor::create_spendable_outputs_psbt(
2246 secp_ctx,
2247 descriptors,
2248 outputs,
2249 change_destination_script,
2250 feerate_sat_per_1000_weight,
2251 locktime,
2252 )?;
2253 psbt = self.sign_spendable_outputs_psbt(descriptors, psbt, secp_ctx)?;
2254
2255 let spend_tx = psbt.extract_tx_unchecked_fee_rate();
2256
2257 debug_assert!(expected_max_weight >= spend_tx.weight().to_wu());
2258 debug_assert!(
2261 expected_max_weight <= spend_tx.weight().to_wu() + descriptors.len() as u64 * 3
2262 );
2263
2264 Ok(spend_tx)
2265 }
2266}
2267
2268impl SignerProvider for KeysManager {
2269 type EcdsaSigner = InMemorySigner;
2270 #[cfg(taproot)]
2271 type TaprootSigner = InMemorySigner;
2272
2273 fn generate_channel_keys_id(
2274 &self, _inbound: bool, _channel_value_satoshis: u64, user_channel_id: u128,
2275 ) -> [u8; 32] {
2276 let child_idx = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
2277 assert!(child_idx < core::u32::MAX as usize, "2^32 channels opened without restart");
2283 let mut id = [0; 32];
2284 id[0..4].copy_from_slice(&(child_idx as u32).to_be_bytes());
2285 id[4..8].copy_from_slice(&self.starting_time_nanos.to_be_bytes());
2286 id[8..16].copy_from_slice(&self.starting_time_secs.to_be_bytes());
2287 id[16..32].copy_from_slice(&user_channel_id.to_be_bytes());
2288 id
2289 }
2290
2291 fn derive_channel_signer(
2292 &self, channel_value_satoshis: u64, channel_keys_id: [u8; 32],
2293 ) -> Self::EcdsaSigner {
2294 self.derive_channel_keys(channel_value_satoshis, &channel_keys_id)
2295 }
2296
2297 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError> {
2298 InMemorySigner::read(&mut io::Cursor::new(reader), self)
2299 }
2300
2301 fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
2302 Ok(self.destination_script.clone())
2303 }
2304
2305 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
2306 Ok(ShutdownScript::new_p2wpkh_from_pubkey(self.shutdown_pubkey.clone()))
2307 }
2308}
2309
2310pub struct PhantomKeysManager {
2332 #[cfg(test)]
2333 pub(crate) inner: KeysManager,
2334 #[cfg(not(test))]
2335 inner: KeysManager,
2336 inbound_payment_key: ExpandedKey,
2337 phantom_secret: SecretKey,
2338 phantom_node_id: PublicKey,
2339}
2340
2341impl EntropySource for PhantomKeysManager {
2342 fn get_secure_random_bytes(&self) -> [u8; 32] {
2343 self.inner.get_secure_random_bytes()
2344 }
2345}
2346
2347impl NodeSigner for PhantomKeysManager {
2348 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
2349 match recipient {
2350 Recipient::Node => self.inner.get_node_id(Recipient::Node),
2351 Recipient::PhantomNode => Ok(self.phantom_node_id.clone()),
2352 }
2353 }
2354
2355 fn ecdh(
2356 &self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
2357 ) -> Result<SharedSecret, ()> {
2358 let mut node_secret = match recipient {
2359 Recipient::Node => self.inner.node_secret.clone(),
2360 Recipient::PhantomNode => self.phantom_secret.clone(),
2361 };
2362 if let Some(tweak) = tweak {
2363 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
2364 }
2365 Ok(SharedSecret::new(other_key, &node_secret))
2366 }
2367
2368 fn get_inbound_payment_key(&self) -> ExpandedKey {
2369 self.inbound_payment_key.clone()
2370 }
2371
2372 fn sign_invoice(
2373 &self, invoice: &RawBolt11Invoice, recipient: Recipient,
2374 ) -> Result<RecoverableSignature, ()> {
2375 let hash = invoice.signable_hash();
2376 let secret = match recipient {
2377 Recipient::Node => &self.inner.node_secret,
2378 Recipient::PhantomNode => &self.phantom_secret,
2379 };
2380 Ok(self.inner.secp_ctx.sign_ecdsa_recoverable(&hash_to_message!(&hash), secret))
2381 }
2382
2383 fn sign_bolt12_invoice(
2384 &self, invoice: &UnsignedBolt12Invoice,
2385 ) -> Result<schnorr::Signature, ()> {
2386 self.inner.sign_bolt12_invoice(invoice)
2387 }
2388
2389 fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
2390 self.inner.sign_gossip_message(msg)
2391 }
2392}
2393
2394impl OutputSpender for PhantomKeysManager {
2395 fn spend_spendable_outputs<C: Signing>(
2398 &self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
2399 change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
2400 locktime: Option<LockTime>, secp_ctx: &Secp256k1<C>,
2401 ) -> Result<Transaction, ()> {
2402 self.inner.spend_spendable_outputs(
2403 descriptors,
2404 outputs,
2405 change_destination_script,
2406 feerate_sat_per_1000_weight,
2407 locktime,
2408 secp_ctx,
2409 )
2410 }
2411}
2412
2413impl SignerProvider for PhantomKeysManager {
2414 type EcdsaSigner = InMemorySigner;
2415 #[cfg(taproot)]
2416 type TaprootSigner = InMemorySigner;
2417
2418 fn generate_channel_keys_id(
2419 &self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128,
2420 ) -> [u8; 32] {
2421 self.inner.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
2422 }
2423
2424 fn derive_channel_signer(
2425 &self, channel_value_satoshis: u64, channel_keys_id: [u8; 32],
2426 ) -> Self::EcdsaSigner {
2427 self.inner.derive_channel_signer(channel_value_satoshis, channel_keys_id)
2428 }
2429
2430 fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError> {
2431 self.inner.read_chan_signer(reader)
2432 }
2433
2434 fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
2435 self.inner.get_destination_script(channel_keys_id)
2436 }
2437
2438 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
2439 self.inner.get_shutdown_scriptpubkey()
2440 }
2441}
2442
2443impl PhantomKeysManager {
2444 pub fn new(
2456 seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32,
2457 cross_node_seed: &[u8; 32],
2458 ) -> Self {
2459 let inner = KeysManager::new(seed, starting_time_secs, starting_time_nanos);
2460 let (inbound_key, phantom_key) = hkdf_extract_expand_twice(
2461 b"LDK Inbound and Phantom Payment Key Expansion",
2462 cross_node_seed,
2463 );
2464 let phantom_secret = SecretKey::from_slice(&phantom_key).unwrap();
2465 let phantom_node_id = PublicKey::from_secret_key(&inner.secp_ctx, &phantom_secret);
2466 Self {
2467 inner,
2468 inbound_payment_key: ExpandedKey::new(inbound_key),
2469 phantom_secret,
2470 phantom_node_id,
2471 }
2472 }
2473
2474 pub fn derive_channel_keys(
2476 &self, channel_value_satoshis: u64, params: &[u8; 32],
2477 ) -> InMemorySigner {
2478 self.inner.derive_channel_keys(channel_value_satoshis, params)
2479 }
2480
2481 pub fn get_node_secret_key(&self) -> SecretKey {
2483 self.inner.get_node_secret_key()
2484 }
2485
2486 pub fn get_phantom_node_secret_key(&self) -> SecretKey {
2489 self.phantom_secret
2490 }
2491}
2492
2493pub struct RandomBytes {
2495 seed: [u8; 32],
2497 index: AtomicCounter,
2500}
2501
2502impl RandomBytes {
2503 pub fn new(seed: [u8; 32]) -> Self {
2505 Self { seed, index: AtomicCounter::new() }
2506 }
2507
2508 #[cfg(test)]
2509 pub(crate) fn set_counter(&self, count: u64) {
2512 self.index.set_counter(count);
2513 }
2514}
2515
2516impl EntropySource for RandomBytes {
2517 fn get_secure_random_bytes(&self) -> [u8; 32] {
2518 let index = self.index.next();
2519 let mut nonce = [0u8; 16];
2520 nonce[..8].copy_from_slice(&index.to_be_bytes());
2521 ChaCha20::get_single_block(&self.seed, &nonce)
2522 }
2523}
2524
2525#[test]
2527pub fn dyn_sign() {
2528 let _signer: Box<dyn EcdsaChannelSigner>;
2529}
2530
2531#[cfg(ldk_bench)]
2532pub mod benches {
2533 use crate::sign::{EntropySource, KeysManager};
2534 use bitcoin::constants::genesis_block;
2535 use bitcoin::Network;
2536 use std::sync::mpsc::TryRecvError;
2537 use std::sync::{mpsc, Arc};
2538 use std::thread;
2539 use std::time::Duration;
2540
2541 use criterion::Criterion;
2542
2543 pub fn bench_get_secure_random_bytes(bench: &mut Criterion) {
2544 let seed = [0u8; 32];
2545 let now = Duration::from_secs(genesis_block(Network::Testnet).header.time as u64);
2546 let keys_manager = Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_micros()));
2547
2548 let mut handles = Vec::new();
2549 let mut stops = Vec::new();
2550 for _ in 1..5 {
2551 let keys_manager_clone = Arc::clone(&keys_manager);
2552 let (stop_sender, stop_receiver) = mpsc::channel();
2553 let handle = thread::spawn(move || loop {
2554 keys_manager_clone.get_secure_random_bytes();
2555 match stop_receiver.try_recv() {
2556 Ok(_) | Err(TryRecvError::Disconnected) => {
2557 println!("Terminating.");
2558 break;
2559 },
2560 Err(TryRecvError::Empty) => {},
2561 }
2562 });
2563 handles.push(handle);
2564 stops.push(stop_sender);
2565 }
2566
2567 bench.bench_function("get_secure_random_bytes", |b| {
2568 b.iter(|| keys_manager.get_secure_random_bytes())
2569 });
2570
2571 for stop in stops {
2572 let _ = stop.send(());
2573 }
2574 for handle in handles {
2575 handle.join().unwrap();
2576 }
2577 }
2578}