lightning_signer/
channel.rs

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