lightning_signer/
channel.rs

1use core::any::Any;
2use core::fmt;
3use core::fmt::{Debug, Error, Formatter};
4
5use bitcoin::hashes::hex::FromHex;
6use bitcoin::hashes::sha256d::Hash as Sha256dHash;
7use bitcoin::hashes::Hash;
8use bitcoin::secp256k1::{self, ecdsa::Signature, All, Message, PublicKey, Secp256k1, SecretKey};
9use bitcoin::sighash::EcdsaSighashType;
10use bitcoin::sighash::SighashCache;
11use bitcoin::{Amount, Network, OutPoint, Script, ScriptBuf, Transaction};
12use lightning::chain;
13use lightning::ln::chan_utils;
14use lightning::ln::chan_utils::{
15    build_htlc_transaction, derive_private_key, get_htlc_redeemscript, make_funding_redeemscript,
16    ChannelPublicKeys, ChannelTransactionParameters, ClosingTransaction, CommitmentTransaction,
17    CounterpartyChannelTransactionParameters, HTLCOutputInCommitment, HolderCommitmentTransaction,
18    TxCreationKeys,
19};
20use lightning::ln::channel_keys::{DelayedPaymentKey, RevocationKey};
21use lightning::sign::ecdsa::EcdsaChannelSigner;
22use lightning::sign::{ChannelSigner, EntropySource, InMemorySigner, SignerProvider};
23use lightning::types::features::ChannelTypeFeatures;
24use lightning::types::payment::{PaymentHash, PaymentPreimage};
25use serde_derive::{Deserialize, Serialize};
26use serde_with::{hex::Hex, serde_as, Bytes, IfIsHumanReadable};
27use tracing::*;
28use vls_common::HexEncode;
29
30use crate::monitor::ChainMonitorBase;
31use crate::node::{Node, RoutedPayment, CHANNEL_STUB_PRUNE_BLOCKS};
32use crate::policy::error::policy_error;
33use crate::policy::validator::{ChainState, CommitmentSignatures, EnforcementState, Validator};
34use crate::prelude::*;
35use crate::tx::tx::{CommitmentInfo2, HTLCInfo2};
36use crate::util::crypto_utils::derive_public_key;
37use crate::util::crypto_utils::derive_public_revocation_key;
38use crate::util::debug_utils::{DebugHTLCOutputInCommitment, DebugInMemorySigner, DebugVecVecU8};
39use crate::util::ser_util::{ChannelPublicKeysDef, OutPointReversedDef, ScriptDef};
40use crate::util::status::{internal_error, invalid_argument, Status};
41use crate::util::transaction_utils::add_holder_sig;
42use crate::util::INITIAL_COMMITMENT_NUMBER;
43use crate::wallet::Wallet;
44use crate::{catch_panic, policy_err, Arc, CommitmentPointProvider, Weak};
45
46/// Channel identifier
47///
48/// This id is used to coordinate with the node and
49/// is not related to the channel ids in the Lightning protocol.
50/// The channel keys are derived from this and a base key.
51///
52/// A channel may have more than one id.
53///
54/// There are currently two ways to generate ids: one which uses
55/// a peer id and is compatible with CLN, and one which doesn't
56/// and is compatible with LDK. In both cases the id of the channel
57/// at the node (called a `dbid` in CLN or `oid in LDK) is stored
58/// in little-endian in the final 8 bytes of the id. This fact is
59/// relied when retrieving the `dbid`/`oid`.
60#[serde_as]
61#[derive(PartialEq, Eq, Clone, PartialOrd, Ord, Serialize, Deserialize)]
62pub struct ChannelId(#[serde_as(as = "IfIsHumanReadable<Hex, Bytes>")] Vec<u8>);
63
64impl ChannelId {
65    /// Create an id from a nonce
66    pub fn new(inner: &[u8]) -> Self {
67        Self(inner.to_vec())
68    }
69
70    /// Create an id from an oid (LDK-style)
71    ///
72    /// The nonce is a 32 byte array, where the first
73    /// 24 bytes are 0 and the last 8 are the original
74    /// id (little-endian)
75    pub fn new_from_oid(oid: u64) -> Self {
76        let mut nonce: [u8; 32] = [0u8; 32];
77        let oid_slice = oid.to_le_bytes();
78        nonce[24..].copy_from_slice(&oid_slice);
79        Self::new(&nonce)
80    }
81
82    /// Create an id from a peer id and oid (CLN-style)
83    ///
84    /// The nonce is a 41 byte array, where the first 33
85    /// bytes are the peer id and the final 8 are the
86    /// original id (little-endian)
87    pub fn new_from_peer_id_and_oid(peer_id: &[u8; 33], oid: u64) -> Self {
88        let mut nonce = [0u8; 33 + 8];
89        nonce[0..33].copy_from_slice(peer_id);
90        nonce[33..].copy_from_slice(&oid.to_le_bytes());
91        Self::new(&nonce)
92    }
93
94    /// Return a byte slice of the nonce
95    pub fn as_slice(&self) -> &[u8] {
96        self.0.as_slice()
97    }
98
99    /// Return a reference to a vector of the nonce
100    pub fn inner(&self) -> &Vec<u8> {
101        &self.0
102    }
103
104    /// Returns the original id used at creation
105    pub fn oid(&self) -> u64 {
106        let bytes_slice = &self.0[&self.0.len() - 8..];
107        let mut bytes_array = [0u8; 8];
108        bytes_array.copy_from_slice(bytes_slice);
109        u64::from_le_bytes(bytes_array)
110    }
111
112    /// Return the id in a format compatible with the LDK
113    /// `SignerProvider` `generate_channel_keys_id` interface
114    ///
115    /// This will panic if the nonce is not exactly 32 bytes
116    pub fn ldk_channel_keys_id(&self) -> [u8; 32] {
117        let mut nonce = [0u8; 32];
118        nonce.copy_from_slice(&self.0);
119        nonce
120    }
121}
122
123impl Debug for ChannelId {
124    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
125        write!(f, "{}", self.0.to_hex())
126    }
127}
128
129impl fmt::Display for ChannelId {
130    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
131        write!(f, "{}", self.0.to_hex())
132    }
133}
134
135/// Bitcoin Signature which specifies EcdsaSighashType
136#[derive(Debug)]
137pub struct TypedSignature {
138    /// The signature
139    pub sig: Signature,
140    /// The sighash type
141    pub typ: EcdsaSighashType,
142}
143
144impl TypedSignature {
145    /// Serialize the signature and append the sighash type byte.
146    pub fn serialize(&self) -> Vec<u8> {
147        let mut ss = self.sig.serialize_der().to_vec();
148        ss.push(self.typ as u8);
149        ss
150    }
151
152    /// A TypedSignature with SIGHASH_ALL
153    pub fn all(sig: Signature) -> Self {
154        Self { sig, typ: EcdsaSighashType::All }
155    }
156}
157
158/// The commitment type, based on the negotiated option
159#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
160pub enum CommitmentType {
161    /// No longer used - dynamic to-remote key
162    /// DEPRECATED
163    Legacy,
164    /// Static to-remote key
165    StaticRemoteKey,
166    /// Anchors
167    /// DEPRECATED
168    Anchors,
169    /// Anchors, zero fee htlc
170    AnchorsZeroFeeHtlc,
171}
172
173/// The negotiated parameters for the [Channel]
174#[serde_as]
175#[derive(Clone, PartialEq, Serialize, Deserialize)]
176pub struct ChannelSetup {
177    /// Whether the channel is outbound
178    pub is_outbound: bool,
179    /// The total the channel was funded with
180    pub channel_value_sat: u64,
181    // DUP keys.inner.channel_value_satoshis
182    /// How much was pushed to the counterparty
183    pub push_value_msat: u64,
184    /// The funding outpoint
185    #[serde_as(as = "IfIsHumanReadable<OutPointReversedDef>")]
186    pub funding_outpoint: OutPoint,
187    /// locally imposed requirement on the remote commitment transaction to_self_delay
188    pub holder_selected_contest_delay: u16,
189    /// The holder's optional upfront shutdown script
190    #[serde_as(as = "IfIsHumanReadable<Option<ScriptDef>>")]
191    pub holder_shutdown_script: Option<ScriptBuf>,
192    /// The counterparty's basepoints and pubkeys
193    #[serde_as(as = "ChannelPublicKeysDef")]
194    pub counterparty_points: ChannelPublicKeys,
195    // DUP keys.inner.remote_channel_pubkeys
196    /// remotely imposed requirement on the local commitment transaction to_self_delay
197    pub counterparty_selected_contest_delay: u16,
198    /// The counterparty's optional upfront shutdown script
199    #[serde_as(as = "IfIsHumanReadable<Option<ScriptDef>>")]
200    pub counterparty_shutdown_script: Option<ScriptBuf>,
201    /// The negotiated commitment type
202    pub commitment_type: CommitmentType,
203}
204
205// Need to define manually because ChannelPublicKeys doesn't derive Debug.
206impl fmt::Debug for ChannelSetup {
207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208        f.debug_struct("ChannelSetup")
209            .field("is_outbound", &self.is_outbound)
210            .field("channel_value_sat", &self.channel_value_sat)
211            .field("push_value_msat", &self.push_value_msat)
212            .field("funding_outpoint", &self.funding_outpoint)
213            .field("holder_selected_contest_delay", &self.holder_selected_contest_delay)
214            .field("holder_shutdown_script", &self.holder_shutdown_script)
215            .field("counterparty_points", log_channel_public_keys!(&self.counterparty_points))
216            .field("counterparty_selected_contest_delay", &self.counterparty_selected_contest_delay)
217            .field("counterparty_shutdown_script", &self.counterparty_shutdown_script)
218            .field("commitment_type", &self.commitment_type)
219            .finish()
220    }
221}
222
223impl ChannelSetup {
224    /// True if this channel uses static to_remote key
225    pub fn is_static_remotekey(&self) -> bool {
226        self.commitment_type != CommitmentType::Legacy
227    }
228
229    /// True if this channel uses anchors
230    pub fn is_anchors(&self) -> bool {
231        self.commitment_type == CommitmentType::Anchors
232            || self.commitment_type == CommitmentType::AnchorsZeroFeeHtlc
233    }
234
235    /// True if this channel uses zero fee htlc with anchors
236    pub fn is_zero_fee_htlc(&self) -> bool {
237        self.commitment_type == CommitmentType::AnchorsZeroFeeHtlc
238    }
239
240    /// Convert the channel type to a ChannelTypeFeatures
241    pub fn features(&self) -> ChannelTypeFeatures {
242        let mut features = ChannelTypeFeatures::empty();
243        features.set_static_remote_key_required();
244        if self.is_anchors() {
245            if self.is_zero_fee_htlc() {
246                features.set_anchors_zero_fee_htlc_tx_optional();
247            } else {
248                features.set_anchors_nonzero_fee_htlc_tx_optional();
249            }
250        }
251        features
252    }
253}
254
255#[derive(Debug)]
256/// Channel slot information for stubs and channels.
257pub enum SlotInfoVariant {
258    /// Information for stubs
259    StubInfo {
260        /// The blockheight that the stub will be pruned
261        pruneheight: u32,
262    },
263    /// Information for channels
264    ChannelInfo {
265        /// The channel's funding outpoint
266        funding: Option<OutPoint>,
267        /// The channel balance
268        balance: ChannelBalance,
269        /// Has the node has forgotten this channel?
270        forget_seen: bool,
271        /// Description of the state of this channel
272        diagnostic: String,
273    },
274}
275
276#[derive(Debug)]
277/// Per-channel-slot summary information for system monitoring
278pub struct SlotInfo {
279    /// An ordinal identifier
280    pub oid: u64,
281    /// The channel id
282    pub id: ChannelId,
283    /// Stub and Channel specific data
284    pub slot: SlotInfoVariant,
285}
286
287/// A trait implemented by both channel states.  See [ChannelSlot]
288pub trait ChannelBase: Any {
289    /// Get the channel basepoints and public keys
290    fn get_channel_basepoints(&self) -> ChannelPublicKeys;
291    /// Get the per-commitment point for a holder commitment transaction.
292    /// Errors if the commitment number is too high given the current state.
293    fn get_per_commitment_point(&self, commitment_number: u64) -> Result<PublicKey, Status>;
294    /// Get the per-commitment secret for a holder commitment transaction
295    /// Errors if the commitment number is not ready to be revoked given the current state.
296    fn get_per_commitment_secret(&self, commitment_number: u64) -> Result<SecretKey, Status>;
297    /// Get the per-commitment secret or None if the arg is out of range
298    fn get_per_commitment_secret_or_none(&self, commitment_number: u64) -> Option<SecretKey>;
299    /// Check a future secret to support `option_data_loss_protect`
300    fn check_future_secret(&self, commit_num: u64, suggested: &SecretKey) -> Result<bool, Status>;
301    /// Returns the validator for this channel
302    fn validator(&self) -> Arc<dyn Validator>;
303    /// Channel information for logging
304    fn chaninfo(&self) -> SlotInfo;
305
306    #[allow(missing_docs)]
307    #[cfg(any(test, feature = "test_utils"))]
308    fn set_next_holder_commit_num_for_testing(&mut self, _num: u64) {
309        // Do nothing for ChannelStub.  Channel will override.
310    }
311}
312
313/// A channel can be in two states - before [Node::setup_channel] it's a
314/// [ChannelStub], afterwards it's a [Channel].  This enum keeps track
315/// of the two different states.
316#[derive(Debug, Clone)]
317pub enum ChannelSlot {
318    /// Initial state, not ready
319    Stub(ChannelStub),
320    /// Ready after negotiation is complete
321    Ready(Channel),
322}
323
324impl ChannelSlot {
325    /// The initial channel ID
326    pub fn id(&self) -> ChannelId {
327        match self {
328            ChannelSlot::Stub(stub) => stub.id0.clone(),
329            ChannelSlot::Ready(chan) => chan.id0.clone(),
330        }
331    }
332
333    /// The basepoints
334    pub fn get_channel_basepoints(&self) -> ChannelPublicKeys {
335        match self {
336            ChannelSlot::Stub(stub) => stub.get_channel_basepoints(),
337            ChannelSlot::Ready(chan) => chan.get_channel_basepoints(),
338        }
339    }
340
341    /// Assume this is a channel stub, and return it.
342    /// Panics if it's not.
343    #[cfg(any(test, feature = "test_utils"))]
344    pub fn unwrap_stub(&self) -> &ChannelStub {
345        match self {
346            ChannelSlot::Stub(stub) => stub,
347            ChannelSlot::Ready(_) => panic!("unwrap_stub called on ChannelSlot::Ready"),
348        }
349    }
350
351    /// Log channel information
352    pub fn chaninfo(&self) -> SlotInfo {
353        match self {
354            ChannelSlot::Stub(stub) => stub.chaninfo(),
355            ChannelSlot::Ready(chan) => chan.chaninfo(),
356        }
357    }
358}
359
360/// A channel takes this form after [Node::new_channel], and before [Node::setup_channel]
361#[derive(Clone)]
362pub struct ChannelStub {
363    /// A backpointer to the node
364    pub node: Weak<Node>,
365    pub(crate) secp_ctx: Secp256k1<All>,
366    /// The signer for this channel
367    pub keys: InMemorySigner,
368    // Incomplete, channel_value_sat is placeholder.
369    /// The initial channel ID, used to find the channel in the node
370    pub id0: ChannelId,
371    /// Blockheight when created
372    pub blockheight: u32,
373}
374
375// Need to define manually because InMemorySigner doesn't derive Debug.
376impl fmt::Debug for ChannelStub {
377    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
378        f.debug_struct("ChannelStub")
379            .field("keys", &DebugInMemorySigner(&self.keys))
380            .field("id0", &self.id0)
381            .finish()
382    }
383}
384
385impl ChannelBase for ChannelStub {
386    fn get_channel_basepoints(&self) -> ChannelPublicKeys {
387        self.keys.pubkeys().clone()
388    }
389
390    fn get_per_commitment_point(&self, commitment_number: u64) -> Result<PublicKey, Status> {
391        if ![0, 1].contains(&commitment_number) {
392            return Err(policy_error(format!(
393                "channel stub can only return point for commitment number zero or one",
394            ))
395            .into());
396        }
397        Ok(self
398            .keys
399            .get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - commitment_number, &self.secp_ctx)
400            .unwrap())
401    }
402
403    fn get_per_commitment_secret(&self, _commitment_number: u64) -> Result<SecretKey, Status> {
404        // We can't release a commitment_secret from a ChannelStub ever.
405        Err(policy_error(format!("channel stub cannot release commitment secret")).into())
406    }
407
408    fn get_per_commitment_secret_or_none(&self, _commitment_number: u64) -> Option<SecretKey> {
409        None
410    }
411
412    fn check_future_secret(
413        &self,
414        commitment_number: u64,
415        suggested: &SecretKey,
416    ) -> Result<bool, Status> {
417        let secret_data = self
418            .keys
419            .release_commitment_secret(INITIAL_COMMITMENT_NUMBER - commitment_number)
420            .unwrap();
421        Ok(suggested[..] == secret_data)
422    }
423
424    fn validator(&self) -> Arc<dyn Validator> {
425        let node = self.get_node();
426        let v = node.validator_factory().make_validator(
427            node.network(),
428            node.get_id(),
429            Some(self.id0.clone()),
430        );
431        v
432    }
433
434    fn chaninfo(&self) -> SlotInfo {
435        SlotInfo {
436            oid: self.id0.oid(),
437            id: self.id0.clone(),
438            slot: SlotInfoVariant::StubInfo {
439                pruneheight: self.blockheight + CHANNEL_STUB_PRUNE_BLOCKS,
440            },
441        }
442    }
443}
444
445impl ChannelStub {
446    pub(crate) fn channel_keys_with_channel_value(&self, channel_value_sat: u64) -> InMemorySigner {
447        let secp_ctx = Secp256k1::signing_only();
448        let keys = &self.keys;
449        InMemorySigner::new(
450            &secp_ctx,
451            keys.funding_key,
452            keys.revocation_base_key,
453            keys.payment_key,
454            keys.delayed_payment_base_key,
455            keys.htlc_base_key,
456            keys.commitment_seed,
457            channel_value_sat,
458            keys.channel_keys_id(),
459            keys.get_secure_random_bytes(),
460        )
461    }
462
463    fn get_node(&self) -> Arc<Node> {
464        // this is safe because the node holds the channel, so it can't be dropped before it
465        self.node.upgrade().unwrap()
466    }
467}
468
469/// After [Node::setup_channel]
470#[derive(Clone)]
471pub struct Channel {
472    /// A backpointer to the node
473    pub node: Weak<Node>,
474    /// The logger
475    pub(crate) secp_ctx: Secp256k1<All>,
476    /// The signer for this channel
477    pub keys: InMemorySigner,
478    /// Channel state for policy enforcement purposes
479    pub enforcement_state: EnforcementState,
480    /// The negotiated channel setup
481    pub setup: ChannelSetup,
482    /// The initial channel ID
483    pub id0: ChannelId,
484    /// The optional permanent channel ID
485    pub id: Option<ChannelId>,
486    /// The chain monitor base
487    pub monitor: ChainMonitorBase,
488}
489
490impl Debug for Channel {
491    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
492        f.write_str("channel")
493    }
494}
495
496impl ChannelBase for Channel {
497    // TODO move out to impl Channel {} once LDK workaround is removed
498    #[cfg(any(test, feature = "test_utils"))]
499    fn set_next_holder_commit_num_for_testing(&mut self, num: u64) {
500        self.enforcement_state.set_next_holder_commit_num_for_testing(num);
501    }
502
503    fn get_channel_basepoints(&self) -> ChannelPublicKeys {
504        self.keys.pubkeys().clone()
505    }
506
507    fn get_per_commitment_point(&self, commitment_number: u64) -> Result<PublicKey, Status> {
508        let next_holder_commit_num = self.enforcement_state.next_holder_commit_num;
509        // The following check is relaxed by +1 because LDK fetches the next commitment point
510        // before it calls validate_holder_commitment_tx.
511        if commitment_number > next_holder_commit_num + 1 {
512            return Err(policy_error(format!(
513                "get_per_commitment_point: \
514                 commitment_number {} invalid when next_holder_commit_num is {}",
515                commitment_number, next_holder_commit_num,
516            ))
517            .into());
518        }
519        Ok(self.get_per_commitment_point_unchecked(commitment_number))
520    }
521
522    fn get_per_commitment_secret(&self, commitment_number: u64) -> Result<SecretKey, Status> {
523        let next_holder_commit_num = self.enforcement_state.next_holder_commit_num;
524        // When we try to release commitment number n, we must have a signature
525        // for commitment number `n+1`, so `next_holder_commit_num` must be at least
526        // `n+2`.
527        // Also, given that we previous validated the commitment tx when we
528        // got the counterparty signature for it, then we must have fulfilled
529        // policy-revoke-new-commitment-valid
530        if commitment_number + 2 > next_holder_commit_num {
531            let validator = self.validator();
532            policy_err!(
533                validator,
534                "policy-revoke-new-commitment-signed",
535                "cannot revoke commitment_number {} when next_holder_commit_num is {}",
536                commitment_number,
537                next_holder_commit_num,
538            )
539        }
540        let secret = self
541            .keys
542            .release_commitment_secret(INITIAL_COMMITMENT_NUMBER - commitment_number)
543            .unwrap();
544        Ok(SecretKey::from_slice(&secret).unwrap())
545    }
546
547    // Like get_per_commitment_secret but just returns None instead of a
548    // policy error if the request is out of range
549    fn get_per_commitment_secret_or_none(&self, commitment_number: u64) -> Option<SecretKey> {
550        let next_holder_commit_num = self.enforcement_state.next_holder_commit_num;
551        if commitment_number + 2 > next_holder_commit_num {
552            warn!(
553                "get_per_commitment_secret_or_none: called past current revoked holder commitment \
554                 implied by next_holder_commit_num: {} + 2 > {}",
555                commitment_number, next_holder_commit_num
556            );
557            None
558        } else {
559            Some(
560                SecretKey::from_slice(
561                    &self
562                        .keys
563                        .release_commitment_secret(INITIAL_COMMITMENT_NUMBER - commitment_number)
564                        .unwrap(),
565                )
566                .unwrap(),
567            )
568        }
569    }
570
571    fn check_future_secret(
572        &self,
573        commitment_number: u64,
574        suggested: &SecretKey,
575    ) -> Result<bool, Status> {
576        let secret_data = self
577            .keys
578            .release_commitment_secret(INITIAL_COMMITMENT_NUMBER - commitment_number)
579            .unwrap();
580        Ok(suggested[..] == secret_data)
581    }
582
583    fn validator(&self) -> Arc<dyn Validator> {
584        let node = self.get_node();
585        let v = node.validator_factory().make_validator(
586            self.network(),
587            node.get_id(),
588            Some(self.id0.clone()),
589        );
590        v
591    }
592
593    fn chaninfo(&self) -> SlotInfo {
594        SlotInfo {
595            oid: self.id0.oid(),
596            id: self.id(),
597            slot: SlotInfoVariant::ChannelInfo {
598                funding: self.monitor.funding_outpoint(),
599                balance: self.balance(),
600                forget_seen: self.monitor.forget_seen(),
601                diagnostic: self.monitor.diagnostic(self.enforcement_state.channel_closed),
602            },
603        }
604    }
605}
606
607impl Channel {
608    /// The channel ID
609    pub fn id(&self) -> ChannelId {
610        self.id.clone().unwrap_or(self.id0.clone())
611    }
612
613    #[allow(missing_docs)]
614    #[cfg(any(test, feature = "test_utils"))]
615    pub fn set_next_counterparty_commit_num_for_testing(
616        &mut self,
617        num: u64,
618        current_point: PublicKey,
619    ) {
620        self.enforcement_state.set_next_counterparty_commit_num_for_testing(num, current_point);
621    }
622
623    #[allow(missing_docs)]
624    #[cfg(any(test, feature = "test_utils"))]
625    pub fn set_next_counterparty_revoke_num_for_testing(&mut self, num: u64) {
626        self.enforcement_state.set_next_counterparty_revoke_num_for_testing(num);
627    }
628
629    pub(crate) fn get_chain_state(&self) -> ChainState {
630        self.monitor.as_chain_state()
631    }
632
633    /// Get the counterparty's public keys
634    pub fn counterparty_pubkeys(&self) -> &ChannelPublicKeys {
635        // this is safe because the channel was readied
636        self.keys.counterparty_pubkeys().expect("counterparty_pubkeys")
637    }
638
639    fn get_per_commitment_point_unchecked(&self, commitment_number: u64) -> PublicKey {
640        self.keys
641            .get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - commitment_number, &self.secp_ctx)
642            .unwrap()
643    }
644
645    pub(crate) fn get_counterparty_commitment_point(
646        &self,
647        commitment_number: u64,
648    ) -> Option<PublicKey> {
649        let state = &self.enforcement_state;
650
651        let next_commit_num = state.next_counterparty_commit_num;
652
653        // we can supply the counterparty's commitment point for the following cases:
654        // - the commitment number is the current or previous one the counterparty signed (we received the point)
655        // - the commitment number is older than that (the commitment was revoked and we received the secret)
656
657        if next_commit_num < commitment_number + 1 {
658            // in the future, we don't have it
659            warn!("asked for counterparty commitment point {} but our next counterparty commitment number is {}",
660                commitment_number, next_commit_num);
661            None
662        } else if next_commit_num == commitment_number + 1 {
663            state.current_counterparty_point
664        } else if next_commit_num == commitment_number {
665            state.previous_counterparty_point
666        } else if let Some(secrets) = state.counterparty_secrets.as_ref() {
667            let secret = secrets.get_secret(INITIAL_COMMITMENT_NUMBER - commitment_number);
668            secret.map(|s| {
669                PublicKey::from_secret_key(
670                    &self.secp_ctx,
671                    &SecretKey::from_slice(&s).expect("secret from storage"),
672                )
673            })
674        } else {
675            warn!(
676                "asked for counterparty commitment point {} but we don't have secrets storage",
677                commitment_number
678            );
679            None
680        }
681    }
682}
683
684// Phase 2
685impl Channel {
686    // Phase 2
687    /// Public for testing purposes
688    pub fn make_counterparty_tx_keys(&self, per_commitment_point: &PublicKey) -> TxCreationKeys {
689        let holder_points = self.keys.pubkeys();
690        let counterparty_points = self.counterparty_pubkeys();
691
692        self.make_tx_keys(per_commitment_point, counterparty_points, holder_points)
693    }
694
695    pub(crate) fn make_holder_tx_keys(&self, per_commitment_point: &PublicKey) -> TxCreationKeys {
696        let holder_points = self.keys.pubkeys();
697        let counterparty_points = self.counterparty_pubkeys();
698
699        self.make_tx_keys(per_commitment_point, holder_points, counterparty_points)
700    }
701
702    fn make_tx_keys(
703        &self,
704        per_commitment_point: &PublicKey,
705        a_points: &ChannelPublicKeys,
706        b_points: &ChannelPublicKeys,
707    ) -> TxCreationKeys {
708        TxCreationKeys::derive_new(
709            &self.secp_ctx,
710            &per_commitment_point,
711            &a_points.delayed_payment_basepoint,
712            &a_points.htlc_basepoint,
713            &b_points.revocation_basepoint,
714            &b_points.htlc_basepoint,
715        )
716    }
717
718    /// Sign a counterparty commitment transaction after rebuilding it
719    /// from the supplied arguments.
720    #[instrument(skip(self))]
721    pub fn sign_counterparty_commitment_tx_phase2(
722        &mut self,
723        remote_per_commitment_point: &PublicKey,
724        commitment_number: u64,
725        feerate_per_kw: u32,
726        to_holder_value_sat: u64,
727        to_counterparty_value_sat: u64,
728        offered_htlcs: Vec<HTLCInfo2>,
729        received_htlcs: Vec<HTLCInfo2>,
730    ) -> Result<(Signature, Vec<Signature>), Status> {
731        // Since we didn't have the value at the real open, validate it now.
732        let validator = self.validator();
733        validator.validate_channel_value(&self.setup)?;
734
735        let info2 = self.build_counterparty_commitment_info(
736            to_holder_value_sat,
737            to_counterparty_value_sat,
738            offered_htlcs.clone(),
739            received_htlcs.clone(),
740            feerate_per_kw,
741        )?;
742
743        let node = self.get_node();
744        let mut state = node.get_state();
745        let delta =
746            self.enforcement_state.claimable_balances(&*state, None, Some(&info2), &self.setup);
747
748        let incoming_payment_summary =
749            self.enforcement_state.incoming_payments_summary(None, Some(&info2));
750
751        validator.validate_counterparty_commitment_tx(
752            &self.enforcement_state,
753            commitment_number,
754            &remote_per_commitment_point,
755            &self.setup,
756            &self.get_chain_state(),
757            &info2,
758        )?;
759
760        let htlcs = Self::htlcs_info2_to_oic(offered_htlcs, received_htlcs);
761
762        #[cfg(fuzzing)]
763        let htlcs_len = htlcs.len();
764
765        // since we independently re-create the tx, this also performs the
766        // policy-commitment-* controls
767        let commitment_tx = self.make_counterparty_commitment_tx(
768            remote_per_commitment_point,
769            commitment_number,
770            feerate_per_kw,
771            to_holder_value_sat,
772            to_counterparty_value_sat,
773            htlcs,
774        );
775
776        #[cfg(not(fuzzing))]
777        let (sig, htlc_sigs) = catch_panic!(
778            self.keys.sign_counterparty_commitment(
779                &commitment_tx,
780                Vec::new(),
781                Vec::new(),
782                &self.secp_ctx
783            ),
784            "sign_counterparty_commitment panic {} chantype={:?}",
785            self.setup.commitment_type,
786        )
787        .map_err(|_| internal_error("failed to sign"))?;
788
789        #[cfg(fuzzing)]
790        let (sig, htlc_sigs, _) = (
791            Signature::from_compact(&[0; 64]).unwrap(),
792            vec![Signature::from_compact(&[0; 64]).unwrap(); htlcs_len],
793            commitment_tx,
794        );
795
796        let outgoing_payment_summary = self.enforcement_state.payments_summary(None, Some(&info2));
797        state.validate_payments(
798            &self.id0,
799            &incoming_payment_summary,
800            &outgoing_payment_summary,
801            &delta,
802            validator.clone(),
803        )?;
804
805        // Only advance the state if nothing goes wrong.
806        validator.set_next_counterparty_commit_num(
807            &mut self.enforcement_state,
808            commitment_number + 1,
809            *remote_per_commitment_point,
810            info2,
811        )?;
812
813        state.apply_payments(
814            &self.id0,
815            &incoming_payment_summary,
816            &outgoing_payment_summary,
817            &delta,
818            validator,
819        );
820
821        trace_enforcement_state!(self);
822        self.persist()?;
823        Ok((sig, htlc_sigs))
824    }
825
826    // restore node state payments from the current commitment transactions
827    pub(crate) fn restore_payments(&self) {
828        let node = self.get_node();
829
830        let incoming_payment_summary = self.enforcement_state.incoming_payments_summary(None, None);
831        let outgoing_payment_summary = self.enforcement_state.payments_summary(None, None);
832
833        let mut hashes: UnorderedSet<&PaymentHash> = UnorderedSet::new();
834        hashes.extend(incoming_payment_summary.keys());
835        hashes.extend(outgoing_payment_summary.keys());
836
837        let mut state = node.get_state();
838
839        for hash in hashes {
840            let payment = state.payments.entry(*hash).or_insert_with(|| RoutedPayment::new());
841            let incoming_sat = incoming_payment_summary.get(hash).map(|a| *a).unwrap_or(0);
842            let outgoing_sat = outgoing_payment_summary.get(hash).map(|a| *a).unwrap_or(0);
843            payment.apply(&self.id0, incoming_sat, outgoing_sat);
844        }
845    }
846
847    // This function is needed for testing with mutated keys.
848    /// Public for testing purposes
849    pub fn make_counterparty_commitment_tx_with_keys(
850        &self,
851        keys: TxCreationKeys,
852        commitment_number: u64,
853        feerate_per_kw: u32,
854        to_holder_value_sat: u64,
855        to_counterparty_value_sat: u64,
856        htlcs: Vec<HTLCOutputInCommitment>,
857    ) -> CommitmentTransaction {
858        let mut htlcs_with_aux = htlcs.iter().map(|h| (h.clone(), ())).collect();
859        let channel_parameters = self.make_channel_parameters();
860        let parameters = channel_parameters.as_counterparty_broadcastable();
861        let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
862            INITIAL_COMMITMENT_NUMBER - commitment_number,
863            to_counterparty_value_sat,
864            to_holder_value_sat,
865            self.counterparty_pubkeys().funding_pubkey,
866            self.keys.pubkeys().funding_pubkey,
867            keys,
868            feerate_per_kw,
869            &mut htlcs_with_aux,
870            &parameters,
871        );
872        commitment_tx
873    }
874
875    /// Public for testing purposes
876    pub fn make_counterparty_commitment_tx(
877        &self,
878        remote_per_commitment_point: &PublicKey,
879        commitment_number: u64,
880        feerate_per_kw: u32,
881        to_holder_value_sat: u64,
882        to_counterparty_value_sat: u64,
883        htlcs: Vec<HTLCOutputInCommitment>,
884    ) -> CommitmentTransaction {
885        let keys = self.make_counterparty_tx_keys(remote_per_commitment_point);
886        self.make_counterparty_commitment_tx_with_keys(
887            keys,
888            commitment_number,
889            feerate_per_kw,
890            to_holder_value_sat,
891            to_counterparty_value_sat,
892            htlcs,
893        )
894    }
895
896    #[instrument(skip(self))]
897    fn check_holder_tx_signatures(
898        &self,
899        per_commitment_point: &PublicKey,
900        txkeys: &TxCreationKeys,
901        feerate_per_kw: u32,
902        counterparty_commit_sig: &Signature,
903        counterparty_htlc_sigs: &[Signature],
904        recomposed_tx: CommitmentTransaction,
905    ) -> Result<(), Status> {
906        let redeemscript = make_funding_redeemscript(
907            &self.keys.pubkeys().funding_pubkey,
908            &self.setup.counterparty_points.funding_pubkey,
909        );
910
911        // unwrap is safe because we just created the tx and it's well formed
912        let sighash = Message::from_digest(
913            SighashCache::new(&recomposed_tx.trust().built_transaction().transaction)
914                .p2wsh_signature_hash(
915                    0,
916                    &redeemscript,
917                    Amount::from_sat(self.setup.channel_value_sat),
918                    EcdsaSighashType::All,
919                )
920                .unwrap()
921                .to_byte_array(),
922        );
923
924        self.secp_ctx
925            .verify_ecdsa(
926                &sighash,
927                &counterparty_commit_sig,
928                &self.setup.counterparty_points.funding_pubkey,
929            )
930            .map_err(|ve| policy_error(format!("commit sig verify failed: {}", ve)))?;
931
932        let commitment_txid = recomposed_tx.trust().txid();
933        let to_self_delay = self.setup.counterparty_selected_contest_delay;
934
935        let htlc_pubkey = derive_public_key(
936            &self.secp_ctx,
937            &per_commitment_point,
938            &self.counterparty_pubkeys().htlc_basepoint.0,
939        )
940        .map_err(|err| internal_error(format!("derive_public_key failed: {}", err)))?;
941
942        let sig_hash_type = if self.setup.is_anchors() {
943            EcdsaSighashType::SinglePlusAnyoneCanPay
944        } else {
945            EcdsaSighashType::All
946        };
947
948        let build_feerate = if self.setup.is_zero_fee_htlc() { 0 } else { feerate_per_kw };
949
950        let features = self.setup.features();
951
952        for ndx in 0..recomposed_tx.htlcs().len() {
953            let htlc = &recomposed_tx.htlcs()[ndx];
954
955            let htlc_redeemscript = get_htlc_redeemscript(htlc, &features, &txkeys);
956
957            let features = self.setup.features();
958
959            // policy-onchain-format-standard
960            let recomposed_htlc_tx = catch_panic!(
961                build_htlc_transaction(
962                    &commitment_txid,
963                    build_feerate,
964                    to_self_delay,
965                    htlc,
966                    &features,
967                    &txkeys.broadcaster_delayed_payment_key,
968                    &txkeys.revocation_key,
969                ),
970                "build_htlc_transaction panic {} chantype={:?}",
971                self.setup.commitment_type
972            );
973
974            // unwrap is safe because we just created the tx and it's well formed
975            let recomposed_tx_sighash = Message::from_digest(
976                SighashCache::new(&recomposed_htlc_tx)
977                    .p2wsh_signature_hash(
978                        0,
979                        &htlc_redeemscript,
980                        Amount::from_sat(htlc.amount_msat / 1000),
981                        sig_hash_type,
982                    )
983                    .unwrap()
984                    .to_byte_array(),
985            );
986
987            self.secp_ctx
988                .verify_ecdsa(&recomposed_tx_sighash, &counterparty_htlc_sigs[ndx], &htlc_pubkey)
989                .map_err(|err| {
990                    policy_error(format!("commit sig verify failed for htlc {}: {}", ndx, err))
991                })?;
992        }
993        Ok(())
994    }
995
996    // Advance the holder commitment state so that `N + 1` is the next
997    // and `N - 1` is revoked, where N is `new_current_commitment_number`.
998    fn advance_holder_commitment_state(
999        &mut self,
1000        validator: Arc<dyn Validator>,
1001        new_current_commitment_number: u64,
1002        info2: CommitmentInfo2,
1003        counterparty_signatures: CommitmentSignatures,
1004    ) -> Result<(PublicKey, Option<SecretKey>), Status> {
1005        // Advance the local commitment number state.
1006        validator.set_next_holder_commit_num(
1007            &mut self.enforcement_state,
1008            new_current_commitment_number + 1,
1009            info2,
1010            counterparty_signatures,
1011        )?;
1012
1013        self.release_commitment_secret(new_current_commitment_number)
1014    }
1015
1016    // Gets the revocation return values for a previous commitments which are
1017    // ready to be released (fails on future commitments)
1018    fn release_commitment_secret(
1019        &mut self,
1020        commitment_number: u64,
1021    ) -> Result<(PublicKey, Option<SecretKey>), Status> {
1022        let next_holder_commitment_point = self.get_per_commitment_point(commitment_number + 1)?;
1023        let maybe_old_secret = if commitment_number >= 1 {
1024            // this will fail if the secret is not ready to be released
1025            Some(self.get_per_commitment_secret(commitment_number - 1)?)
1026        } else {
1027            None
1028        };
1029        Ok((next_holder_commitment_point, maybe_old_secret))
1030    }
1031
1032    /// Validate the counterparty's signatures on the holder's
1033    /// commitment and HTLCs when the commitment_signed message is
1034    /// received.
1035    pub fn validate_holder_commitment_tx_phase2(
1036        &mut self,
1037        commitment_number: u64,
1038        feerate_per_kw: u32,
1039        to_holder_value_sat: u64,
1040        to_counterparty_value_sat: u64,
1041        offered_htlcs: Vec<HTLCInfo2>,
1042        received_htlcs: Vec<HTLCInfo2>,
1043        counterparty_commit_sig: &Signature,
1044        counterparty_htlc_sigs: &[Signature],
1045    ) -> Result<(), Status> {
1046        let per_commitment_point = &self.get_per_commitment_point(commitment_number)?;
1047        let info2 = self.build_holder_commitment_info(
1048            to_holder_value_sat,
1049            to_counterparty_value_sat,
1050            offered_htlcs,
1051            received_htlcs,
1052            feerate_per_kw,
1053        )?;
1054
1055        let node = self.get_node();
1056        let state = node.get_state();
1057        let delta =
1058            self.enforcement_state.claimable_balances(&*state, Some(&info2), None, &self.setup);
1059
1060        let incoming_payment_summary =
1061            self.enforcement_state.incoming_payments_summary(Some(&info2), None);
1062
1063        let validator = self.validator();
1064        validator
1065            .validate_holder_commitment_tx(
1066                &self.enforcement_state,
1067                commitment_number,
1068                &per_commitment_point,
1069                &self.setup,
1070                &self.get_chain_state(),
1071                &info2,
1072            )
1073            .map_err(|ve| {
1074                #[cfg(not(feature = "log_pretty_print"))]
1075                warn!(
1076                    "VALIDATION FAILED: {} setup={:?} state={:?} info={:?}",
1077                    ve,
1078                    &self.setup,
1079                    &self.get_chain_state(),
1080                    &info2,
1081                );
1082                #[cfg(feature = "log_pretty_print")]
1083                warn!(
1084                    "VALIDATION FAILED: {}\nsetup={:#?}\nstate={:#?}\ninfo={:#?}",
1085                    ve,
1086                    &self.setup,
1087                    &self.get_chain_state(),
1088                    &info2,
1089                );
1090                ve
1091            })?;
1092
1093        let htlcs =
1094            Self::htlcs_info2_to_oic(info2.offered_htlcs.clone(), info2.received_htlcs.clone());
1095
1096        let txkeys = self.make_holder_tx_keys(&per_commitment_point);
1097        // policy-commitment-*
1098        let recomposed_tx = self.make_holder_commitment_tx(
1099            commitment_number,
1100            &txkeys,
1101            feerate_per_kw,
1102            to_holder_value_sat,
1103            to_counterparty_value_sat,
1104            htlcs,
1105        );
1106
1107        #[cfg(not(fuzzing))]
1108        self.check_holder_tx_signatures(
1109            &per_commitment_point,
1110            &txkeys,
1111            feerate_per_kw,
1112            counterparty_commit_sig,
1113            counterparty_htlc_sigs,
1114            recomposed_tx,
1115        )?;
1116
1117        #[cfg(fuzzing)]
1118        let _ = recomposed_tx;
1119
1120        let outgoing_payment_summary = self.enforcement_state.payments_summary(Some(&info2), None);
1121        state.validate_payments(
1122            &self.id0,
1123            &incoming_payment_summary,
1124            &outgoing_payment_summary,
1125            &delta,
1126            validator.clone(),
1127        )?;
1128
1129        if commitment_number == self.enforcement_state.next_holder_commit_num {
1130            let counterparty_signatures = CommitmentSignatures(
1131                counterparty_commit_sig.clone(),
1132                counterparty_htlc_sigs.to_vec(),
1133            );
1134            self.enforcement_state.next_holder_commit_info = Some((info2, counterparty_signatures));
1135        }
1136
1137        trace_enforcement_state!(self);
1138        self.persist()?;
1139
1140        Ok(())
1141    }
1142
1143    /// Revoke holder commitment `N - 1` by disclosing its commitment secret.
1144    /// After this, `N` is the current holder commitment and `N + 1`
1145    /// is the next holder commitment.
1146    ///
1147    /// Returns the per_commitment_point for commitment `N + 1` and the
1148    /// holder's revocation secret for commitment `N - 1` if `N > 0`.
1149    ///
1150    /// [`validate_holder_commitment_tx`] (or the phase2 version) must be called
1151    /// before this method.
1152    ///
1153    /// The node should have persisted this state change first, because we cannot
1154    /// safely roll back a revocation.
1155    pub fn revoke_previous_holder_commitment(
1156        &mut self,
1157        new_current_commitment_number: u64,
1158    ) -> Result<(PublicKey, Option<SecretKey>), Status> {
1159        // If we are called on anything other than the next_holder_commit_num
1160        // with existing next_holder_commit_info we must not change any state
1161        if new_current_commitment_number != self.enforcement_state.next_holder_commit_num {
1162            return Ok(self.release_commitment_secret(new_current_commitment_number)?);
1163            // don't persist, this case doesn't change state
1164        }
1165
1166        let validator = self.validator();
1167
1168        if self.enforcement_state.next_holder_commit_info.is_none() {
1169            // the caller failed to call validate_holder_commitment_tx
1170            policy_err!(
1171                validator,
1172                "policy-revoke-new-commitment-signed",
1173                "new_current_commitment == next_holder_commit_num {} \
1174                 but next_holder_commit_info.is_none",
1175                new_current_commitment_number,
1176            );
1177            // `policy_err!` will not return an error in permissive mode, so we need to return
1178            // something plausible here.  The node will likely crash soon after, because we will
1179            // not return a revocation secret (`None` below).
1180            // That's OK, because the node should have called `validate_holder_commitment_tx` first
1181            // so the logic error is in the node.
1182            let holder_commitment_point =
1183                self.get_per_commitment_point(new_current_commitment_number)?;
1184            return Ok((holder_commitment_point, None));
1185        }
1186
1187        // checked above
1188        let (info2, sigs) = self.enforcement_state.next_holder_commit_info.take().unwrap();
1189        let incoming_payment_summary =
1190            self.enforcement_state.incoming_payments_summary(Some(&info2), None);
1191        let outgoing_payment_summary = self.enforcement_state.payments_summary(Some(&info2), None);
1192
1193        let node = self.get_node();
1194        let mut state = node.get_state();
1195
1196        let delta =
1197            self.enforcement_state.claimable_balances(&*state, Some(&info2), None, &self.setup);
1198
1199        let (next_holder_commitment_point, maybe_old_secret) = self
1200            .advance_holder_commitment_state(
1201                validator.clone(),
1202                new_current_commitment_number,
1203                info2,
1204                sigs,
1205            )?;
1206
1207        state.apply_payments(
1208            &self.id0,
1209            &incoming_payment_summary,
1210            &outgoing_payment_summary,
1211            &delta,
1212            validator,
1213        );
1214
1215        trace_enforcement_state!(self);
1216        self.persist()?;
1217        Ok((next_holder_commitment_point, maybe_old_secret))
1218    }
1219
1220    /// Sign a holder commitment when force-closing
1221    pub fn sign_holder_commitment_tx_phase2(
1222        &mut self,
1223        commitment_number: u64,
1224    ) -> Result<Signature, Status> {
1225        // We are just signing the latest commitment info that we previously
1226        // stored in the enforcement state, while checking that the commitment
1227        // number supplied by the caller matches the one we expect.
1228        //
1229        // policy-commitment-holder-not-revoked is implicitly checked by
1230        // the fact that the current holder commitment info in the enforcement
1231        // state cannot have been revoked.
1232        let validator = self.validator();
1233        let info2 = validator
1234            .get_current_holder_commitment_info(&mut self.enforcement_state, commitment_number)?;
1235
1236        let htlcs = Self::htlcs_info2_to_oic(info2.offered_htlcs, info2.received_htlcs);
1237        let per_commitment_point = self.get_per_commitment_point(commitment_number)?;
1238
1239        let build_feerate = if self.setup.is_zero_fee_htlc() { 0 } else { info2.feerate_per_kw };
1240        let txkeys = self.make_holder_tx_keys(&per_commitment_point);
1241        // policy-onchain-format-standard
1242        let recomposed_tx = self.make_holder_commitment_tx(
1243            commitment_number,
1244            &txkeys,
1245            build_feerate,
1246            info2.to_broadcaster_value_sat,
1247            info2.to_countersigner_value_sat,
1248            htlcs,
1249        );
1250
1251        // We provide a dummy signature for the remote, since we don't require that sig
1252        // to be passed in to this call.  It would have been better if HolderCommitmentTransaction
1253        // didn't require the remote sig.
1254        // TODO(516) remove dummy sigs here and in phase 2 protocol
1255        let htlcs_len = recomposed_tx.htlcs().len();
1256        let mut htlc_dummy_sigs = Vec::with_capacity(htlcs_len);
1257        htlc_dummy_sigs.resize(htlcs_len, Self::dummy_sig());
1258
1259        // Holder commitments need an extra wrapper for the LDK signature routine.
1260        let recomposed_holder_tx = HolderCommitmentTransaction::new(
1261            recomposed_tx,
1262            Self::dummy_sig(),
1263            htlc_dummy_sigs,
1264            &self.keys.pubkeys().funding_pubkey,
1265            &self.counterparty_pubkeys().funding_pubkey,
1266        );
1267
1268        // Sign the recomposed commitment.
1269        let sig = self
1270            .keys
1271            .sign_holder_commitment(&recomposed_holder_tx, &self.secp_ctx)
1272            .map_err(|_| internal_error("failed to sign"))?;
1273
1274        self.enforcement_state.channel_closed = true;
1275        trace_enforcement_state!(self);
1276        self.persist()?;
1277        Ok(sig)
1278    }
1279
1280    /// Sign a holder commitment and HTLCs when recovering from node failure
1281    /// Also returns the revocable scriptPubKey so we can identify our outputs
1282    /// Also returns the unilateral close key material
1283    pub fn sign_holder_commitment_tx_for_recovery(
1284        &mut self,
1285    ) -> Result<
1286        (Transaction, Vec<Transaction>, ScriptBuf, (SecretKey, Vec<Vec<u8>>), PublicKey),
1287        Status,
1288    > {
1289        let info2 = self
1290            .enforcement_state
1291            .current_holder_commit_info
1292            .as_ref()
1293            .ok_or_else(|| internal_error("channel was not open - commit info"))?;
1294        let cp_sigs = self
1295            .enforcement_state
1296            .current_counterparty_signatures
1297            .as_ref()
1298            .ok_or_else(|| internal_error("channel was not open - counterparty sigs"))?;
1299        let commitment_number = self.enforcement_state.next_holder_commit_num - 1;
1300        warn!("force-closing channel for recovery at commitment number {}", commitment_number);
1301
1302        let htlcs =
1303            Self::htlcs_info2_to_oic(info2.offered_htlcs.clone(), info2.received_htlcs.clone());
1304        let per_commitment_point = self.get_per_commitment_point(commitment_number)?;
1305
1306        let build_feerate = if self.setup.is_zero_fee_htlc() { 0 } else { info2.feerate_per_kw };
1307        let txkeys = self.make_holder_tx_keys(&per_commitment_point);
1308        // policy-onchain-format-standard
1309        let recomposed_tx = self.make_holder_commitment_tx(
1310            commitment_number,
1311            &txkeys,
1312            build_feerate,
1313            info2.to_broadcaster_value_sat,
1314            info2.to_countersigner_value_sat,
1315            htlcs,
1316        );
1317
1318        // We provide a dummy signature for the remote, since we don't require that sig
1319        // to be passed in to this call.  It would have been better if HolderCommitmentTransaction
1320        // didn't require the remote sig.
1321        // TODO consider if we actually want the sig for policy checks
1322        let htlcs_len = recomposed_tx.htlcs().len();
1323        let mut htlc_dummy_sigs = Vec::with_capacity(htlcs_len);
1324        htlc_dummy_sigs.resize(htlcs_len, Self::dummy_sig());
1325
1326        // Holder commitments need an extra wrapper for the LDK signature routine.
1327        let recomposed_holder_tx = HolderCommitmentTransaction::new(
1328            recomposed_tx,
1329            Self::dummy_sig(),
1330            htlc_dummy_sigs,
1331            &self.keys.pubkeys().funding_pubkey,
1332            &self.counterparty_pubkeys().funding_pubkey,
1333        );
1334
1335        // Sign the recomposed commitment.
1336        let sig = self
1337            .keys
1338            .sign_holder_commitment(&recomposed_holder_tx, &self.secp_ctx)
1339            .map_err(|_| internal_error("failed to sign"))?;
1340
1341        let holder_tx = recomposed_holder_tx.trust();
1342        let mut tx = holder_tx.built_transaction().transaction.clone();
1343        let holder_funding_key = self.keys.pubkeys().funding_pubkey;
1344        let counterparty_funding_key = self.counterparty_pubkeys().funding_pubkey;
1345
1346        let tx_keys = holder_tx.keys();
1347        let revocable_redeemscript = chan_utils::get_revokeable_redeemscript(
1348            &tx_keys.revocation_key,
1349            self.setup.counterparty_selected_contest_delay,
1350            &tx_keys.broadcaster_delayed_payment_key,
1351        );
1352
1353        add_holder_sig(&mut tx, sig, cp_sigs.0, &holder_funding_key, &counterparty_funding_key);
1354        self.enforcement_state.channel_closed = true;
1355        trace_enforcement_state!(self);
1356
1357        let revocation_basepoint = self.counterparty_pubkeys().revocation_basepoint;
1358        let revocation_pubkey = derive_public_revocation_key(
1359            &self.secp_ctx,
1360            &per_commitment_point,
1361            &revocation_basepoint,
1362        )
1363        .map_err(|_| internal_error("failure during derive_public_revocation_key"))?;
1364        let ck =
1365            self.get_unilateral_close_key(&Some(per_commitment_point), &Some(revocation_pubkey))?;
1366
1367        self.persist()?;
1368        Ok((tx, Vec::new(), revocable_redeemscript.to_p2wsh(), ck, revocation_pubkey.0))
1369    }
1370
1371    /// Sign a holder commitment transaction after rebuilding it
1372    /// from the supplied arguments.
1373    /// Use [Channel::sign_counterparty_commitment_tx_phase2()] instead of this,
1374    /// since that one uses the last counter-signed holder tx, which is simpler
1375    /// and doesn't require re-validation of the holder tx.
1376    // TODO(517) remove this method
1377    pub fn sign_holder_commitment_tx_phase2_redundant(
1378        &mut self,
1379        commitment_number: u64,
1380        feerate_per_kw: u32,
1381        to_holder_value_sat: u64,
1382        to_counterparty_value_sat: u64,
1383        offered_htlcs: Vec<HTLCInfo2>,
1384        received_htlcs: Vec<HTLCInfo2>,
1385    ) -> Result<Signature, Status> {
1386        let per_commitment_point = self.get_per_commitment_point(commitment_number)?;
1387
1388        let info2 = self.build_holder_commitment_info(
1389            to_holder_value_sat,
1390            to_counterparty_value_sat,
1391            offered_htlcs.clone(),
1392            received_htlcs.clone(),
1393            feerate_per_kw,
1394        )?;
1395
1396        self.validator().validate_holder_commitment_tx(
1397            &self.enforcement_state,
1398            commitment_number,
1399            &per_commitment_point,
1400            &self.setup,
1401            &self.get_chain_state(),
1402            &info2,
1403        )?;
1404
1405        let htlcs = Self::htlcs_info2_to_oic(offered_htlcs, received_htlcs);
1406
1407        // We provide a dummy signature for the remote, since we don't require that sig
1408        // to be passed in to this call.  It would have been better if HolderCommitmentTransaction
1409        // didn't require the remote sig.
1410        // TODO consider if we actually want the sig for policy checks
1411        let mut htlc_dummy_sigs = Vec::with_capacity(htlcs.len());
1412        htlc_dummy_sigs.resize(htlcs.len(), Self::dummy_sig());
1413
1414        let build_feerate = if self.setup.is_zero_fee_htlc() { 0 } else { feerate_per_kw };
1415        let txkeys = self.make_holder_tx_keys(&per_commitment_point);
1416        let commitment_tx = self.make_holder_commitment_tx(
1417            commitment_number,
1418            &txkeys,
1419            build_feerate,
1420            to_holder_value_sat,
1421            to_counterparty_value_sat,
1422            htlcs,
1423        );
1424        debug!("channel: sign holder txid {}", commitment_tx.trust().built_transaction().txid);
1425
1426        let holder_commitment_tx = HolderCommitmentTransaction::new(
1427            commitment_tx,
1428            Self::dummy_sig(),
1429            htlc_dummy_sigs,
1430            &self.keys.pubkeys().funding_pubkey,
1431            &self.counterparty_pubkeys().funding_pubkey,
1432        );
1433
1434        let sig = self
1435            .keys
1436            .sign_holder_commitment(&holder_commitment_tx, &self.secp_ctx)
1437            .map_err(|_| internal_error("failed to sign"))?;
1438
1439        self.enforcement_state.channel_closed = true;
1440        trace_enforcement_state!(self);
1441        self.persist()?;
1442        Ok(sig)
1443    }
1444
1445    pub(crate) fn make_holder_commitment_tx(
1446        &self,
1447        commitment_number: u64,
1448        keys: &TxCreationKeys,
1449        feerate_per_kw: u32,
1450        to_holder_value_sat: u64,
1451        to_counterparty_value_sat: u64,
1452        htlcs: Vec<HTLCOutputInCommitment>,
1453    ) -> CommitmentTransaction {
1454        let mut htlcs_with_aux = htlcs.into_iter().map(|h| (h, ())).collect();
1455        let channel_parameters = self.make_channel_parameters();
1456        let parameters = channel_parameters.as_holder_broadcastable();
1457        let mut commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1458            INITIAL_COMMITMENT_NUMBER - commitment_number,
1459            to_holder_value_sat,
1460            to_counterparty_value_sat,
1461            self.keys.pubkeys().funding_pubkey,
1462            self.counterparty_pubkeys().funding_pubkey,
1463            keys.clone(),
1464            feerate_per_kw,
1465            &mut htlcs_with_aux,
1466            &parameters,
1467        );
1468        if self.setup.is_anchors() {
1469            commitment_tx = commitment_tx.with_non_zero_fee_anchors();
1470        }
1471        commitment_tx
1472    }
1473
1474    /// Public for testing purposes
1475    pub fn htlcs_info2_to_oic(
1476        offered_htlcs: Vec<HTLCInfo2>,
1477        received_htlcs: Vec<HTLCInfo2>,
1478    ) -> Vec<HTLCOutputInCommitment> {
1479        let mut htlcs = Vec::new();
1480        for htlc in offered_htlcs {
1481            htlcs.push(HTLCOutputInCommitment {
1482                offered: true,
1483                amount_msat: htlc.value_sat * 1000,
1484                cltv_expiry: htlc.cltv_expiry,
1485                payment_hash: htlc.payment_hash,
1486                transaction_output_index: None,
1487            });
1488        }
1489        for htlc in received_htlcs {
1490            htlcs.push(HTLCOutputInCommitment {
1491                offered: false,
1492                amount_msat: htlc.value_sat * 1000,
1493                cltv_expiry: htlc.cltv_expiry,
1494                payment_hash: htlc.payment_hash,
1495                transaction_output_index: None,
1496            });
1497        }
1498        htlcs
1499    }
1500
1501    /// Build channel parameters, used to further build a commitment transaction
1502    pub fn make_channel_parameters(&self) -> ChannelTransactionParameters {
1503        let funding_outpoint = chain::transaction::OutPoint {
1504            txid: self.setup.funding_outpoint.txid,
1505            index: self.setup.funding_outpoint.vout as u16,
1506        };
1507        let channel_parameters = ChannelTransactionParameters {
1508            holder_pubkeys: self.get_channel_basepoints(),
1509            holder_selected_contest_delay: self.setup.holder_selected_contest_delay,
1510            is_outbound_from_holder: self.setup.is_outbound,
1511            counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
1512                pubkeys: self.setup.counterparty_points.clone(),
1513                selected_contest_delay: self.setup.counterparty_selected_contest_delay,
1514            }),
1515            funding_outpoint: Some(funding_outpoint),
1516            channel_type_features: self.setup.features(),
1517        };
1518        channel_parameters
1519    }
1520
1521    /// Get the shutdown script where our funds will go when we mutual-close
1522    // TODO(75) this method is deprecated
1523    pub fn get_ldk_shutdown_script(&self) -> ScriptBuf {
1524        self.setup.holder_shutdown_script.clone().unwrap_or_else(|| {
1525            self.get_node().keys_manager.get_shutdown_scriptpubkey().unwrap().into()
1526        })
1527    }
1528
1529    fn get_node(&self) -> Arc<Node> {
1530        self.node.upgrade().unwrap()
1531    }
1532
1533    /// Sign a mutual close transaction after rebuilding it from the supplied arguments
1534    pub fn sign_mutual_close_tx_phase2(
1535        &mut self,
1536        to_holder_value_sat: u64,
1537        to_counterparty_value_sat: u64,
1538        holder_script: &Option<ScriptBuf>,
1539        counterparty_script: &Option<ScriptBuf>,
1540        holder_wallet_path_hint: &[u32],
1541    ) -> Result<Signature, Status> {
1542        self.validator().validate_mutual_close_tx(
1543            &*self.get_node(),
1544            &self.setup,
1545            &self.enforcement_state,
1546            to_holder_value_sat,
1547            to_counterparty_value_sat,
1548            holder_script,
1549            counterparty_script,
1550            holder_wallet_path_hint,
1551        )?;
1552
1553        let tx = ClosingTransaction::new(
1554            to_holder_value_sat,
1555            to_counterparty_value_sat,
1556            holder_script.clone().unwrap_or_else(|| ScriptBuf::new()),
1557            counterparty_script.clone().unwrap_or_else(|| ScriptBuf::new()),
1558            self.setup.funding_outpoint,
1559        );
1560
1561        let sig = self
1562            .keys
1563            .sign_closing_transaction(&tx, &self.secp_ctx)
1564            .map_err(|_| Status::internal("failed to sign"))?;
1565        self.enforcement_state.channel_closed = true;
1566        trace_enforcement_state!(self);
1567        self.persist()?;
1568        Ok(sig)
1569    }
1570
1571    /// Sign a delayed output that goes to us while sweeping a transaction we broadcast
1572    pub fn sign_delayed_sweep(
1573        &self,
1574        tx: &Transaction,
1575        input: usize,
1576        commitment_number: u64,
1577        redeemscript: &Script,
1578        amount_sat: u64,
1579        wallet_path: &[u32],
1580    ) -> Result<Signature, Status> {
1581        if input >= tx.input.len() {
1582            return Err(invalid_argument(format!(
1583                "sign_delayed_sweep: bad input index: {} >= {}",
1584                input,
1585                tx.input.len()
1586            )));
1587        }
1588        let per_commitment_point = self.get_per_commitment_point(commitment_number)?;
1589
1590        self.validator().validate_delayed_sweep(
1591            &*self.get_node(),
1592            &self.setup,
1593            &self.get_chain_state(),
1594            tx,
1595            input,
1596            amount_sat,
1597            wallet_path,
1598        )?;
1599
1600        // unwrap is safe because we just created the tx and it's well formed
1601        let sighash = Message::from_digest(
1602            SighashCache::new(tx)
1603                .p2wsh_signature_hash(
1604                    input,
1605                    &redeemscript,
1606                    Amount::from_sat(amount_sat),
1607                    EcdsaSighashType::All,
1608                )
1609                .unwrap()
1610                .to_byte_array(),
1611        );
1612
1613        let privkey = derive_private_key(
1614            &self.secp_ctx,
1615            &per_commitment_point,
1616            &self.keys.delayed_payment_base_key,
1617        );
1618
1619        let sig = self.secp_ctx.sign_ecdsa(&sighash, &privkey);
1620        trace_enforcement_state!(self);
1621        Ok(sig)
1622    }
1623
1624    /// Sign an offered or received HTLC output from a commitment the counterparty broadcast.
1625    pub fn sign_counterparty_htlc_sweep(
1626        &self,
1627        tx: &Transaction,
1628        input: usize,
1629        remote_per_commitment_point: &PublicKey,
1630        redeemscript: &ScriptBuf,
1631        htlc_amount_sat: u64,
1632        wallet_path: &[u32],
1633    ) -> Result<Signature, Status> {
1634        if input >= tx.input.len() {
1635            return Err(invalid_argument(format!(
1636                "sign_counterparty_htlc_sweep: bad input index: {} >= {}",
1637                input,
1638                tx.input.len()
1639            )));
1640        }
1641
1642        self.validator().validate_counterparty_htlc_sweep(
1643            &*self.get_node(),
1644            &self.setup,
1645            &self.get_chain_state(),
1646            tx,
1647            redeemscript,
1648            input,
1649            htlc_amount_sat,
1650            wallet_path,
1651        )?;
1652
1653        // unwrap is safe because we just created the tx and it's well formed
1654        let htlc_sighash = Message::from_digest(
1655            SighashCache::new(tx)
1656                .p2wsh_signature_hash(
1657                    input,
1658                    &redeemscript,
1659                    Amount::from_sat(htlc_amount_sat),
1660                    EcdsaSighashType::All,
1661                )
1662                .unwrap()
1663                .to_byte_array(),
1664        );
1665
1666        let htlc_privkey = derive_private_key(
1667            &self.secp_ctx,
1668            &remote_per_commitment_point,
1669            &self.keys.htlc_base_key,
1670        );
1671
1672        let sig = self.secp_ctx.sign_ecdsa(&htlc_sighash, &htlc_privkey);
1673        trace_enforcement_state!(self);
1674        Ok(sig)
1675    }
1676
1677    /// Sign a justice transaction on an old state that the counterparty broadcast
1678    pub fn sign_justice_sweep(
1679        &self,
1680        tx: &Transaction,
1681        input: usize,
1682        revocation_secret: &SecretKey,
1683        redeemscript: &Script,
1684        amount_sat: u64,
1685        wallet_path: &[u32],
1686    ) -> Result<Signature, Status> {
1687        if input >= tx.input.len() {
1688            return Err(invalid_argument(format!(
1689                "sign_justice_sweep: bad input index: {} >= {}",
1690                input,
1691                tx.input.len()
1692            )));
1693        }
1694        self.validator().validate_justice_sweep(
1695            &*self.get_node(),
1696            &self.setup,
1697            &self.get_chain_state(),
1698            tx,
1699            input,
1700            amount_sat,
1701            wallet_path,
1702        )?;
1703
1704        // unwrap is safe because we just created the tx and it's well formed
1705        let sighash = Message::from_digest(
1706            SighashCache::new(tx)
1707                .p2wsh_signature_hash(
1708                    input,
1709                    &redeemscript,
1710                    Amount::from_sat(amount_sat),
1711                    EcdsaSighashType::All,
1712                )
1713                .unwrap()
1714                .to_byte_array(),
1715        );
1716
1717        let privkey = chan_utils::derive_private_revocation_key(
1718            &self.secp_ctx,
1719            revocation_secret,
1720            &self.keys.revocation_base_key,
1721        );
1722
1723        let sig = self.secp_ctx.sign_ecdsa(&sighash, &privkey);
1724        trace_enforcement_state!(self);
1725        Ok(sig)
1726    }
1727
1728    /// Sign a channel announcement with both the node key and the funding key
1729    pub fn sign_channel_announcement_with_funding_key(&self, announcement: &[u8]) -> Signature {
1730        let ann_hash = Sha256dHash::hash(announcement);
1731        let encmsg = secp256k1::Message::from_digest(ann_hash.to_byte_array());
1732
1733        self.secp_ctx.sign_ecdsa(&encmsg, &self.keys.funding_key)
1734    }
1735
1736    fn persist(&self) -> Result<(), Status> {
1737        let node_id = self.get_node().get_id();
1738        self.get_node()
1739            .persister
1740            .update_channel(&node_id, &self)
1741            .map_err(|_| Status::internal("persist failed"))
1742    }
1743
1744    /// The node's network
1745    pub fn network(&self) -> Network {
1746        self.get_node().network()
1747    }
1748
1749    /// The node has signed our funding transaction
1750    pub fn funding_signed(&self, tx: &Transaction, _vout: u32) {
1751        // Start tracking funding inputs, in case an input is double-spent.
1752        // The tracker was already informed of the inputs by the node.
1753
1754        // Note that the fundee won't detect double-spends this way, because
1755        // they never see the details of the funding transaction.
1756        // But the fundee doesn't care about double-spends, because they don't
1757        // have any funds in the channel yet.
1758
1759        // the lock order is backwards (monitor -> tracker), but we release
1760        // the monitor lock, so it's OK
1761
1762        self.monitor.add_funding_inputs(tx);
1763    }
1764
1765    /// Mark this channel as forgotten by the node allowing it to be pruned
1766    pub fn forget(&self) -> Result<(), Status> {
1767        self.monitor.forget_channel();
1768        self.persist()?;
1769        Ok(())
1770    }
1771
1772    /// Return channel balances
1773    pub fn balance(&self) -> ChannelBalance {
1774        let node = self.get_node();
1775        let state = node.get_state();
1776        let is_ready = self.validator().is_ready(&self.get_chain_state());
1777        self.enforcement_state.balance(&*state, &self.setup, is_ready)
1778    }
1779
1780    /// advance the holder commitment in an arbitrary way for testing
1781    #[cfg(feature = "test_utils")]
1782    pub fn advance_holder_commitment(
1783        &mut self,
1784        counterparty_key: &SecretKey,
1785        counterparty_htlc_key: &SecretKey,
1786        offered_htlcs: Vec<HTLCInfo2>,
1787        value_to_holder: u64,
1788        commit_num: u64,
1789    ) -> Result<(), Status> {
1790        let feerate = 1000;
1791        let funding_redeemscript = make_funding_redeemscript(
1792            &self.keys.pubkeys().funding_pubkey,
1793            &self.counterparty_pubkeys().funding_pubkey,
1794        );
1795        let per_commitment_point = self.get_per_commitment_point(commit_num)?;
1796        let txkeys = self.make_holder_tx_keys(&per_commitment_point);
1797
1798        let tx = self.make_holder_commitment_tx(
1799            commit_num,
1800            &txkeys,
1801            feerate,
1802            value_to_holder,
1803            0,
1804            Channel::htlcs_info2_to_oic(offered_htlcs.clone(), vec![]),
1805        );
1806
1807        let trusted_tx = tx.trust();
1808        let built_tx = trusted_tx.built_transaction();
1809        let counterparty_sig = built_tx.sign_counterparty_commitment(
1810            &counterparty_key,
1811            &funding_redeemscript,
1812            self.setup.channel_value_sat,
1813            &self.secp_ctx,
1814        );
1815
1816        let counterparty_htlc_key =
1817            derive_private_key(&self.secp_ctx, &per_commitment_point, &counterparty_htlc_key);
1818
1819        let features = self.setup.features();
1820
1821        let mut htlc_sigs = Vec::with_capacity(tx.htlcs().len());
1822        for htlc in tx.htlcs() {
1823            let htlc_tx = catch_panic!(
1824                build_htlc_transaction(
1825                    &trusted_tx.txid(),
1826                    feerate,
1827                    self.setup.counterparty_selected_contest_delay,
1828                    htlc,
1829                    &features,
1830                    &txkeys.broadcaster_delayed_payment_key,
1831                    &txkeys.revocation_key,
1832                ),
1833                "build_htlc_transaction panic {} chantype={:?} htlc={:?}",
1834                self.setup.commitment_type,
1835                htlc
1836            );
1837            let htlc_redeemscript = get_htlc_redeemscript(&htlc, &features, &txkeys);
1838            let sig_hash_type = if self.setup.is_anchors() {
1839                EcdsaSighashType::SinglePlusAnyoneCanPay
1840            } else {
1841                EcdsaSighashType::All
1842            };
1843
1844            // unwrap is safe because we just created the tx and it's well formed
1845            let htlc_sighash = Message::from(
1846                SighashCache::new(&htlc_tx)
1847                    .p2wsh_signature_hash(
1848                        0,
1849                        &htlc_redeemscript,
1850                        Amount::from_sat(htlc.amount_msat / 1000),
1851                        sig_hash_type,
1852                    )
1853                    .unwrap(),
1854            );
1855            htlc_sigs.push(self.secp_ctx.sign_ecdsa(&htlc_sighash, &counterparty_htlc_key));
1856        }
1857
1858        // add an HTLC
1859        self.validate_holder_commitment_tx_phase2(
1860            commit_num,
1861            feerate,
1862            value_to_holder,
1863            0,
1864            offered_htlcs,
1865            vec![],
1866            &counterparty_sig,
1867            &htlc_sigs,
1868        )?;
1869
1870        self.revoke_previous_holder_commitment(commit_num)?;
1871        Ok(())
1872    }
1873
1874    /// Sign a transaction that spends the anchor output
1875    pub fn sign_holder_anchor_input(
1876        &self,
1877        anchor_tx: &Transaction,
1878        input: usize,
1879    ) -> Result<Signature, Status> {
1880        self.keys
1881            .sign_holder_anchor_input(anchor_tx, input, &self.secp_ctx)
1882            .map_err(|()| internal_error(format!("sign_holder_anchor_input failed")))
1883    }
1884
1885    /// Get the anchor redeemscript
1886    pub fn get_anchor_redeemscript(&self) -> ScriptBuf {
1887        chan_utils::get_anchor_redeemscript(&self.keys.pubkeys().funding_pubkey)
1888    }
1889}
1890
1891/// Balances associated with a channel
1892/// See: <https://gitlab.com/lightning-signer/docs/-/wikis/Proposed-L1-and-Channel-Balance-Reconciliation>
1893///
1894/// All channels that VLS knows about are in one of the four categories:
1895/// 1. channel stubs: assigned channelid and can generate points, keys, ...
1896/// 2. unconfirmed channels: negotiated channels prior to `channel_ready`
1897/// 3. channels: active channels in their normal operating mode
1898/// 4. closing channels: closed channels being swept or aged prior to pruning
1899///
1900#[derive(Debug, PartialEq)]
1901pub struct ChannelBalance {
1902    /// Claimable balance on open channel
1903    pub claimable: u64,
1904    /// Sum of htlcs offered to us
1905    pub received_htlc: u64,
1906    /// Sum of htlcs we offered
1907    pub offered_htlc: u64,
1908    /// Sweeping to wallet
1909    pub sweeping: u64,
1910    /// Current number of channel stubs
1911    pub stub_count: u32,
1912    /// Current number of unconfirmed channels
1913    pub unconfirmed_count: u32,
1914    /// Current number of active channels
1915    pub channel_count: u32,
1916    /// Current number of closing channels
1917    pub closing_count: u32,
1918    /// Current number of received htlcs
1919    pub received_htlc_count: u32,
1920    /// Current number of offered htlcs
1921    pub offered_htlc_count: u32,
1922}
1923
1924impl ChannelBalance {
1925    /// Create a ChannelBalance with specific values
1926    pub fn new(
1927        claimable: u64,
1928        received_htlc: u64,
1929        offered_htlc: u64,
1930        sweeping: u64,
1931        stub_count: u32,
1932        unconfirmed_count: u32,
1933        channel_count: u32,
1934        closing_count: u32,
1935        received_htlc_count: u32,
1936        offered_htlc_count: u32,
1937    ) -> ChannelBalance {
1938        ChannelBalance {
1939            claimable,
1940            received_htlc,
1941            offered_htlc,
1942            sweeping,
1943            stub_count,
1944            unconfirmed_count,
1945            channel_count,
1946            closing_count,
1947            received_htlc_count,
1948            offered_htlc_count,
1949        }
1950    }
1951
1952    /// Create a ChannelBalance with zero values
1953    pub fn zero() -> ChannelBalance {
1954        ChannelBalance {
1955            claimable: 0,
1956            received_htlc: 0,
1957            offered_htlc: 0,
1958            sweeping: 0,
1959            stub_count: 0,
1960            unconfirmed_count: 0,
1961            channel_count: 0,
1962            closing_count: 0,
1963            received_htlc_count: 0,
1964            offered_htlc_count: 0,
1965        }
1966    }
1967
1968    /// Create a ChannelBalance for a stub
1969    pub fn stub() -> ChannelBalance {
1970        let mut bal = ChannelBalance::zero();
1971        bal.stub_count = 1;
1972        bal
1973    }
1974
1975    /// Sum channel balances
1976    pub fn accumulate(&mut self, other: &ChannelBalance) {
1977        self.claimable += other.claimable;
1978        self.received_htlc += other.received_htlc;
1979        self.offered_htlc += other.offered_htlc;
1980        self.sweeping += other.sweeping;
1981        self.stub_count += other.stub_count;
1982        self.unconfirmed_count += other.unconfirmed_count;
1983        self.channel_count += other.channel_count;
1984        self.closing_count += other.closing_count;
1985        self.received_htlc_count += other.received_htlc_count;
1986        self.offered_htlc_count += other.offered_htlc_count;
1987    }
1988}
1989
1990// Phase 1
1991impl Channel {
1992    pub(crate) fn build_counterparty_commitment_info(
1993        &self,
1994        to_holder_value_sat: u64,
1995        to_counterparty_value_sat: u64,
1996        offered_htlcs: Vec<HTLCInfo2>,
1997        received_htlcs: Vec<HTLCInfo2>,
1998        feerate_per_kw: u32,
1999    ) -> Result<CommitmentInfo2, Status> {
2000        Ok(CommitmentInfo2::new(
2001            true,
2002            to_holder_value_sat,
2003            to_counterparty_value_sat,
2004            offered_htlcs,
2005            received_htlcs,
2006            feerate_per_kw,
2007        ))
2008    }
2009
2010    fn build_holder_commitment_info(
2011        &self,
2012        to_holder_value_sat: u64,
2013        to_counterparty_value_sat: u64,
2014        offered_htlcs: Vec<HTLCInfo2>,
2015        received_htlcs: Vec<HTLCInfo2>,
2016        feerate_per_kw: u32,
2017    ) -> Result<CommitmentInfo2, Status> {
2018        Ok(CommitmentInfo2::new(
2019            false,
2020            to_counterparty_value_sat,
2021            to_holder_value_sat,
2022            offered_htlcs,
2023            received_htlcs,
2024            feerate_per_kw,
2025        ))
2026    }
2027
2028    /// Phase 1
2029    pub fn sign_counterparty_commitment_tx(
2030        &mut self,
2031        tx: &Transaction,
2032        output_witscripts: &[Vec<u8>],
2033        remote_per_commitment_point: &PublicKey,
2034        commitment_number: u64,
2035        feerate_per_kw: u32,
2036        offered_htlcs: Vec<HTLCInfo2>,
2037        received_htlcs: Vec<HTLCInfo2>,
2038    ) -> Result<Signature, Status> {
2039        if tx.output.len() != output_witscripts.len() {
2040            return Err(invalid_argument("len(tx.output) != len(witscripts)"));
2041        }
2042
2043        // Since we didn't have the value at the real open, validate it now.
2044        let validator = self.validator();
2045        validator.validate_channel_value(&self.setup)?;
2046
2047        // Derive a CommitmentInfo first, convert to CommitmentInfo2 below ...
2048        let is_counterparty = true;
2049        let info = validator.decode_commitment_tx(
2050            &self.keys,
2051            &self.setup,
2052            is_counterparty,
2053            tx,
2054            output_witscripts,
2055        )?;
2056
2057        let info2 = self.build_counterparty_commitment_info(
2058            info.to_countersigner_value_sat,
2059            info.to_broadcaster_value_sat,
2060            offered_htlcs,
2061            received_htlcs,
2062            feerate_per_kw,
2063        )?;
2064
2065        let node = self.get_node();
2066        let mut state = node.get_state();
2067        let delta =
2068            self.enforcement_state.claimable_balances(&*state, None, Some(&info2), &self.setup);
2069
2070        let incoming_payment_summary =
2071            self.enforcement_state.incoming_payments_summary(None, Some(&info2));
2072
2073        validator
2074            .validate_counterparty_commitment_tx(
2075                &self.enforcement_state,
2076                commitment_number,
2077                &remote_per_commitment_point,
2078                &self.setup,
2079                &self.get_chain_state(),
2080                &info2,
2081            )
2082            .map_err(|ve| {
2083                #[cfg(not(feature = "log_pretty_print"))]
2084                debug!(
2085                    "VALIDATION FAILED: {} tx={:?} setup={:?} cstate={:?} info={:?}",
2086                    ve,
2087                    &tx,
2088                    &self.setup,
2089                    &self.get_chain_state(),
2090                    &info2,
2091                );
2092                #[cfg(feature = "log_pretty_print")]
2093                debug!(
2094                    "VALIDATION FAILED: {}\ntx={:#?}\nsetup={:#?}\ncstate={:#?}\ninfo={:#?}",
2095                    ve,
2096                    &tx,
2097                    &self.setup,
2098                    &self.get_chain_state(),
2099                    &info2,
2100                );
2101                ve
2102            })?;
2103
2104        let htlcs =
2105            Self::htlcs_info2_to_oic(info2.offered_htlcs.clone(), info2.received_htlcs.clone());
2106
2107        let recomposed_tx = self.make_counterparty_commitment_tx(
2108            remote_per_commitment_point,
2109            commitment_number,
2110            feerate_per_kw,
2111            info2.to_countersigner_value_sat,
2112            info2.to_broadcaster_value_sat,
2113            htlcs,
2114        );
2115
2116        if recomposed_tx.trust().built_transaction().transaction != *tx {
2117            #[cfg(not(feature = "log_pretty_print"))]
2118            {
2119                debug!("ORIGINAL_TX={:?}", &tx);
2120                debug!(
2121                    "RECOMPOSED_TX={:?}",
2122                    &recomposed_tx.trust().built_transaction().transaction
2123                );
2124            }
2125            #[cfg(feature = "log_pretty_print")]
2126            {
2127                debug!("ORIGINAL_TX={:#?}", &tx);
2128                debug!(
2129                    "RECOMPOSED_TX={:#?}",
2130                    &recomposed_tx.trust().built_transaction().transaction
2131                );
2132            }
2133            policy_err!(validator, "policy-commitment", "recomposed tx mismatch");
2134        }
2135
2136        // The comparison in the previous block will fail if any of the
2137        // following policies are violated:
2138        // - policy-commitment-version
2139        // - policy-commitment-locktime
2140        // - policy-commitment-sequence
2141        // - policy-commitment-input-single
2142        // - policy-commitment-input-match-funding
2143        // - policy-commitment-revocation-pubkey
2144        // - policy-commitment-broadcaster-pubkey
2145        // - policy-commitment-countersignatory-pubkey
2146        // - policy-commitment-htlc-revocation-pubkey
2147        // - policy-commitment-htlc-counterparty-htlc-pubkey
2148        // - policy-commitment-htlc-holder-htlc-pubkey
2149        // - policy-commitment-singular
2150        // - policy-commitment-to-self-delay
2151        // - policy-commitment-no-unrecognized-outputs
2152
2153        // Convert from backwards counting.
2154        let commit_num = INITIAL_COMMITMENT_NUMBER - recomposed_tx.trust().commitment_number();
2155
2156        let point = recomposed_tx.trust().keys().per_commitment_point;
2157
2158        // we don't use keys.sign_counterparty_commitment here because it also signs HTLCs
2159        let trusted_tx = recomposed_tx.trust();
2160
2161        let funding_pubkey = &self.keys.pubkeys().funding_pubkey;
2162        let counterparty_funding_pubkey = &self.setup.counterparty_points.funding_pubkey;
2163        let channel_funding_redeemscript =
2164            make_funding_redeemscript(funding_pubkey, counterparty_funding_pubkey);
2165
2166        let built_tx = trusted_tx.built_transaction();
2167        let sig = catch_panic!(
2168            built_tx.sign_counterparty_commitment(
2169                &self.keys.funding_key,
2170                &channel_funding_redeemscript,
2171                self.setup.channel_value_sat,
2172                &self.secp_ctx,
2173            ),
2174            "sign_counterparty_commitment panic {} chantype={:?}",
2175            self.setup.commitment_type
2176        );
2177
2178        let outgoing_payment_summary = self.enforcement_state.payments_summary(None, Some(&info2));
2179        state.validate_payments(
2180            &self.id0,
2181            &incoming_payment_summary,
2182            &outgoing_payment_summary,
2183            &delta,
2184            validator.clone(),
2185        )?;
2186
2187        // Only advance the state if nothing goes wrong.
2188        validator.set_next_counterparty_commit_num(
2189            &mut self.enforcement_state,
2190            commit_num + 1,
2191            point,
2192            info2,
2193        )?;
2194
2195        state.apply_payments(
2196            &self.id0,
2197            &incoming_payment_summary,
2198            &outgoing_payment_summary,
2199            &delta,
2200            validator,
2201        );
2202
2203        trace_enforcement_state!(self);
2204        self.persist()?;
2205
2206        Ok(sig)
2207    }
2208
2209    fn make_validated_recomposed_holder_commitment_tx(
2210        &self,
2211        tx: &Transaction,
2212        output_witscripts: &[Vec<u8>],
2213        commitment_number: u64,
2214        per_commitment_point: PublicKey,
2215        txkeys: &TxCreationKeys,
2216        feerate_per_kw: u32,
2217        offered_htlcs: Vec<HTLCInfo2>,
2218        received_htlcs: Vec<HTLCInfo2>,
2219    ) -> Result<(CommitmentTransaction, CommitmentInfo2, Map<PaymentHash, u64>), Status> {
2220        if tx.output.len() != output_witscripts.len() {
2221            return Err(invalid_argument(format!(
2222                "len(tx.output):{} != len(witscripts):{}",
2223                tx.output.len(),
2224                output_witscripts.len()
2225            )));
2226        }
2227
2228        let validator = self.validator();
2229
2230        // Since we didn't have the value at the real open, validate it now.
2231        validator.validate_channel_value(&self.setup)?;
2232
2233        // Derive a CommitmentInfo first, convert to CommitmentInfo2 below ...
2234        let is_counterparty = false;
2235        let info = validator.decode_commitment_tx(
2236            &self.keys,
2237            &self.setup,
2238            is_counterparty,
2239            tx,
2240            output_witscripts,
2241        )?;
2242
2243        let info2 = self.build_holder_commitment_info(
2244            info.to_broadcaster_value_sat,
2245            info.to_countersigner_value_sat,
2246            offered_htlcs.clone(),
2247            received_htlcs.clone(),
2248            feerate_per_kw,
2249        )?;
2250
2251        let incoming_payment_summary =
2252            self.enforcement_state.incoming_payments_summary(Some(&info2), None);
2253
2254        validator
2255            .validate_holder_commitment_tx(
2256                &self.enforcement_state,
2257                commitment_number,
2258                &per_commitment_point,
2259                &self.setup,
2260                &self.get_chain_state(),
2261                &info2,
2262            )
2263            .map_err(|ve| {
2264                #[cfg(not(feature = "log_pretty_print"))]
2265                warn!(
2266                    "VALIDATION FAILED: {} tx={:?} setup={:?} state={:?} info={:?}",
2267                    ve,
2268                    &tx,
2269                    &self.setup,
2270                    &self.get_chain_state(),
2271                    &info2,
2272                );
2273                #[cfg(feature = "log_pretty_print")]
2274                warn!(
2275                    "VALIDATION FAILED: {}\ntx={:#?}\nsetup={:#?}\nstate={:#?}\ninfo={:#?}",
2276                    ve,
2277                    &tx,
2278                    &self.setup,
2279                    &self.get_chain_state(),
2280                    &info2,
2281                );
2282                ve
2283            })?;
2284
2285        let htlcs =
2286            Self::htlcs_info2_to_oic(info2.offered_htlcs.clone(), info2.received_htlcs.clone());
2287
2288        let recomposed_tx = self.make_holder_commitment_tx(
2289            commitment_number,
2290            txkeys,
2291            feerate_per_kw,
2292            info.to_broadcaster_value_sat,
2293            info.to_countersigner_value_sat,
2294            htlcs.clone(),
2295        );
2296
2297        if recomposed_tx.trust().built_transaction().transaction != *tx {
2298            dbgvals!(
2299                &self.setup,
2300                &self.enforcement_state,
2301                tx,
2302                DebugVecVecU8(output_witscripts),
2303                commitment_number,
2304                feerate_per_kw,
2305                &offered_htlcs,
2306                &received_htlcs
2307            );
2308            #[cfg(not(feature = "log_pretty_print"))]
2309            {
2310                warn!("RECOMPOSITION FAILED");
2311                warn!("ORIGINAL_TX={:?}", &tx);
2312                warn!("RECOMPOSED_TX={:?}", &recomposed_tx.trust().built_transaction().transaction);
2313            }
2314            #[cfg(feature = "log_pretty_print")]
2315            {
2316                warn!("RECOMPOSITION FAILED");
2317                warn!("ORIGINAL_TX={:#?}", &tx);
2318                warn!(
2319                    "RECOMPOSED_TX={:#?}",
2320                    &recomposed_tx.trust().built_transaction().transaction
2321                );
2322            }
2323            policy_err!(validator, "policy-commitment", "recomposed tx mismatch");
2324        }
2325
2326        // The comparison in the previous block will fail if any of the
2327        // following policies are violated:
2328        // - policy-commitment-version
2329        // - policy-commitment-locktime
2330        // - policy-commitment-sequence
2331        // - policy-commitment-input-single
2332        // - policy-commitment-input-match-funding
2333        // - policy-commitment-revocation-pubkey
2334        // - policy-commitment-broadcaster-pubkey
2335        // - policy-commitment-htlc-revocation-pubkey
2336        // - policy-commitment-htlc-counterparty-htlc-pubkey
2337        // - policy-commitment-htlc-holder-htlc-pubkey
2338        // - policy-revoke-new-commitment-valid
2339
2340        Ok((recomposed_tx, info2, incoming_payment_summary))
2341    }
2342
2343    /// Validate the counterparty's signatures on the holder's
2344    /// commitment and HTLCs when the commitment_signed message is
2345    /// received.  Returns the next per_commitment_point and the
2346    /// holder's revocation secret for the prior commitment.  This
2347    /// method advances the expected next holder commitment number in
2348    /// the signer's state.
2349    pub fn validate_holder_commitment_tx(
2350        &mut self,
2351        tx: &Transaction,
2352        output_witscripts: &[Vec<u8>],
2353        commitment_number: u64,
2354        feerate_per_kw: u32,
2355        offered_htlcs: Vec<HTLCInfo2>,
2356        received_htlcs: Vec<HTLCInfo2>,
2357        counterparty_commit_sig: &Signature,
2358        counterparty_htlc_sigs: &[Signature],
2359    ) -> Result<(), Status> {
2360        let validator = self.validator();
2361        let per_commitment_point = self.get_per_commitment_point(commitment_number)?;
2362        let txkeys = self.make_holder_tx_keys(&per_commitment_point);
2363
2364        // policy-onchain-format-standard
2365        let (recomposed_tx, info2, incoming_payment_summary) = self
2366            .make_validated_recomposed_holder_commitment_tx(
2367                tx,
2368                output_witscripts,
2369                commitment_number,
2370                per_commitment_point,
2371                &txkeys,
2372                feerate_per_kw,
2373                offered_htlcs,
2374                received_htlcs,
2375            )?;
2376
2377        let node = self.get_node();
2378        let state = node.get_state();
2379        let delta =
2380            self.enforcement_state.claimable_balances(&*state, Some(&info2), None, &self.setup);
2381
2382        #[cfg(not(fuzzing))]
2383        self.check_holder_tx_signatures(
2384            &per_commitment_point,
2385            &txkeys,
2386            feerate_per_kw,
2387            counterparty_commit_sig,
2388            counterparty_htlc_sigs,
2389            recomposed_tx,
2390        )?;
2391
2392        #[cfg(fuzzing)]
2393        let _ = recomposed_tx;
2394
2395        let outgoing_payment_summary = self.enforcement_state.payments_summary(Some(&info2), None);
2396        state.validate_payments(
2397            &self.id0,
2398            &incoming_payment_summary,
2399            &outgoing_payment_summary,
2400            &delta,
2401            validator.clone(),
2402        )?;
2403
2404        if commitment_number == self.enforcement_state.next_holder_commit_num {
2405            let counterparty_signatures = CommitmentSignatures(
2406                counterparty_commit_sig.clone(),
2407                counterparty_htlc_sigs.to_vec(),
2408            );
2409            self.enforcement_state.next_holder_commit_info = Some((info2, counterparty_signatures));
2410        }
2411
2412        trace_enforcement_state!(self);
2413        self.persist()?;
2414
2415        Ok(())
2416    }
2417
2418    /// Activate commitment 0 explicitly
2419    ///
2420    /// Commitment 0 is special because it doesn't have a predecessor
2421    /// commitment.  Since the revocation of the prior commitment normally makes
2422    /// a new commitment "current" this final step must be invoked explicitly.
2423    ///
2424    /// Returns the next per_commitment_point.
2425    pub fn activate_initial_commitment(&mut self) -> Result<PublicKey, Status> {
2426        debug!("activate_initial_commitment");
2427
2428        if self.enforcement_state.next_holder_commit_num != 0 {
2429            return Err(invalid_argument(format!(
2430                "activate_initial_commitment called with next_holder_commit_num {}",
2431                self.enforcement_state.next_holder_commit_num
2432            )));
2433        }
2434
2435        // Remove the info and sigs from next holder and make current
2436        if let Some((info2, sigs)) = self.enforcement_state.next_holder_commit_info.take() {
2437            self.enforcement_state.set_next_holder_commit_num(1, info2, sigs);
2438        } else {
2439            return Err(invalid_argument(format!(
2440                "activate_initial_commitment called before validation of the initial commitment"
2441            )));
2442        }
2443
2444        trace_enforcement_state!(self);
2445        self.persist()?;
2446        Ok(self.get_per_commitment_point_unchecked(1))
2447    }
2448
2449    /// Process the counterparty's revocation
2450    ///
2451    /// When this is provided, we know that the counterparty has committed to
2452    /// the next state.
2453    pub fn validate_counterparty_revocation(
2454        &mut self,
2455        revoke_num: u64,
2456        old_secret: &SecretKey,
2457    ) -> Result<(), Status> {
2458        let validator = self.validator();
2459        validator.validate_counterparty_revocation(
2460            &self.enforcement_state,
2461            revoke_num,
2462            old_secret,
2463        )?;
2464
2465        if let Some(secrets) = self.enforcement_state.counterparty_secrets.as_mut() {
2466            let backwards_num = INITIAL_COMMITMENT_NUMBER - revoke_num;
2467            if secrets.provide_secret(backwards_num, old_secret.secret_bytes()).is_err() {
2468                error!(
2469                    "secret does not chain: {} ({}) {} into {:?}",
2470                    revoke_num,
2471                    backwards_num,
2472                    old_secret.display_secret(),
2473                    secrets
2474                );
2475                policy_err!(
2476                    validator,
2477                    "policy-commitment-previous-revoked",
2478                    "counterparty secret does not chain"
2479                )
2480            }
2481        }
2482
2483        validator.set_next_counterparty_revoke_num(&mut self.enforcement_state, revoke_num + 1)?;
2484
2485        trace_enforcement_state!(self);
2486        self.persist()?;
2487        Ok(())
2488    }
2489
2490    /// Phase 1
2491    pub fn sign_mutual_close_tx(
2492        &mut self,
2493        tx: &Transaction,
2494        opaths: &[Vec<u32>],
2495    ) -> Result<Signature, Status> {
2496        dbgvals!(tx.compute_txid(), self.get_node().allowlist());
2497        if opaths.len() != tx.output.len() {
2498            return Err(invalid_argument(format!(
2499                "{}: bad opath len {} with tx.output len {}",
2500                short_function!(),
2501                opaths.len(),
2502                tx.output.len()
2503            )));
2504        }
2505
2506        let recomposed_tx = self.validator().decode_and_validate_mutual_close_tx(
2507            &*self.get_node(),
2508            &self.setup,
2509            &self.enforcement_state,
2510            tx,
2511            opaths,
2512        )?;
2513
2514        let sig = self
2515            .keys
2516            .sign_closing_transaction(&recomposed_tx, &self.secp_ctx)
2517            .map_err(|_| Status::internal("failed to sign"))?;
2518        self.enforcement_state.channel_closed = true;
2519        trace_enforcement_state!(self);
2520        self.persist()?;
2521        Ok(sig)
2522    }
2523
2524    /// Phase 1
2525    pub fn sign_holder_htlc_tx(
2526        &self,
2527        tx: &Transaction,
2528        commitment_number: u64,
2529        opt_per_commitment_point: Option<PublicKey>,
2530        redeemscript: &ScriptBuf,
2531        htlc_amount_sat: u64,
2532        output_witscript: &ScriptBuf,
2533    ) -> Result<TypedSignature, Status> {
2534        let per_commitment_point = if opt_per_commitment_point.is_some() {
2535            opt_per_commitment_point.unwrap()
2536        } else {
2537            self.get_per_commitment_point(commitment_number)?
2538        };
2539
2540        let txkeys = self.make_holder_tx_keys(&per_commitment_point);
2541
2542        self.sign_htlc_tx(
2543            tx,
2544            &per_commitment_point,
2545            redeemscript,
2546            htlc_amount_sat,
2547            output_witscript,
2548            false, // is_counterparty
2549            txkeys,
2550        )
2551    }
2552
2553    /// Sign a HTLC transaction hanging off a commitment transaction
2554    pub fn sign_holder_htlc_tx_phase2(
2555        &self,
2556        tx: &Transaction,
2557        input: u32,
2558        commitment_number: u64,
2559        is_offered: bool,
2560        cltv_expiry: u32,
2561        htlc_amount_msat: u64,
2562        payment_hash: PaymentHash,
2563    ) -> Result<TypedSignature, Status> {
2564        let per_commitment_point = self.get_per_commitment_point(commitment_number)?;
2565        let keys = self.make_holder_tx_keys(&per_commitment_point);
2566        let htlc = HTLCOutputInCommitment {
2567            offered: is_offered,
2568            cltv_expiry,
2569            payment_hash,
2570            transaction_output_index: None,
2571            amount_msat: htlc_amount_msat,
2572        };
2573        let witness_script =
2574            chan_utils::get_htlc_redeemscript(&htlc, &self.setup.features(), &keys);
2575        let sighash = SighashCache::new(tx)
2576            .p2wsh_signature_hash(
2577                input as usize,
2578                &witness_script,
2579                Amount::from_sat(htlc_amount_msat / 1000),
2580                EcdsaSighashType::All,
2581            )
2582            .unwrap();
2583        let our_htlc_private_key = chan_utils::derive_private_key(
2584            &self.secp_ctx,
2585            &per_commitment_point,
2586            &self.keys.htlc_base_key,
2587        );
2588        let sighash = Message::from_digest(sighash.to_byte_array());
2589        let signature = self.secp_ctx.sign_ecdsa(&sighash, &our_htlc_private_key);
2590        Ok(TypedSignature { sig: signature, typ: EcdsaSighashType::All })
2591    }
2592
2593    /// Phase 1
2594    pub fn sign_counterparty_htlc_tx(
2595        &self,
2596        tx: &Transaction,
2597        remote_per_commitment_point: &PublicKey,
2598        redeemscript: &ScriptBuf,
2599        htlc_amount_sat: u64,
2600        output_witscript: &ScriptBuf,
2601    ) -> Result<TypedSignature, Status> {
2602        let txkeys = self.make_counterparty_tx_keys(&remote_per_commitment_point);
2603
2604        self.sign_htlc_tx(
2605            tx,
2606            remote_per_commitment_point,
2607            redeemscript,
2608            htlc_amount_sat,
2609            output_witscript,
2610            true, // is_counterparty
2611            txkeys,
2612        )
2613    }
2614
2615    /// Sign a 2nd level HTLC transaction hanging off a commitment transaction
2616    pub fn sign_htlc_tx(
2617        &self,
2618        tx: &Transaction,
2619        per_commitment_point: &PublicKey,
2620        redeemscript: &ScriptBuf,
2621        htlc_amount_sat: u64,
2622        output_witscript: &ScriptBuf,
2623        is_counterparty: bool,
2624        txkeys: TxCreationKeys,
2625    ) -> Result<TypedSignature, Status> {
2626        let (feerate_per_kw, htlc, recomposed_tx_sighash, sighash_type) =
2627            self.validator().decode_and_validate_htlc_tx(
2628                is_counterparty,
2629                &self.setup,
2630                &txkeys,
2631                tx,
2632                &redeemscript,
2633                htlc_amount_sat,
2634                output_witscript,
2635            )?;
2636
2637        self.validator()
2638            .validate_htlc_tx(
2639                &self.setup,
2640                &self.get_chain_state(),
2641                is_counterparty,
2642                &htlc,
2643                feerate_per_kw,
2644            )
2645            .map_err(|ve| {
2646                #[cfg(not(feature = "log_pretty_print"))]
2647                debug!(
2648                    "VALIDATION FAILED: {} setup={:?} state={:?} is_counterparty={} \
2649                     tx={:?} htlc={:?} feerate_per_kw={}",
2650                    ve,
2651                    &self.setup,
2652                    &self.get_chain_state(),
2653                    is_counterparty,
2654                    &tx,
2655                    DebugHTLCOutputInCommitment(&htlc),
2656                    feerate_per_kw,
2657                );
2658                #[cfg(feature = "log_pretty_print")]
2659                debug!(
2660                    "VALIDATION FAILED: {}\n\
2661                     setup={:#?}\n\
2662                     state={:#?}\n\
2663                     is_counterparty={}\n\
2664                     tx={:#?}\n\
2665                     htlc={:#?}\n\
2666                     feerate_per_kw={}",
2667                    ve,
2668                    &self.setup,
2669                    &self.get_chain_state(),
2670                    is_counterparty,
2671                    &tx,
2672                    DebugHTLCOutputInCommitment(&htlc),
2673                    feerate_per_kw,
2674                );
2675                ve
2676            })?;
2677
2678        let htlc_privkey =
2679            derive_private_key(&self.secp_ctx, &per_commitment_point, &self.keys.htlc_base_key);
2680
2681        let htlc_sighash = Message::from_digest(recomposed_tx_sighash.to_byte_array());
2682
2683        Ok(TypedSignature {
2684            sig: self.secp_ctx.sign_ecdsa(&htlc_sighash, &htlc_privkey),
2685            typ: sighash_type,
2686        })
2687    }
2688
2689    /// Get the unilateral close key and the witness stack suffix,
2690    /// for sweeping our main output from a commitment transaction.
2691    /// If the revocation_pubkey is Some, then we are sweeping a
2692    /// holder commitment transaction, otherwise we are sweeping a
2693    /// counterparty commitment transaction.
2694    /// commitment_point is used to derive the key if it is Some.
2695    /// Since we don't support legacy channels, commitment_point must
2696    /// be Some iff revocation_pubkey is Some.
2697    pub fn get_unilateral_close_key(
2698        &self,
2699        commitment_point: &Option<PublicKey>,
2700        revocation_pubkey: &Option<RevocationKey>,
2701    ) -> Result<(SecretKey, Vec<Vec<u8>>), Status> {
2702        if let Some(commitment_point) = commitment_point {
2703            // The key is rotated via the commitment point.  Since we removed support
2704            // for rotating the to-remote key (legacy channel type), we enforce below that
2705            // this is the to-local case.
2706            let base_key = if revocation_pubkey.is_some() {
2707                &self.keys.delayed_payment_base_key
2708            } else {
2709                &self.keys.payment_key
2710            };
2711            let key = derive_private_key(&self.secp_ctx, &commitment_point, base_key);
2712            let pubkey = PublicKey::from_secret_key(&self.secp_ctx, &key);
2713
2714            let witness_stack_prefix = if let Some(r) = revocation_pubkey {
2715                // p2wsh
2716                let contest_delay = self.setup.counterparty_selected_contest_delay;
2717                let redeemscript = chan_utils::get_revokeable_redeemscript(
2718                    r,
2719                    contest_delay,
2720                    &DelayedPaymentKey(pubkey),
2721                )
2722                .to_bytes();
2723                vec![vec![], redeemscript]
2724            } else {
2725                return Err(invalid_argument(
2726                    "no support for legacy rotated to-remote, commitment point is provided and revocation_pubkey is not"
2727                ));
2728            };
2729            Ok((key, witness_stack_prefix))
2730        } else {
2731            // The key is not rotated, so we use the base key.  This must be the to-remote case
2732            // because the to-local is always rotated.
2733            if revocation_pubkey.is_some() {
2734                return Err(invalid_argument(
2735                    "delayed to-local output must be rotated, but no commitment point provided",
2736                ));
2737            }
2738
2739            let key = self.keys.payment_key.clone();
2740            let pubkey = PublicKey::from_secret_key(&self.secp_ctx, &key);
2741            let witness_stack_prefix = if self.setup.is_anchors() {
2742                // p2wsh
2743                let redeemscript =
2744                    chan_utils::get_to_countersignatory_with_anchors_redeemscript(&pubkey)
2745                        .to_bytes();
2746                vec![redeemscript]
2747            } else {
2748                // p2wpkh
2749                vec![pubkey.serialize().to_vec()]
2750            };
2751            Ok((key, witness_stack_prefix))
2752        }
2753    }
2754
2755    /// Mark any in-flight payments (outgoing HTLCs) on this channel with the
2756    /// given preimage as filled.
2757    /// Any such payments adjust our expected balance downwards.
2758    pub fn htlcs_fulfilled(&mut self, preimages: Vec<PaymentPreimage>) {
2759        let validator = self.validator();
2760        let node = self.get_node();
2761        node.htlcs_fulfilled(&self.id0, preimages, validator);
2762    }
2763
2764    fn dummy_sig() -> Signature {
2765        Signature::from_compact(&Vec::from_hex("eb299947b140c0e902243ee839ca58c71291f4cce49ac0367fb4617c4b6e890f18bc08b9be6726c090af4c6b49b2277e134b34078f710a72a5752e39f0139149").unwrap()).unwrap()
2766    }
2767}
2768
2769#[derive(Clone)]
2770pub(crate) struct ChannelCommitmentPointProvider {
2771    chan: Arc<Mutex<ChannelSlot>>,
2772}
2773
2774impl ChannelCommitmentPointProvider {
2775    /// Will panic on a channel stub
2776    pub(crate) fn new(chan: Arc<Mutex<ChannelSlot>>) -> Self {
2777        match &*chan.lock().unwrap() {
2778            ChannelSlot::Stub(_) => panic!("unexpected stub"),
2779            ChannelSlot::Ready(_) => {}
2780        }
2781        Self { chan }
2782    }
2783
2784    fn get_channel(&self) -> MutexGuard<ChannelSlot> {
2785        self.chan.lock().unwrap()
2786    }
2787}
2788
2789impl SendSync for ChannelCommitmentPointProvider {}
2790
2791impl CommitmentPointProvider for ChannelCommitmentPointProvider {
2792    fn get_holder_commitment_point(&self, commitment_number: u64) -> PublicKey {
2793        let slot = self.get_channel();
2794        let chan = match &*slot {
2795            ChannelSlot::Stub(_) => panic!("unexpected stub"),
2796            ChannelSlot::Ready(c) => c,
2797        };
2798        chan.get_per_commitment_point_unchecked(commitment_number)
2799    }
2800
2801    fn get_counterparty_commitment_point(&self, commitment_number: u64) -> Option<PublicKey> {
2802        let slot = self.get_channel();
2803        let chan = match &*slot {
2804            ChannelSlot::Stub(_) => panic!("unexpected stub"),
2805            ChannelSlot::Ready(c) => c,
2806        };
2807
2808        chan.get_counterparty_commitment_point(commitment_number)
2809    }
2810
2811    fn get_transaction_parameters(&self) -> ChannelTransactionParameters {
2812        let slot = self.get_channel();
2813        let chan = match &*slot {
2814            ChannelSlot::Stub(_) => panic!("unexpected stub"),
2815            ChannelSlot::Ready(c) => c,
2816        };
2817
2818        chan.make_channel_parameters()
2819    }
2820
2821    fn clone_box(&self) -> Box<dyn CommitmentPointProvider> {
2822        Box::new(ChannelCommitmentPointProvider { chan: self.chan.clone() })
2823    }
2824}
2825
2826#[cfg(test)]
2827mod tests {
2828    use bitcoin::secp256k1::{self, Secp256k1, SecretKey};
2829    use lightning::ln::chan_utils::HTLCOutputInCommitment;
2830    use lightning::types::payment::PaymentHash;
2831    use lightning::util::ser::Writeable;
2832
2833    use crate::channel::ChannelBase;
2834    use crate::util::test_utils::{
2835        init_node_and_channel, make_test_channel_setup, TEST_NODE_CONFIG, TEST_SEED,
2836    };
2837
2838    use super::ChannelId;
2839
2840    #[test]
2841    fn test_dummy_sig() {
2842        let dummy_sig = Secp256k1::new().sign_ecdsa(
2843            &secp256k1::Message::from_digest([42; 32]),
2844            &SecretKey::from_slice(&[42; 32]).unwrap(),
2845        );
2846        let ser = dummy_sig.serialize_compact();
2847        assert_eq!("eb299947b140c0e902243ee839ca58c71291f4cce49ac0367fb4617c4b6e890f18bc08b9be6726c090af4c6b49b2277e134b34078f710a72a5752e39f0139149", hex::encode(ser));
2848    }
2849
2850    #[test]
2851    fn tx_size_test() {
2852        let (node, channel_id) =
2853            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
2854        node.with_channel(&channel_id, |chan| {
2855            let n = 1;
2856            let commitment_point = chan.get_per_commitment_point(n).unwrap();
2857            let txkeys = chan.make_holder_tx_keys(&commitment_point);
2858            let htlcs = (0..583)
2859                .map(|i| HTLCOutputInCommitment {
2860                    offered: true,
2861                    amount_msat: 1000000,
2862                    cltv_expiry: 100,
2863                    payment_hash: PaymentHash([0; 32]),
2864                    transaction_output_index: Some(i),
2865                })
2866                .collect();
2867            let tx = chan.make_holder_commitment_tx(n, &txkeys, 1, 1, 1, htlcs);
2868            let tx_size = tx.trust().built_transaction().transaction.serialized_length();
2869            assert_eq!(tx_size, 25196);
2870            Ok(())
2871        })
2872        .unwrap();
2873    }
2874
2875    #[test]
2876    fn test_ldk_oid_roundtrip() {
2877        let oid: u64 = 42;
2878        assert_eq!(oid, ChannelId::new_from_oid(oid).oid());
2879    }
2880}