lightning_signer/
channel.rs

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