use bitcoin::amount::Amount;
use bitcoin::bip32::{ChildNumber, Xpriv, Xpub};
use bitcoin::ecdsa::Signature as EcdsaSignature;
use bitcoin::locktime::absolute::LockTime;
use bitcoin::network::Network;
use bitcoin::opcodes;
use bitcoin::script::{Builder, Script, ScriptBuf};
use bitcoin::sighash;
use bitcoin::sighash::EcdsaSighashType;
use bitcoin::transaction::Version;
use bitcoin::transaction::{Transaction, TxIn, TxOut};
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::hashes::sha256d::Hash as Sha256dHash;
use bitcoin::hashes::{Hash, HashEngine};
use bitcoin::secp256k1::ecdh::SharedSecret;
use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
use bitcoin::secp256k1::schnorr;
use bitcoin::secp256k1::All;
use bitcoin::secp256k1::{Keypair, PublicKey, Scalar, Secp256k1, SecretKey, Signing};
use bitcoin::{secp256k1, Psbt, Sequence, Txid, WPubkeyHash, Witness};
use lightning_invoice::RawBolt11Invoice;
use crate::chain::transaction::OutPoint;
use crate::crypto::utils::{hkdf_extract_expand_twice, sign, sign_with_aux_rand};
use crate::ln::chan_utils;
use crate::ln::chan_utils::{
get_countersigner_payment_script, get_revokeable_redeemscript, make_funding_redeemscript,
ChannelPublicKeys, ChannelTransactionParameters, ClosingTransaction, CommitmentTransaction,
HTLCOutputInCommitment, HolderCommitmentTransaction,
};
use crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI;
use crate::ln::channel_keys::{
add_public_key_tweak, DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, HtlcKey,
RevocationBasepoint, RevocationKey,
};
use crate::ln::inbound_payment::ExpandedKey;
#[cfg(taproot)]
use crate::ln::msgs::PartialSignatureWithNonce;
use crate::ln::msgs::{UnsignedChannelAnnouncement, UnsignedGossipMessage};
use crate::ln::script::ShutdownScript;
use crate::offers::invoice::UnsignedBolt12Invoice;
use crate::types::features::ChannelTypeFeatures;
use crate::types::payment::PaymentPreimage;
use crate::util::async_poll::AsyncResult;
use crate::util::ser::{ReadableArgs, Writeable};
use crate::util::transaction_utils;
use crate::crypto::chacha20::ChaCha20;
use crate::prelude::*;
use crate::sign::ecdsa::EcdsaChannelSigner;
#[cfg(taproot)]
use crate::sign::taproot::TaprootChannelSigner;
use crate::util::atomic_counter::AtomicCounter;
use core::convert::TryInto;
use core::ops::Deref;
use core::sync::atomic::{AtomicUsize, Ordering};
#[cfg(taproot)]
use musig2::types::{PartialSignature, PublicNonce};
pub(crate) mod type_resolver;
pub mod ecdsa;
#[cfg(taproot)]
pub mod taproot;
pub mod tx_builder;
pub(crate) const COMPRESSED_PUBLIC_KEY_SIZE: usize = bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
pub(crate) const MAX_STANDARD_SIGNATURE_SIZE: usize =
bitcoin::secp256k1::constants::MAX_SIGNATURE_SIZE;
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct DelayedPaymentOutputDescriptor {
pub outpoint: OutPoint,
pub per_commitment_point: PublicKey,
pub to_self_delay: u16,
pub output: TxOut,
pub revocation_pubkey: RevocationKey,
pub channel_keys_id: [u8; 32],
pub channel_value_satoshis: u64,
pub channel_transaction_parameters: Option<ChannelTransactionParameters>,
}
impl DelayedPaymentOutputDescriptor {
pub const MAX_WITNESS_LENGTH: u64 = (1
+ 1
+ MAX_STANDARD_SIGNATURE_SIZE
+ 1
+ 1
+ chan_utils::REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH) as u64;
}
impl_writeable_tlv_based!(DelayedPaymentOutputDescriptor, {
(0, outpoint, required),
(2, per_commitment_point, required),
(4, to_self_delay, required),
(6, output, required),
(8, revocation_pubkey, required),
(10, channel_keys_id, required),
(12, channel_value_satoshis, required),
(13, channel_transaction_parameters, (option: ReadableArgs, Some(channel_value_satoshis.0.unwrap()))),
});
pub(crate) const P2WPKH_WITNESS_WEIGHT: u64 = (1
+ 1
+ MAX_STANDARD_SIGNATURE_SIZE
+ 1
+ COMPRESSED_PUBLIC_KEY_SIZE) as u64;
pub(crate) const P2TR_KEY_PATH_WITNESS_WEIGHT: u64 = (1
+ 1
+ bitcoin::secp256k1::constants::SCHNORR_SIGNATURE_SIZE)
as u64;
pub const STATIC_PAYMENT_KEY_COUNT: u16 = 1000;
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct StaticPaymentOutputDescriptor {
pub outpoint: OutPoint,
pub output: TxOut,
pub channel_keys_id: [u8; 32],
pub channel_value_satoshis: u64,
pub channel_transaction_parameters: Option<ChannelTransactionParameters>,
}
impl StaticPaymentOutputDescriptor {
pub fn witness_script(&self) -> Option<ScriptBuf> {
self.channel_transaction_parameters.as_ref().and_then(|channel_params| {
if channel_params.channel_type_features.supports_anchors_zero_fee_htlc_tx() {
let payment_point = channel_params.holder_pubkeys.payment_point;
Some(chan_utils::get_to_countersigner_keyed_anchor_redeemscript(&payment_point))
} else {
None
}
})
}
pub fn max_witness_length(&self) -> u64 {
if self.needs_csv_1_for_spend() {
let witness_script_weight = 1
+ COMPRESSED_PUBLIC_KEY_SIZE
+ 1
+ 1
+ 1 ;
(1
+ 1
+ MAX_STANDARD_SIGNATURE_SIZE
+ 1
+ witness_script_weight) as u64
} else {
P2WPKH_WITNESS_WEIGHT
}
}
pub fn needs_csv_1_for_spend(&self) -> bool {
let chan_params = self.channel_transaction_parameters.as_ref();
chan_params.map_or(false, |p| p.channel_type_features.supports_anchors_zero_fee_htlc_tx())
}
}
impl_writeable_tlv_based!(StaticPaymentOutputDescriptor, {
(0, outpoint, required),
(2, output, required),
(4, channel_keys_id, required),
(6, channel_value_satoshis, required),
(7, channel_transaction_parameters, (option: ReadableArgs, Some(channel_value_satoshis.0.unwrap()))),
});
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub enum SpendableOutputDescriptor {
StaticOutput {
outpoint: OutPoint,
output: TxOut,
channel_keys_id: Option<[u8; 32]>,
},
DelayedPaymentOutput(DelayedPaymentOutputDescriptor),
StaticPaymentOutput(StaticPaymentOutputDescriptor),
}
impl_writeable_tlv_based_enum_legacy!(SpendableOutputDescriptor,
(0, StaticOutput) => {
(0, outpoint, required),
(1, channel_keys_id, option),
(2, output, required),
},
;
(1, DelayedPaymentOutput),
(2, StaticPaymentOutput),
);
impl SpendableOutputDescriptor {
pub fn to_psbt_input<T: secp256k1::Signing>(
&self, secp_ctx: &Secp256k1<T>,
) -> bitcoin::psbt::Input {
match self {
SpendableOutputDescriptor::StaticOutput { output, .. } => {
bitcoin::psbt::Input { witness_utxo: Some(output.clone()), ..Default::default() }
},
SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
channel_transaction_parameters,
per_commitment_point,
revocation_pubkey,
to_self_delay,
output,
..
}) => {
let delayed_payment_basepoint = channel_transaction_parameters
.as_ref()
.map(|params| params.holder_pubkeys.delayed_payment_basepoint);
let (witness_script, add_tweak) =
if let Some(basepoint) = delayed_payment_basepoint.as_ref() {
let add_tweak = basepoint.derive_add_tweak(&per_commitment_point);
let delayed_payment_key = DelayedPaymentKey(add_public_key_tweak(
secp_ctx,
&basepoint.to_public_key(),
&add_tweak,
));
(
Some(get_revokeable_redeemscript(
&revocation_pubkey,
*to_self_delay,
&delayed_payment_key,
)),
Some(add_tweak),
)
} else {
(None, None)
};
bitcoin::psbt::Input {
witness_utxo: Some(output.clone()),
witness_script,
proprietary: add_tweak
.map(|add_tweak| {
[(
bitcoin::psbt::raw::ProprietaryKey {
prefix: "LDK_spendable_output".as_bytes().to_vec(),
subtype: 0,
key: "add_tweak".as_bytes().to_vec(),
},
add_tweak.as_byte_array().to_vec(),
)]
.into_iter()
.collect()
})
.unwrap_or_default(),
..Default::default()
}
},
SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => bitcoin::psbt::Input {
witness_utxo: Some(descriptor.output.clone()),
witness_script: descriptor.witness_script(),
..Default::default()
},
}
}
pub fn create_spendable_outputs_psbt<T: secp256k1::Signing>(
secp_ctx: &Secp256k1<T>, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
locktime: Option<LockTime>,
) -> Result<(Psbt, u64), ()> {
let mut input = Vec::with_capacity(descriptors.len());
let mut input_value = Amount::ZERO;
let mut witness_weight = 0;
let mut output_set = hash_set_with_capacity(descriptors.len());
for outp in descriptors {
match outp {
SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
if !output_set.insert(descriptor.outpoint) {
return Err(());
}
let sequence = if descriptor.needs_csv_1_for_spend() {
Sequence::from_consensus(1)
} else {
Sequence::ZERO
};
input.push(TxIn {
previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
script_sig: ScriptBuf::new(),
sequence,
witness: Witness::new(),
});
witness_weight += descriptor.max_witness_length();
#[cfg(feature = "grind_signatures")]
{
witness_weight -= 1;
}
input_value += descriptor.output.value;
},
SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
if !output_set.insert(descriptor.outpoint) {
return Err(());
}
input.push(TxIn {
previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
script_sig: ScriptBuf::new(),
sequence: Sequence(descriptor.to_self_delay as u32),
witness: Witness::new(),
});
witness_weight += DelayedPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
#[cfg(feature = "grind_signatures")]
{
witness_weight -= 1;
}
input_value += descriptor.output.value;
},
SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => {
if !output_set.insert(*outpoint) {
return Err(());
}
input.push(TxIn {
previous_output: outpoint.into_bitcoin_outpoint(),
script_sig: ScriptBuf::new(),
sequence: Sequence::ZERO,
witness: Witness::new(),
});
witness_weight += P2WPKH_WITNESS_WEIGHT;
#[cfg(feature = "grind_signatures")]
{
witness_weight -= 1;
}
input_value += output.value;
},
}
if input_value > Amount::MAX_MONEY {
return Err(());
}
}
let mut tx = Transaction {
version: Version::TWO,
lock_time: locktime.unwrap_or(LockTime::ZERO),
input,
output: outputs,
};
let expected_max_weight = transaction_utils::maybe_add_change_output(
&mut tx,
input_value,
witness_weight,
feerate_sat_per_1000_weight,
change_destination_script,
)?;
let psbt_inputs =
descriptors.iter().map(|d| d.to_psbt_input(&secp_ctx)).collect::<Vec<_>>();
let psbt = Psbt {
inputs: psbt_inputs,
outputs: vec![Default::default(); tx.output.len()],
unsigned_tx: tx,
xpub: Default::default(),
version: 0,
proprietary: Default::default(),
unknown: Default::default(),
};
Ok((psbt, expected_max_weight))
}
pub fn spendable_outpoint(&self) -> OutPoint {
match self {
Self::StaticOutput { outpoint, .. } => *outpoint,
Self::StaticPaymentOutput(descriptor) => descriptor.outpoint,
Self::DelayedPaymentOutput(descriptor) => descriptor.outpoint,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ChannelDerivationParameters {
pub value_satoshis: u64,
pub keys_id: [u8; 32],
pub transaction_parameters: ChannelTransactionParameters,
}
impl_writeable_tlv_based!(ChannelDerivationParameters, {
(0, value_satoshis, required),
(2, keys_id, required),
(4, transaction_parameters, (required: ReadableArgs, Some(value_satoshis.0.unwrap()))),
});
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HTLCDescriptor {
pub channel_derivation_parameters: ChannelDerivationParameters,
pub commitment_txid: Txid,
pub per_commitment_number: u64,
pub per_commitment_point: PublicKey,
pub feerate_per_kw: u32,
pub htlc: HTLCOutputInCommitment,
pub preimage: Option<PaymentPreimage>,
pub counterparty_sig: Signature,
}
impl_writeable_tlv_based!(HTLCDescriptor, {
(0, channel_derivation_parameters, required),
(1, feerate_per_kw, (default_value, 0)),
(2, commitment_txid, required),
(4, per_commitment_number, required),
(6, per_commitment_point, required),
(8, htlc, required),
(10, preimage, option),
(12, counterparty_sig, required),
});
impl HTLCDescriptor {
pub fn outpoint(&self) -> bitcoin::OutPoint {
bitcoin::OutPoint {
txid: self.commitment_txid,
vout: self.htlc.transaction_output_index.unwrap(),
}
}
pub fn previous_utxo<C: secp256k1::Signing + secp256k1::Verification>(
&self, secp: &Secp256k1<C>,
) -> TxOut {
TxOut {
script_pubkey: self.witness_script(secp).to_p2wsh(),
value: self.htlc.to_bitcoin_amount(),
}
}
pub fn unsigned_tx_input(&self) -> TxIn {
chan_utils::build_htlc_input(
&self.commitment_txid,
&self.htlc,
&self.channel_derivation_parameters.transaction_parameters.channel_type_features,
)
}
pub fn tx_output<C: secp256k1::Signing + secp256k1::Verification>(
&self, secp: &Secp256k1<C>,
) -> TxOut {
let channel_params =
self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
let broadcaster_keys = channel_params.broadcaster_pubkeys();
let counterparty_keys = channel_params.countersignatory_pubkeys();
let broadcaster_delayed_key = DelayedPaymentKey::from_basepoint(
secp,
&broadcaster_keys.delayed_payment_basepoint,
&self.per_commitment_point,
);
let counterparty_revocation_key = &RevocationKey::from_basepoint(
&secp,
&counterparty_keys.revocation_basepoint,
&self.per_commitment_point,
);
chan_utils::build_htlc_output(
self.feerate_per_kw,
channel_params.contest_delay(),
&self.htlc,
channel_params.channel_type_features(),
&broadcaster_delayed_key,
&counterparty_revocation_key,
)
}
pub fn witness_script<C: secp256k1::Signing + secp256k1::Verification>(
&self, secp: &Secp256k1<C>,
) -> ScriptBuf {
let channel_params =
self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
let broadcaster_keys = channel_params.broadcaster_pubkeys();
let counterparty_keys = channel_params.countersignatory_pubkeys();
let broadcaster_htlc_key = HtlcKey::from_basepoint(
secp,
&broadcaster_keys.htlc_basepoint,
&self.per_commitment_point,
);
let counterparty_htlc_key = HtlcKey::from_basepoint(
secp,
&counterparty_keys.htlc_basepoint,
&self.per_commitment_point,
);
let counterparty_revocation_key = &RevocationKey::from_basepoint(
&secp,
&counterparty_keys.revocation_basepoint,
&self.per_commitment_point,
);
chan_utils::get_htlc_redeemscript_with_explicit_keys(
&self.htlc,
channel_params.channel_type_features(),
&broadcaster_htlc_key,
&counterparty_htlc_key,
&counterparty_revocation_key,
)
}
pub fn tx_input_witness(&self, signature: &Signature, witness_script: &Script) -> Witness {
chan_utils::build_htlc_input_witness(
signature,
&self.counterparty_sig,
&self.preimage,
witness_script,
&self.channel_derivation_parameters.transaction_parameters.channel_type_features,
)
}
}
pub trait ChannelSigner {
fn get_per_commitment_point(
&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<PublicKey, ()>;
fn release_commitment_secret(&self, idx: u64) -> Result<[u8; 32], ()>;
fn validate_holder_commitment(
&self, holder_tx: &HolderCommitmentTransaction,
outbound_htlc_preimages: Vec<PaymentPreimage>,
) -> Result<(), ()>;
fn validate_counterparty_revocation(&self, idx: u64, secret: &SecretKey) -> Result<(), ()>;
fn pubkeys(&self, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelPublicKeys;
fn new_funding_pubkey(
&self, splice_parent_funding_txid: Txid, secp_ctx: &Secp256k1<secp256k1::All>,
) -> PublicKey;
fn channel_keys_id(&self) -> [u8; 32];
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct PeerStorageKey {
pub inner: [u8; 32],
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct ReceiveAuthKey(pub [u8; 32]);
#[derive(Clone, Copy)]
pub enum Recipient {
Node,
PhantomNode,
}
pub trait EntropySource {
fn get_secure_random_bytes(&self) -> [u8; 32];
}
pub trait NodeSigner {
fn get_expanded_key(&self) -> ExpandedKey;
fn get_peer_storage_key(&self) -> PeerStorageKey;
fn get_receive_auth_key(&self) -> ReceiveAuthKey;
fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()>;
fn ecdh(
&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
) -> Result<SharedSecret, ()>;
fn sign_invoice(
&self, invoice: &RawBolt11Invoice, recipient: Recipient,
) -> Result<RecoverableSignature, ()>;
fn sign_bolt12_invoice(
&self, invoice: &UnsignedBolt12Invoice,
) -> Result<schnorr::Signature, ()>;
fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()>;
fn sign_message(&self, msg: &[u8]) -> Result<String, ()>;
}
pub trait OutputSpender {
fn spend_spendable_outputs(
&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
locktime: Option<LockTime>, secp_ctx: &Secp256k1<All>,
) -> Result<Transaction, ()>;
}
#[cfg(taproot)]
#[doc(hidden)]
#[deprecated(note = "Remove once taproot cfg is removed")]
pub type DynSignerProvider =
dyn SignerProvider<EcdsaSigner = InMemorySigner, TaprootSigner = InMemorySigner>;
#[cfg(not(taproot))]
#[doc(hidden)]
#[deprecated(note = "Remove once taproot cfg is removed")]
pub type DynSignerProvider = dyn SignerProvider<EcdsaSigner = InMemorySigner>;
pub trait SignerProvider {
type EcdsaSigner: EcdsaChannelSigner;
#[cfg(taproot)]
type TaprootSigner: TaprootChannelSigner;
fn generate_channel_keys_id(&self, inbound: bool, user_channel_id: u128) -> [u8; 32];
fn derive_channel_signer(&self, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner;
fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()>;
fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()>;
}
pub trait ChangeDestinationSource {
fn get_change_destination_script<'a>(&'a self) -> AsyncResult<'a, ScriptBuf, ()>;
}
pub trait ChangeDestinationSourceSync {
fn get_change_destination_script(&self) -> Result<ScriptBuf, ()>;
}
#[doc(hidden)]
pub struct ChangeDestinationSourceSyncWrapper<T: Deref>(T)
where
T::Target: ChangeDestinationSourceSync;
impl<T: Deref> ChangeDestinationSourceSyncWrapper<T>
where
T::Target: ChangeDestinationSourceSync,
{
pub fn new(source: T) -> Self {
Self(source)
}
}
impl<T: Deref> ChangeDestinationSource for ChangeDestinationSourceSyncWrapper<T>
where
T::Target: ChangeDestinationSourceSync,
{
fn get_change_destination_script<'a>(&'a self) -> AsyncResult<'a, ScriptBuf, ()> {
let script = self.0.get_change_destination_script();
Box::pin(async move { script })
}
}
impl<T: Deref> Deref for ChangeDestinationSourceSyncWrapper<T>
where
T::Target: ChangeDestinationSourceSync,
{
type Target = Self;
fn deref(&self) -> &Self {
self
}
}
mod sealed {
use bitcoin::secp256k1::{Scalar, SecretKey};
#[derive(Clone, PartialEq)]
pub struct MaybeTweakedSecretKey(pub(super) SecretKey);
impl From<SecretKey> for MaybeTweakedSecretKey {
fn from(value: SecretKey) -> Self {
Self(value)
}
}
impl MaybeTweakedSecretKey {
pub fn with_tweak(&self, tweak: Option<Scalar>) -> SecretKey {
tweak
.map(|tweak| {
self.0
.add_tweak(&tweak)
.expect("Addition only fails if the tweak is the inverse of the key")
})
.unwrap_or(self.0)
}
}
}
pub fn compute_funding_key_tweak(
base_funding_secret_key: &SecretKey, splice_parent_funding_txid: &Txid,
) -> Scalar {
let mut sha = Sha256::engine();
sha.input(splice_parent_funding_txid.as_byte_array());
sha.input(&base_funding_secret_key.secret_bytes());
Scalar::from_be_bytes(Sha256::from_engine(sha).to_byte_array()).unwrap()
}
pub struct InMemorySigner {
funding_key: sealed::MaybeTweakedSecretKey,
pub revocation_base_key: SecretKey,
payment_key_v1: SecretKey,
payment_key_v2: SecretKey,
v2_remote_key_derivation: bool,
pub delayed_payment_base_key: SecretKey,
pub htlc_base_key: SecretKey,
pub commitment_seed: [u8; 32],
channel_keys_id: [u8; 32],
entropy_source: RandomBytes,
}
impl PartialEq for InMemorySigner {
fn eq(&self, other: &Self) -> bool {
self.funding_key == other.funding_key
&& self.revocation_base_key == other.revocation_base_key
&& self.payment_key_v1 == other.payment_key_v1
&& self.payment_key_v2 == other.payment_key_v2
&& self.v2_remote_key_derivation == other.v2_remote_key_derivation
&& self.delayed_payment_base_key == other.delayed_payment_base_key
&& self.htlc_base_key == other.htlc_base_key
&& self.commitment_seed == other.commitment_seed
&& self.channel_keys_id == other.channel_keys_id
}
}
impl Clone for InMemorySigner {
fn clone(&self) -> Self {
Self {
funding_key: self.funding_key.clone(),
revocation_base_key: self.revocation_base_key.clone(),
payment_key_v1: self.payment_key_v1.clone(),
payment_key_v2: self.payment_key_v2.clone(),
v2_remote_key_derivation: self.v2_remote_key_derivation,
delayed_payment_base_key: self.delayed_payment_base_key.clone(),
htlc_base_key: self.htlc_base_key.clone(),
commitment_seed: self.commitment_seed.clone(),
channel_keys_id: self.channel_keys_id,
entropy_source: RandomBytes::new(self.get_secure_random_bytes()),
}
}
}
impl InMemorySigner {
#[cfg(any(feature = "_test_utils", test))]
pub fn new(
funding_key: SecretKey, revocation_base_key: SecretKey, payment_key_v1: SecretKey,
payment_key_v2: SecretKey, v2_remote_key_derivation: bool,
delayed_payment_base_key: SecretKey, htlc_base_key: SecretKey, commitment_seed: [u8; 32],
channel_keys_id: [u8; 32], rand_bytes_unique_start: [u8; 32],
) -> InMemorySigner {
InMemorySigner {
funding_key: sealed::MaybeTweakedSecretKey::from(funding_key),
revocation_base_key,
payment_key_v1,
payment_key_v2,
v2_remote_key_derivation,
delayed_payment_base_key,
htlc_base_key,
commitment_seed,
channel_keys_id,
entropy_source: RandomBytes::new(rand_bytes_unique_start),
}
}
#[cfg(not(any(feature = "_test_utils", test)))]
fn new(
funding_key: SecretKey, revocation_base_key: SecretKey, payment_key_v1: SecretKey,
payment_key_v2: SecretKey, v2_remote_key_derivation: bool,
delayed_payment_base_key: SecretKey, htlc_base_key: SecretKey, commitment_seed: [u8; 32],
channel_keys_id: [u8; 32], rand_bytes_unique_start: [u8; 32],
) -> InMemorySigner {
InMemorySigner {
funding_key: sealed::MaybeTweakedSecretKey::from(funding_key),
revocation_base_key,
payment_key_v1,
payment_key_v2,
v2_remote_key_derivation,
delayed_payment_base_key,
htlc_base_key,
commitment_seed,
channel_keys_id,
entropy_source: RandomBytes::new(rand_bytes_unique_start),
}
}
pub fn funding_key(&self, splice_parent_funding_txid: Option<Txid>) -> SecretKey {
let tweak = splice_parent_funding_txid
.map(|txid| compute_funding_key_tweak(&self.funding_key.with_tweak(None), &txid));
self.funding_key.with_tweak(tweak)
}
pub fn sign_counterparty_payment_input<C: Signing>(
&self, spend_tx: &Transaction, input_idx: usize,
descriptor: &StaticPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>,
) -> Result<Witness, ()> {
if spend_tx.input.len() <= input_idx {
return Err(());
}
if !spend_tx.input[input_idx].script_sig.is_empty() {
return Err(());
}
if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint()
{
return Err(());
}
let legacy_default_channel_type = ChannelTypeFeatures::only_static_remote_key();
let channel_type_features = descriptor
.channel_transaction_parameters
.as_ref()
.map(|params| ¶ms.channel_type_features)
.unwrap_or(&legacy_default_channel_type);
let payment_point_v1 = PublicKey::from_secret_key(secp_ctx, &self.payment_key_v1);
let payment_point_v2 = PublicKey::from_secret_key(secp_ctx, &self.payment_key_v2);
let spk_v1 = get_countersigner_payment_script(channel_type_features, &payment_point_v1);
let spk_v2 = get_countersigner_payment_script(channel_type_features, &payment_point_v2);
let (remotepubkey, payment_key) = if spk_v1 == descriptor.output.script_pubkey {
(bitcoin::PublicKey::new(payment_point_v1), &self.payment_key_v1)
} else {
if spk_v2 != descriptor.output.script_pubkey {
return Err(());
}
(bitcoin::PublicKey::new(payment_point_v2), &self.payment_key_v2)
};
let witness_script = if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
chan_utils::get_to_countersigner_keyed_anchor_redeemscript(&remotepubkey.inner)
} else {
ScriptBuf::new_p2pkh(&remotepubkey.pubkey_hash())
};
let sighash = hash_to_message!(
&sighash::SighashCache::new(spend_tx)
.p2wsh_signature_hash(
input_idx,
&witness_script,
descriptor.output.value,
EcdsaSighashType::All
)
.unwrap()[..]
);
let remotesig = sign_with_aux_rand(secp_ctx, &sighash, payment_key, &self);
let payment_script = if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
witness_script.to_p2wsh()
} else {
ScriptBuf::new_p2wpkh(&remotepubkey.wpubkey_hash().unwrap())
};
if payment_script != descriptor.output.script_pubkey {
return Err(());
}
let mut witness = Vec::with_capacity(2);
witness.push(remotesig.serialize_der().to_vec());
witness[0].push(EcdsaSighashType::All as u8);
if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
witness.push(witness_script.to_bytes());
} else {
witness.push(remotepubkey.to_bytes());
}
Ok(witness.into())
}
pub fn sign_dynamic_p2wsh_input<C: Signing>(
&self, spend_tx: &Transaction, input_idx: usize,
descriptor: &DelayedPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>,
) -> Result<Witness, ()> {
if spend_tx.input.len() <= input_idx {
return Err(());
}
if !spend_tx.input[input_idx].script_sig.is_empty() {
return Err(());
}
if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint()
{
return Err(());
}
if spend_tx.input[input_idx].sequence.0 != descriptor.to_self_delay as u32 {
return Err(());
}
let delayed_payment_key = chan_utils::derive_private_key(
&secp_ctx,
&descriptor.per_commitment_point,
&self.delayed_payment_base_key,
);
let delayed_payment_pubkey =
DelayedPaymentKey::from_secret_key(&secp_ctx, &delayed_payment_key);
let witness_script = chan_utils::get_revokeable_redeemscript(
&descriptor.revocation_pubkey,
descriptor.to_self_delay,
&delayed_payment_pubkey,
);
let sighash = hash_to_message!(
&sighash::SighashCache::new(spend_tx)
.p2wsh_signature_hash(
input_idx,
&witness_script,
descriptor.output.value,
EcdsaSighashType::All
)
.unwrap()[..]
);
let local_delayedsig = EcdsaSignature {
signature: sign_with_aux_rand(secp_ctx, &sighash, &delayed_payment_key, &self),
sighash_type: EcdsaSighashType::All,
};
let payment_script =
bitcoin::Address::p2wsh(&witness_script, Network::Bitcoin).script_pubkey();
if descriptor.output.script_pubkey != payment_script {
return Err(());
}
Ok(Witness::from_slice(&[
&local_delayedsig.serialize()[..],
&[], witness_script.as_bytes(),
]))
}
}
impl EntropySource for InMemorySigner {
fn get_secure_random_bytes(&self) -> [u8; 32] {
self.entropy_source.get_secure_random_bytes()
}
}
impl ChannelSigner for InMemorySigner {
fn get_per_commitment_point(
&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<PublicKey, ()> {
let commitment_secret =
SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx))
.unwrap();
Ok(PublicKey::from_secret_key(secp_ctx, &commitment_secret))
}
fn release_commitment_secret(&self, idx: u64) -> Result<[u8; 32], ()> {
Ok(chan_utils::build_commitment_secret(&self.commitment_seed, idx))
}
fn validate_holder_commitment(
&self, _holder_tx: &HolderCommitmentTransaction,
_outbound_htlc_preimages: Vec<PaymentPreimage>,
) -> Result<(), ()> {
Ok(())
}
fn validate_counterparty_revocation(&self, _idx: u64, _secret: &SecretKey) -> Result<(), ()> {
Ok(())
}
fn pubkeys(&self, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelPublicKeys {
let payment_key =
if self.v2_remote_key_derivation { &self.payment_key_v2 } else { &self.payment_key_v1 };
let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
let pubkeys = ChannelPublicKeys {
funding_pubkey: from_secret(&self.funding_key.0),
revocation_basepoint: RevocationBasepoint::from(from_secret(&self.revocation_base_key)),
payment_point: from_secret(payment_key),
delayed_payment_basepoint: DelayedPaymentBasepoint::from(from_secret(
&self.delayed_payment_base_key,
)),
htlc_basepoint: HtlcBasepoint::from(from_secret(&self.htlc_base_key)),
};
pubkeys
}
fn new_funding_pubkey(
&self, splice_parent_funding_txid: Txid, secp_ctx: &Secp256k1<secp256k1::All>,
) -> PublicKey {
self.funding_key(Some(splice_parent_funding_txid)).public_key(secp_ctx)
}
fn channel_keys_id(&self) -> [u8; 32] {
self.channel_keys_id
}
}
const MISSING_PARAMS_ERR: &'static str =
"ChannelTransactionParameters must be populated before signing operations";
impl EcdsaChannelSigner for InMemorySigner {
fn sign_counterparty_commitment(
&self, channel_parameters: &ChannelTransactionParameters,
commitment_tx: &CommitmentTransaction, _inbound_htlc_preimages: Vec<PaymentPreimage>,
_outbound_htlc_preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<(Signature, Vec<Signature>), ()> {
assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
let trusted_tx = commitment_tx.trust();
let keys = trusted_tx.keys();
let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
let funding_pubkey = funding_key.public_key(secp_ctx);
let counterparty_keys =
channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
let channel_funding_redeemscript =
make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
let built_tx = trusted_tx.built_transaction();
let commitment_sig = built_tx.sign_counterparty_commitment(
&funding_key,
&channel_funding_redeemscript,
channel_parameters.channel_value_satoshis,
secp_ctx,
);
let commitment_txid = built_tx.txid;
let mut htlc_sigs = Vec::with_capacity(commitment_tx.nondust_htlcs().len());
for htlc in commitment_tx.nondust_htlcs() {
let holder_selected_contest_delay = channel_parameters.holder_selected_contest_delay;
let chan_type = &channel_parameters.channel_type_features;
let htlc_tx = chan_utils::build_htlc_transaction(
&commitment_txid,
commitment_tx.negotiated_feerate_per_kw(),
holder_selected_contest_delay,
htlc,
chan_type,
&keys.broadcaster_delayed_payment_key,
&keys.revocation_key,
);
let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, chan_type, &keys);
let htlc_sighashtype = if chan_type.supports_anchors_zero_fee_htlc_tx()
|| chan_type.supports_anchor_zero_fee_commitments()
{
EcdsaSighashType::SinglePlusAnyoneCanPay
} else {
EcdsaSighashType::All
};
let htlc_sighash = hash_to_message!(
&sighash::SighashCache::new(&htlc_tx)
.p2wsh_signature_hash(
0,
&htlc_redeemscript,
htlc.to_bitcoin_amount(),
htlc_sighashtype
)
.unwrap()[..]
);
let holder_htlc_key = chan_utils::derive_private_key(
&secp_ctx,
&keys.per_commitment_point,
&self.htlc_base_key,
);
htlc_sigs.push(sign(secp_ctx, &htlc_sighash, &holder_htlc_key));
}
Ok((commitment_sig, htlc_sigs))
}
fn sign_holder_commitment(
&self, channel_parameters: &ChannelTransactionParameters,
commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<Signature, ()> {
assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
let funding_pubkey = funding_key.public_key(secp_ctx);
let counterparty_keys =
channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
let funding_redeemscript =
make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
let trusted_tx = commitment_tx.trust();
Ok(trusted_tx.built_transaction().sign_holder_commitment(
&funding_key,
&funding_redeemscript,
channel_parameters.channel_value_satoshis,
&self,
secp_ctx,
))
}
#[cfg(any(test, feature = "_test_utils", feature = "unsafe_revoked_tx_signing"))]
fn unsafe_sign_holder_commitment(
&self, channel_parameters: &ChannelTransactionParameters,
commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<Signature, ()> {
assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
let funding_pubkey = funding_key.public_key(secp_ctx);
let counterparty_keys =
channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
let funding_redeemscript =
make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
let trusted_tx = commitment_tx.trust();
Ok(trusted_tx.built_transaction().sign_holder_commitment(
&funding_key,
&funding_redeemscript,
channel_parameters.channel_value_satoshis,
&self,
secp_ctx,
))
}
fn sign_justice_revoked_output(
&self, channel_parameters: &ChannelTransactionParameters, justice_tx: &Transaction,
input: usize, amount: u64, per_commitment_key: &SecretKey,
secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<Signature, ()> {
assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
let revocation_key = chan_utils::derive_private_revocation_key(
&secp_ctx,
&per_commitment_key,
&self.revocation_base_key,
);
let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
let revocation_pubkey = RevocationKey::from_basepoint(
&secp_ctx,
&channel_parameters.holder_pubkeys.revocation_basepoint,
&per_commitment_point,
);
let witness_script = {
let counterparty_keys =
channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
let holder_selected_contest_delay = channel_parameters.holder_selected_contest_delay;
let counterparty_delayedpubkey = DelayedPaymentKey::from_basepoint(
&secp_ctx,
&counterparty_keys.delayed_payment_basepoint,
&per_commitment_point,
);
chan_utils::get_revokeable_redeemscript(
&revocation_pubkey,
holder_selected_contest_delay,
&counterparty_delayedpubkey,
)
};
let mut sighash_parts = sighash::SighashCache::new(justice_tx);
let sighash = hash_to_message!(
&sighash_parts
.p2wsh_signature_hash(
input,
&witness_script,
Amount::from_sat(amount),
EcdsaSighashType::All
)
.unwrap()[..]
);
return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self));
}
fn sign_justice_revoked_htlc(
&self, channel_parameters: &ChannelTransactionParameters, justice_tx: &Transaction,
input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &HTLCOutputInCommitment,
secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<Signature, ()> {
assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
let revocation_key = chan_utils::derive_private_revocation_key(
&secp_ctx,
&per_commitment_key,
&self.revocation_base_key,
);
let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
let revocation_pubkey = RevocationKey::from_basepoint(
&secp_ctx,
&channel_parameters.holder_pubkeys.revocation_basepoint,
&per_commitment_point,
);
let witness_script = {
let counterparty_keys =
channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
let counterparty_htlcpubkey = HtlcKey::from_basepoint(
&secp_ctx,
&counterparty_keys.htlc_basepoint,
&per_commitment_point,
);
let holder_htlcpubkey = HtlcKey::from_basepoint(
&secp_ctx,
&channel_parameters.holder_pubkeys.htlc_basepoint,
&per_commitment_point,
);
chan_utils::get_htlc_redeemscript_with_explicit_keys(
&htlc,
&channel_parameters.channel_type_features,
&counterparty_htlcpubkey,
&holder_htlcpubkey,
&revocation_pubkey,
)
};
let mut sighash_parts = sighash::SighashCache::new(justice_tx);
let sighash = hash_to_message!(
&sighash_parts
.p2wsh_signature_hash(
input,
&witness_script,
Amount::from_sat(amount),
EcdsaSighashType::All
)
.unwrap()[..]
);
return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self));
}
fn sign_holder_htlc_transaction(
&self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<Signature, ()> {
let channel_parameters =
&htlc_descriptor.channel_derivation_parameters.transaction_parameters;
assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
let witness_script = htlc_descriptor.witness_script(secp_ctx);
let sighash = &sighash::SighashCache::new(&*htlc_tx)
.p2wsh_signature_hash(
input,
&witness_script,
htlc_descriptor.htlc.to_bitcoin_amount(),
EcdsaSighashType::All,
)
.map_err(|_| ())?;
let our_htlc_private_key = chan_utils::derive_private_key(
&secp_ctx,
&htlc_descriptor.per_commitment_point,
&self.htlc_base_key,
);
let sighash = hash_to_message!(sighash.as_byte_array());
Ok(sign_with_aux_rand(&secp_ctx, &sighash, &our_htlc_private_key, &self))
}
fn sign_counterparty_htlc_transaction(
&self, channel_parameters: &ChannelTransactionParameters, htlc_tx: &Transaction,
input: usize, amount: u64, per_commitment_point: &PublicKey, htlc: &HTLCOutputInCommitment,
secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<Signature, ()> {
assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
let htlc_key =
chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key);
let revocation_pubkey = RevocationKey::from_basepoint(
&secp_ctx,
&channel_parameters.holder_pubkeys.revocation_basepoint,
&per_commitment_point,
);
let counterparty_keys =
channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
let counterparty_htlcpubkey = HtlcKey::from_basepoint(
&secp_ctx,
&counterparty_keys.htlc_basepoint,
&per_commitment_point,
);
let htlc_basepoint = channel_parameters.holder_pubkeys.htlc_basepoint;
let htlcpubkey = HtlcKey::from_basepoint(&secp_ctx, &htlc_basepoint, &per_commitment_point);
let chan_type = &channel_parameters.channel_type_features;
let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(
&htlc,
chan_type,
&counterparty_htlcpubkey,
&htlcpubkey,
&revocation_pubkey,
);
let mut sighash_parts = sighash::SighashCache::new(htlc_tx);
let sighash = hash_to_message!(
&sighash_parts
.p2wsh_signature_hash(
input,
&witness_script,
Amount::from_sat(amount),
EcdsaSighashType::All
)
.unwrap()[..]
);
Ok(sign_with_aux_rand(secp_ctx, &sighash, &htlc_key, &self))
}
fn sign_closing_transaction(
&self, channel_parameters: &ChannelTransactionParameters, closing_tx: &ClosingTransaction,
secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<Signature, ()> {
assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
let funding_pubkey = funding_key.public_key(secp_ctx);
let counterparty_funding_key =
&channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR).funding_pubkey;
let channel_funding_redeemscript =
make_funding_redeemscript(&funding_pubkey, counterparty_funding_key);
Ok(closing_tx.trust().sign(
&funding_key,
&channel_funding_redeemscript,
channel_parameters.channel_value_satoshis,
secp_ctx,
))
}
fn sign_holder_keyed_anchor_input(
&self, chan_params: &ChannelTransactionParameters, anchor_tx: &Transaction, input: usize,
secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<Signature, ()> {
assert!(chan_params.is_populated(), "Channel parameters must be fully populated");
let witness_script =
chan_utils::get_keyed_anchor_redeemscript(&chan_params.holder_pubkeys.funding_pubkey);
let amt = Amount::from_sat(ANCHOR_OUTPUT_VALUE_SATOSHI);
let sighash = sighash::SighashCache::new(&*anchor_tx)
.p2wsh_signature_hash(input, &witness_script, amt, EcdsaSighashType::All)
.unwrap();
let funding_key = self.funding_key(chan_params.splice_parent_funding_txid);
Ok(sign_with_aux_rand(secp_ctx, &hash_to_message!(&sighash[..]), &funding_key, &self))
}
fn sign_channel_announcement_with_funding_key(
&self, channel_parameters: &ChannelTransactionParameters,
msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<Signature, ()> {
let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
Ok(secp_ctx.sign_ecdsa(&msghash, &funding_key))
}
fn sign_splice_shared_input(
&self, channel_parameters: &ChannelTransactionParameters, tx: &Transaction,
input_index: usize, secp_ctx: &Secp256k1<secp256k1::All>,
) -> Signature {
assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
assert_eq!(
tx.input[input_index].previous_output,
channel_parameters
.funding_outpoint
.as_ref()
.expect("Funding outpoint must be known prior to signing")
.into_bitcoin_outpoint()
);
let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
let funding_pubkey = funding_key.public_key(secp_ctx);
let counterparty_funding_key =
&channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR).funding_pubkey;
let funding_redeemscript =
make_funding_redeemscript(&funding_pubkey, counterparty_funding_key);
let sighash = &sighash::SighashCache::new(tx)
.p2wsh_signature_hash(
input_index,
&funding_redeemscript,
Amount::from_sat(channel_parameters.channel_value_satoshis),
EcdsaSighashType::All,
)
.unwrap()[..];
let msg = hash_to_message!(sighash);
sign(secp_ctx, &msg, &funding_key)
}
}
#[cfg(taproot)]
#[allow(unused)]
impl TaprootChannelSigner for InMemorySigner {
fn generate_local_nonce_pair(
&self, commitment_number: u64, secp_ctx: &Secp256k1<All>,
) -> PublicNonce {
todo!()
}
fn partially_sign_counterparty_commitment(
&self, counterparty_nonce: PublicNonce, commitment_tx: &CommitmentTransaction,
inbound_htlc_preimages: Vec<PaymentPreimage>,
outbound_htlc_preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<All>,
) -> Result<(PartialSignatureWithNonce, Vec<schnorr::Signature>), ()> {
todo!()
}
fn finalize_holder_commitment(
&self, commitment_tx: &HolderCommitmentTransaction,
counterparty_partial_signature: PartialSignatureWithNonce, secp_ctx: &Secp256k1<All>,
) -> Result<PartialSignature, ()> {
todo!()
}
fn sign_justice_revoked_output(
&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
secp_ctx: &Secp256k1<All>,
) -> Result<schnorr::Signature, ()> {
todo!()
}
fn sign_justice_revoked_htlc(
&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<All>,
) -> Result<schnorr::Signature, ()> {
todo!()
}
fn sign_holder_htlc_transaction(
&self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
secp_ctx: &Secp256k1<All>,
) -> Result<schnorr::Signature, ()> {
todo!()
}
fn sign_counterparty_htlc_transaction(
&self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey,
htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<All>,
) -> Result<schnorr::Signature, ()> {
todo!()
}
fn partially_sign_closing_transaction(
&self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<All>,
) -> Result<PartialSignature, ()> {
todo!()
}
}
pub struct KeysManager {
secp_ctx: Secp256k1<secp256k1::All>,
node_secret: SecretKey,
node_id: PublicKey,
inbound_payment_key: ExpandedKey,
destination_script: ScriptBuf,
shutdown_pubkey: PublicKey,
channel_master_key: Xpriv,
static_payment_key: Xpriv,
v2_remote_key_derivation: bool,
channel_child_index: AtomicUsize,
peer_storage_key: PeerStorageKey,
receive_auth_key: ReceiveAuthKey,
#[cfg(test)]
pub(crate) entropy_source: RandomBytes,
#[cfg(not(test))]
entropy_source: RandomBytes,
seed: [u8; 32],
starting_time_secs: u64,
starting_time_nanos: u32,
}
impl KeysManager {
pub fn new(
seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32,
v2_remote_key_derivation: bool,
) -> Self {
const NODE_SECRET_INDEX: ChildNumber = ChildNumber::Hardened { index: 0 };
const DESTINATION_SCRIPT_INDEX: ChildNumber = ChildNumber::Hardened { index: 1 };
const SHUTDOWN_PUBKEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 2 };
const CHANNEL_MASTER_KEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 3 };
const INBOUND_PAYMENT_KEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 5 };
const PEER_STORAGE_KEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 6 };
const RECEIVE_AUTH_KEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 7 };
const STATIC_PAYMENT_KEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 8 };
let secp_ctx = Secp256k1::new();
match Xpriv::new_master(Network::Testnet, seed) {
Ok(master_key) => {
let node_secret = master_key
.derive_priv(&secp_ctx, &NODE_SECRET_INDEX)
.expect("Your RNG is busted")
.private_key;
let node_id = PublicKey::from_secret_key(&secp_ctx, &node_secret);
let destination_script =
match master_key.derive_priv(&secp_ctx, &DESTINATION_SCRIPT_INDEX) {
Ok(destination_key) => {
let wpubkey_hash = WPubkeyHash::hash(
&Xpub::from_priv(&secp_ctx, &destination_key).to_pub().to_bytes(),
);
Builder::new()
.push_opcode(opcodes::all::OP_PUSHBYTES_0)
.push_slice(&wpubkey_hash.to_byte_array())
.into_script()
},
Err(_) => panic!("Your RNG is busted"),
};
let shutdown_pubkey =
match master_key.derive_priv(&secp_ctx, &SHUTDOWN_PUBKEY_INDEX) {
Ok(shutdown_key) => Xpub::from_priv(&secp_ctx, &shutdown_key).public_key,
Err(_) => panic!("Your RNG is busted"),
};
let channel_master_key = master_key
.derive_priv(&secp_ctx, &CHANNEL_MASTER_KEY_INDEX)
.expect("Your RNG is busted");
let inbound_payment_key: SecretKey = master_key
.derive_priv(&secp_ctx, &INBOUND_PAYMENT_KEY_INDEX)
.expect("Your RNG is busted")
.private_key;
let mut inbound_pmt_key_bytes = [0; 32];
inbound_pmt_key_bytes.copy_from_slice(&inbound_payment_key[..]);
let peer_storage_key = master_key
.derive_priv(&secp_ctx, &PEER_STORAGE_KEY_INDEX)
.expect("Your RNG is busted")
.private_key;
let receive_auth_key = master_key
.derive_priv(&secp_ctx, &RECEIVE_AUTH_KEY_INDEX)
.expect("Your RNG is busted")
.private_key;
let static_payment_key = master_key
.derive_priv(&secp_ctx, &STATIC_PAYMENT_KEY_INDEX)
.expect("Your RNG is busted");
let mut rand_bytes_engine = Sha256::engine();
rand_bytes_engine.input(&starting_time_secs.to_be_bytes());
rand_bytes_engine.input(&starting_time_nanos.to_be_bytes());
rand_bytes_engine.input(seed);
rand_bytes_engine.input(b"LDK PRNG Seed");
let rand_bytes_unique_start =
Sha256::from_engine(rand_bytes_engine).to_byte_array();
let mut res = KeysManager {
secp_ctx,
node_secret,
node_id,
inbound_payment_key: ExpandedKey::new(inbound_pmt_key_bytes),
peer_storage_key: PeerStorageKey { inner: peer_storage_key.secret_bytes() },
receive_auth_key: ReceiveAuthKey(receive_auth_key.secret_bytes()),
destination_script,
shutdown_pubkey,
channel_master_key,
channel_child_index: AtomicUsize::new(0),
static_payment_key,
v2_remote_key_derivation,
entropy_source: RandomBytes::new(rand_bytes_unique_start),
seed: *seed,
starting_time_secs,
starting_time_nanos,
};
let secp_seed = res.get_secure_random_bytes();
res.secp_ctx.seeded_randomize(&secp_seed);
res
},
Err(_) => panic!("Your rng is busted"),
}
}
pub fn get_node_secret_key(&self) -> SecretKey {
self.node_secret
}
pub fn possible_v2_counterparty_closed_balance_spks<C: Signing>(
&self, secp_ctx: &Secp256k1<C>,
) -> Vec<ScriptBuf> {
let mut res = Vec::with_capacity(usize::from(STATIC_PAYMENT_KEY_COUNT) * 2);
let static_remote_key_features = ChannelTypeFeatures::only_static_remote_key();
let mut zero_fee_htlc_features = ChannelTypeFeatures::only_static_remote_key();
zero_fee_htlc_features.set_anchors_zero_fee_htlc_tx_required();
for idx in 0..STATIC_PAYMENT_KEY_COUNT {
let key = self
.static_payment_key
.derive_priv(
&self.secp_ctx,
&ChildNumber::from_hardened_idx(u32::from(idx)).expect("key space exhausted"),
)
.expect("Your RNG is busted")
.private_key;
let pubkey = PublicKey::from_secret_key(secp_ctx, &key);
res.push(get_countersigner_payment_script(&static_remote_key_features, &pubkey));
res.push(get_countersigner_payment_script(&zero_fee_htlc_features, &pubkey));
}
res
}
fn derive_payment_key_v2(&self, key_idx: u64) -> SecretKey {
let idx = key_idx % u64::from(STATIC_PAYMENT_KEY_COUNT);
self.static_payment_key
.derive_priv(
&self.secp_ctx,
&ChildNumber::from_hardened_idx(idx as u32).expect("key space exhausted"),
)
.expect("Your RNG is busted")
.private_key
}
pub fn derive_channel_keys(&self, params: &[u8; 32]) -> InMemorySigner {
let chan_id = u64::from_be_bytes(params[0..8].try_into().unwrap());
let mut unique_start = Sha256::engine();
unique_start.input(params);
unique_start.input(&self.seed);
let child_privkey = self
.channel_master_key
.derive_priv(
&self.secp_ctx,
&ChildNumber::from_hardened_idx((chan_id as u32) % (1 << 31))
.expect("key space exhausted"),
)
.expect("Your RNG is busted");
unique_start.input(&child_privkey.private_key[..]);
let seed = Sha256::from_engine(unique_start).to_byte_array();
let commitment_seed = {
let mut sha = Sha256::engine();
sha.input(&seed);
sha.input(&b"commitment seed"[..]);
Sha256::from_engine(sha).to_byte_array()
};
macro_rules! key_step {
($info: expr, $prev_key: expr) => {{
let mut sha = Sha256::engine();
sha.input(&seed);
sha.input(&$prev_key[..]);
sha.input(&$info[..]);
SecretKey::from_slice(&Sha256::from_engine(sha).to_byte_array())
.expect("SHA-256 is busted")
}};
}
let funding_key = key_step!(b"funding key", commitment_seed);
let revocation_base_key = key_step!(b"revocation base key", funding_key);
let payment_key_v1 = key_step!(b"payment key", revocation_base_key);
let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key_v1);
let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
let prng_seed = self.get_secure_random_bytes();
let payment_key_v2_idx =
u64::from_le_bytes(commitment_seed[..8].try_into().expect("8 bytes"));
InMemorySigner::new(
funding_key,
revocation_base_key,
payment_key_v1,
self.derive_payment_key_v2(payment_key_v2_idx),
self.v2_remote_key_derivation,
delayed_payment_base_key,
htlc_base_key,
commitment_seed,
params.clone(),
prng_seed,
)
}
pub fn sign_spendable_outputs_psbt<C: Signing>(
&self, descriptors: &[&SpendableOutputDescriptor], mut psbt: Psbt, secp_ctx: &Secp256k1<C>,
) -> Result<Psbt, ()> {
let mut keys_cache: Option<(InMemorySigner, [u8; 32])> = None;
for outp in descriptors {
let get_input_idx = |outpoint: &OutPoint| {
psbt.unsigned_tx
.input
.iter()
.position(|i| i.previous_output == outpoint.into_bitcoin_outpoint())
.ok_or(())
};
match outp {
SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
let input_idx = get_input_idx(&descriptor.outpoint)?;
if keys_cache.is_none()
|| keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id
{
let signer = self.derive_channel_keys(&descriptor.channel_keys_id);
keys_cache = Some((signer, descriptor.channel_keys_id));
}
#[cfg(test)]
if self.v2_remote_key_derivation {
let possible_spks =
self.possible_v2_counterparty_closed_balance_spks(secp_ctx);
assert!(possible_spks.contains(&descriptor.output.script_pubkey));
}
let witness = keys_cache.as_ref().unwrap().0.sign_counterparty_payment_input(
&psbt.unsigned_tx,
input_idx,
&descriptor,
&secp_ctx,
)?;
psbt.inputs[input_idx].final_script_witness = Some(witness);
},
SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
let input_idx = get_input_idx(&descriptor.outpoint)?;
if keys_cache.is_none()
|| keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id
{
keys_cache = Some((
self.derive_channel_keys(&descriptor.channel_keys_id),
descriptor.channel_keys_id,
));
}
let witness = keys_cache.as_ref().unwrap().0.sign_dynamic_p2wsh_input(
&psbt.unsigned_tx,
input_idx,
&descriptor,
&secp_ctx,
)?;
psbt.inputs[input_idx].final_script_witness = Some(witness);
},
SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => {
let input_idx = get_input_idx(outpoint)?;
let derivation_idx =
if output.script_pubkey == self.destination_script { 1 } else { 2 };
let secret = {
match Xpriv::new_master(Network::Testnet, &self.seed) {
Ok(master_key) => {
match master_key.derive_priv(
&secp_ctx,
&ChildNumber::from_hardened_idx(derivation_idx)
.expect("key space exhausted"),
) {
Ok(key) => key,
Err(_) => panic!("Your RNG is busted"),
}
},
Err(_) => panic!("Your rng is busted"),
}
};
let pubkey = Xpub::from_priv(&secp_ctx, &secret).to_pub();
if derivation_idx == 2 {
assert_eq!(pubkey.0, self.shutdown_pubkey);
}
let witness_script =
bitcoin::Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
let payment_script =
bitcoin::Address::p2wpkh(&pubkey, Network::Testnet).script_pubkey();
if payment_script != output.script_pubkey {
return Err(());
};
let sighash = hash_to_message!(
&sighash::SighashCache::new(&psbt.unsigned_tx)
.p2wsh_signature_hash(
input_idx,
&witness_script,
output.value,
EcdsaSighashType::All
)
.unwrap()[..]
);
let sig = sign_with_aux_rand(secp_ctx, &sighash, &secret.private_key, &self);
let mut sig_ser = sig.serialize_der().to_vec();
sig_ser.push(EcdsaSighashType::All as u8);
let witness = Witness::from_slice(&[&sig_ser, &pubkey.0.serialize().to_vec()]);
psbt.inputs[input_idx].final_script_witness = Some(witness);
},
}
}
Ok(psbt)
}
}
impl EntropySource for KeysManager {
fn get_secure_random_bytes(&self) -> [u8; 32] {
self.entropy_source.get_secure_random_bytes()
}
}
impl NodeSigner for KeysManager {
fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
match recipient {
Recipient::Node => Ok(self.node_id.clone()),
Recipient::PhantomNode => Err(()),
}
}
fn ecdh(
&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
) -> Result<SharedSecret, ()> {
let mut node_secret = match recipient {
Recipient::Node => Ok(self.node_secret.clone()),
Recipient::PhantomNode => Err(()),
}?;
if let Some(tweak) = tweak {
node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
}
Ok(SharedSecret::new(other_key, &node_secret))
}
fn get_expanded_key(&self) -> ExpandedKey {
self.inbound_payment_key.clone()
}
fn get_peer_storage_key(&self) -> PeerStorageKey {
self.peer_storage_key.clone()
}
fn get_receive_auth_key(&self) -> ReceiveAuthKey {
self.receive_auth_key.clone()
}
fn sign_invoice(
&self, invoice: &RawBolt11Invoice, recipient: Recipient,
) -> Result<RecoverableSignature, ()> {
let hash = invoice.signable_hash();
let secret = match recipient {
Recipient::Node => Ok(&self.node_secret),
Recipient::PhantomNode => Err(()),
}?;
Ok(self.secp_ctx.sign_ecdsa_recoverable(&hash_to_message!(&hash), secret))
}
fn sign_bolt12_invoice(
&self, invoice: &UnsignedBolt12Invoice,
) -> Result<schnorr::Signature, ()> {
let message = invoice.tagged_hash().as_digest();
let keys = Keypair::from_secret_key(&self.secp_ctx, &self.node_secret);
let aux_rand = self.get_secure_random_bytes();
Ok(self.secp_ctx.sign_schnorr_with_aux_rand(message, &keys, &aux_rand))
}
fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
Ok(self.secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret))
}
fn sign_message(&self, msg: &[u8]) -> Result<String, ()> {
Ok(crate::util::message_signing::sign(msg, &self.node_secret))
}
}
impl OutputSpender for KeysManager {
fn spend_spendable_outputs(
&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
locktime: Option<LockTime>, secp_ctx: &Secp256k1<All>,
) -> Result<Transaction, ()> {
let (mut psbt, expected_max_weight) =
SpendableOutputDescriptor::create_spendable_outputs_psbt(
secp_ctx,
descriptors,
outputs,
change_destination_script,
feerate_sat_per_1000_weight,
locktime,
)?;
psbt = self.sign_spendable_outputs_psbt(descriptors, psbt, secp_ctx)?;
let spend_tx = psbt.extract_tx_unchecked_fee_rate();
debug_assert!(expected_max_weight >= spend_tx.weight().to_wu());
debug_assert!(
expected_max_weight <= spend_tx.weight().to_wu() + descriptors.len() as u64 * 3
);
Ok(spend_tx)
}
}
impl SignerProvider for KeysManager {
type EcdsaSigner = InMemorySigner;
#[cfg(taproot)]
type TaprootSigner = InMemorySigner;
fn generate_channel_keys_id(&self, _inbound: bool, user_channel_id: u128) -> [u8; 32] {
let child_idx = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
assert!(child_idx < core::u32::MAX as usize, "2^32 channels opened without restart");
let mut id = [0; 32];
id[0..4].copy_from_slice(&(child_idx as u32).to_be_bytes());
id[4..8].copy_from_slice(&self.starting_time_nanos.to_be_bytes());
id[8..16].copy_from_slice(&self.starting_time_secs.to_be_bytes());
id[16..32].copy_from_slice(&user_channel_id.to_be_bytes());
id
}
fn derive_channel_signer(&self, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner {
self.derive_channel_keys(&channel_keys_id)
}
fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
Ok(self.destination_script.clone())
}
fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
Ok(ShutdownScript::new_p2wpkh_from_pubkey(self.shutdown_pubkey.clone()))
}
}
pub struct PhantomKeysManager {
#[cfg(test)]
pub(crate) inner: KeysManager,
#[cfg(not(test))]
inner: KeysManager,
inbound_payment_key: ExpandedKey,
phantom_secret: SecretKey,
phantom_node_id: PublicKey,
}
impl EntropySource for PhantomKeysManager {
fn get_secure_random_bytes(&self) -> [u8; 32] {
self.inner.get_secure_random_bytes()
}
}
impl NodeSigner for PhantomKeysManager {
fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
match recipient {
Recipient::Node => self.inner.get_node_id(Recipient::Node),
Recipient::PhantomNode => Ok(self.phantom_node_id.clone()),
}
}
fn ecdh(
&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
) -> Result<SharedSecret, ()> {
let mut node_secret = match recipient {
Recipient::Node => self.inner.node_secret.clone(),
Recipient::PhantomNode => self.phantom_secret.clone(),
};
if let Some(tweak) = tweak {
node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
}
Ok(SharedSecret::new(other_key, &node_secret))
}
fn get_expanded_key(&self) -> ExpandedKey {
self.inbound_payment_key.clone()
}
fn get_peer_storage_key(&self) -> PeerStorageKey {
self.inner.peer_storage_key.clone()
}
fn get_receive_auth_key(&self) -> ReceiveAuthKey {
self.inner.receive_auth_key.clone()
}
fn sign_invoice(
&self, invoice: &RawBolt11Invoice, recipient: Recipient,
) -> Result<RecoverableSignature, ()> {
let hash = invoice.signable_hash();
let secret = match recipient {
Recipient::Node => &self.inner.node_secret,
Recipient::PhantomNode => &self.phantom_secret,
};
Ok(self.inner.secp_ctx.sign_ecdsa_recoverable(&hash_to_message!(&hash), secret))
}
fn sign_bolt12_invoice(
&self, invoice: &UnsignedBolt12Invoice,
) -> Result<schnorr::Signature, ()> {
self.inner.sign_bolt12_invoice(invoice)
}
fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
self.inner.sign_gossip_message(msg)
}
fn sign_message(&self, msg: &[u8]) -> Result<String, ()> {
self.inner.sign_message(msg)
}
}
impl OutputSpender for PhantomKeysManager {
fn spend_spendable_outputs(
&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
locktime: Option<LockTime>, secp_ctx: &Secp256k1<All>,
) -> Result<Transaction, ()> {
self.inner.spend_spendable_outputs(
descriptors,
outputs,
change_destination_script,
feerate_sat_per_1000_weight,
locktime,
secp_ctx,
)
}
}
impl SignerProvider for PhantomKeysManager {
type EcdsaSigner = InMemorySigner;
#[cfg(taproot)]
type TaprootSigner = InMemorySigner;
fn generate_channel_keys_id(&self, inbound: bool, user_channel_id: u128) -> [u8; 32] {
self.inner.generate_channel_keys_id(inbound, user_channel_id)
}
fn derive_channel_signer(&self, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner {
self.inner.derive_channel_signer(channel_keys_id)
}
fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
self.inner.get_destination_script(channel_keys_id)
}
fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
self.inner.get_shutdown_scriptpubkey()
}
}
impl PhantomKeysManager {
pub fn new(
seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32,
cross_node_seed: &[u8; 32], v2_remote_key_derivation: bool,
) -> Self {
let inner = KeysManager::new(
seed,
starting_time_secs,
starting_time_nanos,
v2_remote_key_derivation,
);
let (inbound_key, phantom_key) = hkdf_extract_expand_twice(
b"LDK Inbound and Phantom Payment Key Expansion",
cross_node_seed,
);
let phantom_secret = SecretKey::from_slice(&phantom_key).unwrap();
let phantom_node_id = PublicKey::from_secret_key(&inner.secp_ctx, &phantom_secret);
Self {
inner,
inbound_payment_key: ExpandedKey::new(inbound_key),
phantom_secret,
phantom_node_id,
}
}
pub fn derive_channel_keys(&self, params: &[u8; 32]) -> InMemorySigner {
self.inner.derive_channel_keys(params)
}
pub fn get_node_secret_key(&self) -> SecretKey {
self.inner.get_node_secret_key()
}
pub fn get_phantom_node_secret_key(&self) -> SecretKey {
self.phantom_secret
}
}
pub struct RandomBytes {
seed: [u8; 32],
index: AtomicCounter,
}
impl RandomBytes {
pub fn new(seed: [u8; 32]) -> Self {
Self { seed, index: AtomicCounter::new() }
}
}
impl EntropySource for RandomBytes {
fn get_secure_random_bytes(&self) -> [u8; 32] {
let index = self.index.next();
let mut nonce = [0u8; 16];
nonce[..8].copy_from_slice(&index.to_be_bytes());
ChaCha20::get_single_block(&self.seed, &nonce)
}
}
#[test]
pub fn dyn_sign() {
let _signer: Box<dyn EcdsaChannelSigner>;
}
#[cfg(ldk_bench)]
pub mod benches {
use crate::sign::{EntropySource, KeysManager};
use bitcoin::constants::genesis_block;
use bitcoin::Network;
use std::sync::mpsc::TryRecvError;
use std::sync::{mpsc, Arc};
use std::thread;
use std::time::Duration;
use criterion::Criterion;
pub fn bench_get_secure_random_bytes(bench: &mut Criterion) {
let seed = [0u8; 32];
let now = Duration::from_secs(genesis_block(Network::Testnet).header.time as u64);
let keys_manager =
Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_micros(), true));
let mut handles = Vec::new();
let mut stops = Vec::new();
for _ in 1..5 {
let keys_manager_clone = Arc::clone(&keys_manager);
let (stop_sender, stop_receiver) = mpsc::channel();
let handle = thread::spawn(move || loop {
keys_manager_clone.get_secure_random_bytes();
match stop_receiver.try_recv() {
Ok(_) | Err(TryRecvError::Disconnected) => {
println!("Terminating.");
break;
},
Err(TryRecvError::Empty) => {},
}
});
handles.push(handle);
stops.push(stop_sender);
}
bench.bench_function("get_secure_random_bytes", |b| {
b.iter(|| keys_manager.get_secure_random_bytes())
});
for stop in stops {
let _ = stop.send(());
}
for handle in handles {
handle.join().unwrap();
}
}
}