1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 use crate::ln::channel::{ANCHOR_OUTPUT_VALUE_SATOSHI, MIN_CHAN_DUST_LIMIT_SATOSHIS};
11 use crate::ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, HolderCommitmentTransaction, CommitmentTransaction, ChannelTransactionParameters, TrustedCommitmentTransaction, ClosingTransaction};
12 use crate::ln::channel_keys::{HtlcKey};
14 use crate::ln::types::PaymentPreimage;
15 use crate::sign::{InMemorySigner, ChannelSigner};
16 use crate::sign::ecdsa::EcdsaChannelSigner;
18 #[allow(unused_imports)]
19 use crate::prelude::*;
22 use crate::sync::{Mutex, Arc};
23 #[cfg(test)] use crate::sync::MutexGuard;
25 use bitcoin::blockdata::transaction::Transaction;
26 use bitcoin::hashes::Hash;
28 use bitcoin::sighash::EcdsaSighashType;
30 use bitcoin::secp256k1;
32 use bitcoin::secp256k1::All;
33 use bitcoin::secp256k1::{SecretKey, PublicKey};
34 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
36 use musig2::types::{PartialSignature, PublicNonce, SecretNonce};
37 use crate::sign::HTLCDescriptor;
38 use crate::util::ser::{Writeable, Writer};
40 use crate::ln::features::ChannelTypeFeatures;
42 use crate::ln::msgs::PartialSignatureWithNonce;
44 use crate::sign::taproot::TaprootChannelSigner;
46 /// Initial value for revoked commitment downward counter
47 pub const INITIAL_REVOKED_COMMITMENT_NUMBER: u64 = 1 << 48;
49 /// An implementation of Sign that enforces some policy checks. The current checks
50 /// are an incomplete set. They include:
52 /// - When signing, the holder transaction has not been revoked
53 /// - When revoking, the holder transaction has not been signed
54 /// - The holder commitment number is monotonic and without gaps
55 /// - The revoked holder commitment number is monotonic and without gaps
56 /// - There is at least one unrevoked holder transaction at all times
57 /// - The counterparty commitment number is monotonic and without gaps
58 /// - The pre-derived keys and pre-built transaction in CommitmentTransaction were correctly built
60 /// Eventually we will probably want to expose a variant of this which would essentially
61 /// be what you'd want to run on a hardware wallet.
63 /// Note that counterparty signatures on the holder transaction are not checked, but it should
64 /// be in a complete implementation.
66 /// Note that before we do so we should ensure its serialization format has backwards- and
67 /// forwards-compatibility prefix/suffixes!
69 pub struct TestChannelSigner {
70 pub inner: InMemorySigner,
71 /// Channel state used for policy enforcement
72 pub state: Arc<Mutex<EnforcementState>>,
73 pub disable_revocation_policy_check: bool,
74 /// Set of signer operations that are disabled. If an operation is disabled,
75 /// the signer will return `Err` when the corresponding method is called.
76 pub disabled_signer_ops: Arc<Mutex<HashSet<SignerOp>>>,
79 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
81 GetPerCommitmentPoint,
82 ReleaseCommitmentSecret,
83 ValidateHolderCommitment,
84 SignCounterpartyCommitment,
85 ValidateCounterpartyRevocation,
87 SignJusticeRevokedOutput,
88 SignJusticeRevokedHtlc,
89 SignHolderHtlcTransaction,
90 SignCounterpartyHtlcTransaction,
91 SignClosingTransaction,
92 SignHolderAnchorInput,
93 SignChannelAnnouncementWithFundingKey,
96 impl fmt::Display for SignerOp {
97 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
99 SignerOp::GetPerCommitmentPoint => write!(f, "get_per_commitment_point"),
100 SignerOp::ReleaseCommitmentSecret => write!(f, "release_commitment_secret"),
101 SignerOp::ValidateHolderCommitment => write!(f, "validate_holder_commitment"),
102 SignerOp::SignCounterpartyCommitment => write!(f, "sign_counterparty_commitment"),
103 SignerOp::ValidateCounterpartyRevocation => write!(f, "validate_counterparty_revocation"),
104 SignerOp::SignHolderCommitment => write!(f, "sign_holder_commitment"),
105 SignerOp::SignJusticeRevokedOutput => write!(f, "sign_justice_revoked_output"),
106 SignerOp::SignJusticeRevokedHtlc => write!(f, "sign_justice_revoked_htlc"),
107 SignerOp::SignHolderHtlcTransaction => write!(f, "sign_holder_htlc_transaction"),
108 SignerOp::SignCounterpartyHtlcTransaction => write!(f, "sign_counterparty_htlc_transaction"),
109 SignerOp::SignClosingTransaction => write!(f, "sign_closing_transaction"),
110 SignerOp::SignHolderAnchorInput => write!(f, "sign_holder_anchor_input"),
111 SignerOp::SignChannelAnnouncementWithFundingKey => write!(f, "sign_channel_announcement_with_funding_key"),
116 impl PartialEq for TestChannelSigner {
117 fn eq(&self, o: &Self) -> bool {
118 Arc::ptr_eq(&self.state, &o.state)
122 impl TestChannelSigner {
123 /// Construct an TestChannelSigner
124 pub fn new(inner: InMemorySigner) -> Self {
125 let state = Arc::new(Mutex::new(EnforcementState::new()));
129 disable_revocation_policy_check: false,
130 disabled_signer_ops: Arc::new(Mutex::new(new_hash_set())),
134 /// Construct an TestChannelSigner with externally managed storage
136 /// Since there are multiple copies of this struct for each channel, some coordination is needed
137 /// so that all copies are aware of enforcement state. A pointer to this state is provided
138 /// here, usually by an implementation of KeysInterface.
139 pub fn new_with_revoked(inner: InMemorySigner, state: Arc<Mutex<EnforcementState>>, disable_revocation_policy_check: bool) -> Self {
143 disable_revocation_policy_check,
144 disabled_signer_ops: Arc::new(Mutex::new(new_hash_set())),
148 pub fn channel_type_features(&self) -> &ChannelTypeFeatures { self.inner.channel_type_features().unwrap() }
151 pub fn get_enforcement_state(&self) -> MutexGuard<EnforcementState> {
152 self.state.lock().unwrap()
155 pub fn enable_op(&mut self, signer_op: SignerOp) {
156 self.disabled_signer_ops.lock().unwrap().remove(&signer_op);
159 pub fn disable_op(&mut self, signer_op: SignerOp) {
160 self.disabled_signer_ops.lock().unwrap().insert(signer_op);
163 fn is_signer_available(&self, signer_op: SignerOp) -> bool {
164 !self.disabled_signer_ops.lock().unwrap().contains(&signer_op)
168 impl ChannelSigner for TestChannelSigner {
169 fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>) -> PublicKey {
170 self.inner.get_per_commitment_point(idx, secp_ctx)
173 fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
175 let mut state = self.state.lock().unwrap();
176 assert!(idx == state.last_holder_revoked_commitment || idx == state.last_holder_revoked_commitment - 1, "can only revoke the current or next unrevoked commitment - trying {}, last revoked {}", idx, state.last_holder_revoked_commitment);
177 assert!(idx > state.last_holder_commitment, "cannot revoke the last holder commitment - attempted to revoke {} last commitment {}", idx, state.last_holder_commitment);
178 state.last_holder_revoked_commitment = idx;
180 self.inner.release_commitment_secret(idx)
183 fn validate_holder_commitment(&self, holder_tx: &HolderCommitmentTransaction, _outbound_htlc_preimages: Vec<PaymentPreimage>) -> Result<(), ()> {
184 let mut state = self.state.lock().unwrap();
185 let idx = holder_tx.commitment_number();
186 assert!(idx == state.last_holder_commitment || idx == state.last_holder_commitment - 1, "expecting to validate the current or next holder commitment - trying {}, current {}", idx, state.last_holder_commitment);
187 state.last_holder_commitment = idx;
191 fn validate_counterparty_revocation(&self, idx: u64, _secret: &SecretKey) -> Result<(), ()> {
192 if !self.is_signer_available(SignerOp::ValidateCounterpartyRevocation) {
195 let mut state = self.state.lock().unwrap();
196 assert!(idx == state.last_counterparty_revoked_commitment || idx == state.last_counterparty_revoked_commitment - 1, "expecting to validate the current or next counterparty revocation - trying {}, current {}", idx, state.last_counterparty_revoked_commitment);
197 state.last_counterparty_revoked_commitment = idx;
201 fn pubkeys(&self) -> &ChannelPublicKeys { self.inner.pubkeys() }
203 fn channel_keys_id(&self) -> [u8; 32] { self.inner.channel_keys_id() }
205 fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters) {
206 self.inner.provide_channel_parameters(channel_parameters)
210 impl EcdsaChannelSigner for TestChannelSigner {
211 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>), ()> {
212 self.verify_counterparty_commitment_tx(commitment_tx, secp_ctx);
215 if !self.is_signer_available(SignerOp::SignCounterpartyCommitment) {
218 let mut state = self.state.lock().unwrap();
219 let actual_commitment_number = commitment_tx.commitment_number();
220 let last_commitment_number = state.last_counterparty_commitment;
221 // These commitment numbers are backwards counting. We expect either the same as the previously encountered,
223 assert!(last_commitment_number == actual_commitment_number || last_commitment_number - 1 == actual_commitment_number, "{} doesn't come after {}", actual_commitment_number, last_commitment_number);
224 // Ensure that the counterparty doesn't get more than two broadcastable commitments -
225 // the last and the one we are trying to sign
226 assert!(actual_commitment_number >= state.last_counterparty_revoked_commitment - 2, "cannot sign a commitment if second to last wasn't revoked - signing {} revoked {}", actual_commitment_number, state.last_counterparty_revoked_commitment);
227 state.last_counterparty_commitment = cmp::min(last_commitment_number, actual_commitment_number)
230 Ok(self.inner.sign_counterparty_commitment(commitment_tx, inbound_htlc_preimages, outbound_htlc_preimages, secp_ctx).unwrap())
233 fn sign_holder_commitment(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
234 if !self.is_signer_available(SignerOp::SignHolderCommitment) {
237 let trusted_tx = self.verify_holder_commitment_tx(commitment_tx, secp_ctx);
238 let state = self.state.lock().unwrap();
239 let commitment_number = trusted_tx.commitment_number();
240 if state.last_holder_revoked_commitment - 1 != commitment_number && state.last_holder_revoked_commitment - 2 != commitment_number {
241 if !self.disable_revocation_policy_check {
242 panic!("can only sign the next two unrevoked commitment numbers, revoked={} vs requested={} for {}",
243 state.last_holder_revoked_commitment, commitment_number, self.inner.commitment_seed[0])
246 Ok(self.inner.sign_holder_commitment(commitment_tx, secp_ctx).unwrap())
249 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
250 fn unsafe_sign_holder_commitment(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
251 Ok(self.inner.unsafe_sign_holder_commitment(commitment_tx, secp_ctx).unwrap())
254 fn sign_justice_revoked_output(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
255 if !self.is_signer_available(SignerOp::SignJusticeRevokedOutput) {
258 Ok(EcdsaChannelSigner::sign_justice_revoked_output(&self.inner, justice_tx, input, amount, per_commitment_key, secp_ctx).unwrap())
261 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, ()> {
262 if !self.is_signer_available(SignerOp::SignJusticeRevokedHtlc) {
265 Ok(EcdsaChannelSigner::sign_justice_revoked_htlc(&self.inner, justice_tx, input, amount, per_commitment_key, htlc, secp_ctx).unwrap())
268 fn sign_holder_htlc_transaction(
269 &self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
270 secp_ctx: &Secp256k1<secp256k1::All>
271 ) -> Result<Signature, ()> {
272 if !self.is_signer_available(SignerOp::SignHolderHtlcTransaction) {
275 let state = self.state.lock().unwrap();
276 if state.last_holder_revoked_commitment - 1 != htlc_descriptor.per_commitment_number &&
277 state.last_holder_revoked_commitment - 2 != htlc_descriptor.per_commitment_number
279 if !self.disable_revocation_policy_check {
280 panic!("can only sign the next two unrevoked commitment numbers, revoked={} vs requested={} for {}",
281 state.last_holder_revoked_commitment, htlc_descriptor.per_commitment_number, self.inner.commitment_seed[0])
284 assert_eq!(htlc_tx.input[input], htlc_descriptor.unsigned_tx_input());
285 assert_eq!(htlc_tx.output[input], htlc_descriptor.tx_output(secp_ctx));
287 let witness_script = htlc_descriptor.witness_script(secp_ctx);
288 let sighash_type = if self.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
289 EcdsaSighashType::SinglePlusAnyoneCanPay
291 EcdsaSighashType::All
293 let sighash = &sighash::SighashCache::new(&*htlc_tx).p2wsh_signature_hash(
294 input, &witness_script, htlc_descriptor.htlc.to_bitcoin_amount(), sighash_type
296 let countersignatory_htlc_key = HtlcKey::from_basepoint(
297 &secp_ctx, &self.inner.counterparty_pubkeys().unwrap().htlc_basepoint, &htlc_descriptor.per_commitment_point,
300 secp_ctx.verify_ecdsa(
301 &hash_to_message!(sighash.as_byte_array()), &htlc_descriptor.counterparty_sig, &countersignatory_htlc_key.to_public_key()
304 Ok(EcdsaChannelSigner::sign_holder_htlc_transaction(&self.inner, htlc_tx, input, htlc_descriptor, secp_ctx).unwrap())
307 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, ()> {
308 if !self.is_signer_available(SignerOp::SignCounterpartyHtlcTransaction) {
311 Ok(EcdsaChannelSigner::sign_counterparty_htlc_transaction(&self.inner, htlc_tx, input, amount, per_commitment_point, htlc, secp_ctx).unwrap())
314 fn sign_closing_transaction(&self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
315 closing_tx.verify(self.inner.funding_outpoint().unwrap().into_bitcoin_outpoint())
316 .expect("derived different closing transaction");
317 Ok(self.inner.sign_closing_transaction(closing_tx, secp_ctx).unwrap())
320 fn sign_holder_anchor_input(
321 &self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<secp256k1::All>,
322 ) -> Result<Signature, ()> {
323 debug_assert!(MIN_CHAN_DUST_LIMIT_SATOSHIS > ANCHOR_OUTPUT_VALUE_SATOSHI);
324 // As long as our minimum dust limit is enforced and is greater than our anchor output
325 // value, an anchor output can only have an index within [0, 1].
326 assert!(anchor_tx.input[input].previous_output.vout == 0 || anchor_tx.input[input].previous_output.vout == 1);
327 if !self.is_signer_available(SignerOp::SignHolderAnchorInput) {
330 EcdsaChannelSigner::sign_holder_anchor_input(&self.inner, anchor_tx, input, secp_ctx)
333 fn sign_channel_announcement_with_funding_key(
334 &self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>
335 ) -> Result<Signature, ()> {
336 self.inner.sign_channel_announcement_with_funding_key(msg, secp_ctx)
341 impl TaprootChannelSigner for TestChannelSigner {
342 fn generate_local_nonce_pair(&self, commitment_number: u64, secp_ctx: &Secp256k1<All>) -> PublicNonce {
346 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<secp256k1::schnorr::Signature>), ()> {
350 fn finalize_holder_commitment(&self, commitment_tx: &HolderCommitmentTransaction, counterparty_partial_signature: PartialSignatureWithNonce, secp_ctx: &Secp256k1<All>) -> Result<PartialSignature, ()> {
354 fn sign_justice_revoked_output(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, secp_ctx: &Secp256k1<All>) -> Result<secp256k1::schnorr::Signature, ()> {
358 fn sign_justice_revoked_htlc(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<All>) -> Result<secp256k1::schnorr::Signature, ()> {
362 fn sign_holder_htlc_transaction(&self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor, secp_ctx: &Secp256k1<All>) -> Result<secp256k1::schnorr::Signature, ()> {
366 fn sign_counterparty_htlc_transaction(&self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<All>) -> Result<secp256k1::schnorr::Signature, ()> {
370 fn partially_sign_closing_transaction(&self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<All>) -> Result<PartialSignature, ()> {
374 fn sign_holder_anchor_input(&self, anchor_tx: &Transaction, input: usize, secp_ctx: &Secp256k1<All>) -> Result<secp256k1::schnorr::Signature, ()> {
379 impl Writeable for TestChannelSigner {
380 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
381 // TestChannelSigner has two fields - `inner` ([`InMemorySigner`]) and `state`
382 // ([`EnforcementState`]). `inner` is serialized here and deserialized by
383 // [`SignerProvider::read_chan_signer`]. `state` is managed by [`SignerProvider`]
384 // and will be serialized as needed by the implementation of that trait.
385 self.inner.write(writer)?;
390 impl TestChannelSigner {
391 fn verify_counterparty_commitment_tx<'a, T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &'a CommitmentTransaction, secp_ctx: &Secp256k1<T>) -> TrustedCommitmentTransaction<'a> {
392 commitment_tx.verify(
393 &self.inner.get_channel_parameters().unwrap().as_counterparty_broadcastable(),
394 self.inner.counterparty_pubkeys().unwrap(), self.inner.pubkeys(), secp_ctx
395 ).expect("derived different per-tx keys or built transaction")
398 fn verify_holder_commitment_tx<'a, T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &'a CommitmentTransaction, secp_ctx: &Secp256k1<T>) -> TrustedCommitmentTransaction<'a> {
399 commitment_tx.verify(
400 &self.inner.get_channel_parameters().unwrap().as_holder_broadcastable(),
401 self.inner.pubkeys(), self.inner.counterparty_pubkeys().unwrap(), secp_ctx
402 ).expect("derived different per-tx keys or built transaction")
406 /// The state used by [`TestChannelSigner`] in order to enforce policy checks
408 /// This structure is maintained by KeysInterface since we may have multiple copies of
409 /// the signer and they must coordinate their state.
411 pub struct EnforcementState {
412 /// The last counterparty commitment number we signed, backwards counting
413 pub last_counterparty_commitment: u64,
414 /// The last counterparty commitment they revoked, backwards counting
415 pub last_counterparty_revoked_commitment: u64,
416 /// The last holder commitment number we revoked, backwards counting
417 pub last_holder_revoked_commitment: u64,
418 /// The last validated holder commitment number, backwards counting
419 pub last_holder_commitment: u64,
422 impl EnforcementState {
423 /// Enforcement state for a new channel
424 pub fn new() -> Self {
426 last_counterparty_commitment: INITIAL_REVOKED_COMMITMENT_NUMBER,
427 last_counterparty_revoked_commitment: INITIAL_REVOKED_COMMITMENT_NUMBER,
428 last_holder_revoked_commitment: INITIAL_REVOKED_COMMITMENT_NUMBER,
429 last_holder_commitment: INITIAL_REVOKED_COMMITMENT_NUMBER,