use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, EcdsaSighashType};
use bitcoin::blockdata::script::{Script, Builder};
use bitcoin::blockdata::opcodes;
use bitcoin::network::constants::Network;
use bitcoin::util::bip32::{ExtendedPrivKey, ExtendedPubKey, ChildNumber};
use bitcoin::util::sighash;
use bitcoin::bech32::u5;
use bitcoin::hashes::{Hash, HashEngine};
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::hashes::sha256d::Hash as Sha256dHash;
use bitcoin::hash_types::WPubkeyHash;
use bitcoin::secp256k1::{SecretKey, PublicKey, Scalar};
use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Signing};
use bitcoin::secp256k1::ecdh::SharedSecret;
use bitcoin::secp256k1::ecdsa::RecoverableSignature;
use bitcoin::{PackedLockTime, secp256k1, Sequence, Witness};
use crate::util::transaction_utils;
use crate::util::crypto::{hkdf_extract_expand_twice, sign, sign_with_aux_rand};
use crate::util::ser::{Writeable, Writer, Readable, ReadableArgs};
use crate::chain::transaction::OutPoint;
#[cfg(anchors)]
use crate::events::bump_transaction::HTLCDescriptor;
use crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI;
use crate::ln::{chan_utils, PaymentPreimage};
use crate::ln::chan_utils::{HTLCOutputInCommitment, make_funding_redeemscript, ChannelPublicKeys, HolderCommitmentTransaction, ChannelTransactionParameters, CommitmentTransaction, ClosingTransaction};
use crate::ln::msgs::{UnsignedChannelAnnouncement, UnsignedGossipMessage};
use crate::ln::script::ShutdownScript;
use crate::prelude::*;
use core::convert::TryInto;
use core::ops::Deref;
use core::sync::atomic::{AtomicUsize, Ordering};
use crate::io::{self, Error};
use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
use crate::util::atomic_counter::AtomicCounter;
use crate::util::chacha20::ChaCha20;
use crate::util::invoice::construct_invoice_preimage;
#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
pub struct KeyMaterial(pub [u8; 32]);
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DelayedPaymentOutputDescriptor {
pub outpoint: OutPoint,
pub per_commitment_point: PublicKey,
pub to_self_delay: u16,
pub output: TxOut,
pub revocation_pubkey: PublicKey,
pub channel_keys_id: [u8; 32],
pub channel_value_satoshis: u64,
}
impl DelayedPaymentOutputDescriptor {
pub const MAX_WITNESS_LENGTH: usize = 1 + 73 + 1 + chan_utils::REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH + 1;
}
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),
});
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StaticPaymentOutputDescriptor {
pub outpoint: OutPoint,
pub output: TxOut,
pub channel_keys_id: [u8; 32],
pub channel_value_satoshis: u64,
}
impl StaticPaymentOutputDescriptor {
pub const MAX_WITNESS_LENGTH: usize = 1 + 73 + 34;
}
impl_writeable_tlv_based!(StaticPaymentOutputDescriptor, {
(0, outpoint, required),
(2, output, required),
(4, channel_keys_id, required),
(6, channel_value_satoshis, required),
});
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SpendableOutputDescriptor {
StaticOutput {
outpoint: OutPoint,
output: TxOut,
},
DelayedPaymentOutput(DelayedPaymentOutputDescriptor),
StaticPaymentOutput(StaticPaymentOutputDescriptor),
}
impl_writeable_tlv_based_enum!(SpendableOutputDescriptor,
(0, StaticOutput) => {
(0, outpoint, required),
(2, output, required),
},
;
(1, DelayedPaymentOutput),
(2, StaticPaymentOutput),
);
pub trait ChannelSigner {
fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>) -> PublicKey;
fn release_commitment_secret(&self, idx: u64) -> [u8; 32];
fn validate_holder_commitment(&self, holder_tx: &HolderCommitmentTransaction,
preimages: Vec<PaymentPreimage>) -> Result<(), ()>;
fn pubkeys(&self) -> &ChannelPublicKeys;
fn channel_keys_id(&self) -> [u8; 32];
fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters);
}
pub trait EcdsaChannelSigner: ChannelSigner {
fn sign_counterparty_commitment(&self, commitment_tx: &CommitmentTransaction,
preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<secp256k1::All>
) -> Result<(Signature, Vec<Signature>), ()>;
fn validate_counterparty_revocation(&self, idx: u64, secret: &SecretKey) -> Result<(), ()>;
fn sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction,
secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()>;
#[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
fn unsafe_sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction,
secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()>;
fn sign_justice_revoked_output(&self, justice_tx: &Transaction, input: usize, amount: u64,
per_commitment_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>
) -> Result<Signature, ()>;
fn sign_justice_revoked_htlc(&self, justice_tx: &Transaction, input: usize, amount: u64,
per_commitment_key: &SecretKey, htlc: &HTLCOutputInCommitment,
secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()>;
#[cfg(anchors)]
fn sign_holder_htlc_transaction(&self, htlc_tx: &Transaction, input: usize,
htlc_descriptor: &HTLCDescriptor, secp_ctx: &Secp256k1<secp256k1::All>
) -> Result<Signature, ()>;
fn sign_counterparty_htlc_transaction(&self, htlc_tx: &Transaction, input: usize, amount: u64,
per_commitment_point: &PublicKey, htlc: &HTLCOutputInCommitment,
secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()>;
fn sign_closing_transaction(&self, closing_tx: &ClosingTransaction,
secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()>;
fn sign_holder_anchor_input(
&self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<Signature, ()>;
fn sign_channel_announcement_with_funding_key(
&self, msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>
) -> Result<Signature, ()>;
}
pub trait WriteableEcdsaChannelSigner: EcdsaChannelSigner + Writeable {}
pub enum Recipient {
Node,
PhantomNode,
}
pub trait EntropySource {
fn get_secure_random_bytes(&self) -> [u8; 32];
}
pub trait NodeSigner {
fn get_inbound_payment_key_material(&self) -> KeyMaterial;
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, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()>;
fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()>;
}
pub trait SignerProvider {
type Signer : WriteableEcdsaChannelSigner;
fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32];
fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::Signer;
fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, DecodeError>;
fn get_destination_script(&self) -> Script;
fn get_shutdown_scriptpubkey(&self) -> ShutdownScript;
}
pub struct InMemorySigner {
pub funding_key: SecretKey,
pub revocation_base_key: SecretKey,
pub payment_key: SecretKey,
pub delayed_payment_base_key: SecretKey,
pub htlc_base_key: SecretKey,
pub commitment_seed: [u8; 32],
pub(crate) holder_channel_pubkeys: ChannelPublicKeys,
channel_parameters: Option<ChannelTransactionParameters>,
channel_value_satoshis: u64,
channel_keys_id: [u8; 32],
rand_bytes_unique_start: [u8; 32],
rand_bytes_index: AtomicCounter,
}
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: self.payment_key.clone(),
delayed_payment_base_key: self.delayed_payment_base_key.clone(),
htlc_base_key: self.htlc_base_key.clone(),
commitment_seed: self.commitment_seed.clone(),
holder_channel_pubkeys: self.holder_channel_pubkeys.clone(),
channel_parameters: self.channel_parameters.clone(),
channel_value_satoshis: self.channel_value_satoshis,
channel_keys_id: self.channel_keys_id,
rand_bytes_unique_start: self.get_secure_random_bytes(),
rand_bytes_index: AtomicCounter::new(),
}
}
}
impl InMemorySigner {
pub fn new<C: Signing>(
secp_ctx: &Secp256k1<C>,
funding_key: SecretKey,
revocation_base_key: SecretKey,
payment_key: SecretKey,
delayed_payment_base_key: SecretKey,
htlc_base_key: SecretKey,
commitment_seed: [u8; 32],
channel_value_satoshis: u64,
channel_keys_id: [u8; 32],
rand_bytes_unique_start: [u8; 32],
) -> InMemorySigner {
let holder_channel_pubkeys =
InMemorySigner::make_holder_keys(secp_ctx, &funding_key, &revocation_base_key,
&payment_key, &delayed_payment_base_key,
&htlc_base_key);
InMemorySigner {
funding_key,
revocation_base_key,
payment_key,
delayed_payment_base_key,
htlc_base_key,
commitment_seed,
channel_value_satoshis,
holder_channel_pubkeys,
channel_parameters: None,
channel_keys_id,
rand_bytes_unique_start,
rand_bytes_index: AtomicCounter::new(),
}
}
fn make_holder_keys<C: Signing>(secp_ctx: &Secp256k1<C>,
funding_key: &SecretKey,
revocation_base_key: &SecretKey,
payment_key: &SecretKey,
delayed_payment_base_key: &SecretKey,
htlc_base_key: &SecretKey) -> ChannelPublicKeys {
let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
ChannelPublicKeys {
funding_pubkey: from_secret(&funding_key),
revocation_basepoint: from_secret(&revocation_base_key),
payment_point: from_secret(&payment_key),
delayed_payment_basepoint: from_secret(&delayed_payment_base_key),
htlc_basepoint: from_secret(&htlc_base_key),
}
}
pub fn counterparty_pubkeys(&self) -> &ChannelPublicKeys { &self.get_channel_parameters().counterparty_parameters.as_ref().unwrap().pubkeys }
pub fn counterparty_selected_contest_delay(&self) -> u16 { self.get_channel_parameters().counterparty_parameters.as_ref().unwrap().selected_contest_delay }
pub fn holder_selected_contest_delay(&self) -> u16 { self.get_channel_parameters().holder_selected_contest_delay }
pub fn is_outbound(&self) -> bool { self.get_channel_parameters().is_outbound_from_holder }
pub fn funding_outpoint(&self) -> &OutPoint { self.get_channel_parameters().funding_outpoint.as_ref().unwrap() }
pub fn get_channel_parameters(&self) -> &ChannelTransactionParameters {
self.channel_parameters.as_ref().unwrap()
}
pub fn opt_anchors(&self) -> bool {
self.get_channel_parameters().opt_anchors.is_some()
}
pub fn sign_counterparty_payment_input<C: Signing>(&self, spend_tx: &Transaction, input_idx: usize, descriptor: &StaticPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>) -> Result<Vec<Vec<u8>>, ()> {
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 remotepubkey = self.pubkeys().payment_point;
let witness_script = bitcoin::Address::p2pkh(&::bitcoin::PublicKey{compressed: true, inner: remotepubkey}, Network::Testnet).script_pubkey();
let sighash = hash_to_message!(&sighash::SighashCache::new(spend_tx).segwit_signature_hash(input_idx, &witness_script, descriptor.output.value, EcdsaSighashType::All).unwrap()[..]);
let remotesig = sign_with_aux_rand(secp_ctx, &sighash, &self.payment_key, &self);
let payment_script = bitcoin::Address::p2wpkh(&::bitcoin::PublicKey{compressed: true, inner: remotepubkey}, Network::Bitcoin).unwrap().script_pubkey();
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);
witness.push(remotepubkey.serialize().to_vec());
Ok(witness)
}
pub fn sign_dynamic_p2wsh_input<C: Signing>(&self, spend_tx: &Transaction, input_idx: usize, descriptor: &DelayedPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>) -> Result<Vec<Vec<u8>>, ()> {
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 = PublicKey::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).segwit_signature_hash(input_idx, &witness_script, descriptor.output.value, EcdsaSighashType::All).unwrap()[..]);
let local_delayedsig = sign_with_aux_rand(secp_ctx, &sighash, &delayed_payment_key, &self);
let payment_script = bitcoin::Address::p2wsh(&witness_script, Network::Bitcoin).script_pubkey();
if descriptor.output.script_pubkey != payment_script { return Err(()); }
let mut witness = Vec::with_capacity(3);
witness.push(local_delayedsig.serialize_der().to_vec());
witness[0].push(EcdsaSighashType::All as u8);
witness.push(vec!()); witness.push(witness_script.clone().into_bytes());
Ok(witness)
}
}
impl EntropySource for InMemorySigner {
fn get_secure_random_bytes(&self) -> [u8; 32] {
let index = self.rand_bytes_index.get_increment();
let mut nonce = [0u8; 16];
nonce[..8].copy_from_slice(&index.to_be_bytes());
ChaCha20::get_single_block(&self.rand_bytes_unique_start, &nonce)
}
}
impl ChannelSigner for InMemorySigner {
fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>) -> PublicKey {
let commitment_secret = SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx)).unwrap();
PublicKey::from_secret_key(secp_ctx, &commitment_secret)
}
fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
chan_utils::build_commitment_secret(&self.commitment_seed, idx)
}
fn validate_holder_commitment(&self, _holder_tx: &HolderCommitmentTransaction, _preimages: Vec<PaymentPreimage>) -> Result<(), ()> {
Ok(())
}
fn pubkeys(&self) -> &ChannelPublicKeys { &self.holder_channel_pubkeys }
fn channel_keys_id(&self) -> [u8; 32] { self.channel_keys_id }
fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters) {
assert!(self.channel_parameters.is_none() || self.channel_parameters.as_ref().unwrap() == channel_parameters);
if self.channel_parameters.is_some() {
return;
}
assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
self.channel_parameters = Some(channel_parameters.clone());
}
}
impl EcdsaChannelSigner for InMemorySigner {
fn sign_counterparty_commitment(&self, commitment_tx: &CommitmentTransaction, _preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
let trusted_tx = commitment_tx.trust();
let keys = trusted_tx.keys();
let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
let built_tx = trusted_tx.built_transaction();
let commitment_sig = built_tx.sign_counterparty_commitment(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx);
let commitment_txid = built_tx.txid;
let mut htlc_sigs = Vec::with_capacity(commitment_tx.htlcs().len());
for htlc in commitment_tx.htlcs() {
let channel_parameters = self.get_channel_parameters();
let htlc_tx = chan_utils::build_htlc_transaction(&commitment_txid, commitment_tx.feerate_per_kw(), self.holder_selected_contest_delay(), htlc, self.opt_anchors(), channel_parameters.opt_non_zero_fee_anchors.is_some(), &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, self.opt_anchors(), &keys);
let htlc_sighashtype = if self.opt_anchors() { EcdsaSighashType::SinglePlusAnyoneCanPay } else { EcdsaSighashType::All };
let htlc_sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, htlc.amount_msat / 1000, 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 validate_counterparty_revocation(&self, _idx: u64, _secret: &SecretKey) -> Result<(), ()> {
Ok(())
}
fn sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
let trusted_tx = commitment_tx.trust();
let sig = trusted_tx.built_transaction().sign_holder_commitment(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, &self, secp_ctx);
let channel_parameters = self.get_channel_parameters();
let htlc_sigs = trusted_tx.get_htlc_sigs(&self.htlc_base_key, &channel_parameters.as_holder_broadcastable(), &self, secp_ctx)?;
Ok((sig, htlc_sigs))
}
#[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
fn unsafe_sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
let trusted_tx = commitment_tx.trust();
let sig = trusted_tx.built_transaction().sign_holder_commitment(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, &self, secp_ctx);
let channel_parameters = self.get_channel_parameters();
let htlc_sigs = trusted_tx.get_htlc_sigs(&self.htlc_base_key, &channel_parameters.as_holder_broadcastable(), &self, secp_ctx)?;
Ok((sig, htlc_sigs))
}
fn sign_justice_revoked_output(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
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 = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint);
let witness_script = {
let counterparty_delayedpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().delayed_payment_basepoint);
chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.holder_selected_contest_delay(), &counterparty_delayedpubkey)
};
let mut sighash_parts = sighash::SighashCache::new(justice_tx);
let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self))
}
fn sign_justice_revoked_htlc(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
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 = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint);
let witness_script = {
let counterparty_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().htlc_basepoint);
let holder_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint);
chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, self.opt_anchors(), &counterparty_htlcpubkey, &holder_htlcpubkey, &revocation_pubkey)
};
let mut sighash_parts = sighash::SighashCache::new(justice_tx);
let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self))
}
#[cfg(anchors)]
fn sign_holder_htlc_transaction(
&self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
secp_ctx: &Secp256k1<secp256k1::All>
) -> Result<Signature, ()> {
let per_commitment_point = self.get_per_commitment_point(
htlc_descriptor.per_commitment_number, &secp_ctx
);
let witness_script = htlc_descriptor.witness_script(&per_commitment_point, secp_ctx);
let sighash = &sighash::SighashCache::new(&*htlc_tx).segwit_signature_hash(
input, &witness_script, htlc_descriptor.htlc.amount_msat / 1000, EcdsaSighashType::All
).map_err(|_| ())?;
let our_htlc_private_key = chan_utils::derive_private_key(
&secp_ctx, &per_commitment_point, &self.htlc_base_key
);
Ok(sign_with_aux_rand(&secp_ctx, &hash_to_message!(sighash), &our_htlc_private_key, &self))
}
fn sign_counterparty_htlc_transaction(&self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
let htlc_key = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key);
let revocation_pubkey = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint);
let counterparty_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().htlc_basepoint);
let htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint);
let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, self.opt_anchors(), &counterparty_htlcpubkey, &htlcpubkey, &revocation_pubkey);
let mut sighash_parts = sighash::SighashCache::new(htlc_tx);
let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
Ok(sign_with_aux_rand(secp_ctx, &sighash, &htlc_key, &self))
}
fn sign_closing_transaction(&self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
Ok(closing_tx.trust().sign(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
}
fn sign_holder_anchor_input(
&self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<Signature, ()> {
let witness_script = chan_utils::get_anchor_redeemscript(&self.holder_channel_pubkeys.funding_pubkey);
let sighash = sighash::SighashCache::new(&*anchor_tx).segwit_signature_hash(
input, &witness_script, ANCHOR_OUTPUT_VALUE_SATOSHI, EcdsaSighashType::All,
).unwrap();
Ok(sign_with_aux_rand(secp_ctx, &hash_to_message!(&sighash[..]), &self.funding_key, &self))
}
fn sign_channel_announcement_with_funding_key(
&self, msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>
) -> Result<Signature, ()> {
let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
Ok(secp_ctx.sign_ecdsa(&msghash, &self.funding_key))
}
}
const SERIALIZATION_VERSION: u8 = 1;
const MIN_SERIALIZATION_VERSION: u8 = 1;
impl WriteableEcdsaChannelSigner for InMemorySigner {}
impl Writeable for InMemorySigner {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
self.funding_key.write(writer)?;
self.revocation_base_key.write(writer)?;
self.payment_key.write(writer)?;
self.delayed_payment_base_key.write(writer)?;
self.htlc_base_key.write(writer)?;
self.commitment_seed.write(writer)?;
self.channel_parameters.write(writer)?;
self.channel_value_satoshis.write(writer)?;
self.channel_keys_id.write(writer)?;
write_tlv_fields!(writer, {});
Ok(())
}
}
impl<ES: Deref> ReadableArgs<ES> for InMemorySigner where ES::Target: EntropySource {
fn read<R: io::Read>(reader: &mut R, entropy_source: ES) -> Result<Self, DecodeError> {
let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
let funding_key = Readable::read(reader)?;
let revocation_base_key = Readable::read(reader)?;
let payment_key = Readable::read(reader)?;
let delayed_payment_base_key = Readable::read(reader)?;
let htlc_base_key = Readable::read(reader)?;
let commitment_seed = Readable::read(reader)?;
let counterparty_channel_data = Readable::read(reader)?;
let channel_value_satoshis = Readable::read(reader)?;
let secp_ctx = Secp256k1::signing_only();
let holder_channel_pubkeys =
InMemorySigner::make_holder_keys(&secp_ctx, &funding_key, &revocation_base_key,
&payment_key, &delayed_payment_base_key, &htlc_base_key);
let keys_id = Readable::read(reader)?;
read_tlv_fields!(reader, {});
Ok(InMemorySigner {
funding_key,
revocation_base_key,
payment_key,
delayed_payment_base_key,
htlc_base_key,
commitment_seed,
channel_value_satoshis,
holder_channel_pubkeys,
channel_parameters: counterparty_channel_data,
channel_keys_id: keys_id,
rand_bytes_unique_start: entropy_source.get_secure_random_bytes(),
rand_bytes_index: AtomicCounter::new(),
})
}
}
pub struct KeysManager {
secp_ctx: Secp256k1<secp256k1::All>,
node_secret: SecretKey,
node_id: PublicKey,
inbound_payment_key: KeyMaterial,
destination_script: Script,
shutdown_pubkey: PublicKey,
channel_master_key: ExtendedPrivKey,
channel_child_index: AtomicUsize,
rand_bytes_unique_start: [u8; 32],
rand_bytes_index: AtomicCounter,
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) -> Self {
let secp_ctx = Secp256k1::new();
match ExtendedPrivKey::new_master(Network::Testnet, seed) {
Ok(master_key) => {
let node_secret = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(0).unwrap()).expect("Your RNG is busted").private_key;
let node_id = PublicKey::from_secret_key(&secp_ctx, &node_secret);
let destination_script = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(1).unwrap()) {
Ok(destination_key) => {
let wpubkey_hash = WPubkeyHash::hash(&ExtendedPubKey::from_priv(&secp_ctx, &destination_key).to_pub().to_bytes());
Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
.push_slice(&wpubkey_hash.into_inner())
.into_script()
},
Err(_) => panic!("Your RNG is busted"),
};
let shutdown_pubkey = match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(2).unwrap()) {
Ok(shutdown_key) => ExtendedPubKey::from_priv(&secp_ctx, &shutdown_key).public_key,
Err(_) => panic!("Your RNG is busted"),
};
let channel_master_key = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(3).unwrap()).expect("Your RNG is busted");
let inbound_payment_key: SecretKey = master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(5).unwrap()).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 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).into_inner();
let mut res = KeysManager {
secp_ctx,
node_secret,
node_id,
inbound_payment_key: KeyMaterial(inbound_pmt_key_bytes),
destination_script,
shutdown_pubkey,
channel_master_key,
channel_child_index: AtomicUsize::new(0),
rand_bytes_unique_start,
rand_bytes_index: AtomicCounter::new(),
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 derive_channel_keys(&self, channel_value_satoshis: u64, 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.ckd_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).into_inner();
let commitment_seed = {
let mut sha = Sha256::engine();
sha.input(&seed);
sha.input(&b"commitment seed"[..]);
Sha256::from_engine(sha).into_inner()
};
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).into_inner()).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 = key_step!(b"payment key", revocation_base_key);
let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key);
let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
let prng_seed = self.get_secure_random_bytes();
InMemorySigner::new(
&self.secp_ctx,
funding_key,
revocation_base_key,
payment_key,
delayed_payment_base_key,
htlc_base_key,
commitment_seed,
channel_value_satoshis,
params.clone(),
prng_seed,
)
}
pub fn spend_spendable_outputs<C: Signing>(&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>, change_destination_script: Script, feerate_sat_per_1000_weight: u32, secp_ctx: &Secp256k1<C>) -> Result<Transaction, ()> {
let mut input = Vec::new();
let mut input_value = 0;
let mut witness_weight = 0;
let mut output_set = HashSet::with_capacity(descriptors.len());
for outp in descriptors {
match outp {
SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
input.push(TxIn {
previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
script_sig: Script::new(),
sequence: Sequence::ZERO,
witness: Witness::new(),
});
witness_weight += StaticPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
input_value += descriptor.output.value;
if !output_set.insert(descriptor.outpoint) { return Err(()); }
},
SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
input.push(TxIn {
previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
script_sig: Script::new(),
sequence: Sequence(descriptor.to_self_delay as u32),
witness: Witness::new(),
});
witness_weight += DelayedPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
input_value += descriptor.output.value;
if !output_set.insert(descriptor.outpoint) { return Err(()); }
},
SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
input.push(TxIn {
previous_output: outpoint.into_bitcoin_outpoint(),
script_sig: Script::new(),
sequence: Sequence::ZERO,
witness: Witness::new(),
});
witness_weight += 1 + 73 + 34;
input_value += output.value;
if !output_set.insert(*outpoint) { return Err(()); }
}
}
if input_value > MAX_VALUE_MSAT / 1000 { return Err(()); }
}
let mut spend_tx = Transaction {
version: 2,
lock_time: PackedLockTime(0),
input,
output: outputs,
};
let expected_max_weight =
transaction_utils::maybe_add_change_output(&mut spend_tx, input_value, witness_weight, feerate_sat_per_1000_weight, change_destination_script)?;
let mut keys_cache: Option<(InMemorySigner, [u8; 32])> = None;
let mut input_idx = 0;
for outp in descriptors {
match outp {
SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
if keys_cache.is_none() || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id {
keys_cache = Some((
self.derive_channel_keys(descriptor.channel_value_satoshis, &descriptor.channel_keys_id),
descriptor.channel_keys_id));
}
spend_tx.input[input_idx].witness = Witness::from_vec(keys_cache.as_ref().unwrap().0.sign_counterparty_payment_input(&spend_tx, input_idx, &descriptor, &secp_ctx)?);
},
SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
if keys_cache.is_none() || keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id {
keys_cache = Some((
self.derive_channel_keys(descriptor.channel_value_satoshis, &descriptor.channel_keys_id),
descriptor.channel_keys_id));
}
spend_tx.input[input_idx].witness = Witness::from_vec(keys_cache.as_ref().unwrap().0.sign_dynamic_p2wsh_input(&spend_tx, input_idx, &descriptor, &secp_ctx)?);
},
SpendableOutputDescriptor::StaticOutput { ref output, .. } => {
let derivation_idx = if output.script_pubkey == self.destination_script {
1
} else {
2
};
let secret = {
match ExtendedPrivKey::new_master(Network::Testnet, &self.seed) {
Ok(master_key) => {
match master_key.ckd_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 = ExtendedPubKey::from_priv(&secp_ctx, &secret).to_pub();
if derivation_idx == 2 {
assert_eq!(pubkey.inner, self.shutdown_pubkey);
}
let witness_script = bitcoin::Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
let payment_script = bitcoin::Address::p2wpkh(&pubkey, Network::Testnet).expect("uncompressed key found").script_pubkey();
if payment_script != output.script_pubkey { return Err(()); };
let sighash = hash_to_message!(&sighash::SighashCache::new(&spend_tx).segwit_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);
spend_tx.input[input_idx].witness.push(sig_ser);
spend_tx.input[input_idx].witness.push(pubkey.inner.serialize().to_vec());
},
}
input_idx += 1;
}
debug_assert!(expected_max_weight >= spend_tx.weight());
debug_assert!(expected_max_weight <= spend_tx.weight() + descriptors.len() * 3);
Ok(spend_tx)
}
}
impl EntropySource for KeysManager {
fn get_secure_random_bytes(&self) -> [u8; 32] {
let index = self.rand_bytes_index.get_increment();
let mut nonce = [0u8; 16];
nonce[..8].copy_from_slice(&index.to_be_bytes());
ChaCha20::get_single_block(&self.rand_bytes_unique_start, &nonce)
}
}
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_inbound_payment_key_material(&self) -> KeyMaterial {
self.inbound_payment_key.clone()
}
fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
let preimage = construct_invoice_preimage(&hrp_bytes, &invoice_data);
let secret = match recipient {
Recipient::Node => Ok(&self.node_secret),
Recipient::PhantomNode => Err(())
}?;
Ok(self.secp_ctx.sign_ecdsa_recoverable(&hash_to_message!(&Sha256::hash(&preimage)), secret))
}
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))
}
}
impl SignerProvider for KeysManager {
type Signer = InMemorySigner;
fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, 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_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::Signer {
self.derive_channel_keys(channel_value_satoshis, &channel_keys_id)
}
fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, DecodeError> {
InMemorySigner::read(&mut io::Cursor::new(reader), self)
}
fn get_destination_script(&self) -> Script {
self.destination_script.clone()
}
fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
ShutdownScript::new_p2wpkh_from_pubkey(self.shutdown_pubkey.clone())
}
}
pub struct PhantomKeysManager {
inner: KeysManager,
inbound_payment_key: KeyMaterial,
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_inbound_payment_key_material(&self) -> KeyMaterial {
self.inbound_payment_key.clone()
}
fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
let preimage = construct_invoice_preimage(&hrp_bytes, &invoice_data);
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!(&Sha256::hash(&preimage)), secret))
}
fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
self.inner.sign_gossip_message(msg)
}
}
impl SignerProvider for PhantomKeysManager {
type Signer = InMemorySigner;
fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
self.inner.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
}
fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::Signer {
self.inner.derive_channel_signer(channel_value_satoshis, channel_keys_id)
}
fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, DecodeError> {
self.inner.read_chan_signer(reader)
}
fn get_destination_script(&self) -> Script {
self.inner.get_destination_script()
}
fn get_shutdown_scriptpubkey(&self) -> 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]) -> Self {
let inner = KeysManager::new(seed, starting_time_secs, starting_time_nanos);
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: KeyMaterial(inbound_key),
phantom_secret,
phantom_node_id,
}
}
pub fn spend_spendable_outputs<C: Signing>(&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>, change_destination_script: Script, feerate_sat_per_1000_weight: u32, secp_ctx: &Secp256k1<C>) -> Result<Transaction, ()> {
self.inner.spend_spendable_outputs(descriptors, outputs, change_destination_script, feerate_sat_per_1000_weight, secp_ctx)
}
pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner {
self.inner.derive_channel_keys(channel_value_satoshis, 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
}
}
#[test]
pub fn dyn_sign() {
let _signer: Box<dyn EcdsaChannelSigner>;
}
#[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
mod benches {
use std::sync::{Arc, mpsc};
use std::sync::mpsc::TryRecvError;
use std::thread;
use std::time::Duration;
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::Network;
use crate::chain::keysinterface::{EntropySource, KeysManager};
use test::Bencher;
#[bench]
fn bench_get_secure_random_bytes(bench: &mut Bencher) {
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()));
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.iter(|| {
for _ in 1..100 {
keys_manager.get_secure_random_bytes();
}
});
for stop in stops {
let _ = stop.send(());
}
for handle in handles {
handle.join().unwrap();
}
}
}