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;
#[cfg(taproot)]
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_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,
};
#[cfg(taproot)]
use crate::ln::msgs::PartialSignatureWithNonce;
use crate::ln::msgs::{UnsignedChannelAnnouncement, UnsignedGossipMessage};
use crate::ln::script::ShutdownScript;
use crate::ln::types::PaymentPreimage;
use crate::offers::invoice::UnsignedBolt12Invoice;
use crate::offers::invoice_request::UnsignedInvoiceRequest;
use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer};
use crate::util::transaction_utils;
use crate::crypto::chacha20::ChaCha20;
use crate::io::{self, Error};
use crate::ln::features::ChannelTypeFeatures;
use crate::ln::msgs::DecodeError;
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;
#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
pub struct KeyMaterial(pub [u8; 32]);
#[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 + 73 + 1 + chan_utils::REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH as u64 + 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),
(13, channel_transaction_parameters, option),
});
pub(crate) const P2WPKH_WITNESS_WEIGHT: u64 = 1 +
1 +
73 +
1 +
33 ;
pub(crate) const P2TR_KEY_PATH_WITNESS_WEIGHT: u64 = 1 + 1 + 64 ;
#[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.supports_anchors() {
let payment_point = channel_params.holder_pubkeys.payment_point;
Some(chan_utils::get_to_countersignatory_with_anchors_redeemscript(&payment_point))
} else {
None
}
})
}
pub fn max_witness_length(&self) -> u64 {
if self.channel_transaction_parameters.as_ref().map_or(false, |p| p.supports_anchors()) {
let witness_script_weight = 1 + 33 +
1 + 1 + 1 ;
1 + 1 + 73 +
1 + witness_script_weight
} else {
P2WPKH_WITNESS_WEIGHT
}
}
}
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),
});
#[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 payment_key = DelayedPaymentKey(add_public_key_tweak(
secp_ctx,
&basepoint.to_public_key(),
&add_tweak,
));
(
Some(get_revokeable_redeemscript(
&revocation_pubkey,
*to_self_delay,
&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
.channel_transaction_parameters
.as_ref()
.map_or(false, |p| p.supports_anchors())
{
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 += 1 + 73 + 34;
#[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))
}
}
#[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),
});
#[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 fn derive_channel_signer<S: EcdsaChannelSigner, SP: Deref>(&self, signer_provider: &SP) -> S
where
SP::Target: SignerProvider<EcdsaSigner = S>,
{
let mut signer = signer_provider.derive_channel_signer(
self.channel_derivation_parameters.value_satoshis,
self.channel_derivation_parameters.keys_id,
);
signer
.provide_channel_parameters(&self.channel_derivation_parameters.transaction_parameters);
signer
}
}
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) -> &ChannelPublicKeys;
fn channel_keys_id(&self) -> [u8; 32];
fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters);
}
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, invoice: &RawBolt11Invoice, recipient: Recipient,
) -> Result<RecoverableSignature, ()>;
fn sign_bolt12_invoice_request(
&self, invoice_request: &UnsignedInvoiceRequest,
) -> Result<schnorr::Signature, ()>;
fn sign_bolt12_invoice(
&self, invoice: &UnsignedBolt12Invoice,
) -> Result<schnorr::Signature, ()>;
fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()>;
}
pub trait OutputSpender {
fn spend_spendable_outputs<C: Signing>(
&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
locktime: Option<LockTime>, secp_ctx: &Secp256k1<C>,
) -> 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, 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::EcdsaSigner;
fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError>;
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(&self) -> Result<ScriptBuf, ()>;
}
#[derive(Debug)]
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],
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 == other.payment_key
&& 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.holder_channel_pubkeys == other.holder_channel_pubkeys
&& self.channel_parameters == other.channel_parameters
&& self.channel_value_satoshis == other.channel_value_satoshis
&& 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: 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,
entropy_source: RandomBytes::new(self.get_secure_random_bytes()),
}
}
}
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,
entropy_source: RandomBytes::new(rand_bytes_unique_start),
}
}
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: RevocationBasepoint::from(from_secret(&revocation_base_key)),
payment_point: from_secret(&payment_key),
delayed_payment_basepoint: DelayedPaymentBasepoint::from(from_secret(
&delayed_payment_base_key,
)),
htlc_basepoint: HtlcBasepoint::from(from_secret(&htlc_base_key)),
}
}
pub fn counterparty_pubkeys(&self) -> Option<&ChannelPublicKeys> {
self.get_channel_parameters().and_then(|params| {
params.counterparty_parameters.as_ref().map(|params| ¶ms.pubkeys)
})
}
pub fn counterparty_selected_contest_delay(&self) -> Option<u16> {
self.get_channel_parameters().and_then(|params| {
params.counterparty_parameters.as_ref().map(|params| params.selected_contest_delay)
})
}
pub fn holder_selected_contest_delay(&self) -> Option<u16> {
self.get_channel_parameters().map(|params| params.holder_selected_contest_delay)
}
pub fn is_outbound(&self) -> Option<bool> {
self.get_channel_parameters().map(|params| params.is_outbound_from_holder)
}
pub fn funding_outpoint(&self) -> Option<&OutPoint> {
self.get_channel_parameters().map(|params| params.funding_outpoint.as_ref()).flatten()
}
pub fn get_channel_parameters(&self) -> Option<&ChannelTransactionParameters> {
self.channel_parameters.as_ref()
}
pub fn channel_type_features(&self) -> Option<&ChannelTypeFeatures> {
self.get_channel_parameters().map(|params| ¶ms.channel_type_features)
}
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 remotepubkey = bitcoin::PublicKey::new(self.pubkeys().payment_point);
let supports_anchors_zero_fee_htlc_tx = self
.channel_type_features()
.map(|features| features.supports_anchors_zero_fee_htlc_tx())
.unwrap_or(false);
let witness_script = if supports_anchors_zero_fee_htlc_tx {
chan_utils::get_to_countersignatory_with_anchors_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, &self.payment_key, &self);
let payment_script = if 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 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) -> &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());
}
}
const MISSING_PARAMS_ERR: &'static str =
"ChannelSigner::provide_channel_parameters must be called before signing operations";
impl EcdsaChannelSigner for InMemorySigner {
fn sign_counterparty_commitment(
&self, commitment_tx: &CommitmentTransaction,
_inbound_htlc_preimages: Vec<PaymentPreimage>,
_outbound_htlc_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 counterparty_keys = self.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(
&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().expect(MISSING_PARAMS_ERR);
let holder_selected_contest_delay =
self.holder_selected_contest_delay().expect(MISSING_PARAMS_ERR);
let chan_type = &channel_parameters.channel_type_features;
let htlc_tx = chan_utils::build_htlc_transaction(
&commitment_txid,
commitment_tx.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() {
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, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<Signature, ()> {
let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
let counterparty_keys = self.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(
&self.funding_key,
&funding_redeemscript,
self.channel_value_satoshis,
&self,
secp_ctx,
))
}
#[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
fn unsafe_sign_holder_commitment(
&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<Signature, ()> {
let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
let counterparty_keys = self.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(
&self.funding_key,
&funding_redeemscript,
self.channel_value_satoshis,
&self,
secp_ctx,
))
}
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 = RevocationKey::from_basepoint(
&secp_ctx,
&self.pubkeys().revocation_basepoint,
&per_commitment_point,
);
let witness_script = {
let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
let holder_selected_contest_delay =
self.holder_selected_contest_delay().expect(MISSING_PARAMS_ERR);
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, 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 = RevocationKey::from_basepoint(
&secp_ctx,
&self.pubkeys().revocation_basepoint,
&per_commitment_point,
);
let witness_script = {
let counterparty_keys = self.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,
&self.pubkeys().htlc_basepoint,
&per_commitment_point,
);
let chan_type = self.channel_type_features().expect(MISSING_PARAMS_ERR);
chan_utils::get_htlc_redeemscript_with_explicit_keys(
&htlc,
chan_type,
&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 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, 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 = RevocationKey::from_basepoint(
&secp_ctx,
&self.pubkeys().revocation_basepoint,
&per_commitment_point,
);
let counterparty_keys = self.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
let counterparty_htlcpubkey = HtlcKey::from_basepoint(
&secp_ctx,
&counterparty_keys.htlc_basepoint,
&per_commitment_point,
);
let htlc_basepoint = self.pubkeys().htlc_basepoint;
let htlcpubkey = HtlcKey::from_basepoint(&secp_ctx, &htlc_basepoint, &per_commitment_point);
let chan_type = self.channel_type_features().expect(MISSING_PARAMS_ERR);
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, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<Signature, ()> {
let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
let counterparty_funding_key =
&self.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(
&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)
.p2wsh_signature_hash(
input,
&witness_script,
Amount::from_sat(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))
}
}
#[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!()
}
fn sign_holder_anchor_input(
&self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<All>,
) -> Result<schnorr::Signature, ()> {
todo!()
}
}
const SERIALIZATION_VERSION: u8 = 1;
const MIN_SERIALIZATION_VERSION: u8 = 1;
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,
entropy_source: RandomBytes::new(entropy_source.get_secure_random_bytes()),
})
}
}
pub struct KeysManager {
secp_ctx: Secp256k1<secp256k1::All>,
node_secret: SecretKey,
node_id: PublicKey,
inbound_payment_key: KeyMaterial,
destination_script: ScriptBuf,
shutdown_pubkey: PublicKey,
channel_master_key: Xpriv,
channel_child_index: AtomicUsize,
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) -> Self {
let secp_ctx = Secp256k1::new();
match Xpriv::new_master(Network::Testnet, seed) {
Ok(master_key) => {
let node_secret = master_key
.derive_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
.derive_priv(&secp_ctx, &ChildNumber::from_hardened_idx(1).unwrap())
{
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, &ChildNumber::from_hardened_idx(2).unwrap())
{
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, &ChildNumber::from_hardened_idx(3).unwrap())
.expect("Your RNG is busted");
let inbound_payment_key: SecretKey = master_key
.derive_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).to_byte_array();
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),
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 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
.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 = 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 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 mut signer = self.derive_channel_keys(
descriptor.channel_value_satoshis,
&descriptor.channel_keys_id,
);
if let Some(channel_params) =
descriptor.channel_transaction_parameters.as_ref()
{
signer.provide_channel_parameters(channel_params);
}
keys_cache = Some((signer, descriptor.channel_keys_id));
}
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_value_satoshis,
&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_inbound_payment_key_material(&self) -> KeyMaterial {
self.inbound_payment_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_request(
&self, invoice_request: &UnsignedInvoiceRequest,
) -> Result<schnorr::Signature, ()> {
let message = invoice_request.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_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))
}
}
impl OutputSpender for KeysManager {
fn spend_spendable_outputs<C: Signing>(
&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
locktime: Option<LockTime>, secp_ctx: &Secp256k1<C>,
) -> 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, _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::EcdsaSigner {
self.derive_channel_keys(channel_value_satoshis, &channel_keys_id)
}
fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError> {
InMemorySigner::read(&mut io::Cursor::new(reader), self)
}
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 {
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, 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_request(
&self, invoice_request: &UnsignedInvoiceRequest,
) -> Result<schnorr::Signature, ()> {
self.inner.sign_bolt12_invoice_request(invoice_request)
}
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)
}
}
impl OutputSpender for PhantomKeysManager {
fn spend_spendable_outputs<C: Signing>(
&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
locktime: Option<LockTime>, secp_ctx: &Secp256k1<C>,
) -> 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, 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::EcdsaSigner {
self.inner.derive_channel_signer(channel_value_satoshis, channel_keys_id)
}
fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::EcdsaSigner, DecodeError> {
self.inner.read_chan_signer(reader)
}
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],
) -> 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 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
}
}
#[derive(Debug)]
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.get_increment();
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()));
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();
}
}
}