Skip to main content

lightning_signer/
node.rs

1use alloc::collections::VecDeque;
2use core::borrow::Borrow;
3use core::fmt::{self, Debug, Formatter};
4use core::str::FromStr;
5use core::time::Duration;
6
7use scopeguard::defer;
8
9use bitcoin::bip32::{DerivationPath, Xpriv, Xpub};
10use bitcoin::hashes::sha256::Hash as Sha256Hash;
11use bitcoin::hashes::sha256d::Hash as Sha256dHash;
12use bitcoin::hashes::{Hash, HashEngine};
13use bitcoin::key::UntweakedPublicKey;
14use bitcoin::key::XOnlyPublicKey;
15use bitcoin::secp256k1::ecdh::SharedSecret;
16use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
17use bitcoin::secp256k1::{schnorr, Message, PublicKey, Secp256k1, SecretKey};
18use bitcoin::sighash::{EcdsaSighashType, Prevouts, SighashCache, TapSighashType};
19use bitcoin::{secp256k1, Address, CompressedPublicKey, PrivateKey, ScriptBuf, Transaction, TxOut};
20use bitcoin::{Network, OutPoint, Script};
21use bitcoin_consensus_derive::{Decodable, Encodable};
22use lightning::ln::inbound_payment::ExpandedKey;
23use lightning::ln::msgs::UnsignedGossipMessage;
24use lightning::ln::script::ShutdownScript;
25use lightning::offers::invoice::UnsignedBolt12Invoice;
26use lightning::sign::{
27    EntropySource, NodeSigner, Recipient, SignerProvider, SpendableOutputDescriptor,
28};
29use lightning::types::payment::{PaymentHash, PaymentPreimage};
30use lightning::util::logger::Logger;
31use lightning::util::ser::Writeable;
32use lightning_invoice::{RawBolt11Invoice, SignedRawBolt11Invoice};
33use serde::{Deserialize, Serialize};
34
35#[allow(unused_imports)]
36use log::*;
37
38use serde_with::{serde_as, Bytes, IfIsHumanReadable};
39
40use crate::chain::tracker::ChainTracker;
41use crate::chain::tracker::Headers;
42use crate::channel::{
43    Channel, ChannelBalance, ChannelBase, ChannelCommitmentPointProvider, ChannelId, ChannelSetup,
44    ChannelSlot, ChannelStub, SlotInfo,
45};
46use crate::invoice::{Invoice, InvoiceAttributes};
47use crate::monitor::{ChainMonitor, ChainMonitorBase};
48use crate::persist::model::NodeEntry;
49use crate::persist::{Persist, SeedPersist};
50use crate::policy::error::{policy_error, ValidationError};
51use crate::policy::validator::{BalanceDelta, ValidatorFactory};
52use crate::policy::validator::{EnforcementState, Validator};
53use crate::policy::Policy;
54#[cfg(feature = "timeless_workaround")]
55use crate::policy::INVOICE_AHEAD_TOLERANCE;
56use crate::policy_err;
57use crate::prelude::*;
58use crate::signer::derive::KeyDerivationStyle;
59use crate::signer::my_keys_manager::MyKeysManager;
60use crate::signer::StartingTimeFactory;
61use crate::tx::tx::{CommitmentInfo2, PreimageMap};
62use crate::txoo::get_latest_checkpoint;
63use crate::util::clock::Clock;
64use crate::util::crypto_utils::{
65    ecdsa_sign, schnorr_signature_to_bitcoin_vec, signature_to_bitcoin_vec, taproot_sign,
66};
67use crate::util::debug_utils::{
68    DebugBytes, DebugMapPaymentState, DebugMapPaymentSummary, DebugMapRoutedPayment,
69};
70use crate::util::ser_util::DurationHandler;
71use crate::util::status::{failed_precondition, internal_error, invalid_argument, Status};
72use crate::util::velocity::VelocityControl;
73use crate::wallet::Wallet;
74use vls_common::HexEncode;
75
76// =============================================================================
77// LOCK ORDERING
78// =============================================================================
79//
80// Node has 4 mutex-protected fields. When acquiring multiple locks,
81// always acquire in this order to prevent deadlocks:
82//
83//   1. tracker (ChainTracker)    - chain tip, block monitoring
84//   2. channels (channel map)    - map of channel IDs to slots
85//   3. channel_slot (per-channel) - individual channel data
86//   4. state (NodeState)         - node-wide state, allowlist, payments
87//
88// Only *nested* acquisitions are constrained. Taking a lock, extracting what
89// you need, and releasing it before acquiring the next one is always fine, and
90// is preferred when possible.
91//
92// Methods that acquire multiple locks should reference this comment.
93//
94// State comes last because the signing path demands it: LDK calls into
95// Node::with_channel, which locks a channel_slot and then calls channel
96// methods that take node state (Channel::balance, htlcs_fulfilled, and many
97// more in channel.rs). That slot -> state order is pervasive and cannot be
98// reversed without restructuring most of channel.rs, so everything else
99// conforms to it instead.
100//
101// The corollary is that methods running off the signing path must not hold
102// state while reaching for a channel: channel_balance (admin RPC, heartbeat)
103// and forget_channel both take state only after the slot guard is released.
104// Holding state across a slot lock deadlocks against any concurrent signing
105// operation - see test_channel_balance_vs_signing_ready.
106// =============================================================================
107
108/// Prune invoices expired more than this long ago
109const INVOICE_PRUNE_TIME: Duration = Duration::from_secs(60 * 60 * 24);
110/// Prune keysends expired more than this long ago
111const KEYSEND_PRUNE_TIME: Duration = Duration::from_secs(0);
112
113/// Number of blocks to wait before removing failed channel stubs
114pub(crate) const CHANNEL_STUB_PRUNE_BLOCKS: u32 = 6;
115
116/// Node configuration parameters.
117
118#[derive(Copy, Clone, Debug)]
119pub struct NodeConfig {
120    /// The network type
121    pub network: Network,
122    /// The derivation style to use when deriving purpose-specific keys
123    pub key_derivation_style: KeyDerivationStyle,
124    /// Whether to use checkpoints for the tracker
125    pub use_checkpoints: bool,
126    /// Whether to allow deep reorgs
127    ///
128    /// This may be unsafe in the Lightning security model.
129    pub allow_deep_reorgs: bool,
130}
131
132impl NodeConfig {
133    /// Create a new node config with native key derivation
134    pub fn new(network: Network) -> NodeConfig {
135        let allow_deep_reorgs = if network == Network::Testnet { true } else { false };
136        NodeConfig {
137            network,
138            key_derivation_style: KeyDerivationStyle::Native,
139            use_checkpoints: true,
140            allow_deep_reorgs,
141        }
142    }
143}
144
145/// Payment details and payment state
146#[serde_as]
147#[derive(Clone, Serialize, Deserialize)]
148pub struct PaymentState {
149    /// The hash of the invoice, as a unique ID
150    #[serde_as(as = "IfIsHumanReadable<_, Bytes>")]
151    pub invoice_hash: [u8; 32],
152    /// Invoiced amount
153    pub amount_msat: u64,
154    /// Payee's public key, if known
155    pub payee: PublicKey,
156    /// Timestamp of the payment, as duration since the UNIX epoch
157    #[serde_as(as = "IfIsHumanReadable<DurationHandler>")]
158    pub duration_since_epoch: Duration,
159    /// Expiry, as duration since the timestamp
160    #[serde_as(as = "IfIsHumanReadable<DurationHandler>")]
161    pub expiry_duration: Duration,
162    /// Whether the invoice was fulfilled
163    /// note: for issued invoices only
164    pub is_fulfilled: bool,
165    /// Payment type
166    pub payment_type: PaymentType,
167}
168
169impl Debug for PaymentState {
170    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
171        f.debug_struct("PaymentState")
172            .field("invoice_hash", &DebugBytes(&self.invoice_hash))
173            .field("amount_msat", &self.amount_msat)
174            .field("payee", &self.payee)
175            .field("duration_since_epoch", &self.duration_since_epoch)
176            .field("expiry_duration", &self.expiry_duration)
177            .field("is_fulfilled", &self.is_fulfilled)
178            .field("payment_type", &self.payment_type)
179            .finish()
180    }
181}
182
183/// Outgoing payment type
184#[derive(Clone, Debug, Serialize, Deserialize)]
185pub enum PaymentType {
186    /// We are paying an invoice
187    Invoice,
188    /// We are sending via keysend
189    Keysend,
190}
191
192/// Display as string for PaymentType
193impl fmt::Display for PaymentType {
194    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
195        write!(
196            f,
197            "{}",
198            match self {
199                Self::Invoice => "invoice",
200                Self::Keysend => "keysend",
201            }
202        )
203    }
204}
205
206/// Keeps track of incoming and outgoing HTLCs for a routed payment
207#[derive(Clone, Debug)]
208pub struct RoutedPayment {
209    /// Incoming payments per channel in satoshi
210    pub incoming: OrderedMap<ChannelId, u64>,
211    /// Outgoing payments per channel in satoshi
212    pub outgoing: OrderedMap<ChannelId, u64>,
213    /// Minimum incoming CLTV expiry (block height) across all channels
214    pub incoming_cltv_min: Option<u32>,
215    /// Maximum outgoing CLTV expiry (block height) across all channels
216    pub outgoing_cltv_max: Option<u32>,
217    /// The preimage for the hash, filled in on success
218    pub preimage: Option<PaymentPreimage>,
219}
220
221impl RoutedPayment {
222    /// Create an empty routed payment
223    pub fn new() -> RoutedPayment {
224        RoutedPayment {
225            incoming: OrderedMap::new(),
226            outgoing: OrderedMap::new(),
227            incoming_cltv_min: None,
228            outgoing_cltv_max: None,
229            preimage: None,
230        }
231    }
232
233    /// Whether we know the preimage, and therefore the incoming is claimable
234    pub fn is_fulfilled(&self) -> bool {
235        self.preimage.is_some()
236    }
237
238    /// Whether there is any incoming payment
239    pub fn is_no_incoming(&self) -> bool {
240        self.incoming.values().into_iter().sum::<u64>() == 0
241    }
242
243    /// Whether there is no outgoing payment
244    pub fn is_no_outgoing(&self) -> bool {
245        self.outgoing.values().into_iter().sum::<u64>() == 0
246    }
247
248    /// The total incoming and outgoing, if this channel updates to the specified values
249    pub fn updated_incoming_outgoing(
250        &self,
251        channel_id: &ChannelId,
252        incoming_amount_sat: u64,
253        outgoing_amount_sat: u64,
254    ) -> (u64, u64) {
255        let incoming_sum = self.incoming.values().sum::<u64>() + incoming_amount_sat
256            - *self.incoming.get(channel_id).unwrap_or(&0);
257        let outgoing_sum = self.outgoing.values().sum::<u64>() + outgoing_amount_sat
258            - *self.outgoing.get(channel_id).unwrap_or(&0);
259
260        (incoming_sum, outgoing_sum)
261    }
262
263    /// The total incoming and outgoing, in satoshi
264    pub fn incoming_outgoing(&self) -> (u64, u64) {
265        (
266            self.incoming.values().into_iter().sum::<u64>(),
267            self.outgoing.values().into_iter().sum::<u64>(),
268        )
269    }
270
271    /// Apply incoming and outgoing payment for a channel, in satoshi
272    pub fn apply(
273        &mut self,
274        channel_id: &ChannelId,
275        incoming_amount_sat: u64,
276        outgoing_amount_sat: u64,
277        incoming_cltv: Option<u32>,
278        outgoing_cltv: Option<u32>,
279    ) {
280        self.incoming.insert(channel_id.clone(), incoming_amount_sat);
281        self.outgoing.insert(channel_id.clone(), outgoing_amount_sat);
282
283        if let Some(inc_cltv) = incoming_cltv {
284            self.incoming_cltv_min =
285                Some(self.incoming_cltv_min.map_or(inc_cltv, |existing| existing.min(inc_cltv)));
286        }
287
288        if let Some(out_cltv) = outgoing_cltv {
289            self.outgoing_cltv_max =
290                Some(self.outgoing_cltv_max.map_or(out_cltv, |existing| existing.max(out_cltv)));
291        }
292    }
293
294    /// Get CLTV bounds for validation
295    /// Returns Some((incoming_min, outgoing_max)) if both bounds exist (routed payment)
296    /// Returns None if either bound is missing (terminal or originating payment)
297    pub fn get_cltv_bounds(&self) -> Option<(u32, u32)> {
298        match (self.incoming_cltv_min, self.outgoing_cltv_max) {
299            (Some(inc), Some(out)) => Some((inc, out)),
300            _ => None,
301        }
302    }
303}
304
305/// Enforcement state for a node
306pub struct NodeState {
307    /// Added invoices for outgoing payments indexed by their payment hash
308    pub invoices: Map<PaymentHash, PaymentState>,
309    /// Issued invoices for incoming payments indexed by their payment hash
310    pub issued_invoices: Map<PaymentHash, PaymentState>,
311    /// Payment states.
312    /// There is one entry for each invoice.  Entries also exist for HTLCs
313    /// we route.
314    pub payments: Map<PaymentHash, RoutedPayment>,
315    /// Accumulator of excess payment amount in satoshi, for tracking certain
316    /// payment corner cases.
317    /// If this falls below zero, the attempted commit is failed.
318    // TODO(519) fee accumulation adjustment
319    // As we accumulate routing fees, this value grows without bounds.  We should
320    // take accumulated fees out over time to keep this bounded.
321    pub excess_amount: u64,
322    /// Prefix for emitted logs lines
323    pub log_prefix: String,
324    /// Per node velocity control
325    pub velocity_control: VelocityControl,
326    /// Per node fee velocity control
327    pub fee_velocity_control: VelocityControl,
328    /// Last summary string
329    pub last_summary: String,
330    /// dbid high water mark
331    pub dbid_high_water_mark: u64,
332    /// Set of allowed addresses or scripts for the node
333    pub allowlist: OrderedSet<Allowable>,
334}
335
336impl Debug for NodeState {
337    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
338        f.debug_struct("NodeState")
339            .field("invoices", &DebugMapPaymentState(&self.invoices))
340            .field("issued_invoices", &DebugMapPaymentState(&self.issued_invoices))
341            .field("payments", &DebugMapRoutedPayment(&self.payments))
342            .field("excess_amount", &self.excess_amount)
343            .field("log_prefix", &self.log_prefix)
344            .field("velocity_control", &self.velocity_control)
345            .field("last_summary", &self.last_summary)
346            .field("dbid_high_water_mark", &self.dbid_high_water_mark)
347            .finish()
348    }
349}
350
351impl PreimageMap for NodeState {
352    fn has_preimage(&self, hash: &PaymentHash) -> bool {
353        self.payments.get(hash).map(|p| p.preimage.is_some()).unwrap_or(false)
354    }
355}
356
357impl NodeState {
358    /// Create a state
359    pub fn new(
360        velocity_control: VelocityControl,
361        fee_velocity_control: VelocityControl,
362        allowlist: Vec<Allowable>,
363    ) -> Self {
364        NodeState {
365            invoices: Map::new(),
366            issued_invoices: Map::new(),
367            payments: Map::new(),
368            excess_amount: 0,
369            log_prefix: String::new(),
370            velocity_control,
371            fee_velocity_control,
372            last_summary: String::new(),
373            dbid_high_water_mark: 0,
374            allowlist: allowlist.into_iter().collect(),
375        }
376    }
377
378    /// Restore a state from persistence
379    pub fn restore(
380        invoices_v: Vec<(Vec<u8>, PaymentState)>,
381        issued_invoices_v: Vec<(Vec<u8>, PaymentState)>,
382        preimages: Vec<[u8; 32]>,
383        excess_amount: u64,
384        velocity_control: VelocityControl,
385        fee_velocity_control: VelocityControl,
386        dbid_high_water_mark: u64,
387        allowlist: Vec<Allowable>,
388    ) -> Self {
389        // the try_into must succeed, because we persisted hashes of the right length
390        let invoices = invoices_v
391            .into_iter()
392            .map(|(k, v)| (PaymentHash(k.try_into().expect("payment hash decode")), v.into()))
393            .collect();
394        let issued_invoices = issued_invoices_v
395            .into_iter()
396            .map(|(k, v)| (PaymentHash(k.try_into().expect("payment hash decode")), v.into()))
397            .collect();
398        let payments = preimages
399            .into_iter()
400            .map(|preimage| {
401                let hash = PaymentHash(Sha256Hash::hash(&preimage).to_byte_array());
402                let mut payment = RoutedPayment::new();
403                payment.preimage = Some(PaymentPreimage(preimage));
404                (hash, payment)
405            })
406            .collect();
407        NodeState {
408            invoices,
409            issued_invoices,
410            payments,
411            excess_amount,
412            log_prefix: String::new(),
413            velocity_control,
414            fee_velocity_control,
415            last_summary: String::new(),
416            dbid_high_water_mark,
417            allowlist: allowlist.into_iter().collect(),
418        }
419    }
420
421    fn with_log_prefix(
422        self,
423        velocity_control: VelocityControl,
424        fee_velocity_control: VelocityControl,
425        log_prefix: String,
426    ) -> Self {
427        NodeState {
428            invoices: self.invoices,
429            issued_invoices: self.issued_invoices,
430            payments: self.payments,
431            excess_amount: self.excess_amount,
432            log_prefix,
433            velocity_control,
434            fee_velocity_control,
435            last_summary: String::new(),
436            dbid_high_water_mark: self.dbid_high_water_mark,
437            allowlist: self.allowlist,
438        }
439    }
440
441    /// Return a summary for debugging and whether it changed since last call
442    pub fn summary(&mut self) -> (String, bool) {
443        let summary = format!(
444            "NodeState::summary {}: {} invoices, {} issued_invoices, {} payments, excess_amount {}, dbid_high_water_mark {}",
445            self.log_prefix,
446            self.invoices.len(),
447            self.issued_invoices.len(),
448            self.payments.len(),
449            self.excess_amount,
450            self.dbid_high_water_mark,
451        );
452        if self.last_summary != summary {
453            self.last_summary = summary.clone();
454            (summary, true)
455        } else {
456            (summary, false)
457        }
458    }
459
460    #[cfg(test)]
461    pub(crate) fn validate_and_apply_payments(
462        &mut self,
463        channel_id: &ChannelId,
464        incoming_payment_summary: &Map<PaymentHash, u64>,
465        outgoing_payment_summary: &Map<PaymentHash, u64>,
466        balance_delta: &BalanceDelta,
467        validator: Arc<dyn Validator>,
468    ) -> Result<(), ValidationError> {
469        self.validate_payments(
470            channel_id,
471            incoming_payment_summary,
472            outgoing_payment_summary,
473            balance_delta,
474            validator.clone(),
475        )?;
476        self.apply_payments(
477            channel_id,
478            incoming_payment_summary,
479            outgoing_payment_summary,
480            balance_delta,
481            validator.clone(),
482            None,
483        );
484        Ok(())
485    }
486    /// Validate outgoing in-flight payment amounts as a result of a new commitment tx.
487    ///
488    /// The following policies are checked:
489    /// - no overpayment for any invoice.
490    /// - Sends without invoices (e.g. keysend) are only allowed if
491    /// `policy.require_invoices` is false.
492    ///
493    /// The amounts are in satoshi.
494    pub fn validate_payments(
495        &self,
496        channel_id: &ChannelId,
497        incoming_payment_summary: &Map<PaymentHash, u64>,
498        outgoing_payment_summary: &Map<PaymentHash, u64>,
499        balance_delta: &BalanceDelta,
500        validator: Arc<dyn Validator>,
501    ) -> Result<(), ValidationError> {
502        let mut debug_on_return = scoped_debug_return!(self);
503        debug!(
504            "{} validating payments on channel {} - in {:?} out {:?}",
505            self.log_prefix,
506            channel_id,
507            &DebugMapPaymentSummary(&incoming_payment_summary),
508            &DebugMapPaymentSummary(&outgoing_payment_summary)
509        );
510
511        let mut hashes: UnorderedSet<&PaymentHash> = UnorderedSet::new();
512        hashes.extend(incoming_payment_summary.keys());
513        hashes.extend(outgoing_payment_summary.keys());
514
515        let mut unbalanced = Vec::new();
516
517        // Preflight check
518        for hash_r in hashes.iter() {
519            let hash = **hash_r;
520            let incoming_for_chan_sat =
521                incoming_payment_summary.get(&hash).map(|a| *a).unwrap_or(0);
522            let outgoing_for_chan_sat =
523                outgoing_payment_summary.get(&hash).map(|a| *a).unwrap_or(0);
524            let payment = self.payments.get(&hash);
525            let (incoming_sat, outgoing_sat) = if let Some(p) = payment {
526                if let Some((incoming_cltv, outgoing_cltv)) = p.get_cltv_bounds() {
527                    validator.validate_payment_cltv(incoming_cltv, outgoing_cltv)?;
528                }
529
530                p.updated_incoming_outgoing(
531                    channel_id,
532                    incoming_for_chan_sat,
533                    outgoing_for_chan_sat,
534                )
535            } else {
536                (incoming_for_chan_sat, outgoing_for_chan_sat)
537            };
538            let invoiced_amount = self.invoices.get(&hash).map(|i| i.amount_msat);
539            if let Err(err) = validator.validate_payment_balance(
540                incoming_sat * 1000,
541                outgoing_sat * 1000,
542                invoiced_amount,
543            ) {
544                if payment.is_some() && invoiced_amount.is_none() {
545                    // TODO(331) workaround for an uninvoiced existing payment
546                    // is allowed to go out of balance because LDK does not
547                    // provide the preimage in time and removes the incoming HTLC first.
548                    #[cfg(not(feature = "log_pretty_print"))]
549                    warn!(
550                        "unbalanced routed payment on channel {} for hash {:?} \
551                         payment state {:?}: {:}",
552                        channel_id,
553                        DebugBytes(&hash.0),
554                        payment,
555                        err,
556                    );
557                    #[cfg(feature = "log_pretty_print")]
558                    warn!(
559                        "unbalanced routed payment on channel {} for hash {:?} \
560                         payment state {:#?}: {:}",
561                        channel_id,
562                        DebugBytes(&hash.0),
563                        payment,
564                        err,
565                    );
566                } else {
567                    #[cfg(not(feature = "log_pretty_print"))]
568                    error!(
569                        "unbalanced payment on channel {} for hash {:?} payment state {:?}: {:}",
570                        channel_id,
571                        DebugBytes(&hash.0),
572                        payment,
573                        err
574                    );
575                    #[cfg(feature = "log_pretty_print")]
576                    error!(
577                        "unbalanced payment on channel {} for hash {:?} payment state {:#?}: {:}",
578                        channel_id,
579                        DebugBytes(&hash.0),
580                        payment,
581                        err
582                    );
583                    unbalanced.push(hash);
584                }
585            }
586        }
587
588        if !unbalanced.is_empty() {
589            policy_err!(
590                validator,
591                "policy-commitment-htlc-routing-balance",
592                "unbalanced payments on channel {}: {:?}",
593                channel_id,
594                unbalanced.into_iter().map(|h| h.0.to_hex()).collect::<Vec<_>>()
595            );
596        }
597
598        if validator.enforce_balance() {
599            info!(
600                "{} validate payments adjust excess {} +{} -{}",
601                self.log_prefix, self.excess_amount, balance_delta.1, balance_delta.0
602            );
603            self.excess_amount
604                .checked_add(balance_delta.1)
605                .expect("overflow")
606                .checked_sub(balance_delta.0)
607                .ok_or_else(|| {
608                    // policy-routing-deltas-only-htlc
609                    policy_error(
610                        "policy-routing-balanced",
611                        format!(
612                            "shortfall {} + {} - {}",
613                            self.excess_amount, balance_delta.1, balance_delta.0
614                        ),
615                    )
616                })?;
617        }
618        *debug_on_return = false;
619        Ok(())
620    }
621
622    /// Apply outgoing in-flight payment amounts as a result of a new commitment tx.
623    /// Must call [NodeState::validate_payments] first.
624    pub fn apply_payments(
625        &mut self,
626        channel_id: &ChannelId,
627        incoming_payment_summary: &Map<PaymentHash, u64>,
628        outgoing_payment_summary: &Map<PaymentHash, u64>,
629        balance_delta: &BalanceDelta,
630        validator: Arc<dyn Validator>,
631        commit_info: Option<&CommitmentInfo2>,
632    ) {
633        debug!("applying payments on channel {}", channel_id);
634
635        let mut hashes: UnorderedSet<&PaymentHash> = UnorderedSet::new();
636        hashes.extend(incoming_payment_summary.keys());
637        hashes.extend(outgoing_payment_summary.keys());
638
639        let mut fulfilled_issued_invoices = Vec::new();
640
641        // Preflight check
642        for hash_r in hashes.iter() {
643            let hash = **hash_r;
644            let payment = self.payments.entry(hash).or_insert_with(|| RoutedPayment::new());
645            if let Some(issued) = self.issued_invoices.get(&hash) {
646                if !payment.is_fulfilled() {
647                    let incoming_for_chan_sat =
648                        incoming_payment_summary.get(&hash).map(|a| *a).unwrap_or(0);
649                    let outgoing_for_chan_sat =
650                        outgoing_payment_summary.get(&hash).map(|a| *a).unwrap_or(0);
651                    let (incoming_sat, outgoing_sat) = payment.updated_incoming_outgoing(
652                        channel_id,
653                        incoming_for_chan_sat,
654                        outgoing_for_chan_sat,
655                    );
656                    if incoming_sat >= outgoing_sat + issued.amount_msat / 1000 {
657                        fulfilled_issued_invoices.push(hash);
658                    }
659                }
660            }
661        }
662
663        for hash in fulfilled_issued_invoices.iter() {
664            if let Some(issued) = self.issued_invoices.get_mut(hash) {
665                issued.is_fulfilled = true;
666            }
667        }
668
669        if validator.enforce_balance() {
670            info!(
671                "{} apply payments adjust excess {} +{} -{}",
672                self.log_prefix, self.excess_amount, balance_delta.1, balance_delta.0
673            );
674            let excess_amount = self
675                .excess_amount
676                .checked_add(balance_delta.1)
677                .expect("overflow")
678                .checked_sub(balance_delta.0)
679                .expect("validation didn't catch underflow");
680            for hash in fulfilled_issued_invoices.iter() {
681                debug!("mark issued invoice {} as fulfilled", hash.0.to_hex());
682                let payment = self.payments.get_mut(&*hash).expect("already checked");
683                // Mark as fulfilled by setting a dummy preimage.
684                // This has the side-effect of the payment amount not being added
685                // to the excess_amount, because we set the preimage after the balance
686                // delta has already been calculated.
687                payment.preimage = Some(PaymentPreimage([0; 32]));
688            }
689            self.excess_amount = excess_amount;
690        }
691
692        debug!(
693            "applying incoming payments from channel {} - {:?}",
694            channel_id, incoming_payment_summary
695        );
696
697        for hash_r in hashes.iter() {
698            let hash = **hash_r;
699            let incoming_sat = incoming_payment_summary.get(&hash).map(|a| *a).unwrap_or(0);
700            let outgoing_sat = outgoing_payment_summary.get(&hash).map(|a| *a).unwrap_or(0);
701            let payment = self.payments.get_mut(&hash).expect("created above");
702
703            let (incoming_cltv, outgoing_cltv) = if let Some(info) = commit_info {
704                // For counterparty commitment: offered=incoming (counterparty offers to us),
705                //                              received=outgoing (counterparty receives from us)
706                // For holder commitment: offered=outgoing (we offer to counterparty),
707                //                        received=incoming (we receive from counterparty)
708                let (incoming_htlcs, outgoing_htlcs) = if info.is_counterparty_broadcaster {
709                    (&info.offered_htlcs, &info.received_htlcs)
710                } else {
711                    (&info.received_htlcs, &info.offered_htlcs)
712                };
713                let inc_cltv = incoming_htlcs
714                    .iter()
715                    .filter(|h| h.payment_hash == hash)
716                    .map(|h| h.cltv_expiry)
717                    .min();
718                let out_cltv = outgoing_htlcs
719                    .iter()
720                    .filter(|h| h.payment_hash == hash)
721                    .map(|h| h.cltv_expiry)
722                    .max();
723                (inc_cltv, out_cltv)
724            } else {
725                (None, None)
726            };
727
728            payment.apply(channel_id, incoming_sat, outgoing_sat, incoming_cltv, outgoing_cltv);
729        }
730
731        trace_node_state!(self);
732    }
733
734    /// Fulfills an HTLC.
735    /// Performs bookkeeping on any invoice or routed payment with this payment hash.
736    pub fn htlc_fulfilled(
737        &mut self,
738        channel_id: &ChannelId,
739        preimage: PaymentPreimage,
740        validator: Arc<dyn Validator>,
741    ) -> bool {
742        let payment_hash = PaymentHash(Sha256Hash::hash(&preimage.0).to_byte_array());
743        let mut fulfilled = false;
744        if let Some(issued) = self.issued_invoices.get_mut(&payment_hash) {
745            if !issued.is_fulfilled {
746                issued.is_fulfilled = true;
747                fulfilled = true;
748            }
749        }
750        if let Some(payment) = self.payments.get_mut(&payment_hash) {
751            // Getting an HTLC preimage moves HTLC values to the virtual balance of the recipient
752            // on both input and output.
753            // We gain the difference between the input and the output amounts,
754            // so record that in the excess_amount register.
755            // However, when we pay an invoice, the excess_amount is not
756            // updated.
757            if payment.preimage.is_some() {
758                info!(
759                    "{} duplicate preimage {} on channel {}",
760                    self.log_prefix,
761                    payment_hash.0.to_hex(),
762                    channel_id
763                );
764            } else {
765                let (incoming, outgoing) = payment.incoming_outgoing();
766                if self.invoices.contains_key(&payment_hash) {
767                    if incoming > 0 {
768                        info!(
769                            "{} preimage invoice+routing {} +{} -{} msat",
770                            self.log_prefix,
771                            payment_hash.0.to_hex(),
772                            incoming,
773                            outgoing
774                        )
775                    } else {
776                        info!(
777                            "{} preimage invoice {} -{} msat",
778                            self.log_prefix,
779                            payment_hash.0.to_hex(),
780                            outgoing
781                        )
782                    }
783                } else {
784                    info!(
785                        "{} preimage routing {} adjust excess {} +{} -{} msat",
786                        self.log_prefix,
787                        payment_hash.0.to_hex(),
788                        self.excess_amount,
789                        incoming,
790                        outgoing
791                    );
792                    if validator.enforce_balance() {
793                        self.excess_amount =
794                            self.excess_amount.checked_add(incoming).expect("overflow");
795                        // TODO(519) convert to checked error
796                        self.excess_amount =
797                            self.excess_amount.checked_sub(outgoing).expect("underflow");
798                    }
799                }
800                payment.preimage = Some(preimage);
801                fulfilled = true;
802            }
803        }
804        fulfilled
805    }
806
807    fn prune_time(pstate: &PaymentState) -> Duration {
808        let mut prune = Duration::from_secs(0);
809        prune += match pstate.payment_type {
810            PaymentType::Invoice => INVOICE_PRUNE_TIME,
811            PaymentType::Keysend => KEYSEND_PRUNE_TIME,
812        };
813        #[cfg(feature = "timeless_workaround")]
814        {
815            prune += INVOICE_AHEAD_TOLERANCE
816        }
817        prune
818    }
819
820    fn prune_issued_invoices(&mut self, now: Duration) -> bool {
821        let mut modified = false;
822        self.issued_invoices.retain(|hash, issued| {
823            let keep =
824                issued.duration_since_epoch + issued.expiry_duration + Self::prune_time(issued)
825                    > now;
826            if !keep {
827                info!(
828                    "pruning {} {:?} from issued_invoices",
829                    issued.payment_type.to_string(),
830                    DebugBytes(&hash.0)
831                );
832                modified = true;
833            }
834            keep
835        });
836        modified
837    }
838
839    fn prune_invoices(&mut self, now: Duration) -> bool {
840        let invoices = &mut self.invoices;
841        let payments = &mut self.payments;
842        let prune: UnorderedSet<_> = invoices
843            .iter_mut()
844            .filter_map(|(hash, payment_state)| {
845                let payments =
846                    payments.get(hash).unwrap_or_else(|| {
847                        // we create a payment struct for each invoice
848                        panic!(
849                            "missing payments struct for {}",
850                            payment_state.payment_type.to_string(),
851                        )
852                    });
853                if Self::is_invoice_prunable(now, hash, payment_state, payments) {
854                    Some(*hash)
855                } else {
856                    None
857                }
858            })
859            .collect();
860
861        let mut modified = false;
862        invoices.retain(|hash, state| {
863            let keep = !prune.contains(hash);
864            if !keep {
865                info!(
866                    "pruning {} {:?} from invoices",
867                    state.payment_type.to_string(),
868                    DebugBytes(&hash.0)
869                );
870                modified = true;
871            }
872            keep
873        });
874        payments.retain(|hash, _| {
875            let keep = !prune.contains(hash);
876            if !keep {
877                info!(
878                    "pruning {:?} from payments because invoice/keysend expired",
879                    DebugBytes(&hash.0)
880                );
881                modified = true;
882            }
883            keep
884        });
885        modified
886    }
887
888    fn prune_forwarded_payments(&mut self) -> bool {
889        let payments = &mut self.payments;
890        let invoices = &self.invoices;
891        let issued_invoices = &self.issued_invoices;
892        let mut modified = false;
893        payments.retain(|hash, payment| {
894            let keep =
895                !Self::is_forwarded_payment_prunable(hash, invoices, issued_invoices, payment);
896            if !keep {
897                info!("pruning {:?} from payments because forward has ended", DebugBytes(&hash.0));
898                modified = true;
899            }
900            keep
901        });
902        modified
903    }
904
905    fn is_invoice_prunable(
906        now: Duration,
907        hash: &PaymentHash,
908        state: &PaymentState,
909        payment: &RoutedPayment,
910    ) -> bool {
911        let is_payment_complete = payment.is_fulfilled() || payment.is_no_outgoing();
912        let is_past_prune_time =
913            now > state.duration_since_epoch + state.expiry_duration + Self::prune_time(state);
914        // warn if past prune time but incomplete
915        if is_past_prune_time && !is_payment_complete {
916            warn!(
917                "{} {:?} is past prune time but there are still pending outgoing payments",
918                state.payment_type.to_string(),
919                DebugBytes(&hash.0)
920            );
921        }
922        is_past_prune_time && is_payment_complete
923    }
924
925    fn is_forwarded_payment_prunable(
926        hash: &PaymentHash,
927        invoices: &Map<PaymentHash, PaymentState>,
928        issued_invoices: &Map<PaymentHash, PaymentState>,
929        payment: &RoutedPayment,
930    ) -> bool {
931        invoices.get(hash).is_none()
932            && issued_invoices.get(hash).is_none()
933            && payment.is_no_incoming()
934            && payment.is_no_outgoing()
935    }
936}
937
938/// Allowlist entry
939#[derive(Eq, PartialEq, Hash, Clone, PartialOrd, Ord)]
940pub enum Allowable {
941    /// A layer-1 destination
942    Script(ScriptBuf),
943    /// A layer-1 xpub destination
944    XPub(Xpub),
945    /// A layer-2 payee (node_id)
946    Payee(PublicKey),
947}
948
949/// Convert to String for a specified Bitcoin network type
950pub trait ToStringForNetwork {
951    /// Convert to String for a specified Bitcoin network type
952    fn to_string(&self, network: Network) -> String;
953}
954
955impl ToStringForNetwork for Allowable {
956    fn to_string(&self, network: Network) -> String {
957        match self {
958            Allowable::Script(script) => {
959                let addr_res = Address::from_script(&script, network);
960                addr_res
961                    .map(|a| format!("address:{}", a.to_string()))
962                    .unwrap_or_else(|_| format!("invalid_script:{}", script.to_hex_string()))
963            }
964            Allowable::Payee(pubkey) => format!("payee:{}", pubkey.to_string()),
965            Allowable::XPub(xpub) => {
966                format!("xpub:{}", xpub.to_string())
967            }
968        }
969    }
970}
971
972impl Allowable {
973    /// Convert from string, while checking that the network matches
974    pub fn from_str(s: &str, network: Network) -> Result<Allowable, String> {
975        let mut splits = s.splitn(2, ":");
976        let prefix = splits.next().ok_or_else(|| "empty Allowable")?;
977        if let Some(body) = splits.next() {
978            if prefix == "address" {
979                let address = Address::from_str(body)
980                    .map_err(|_| s.to_string())?
981                    .require_network(network)
982                    .map_err(|_| format!("{}: expected network {}", s, network))?;
983                Ok(Allowable::Script(address.script_pubkey()))
984            } else if prefix == "payee" {
985                let pubkey = PublicKey::from_str(body).map_err(|_| s.to_string())?;
986                Ok(Allowable::Payee(pubkey))
987            } else if prefix == "xpub" {
988                let xpub = Xpub::from_str(body).map_err(|_| s.to_string())?;
989                if xpub.network != network.into() {
990                    return Err(format!("{}: expected network {}", s, network));
991                }
992                Ok(Allowable::XPub(xpub))
993            } else {
994                Err(s.to_string())
995            }
996        } else {
997            let address = Address::from_str(prefix)
998                .map_err(|_| s.to_string())?
999                .require_network(network)
1000                .map_err(|_| format!("{}: expected network {}", s, network))?;
1001            Ok(Allowable::Script(address.script_pubkey()))
1002        }
1003    }
1004
1005    /// Convert to a scriptpubkey
1006    /// Will error if this is a bare pubkey (Lightning payee)
1007    pub fn to_script(self) -> Result<ScriptBuf, ()> {
1008        match self {
1009            Allowable::Script(script) => Ok(script),
1010            _ => Err(()),
1011        }
1012    }
1013}
1014
1015/// A signer heartbeat message.
1016///
1017/// This includes information that determines if we think our
1018/// view of the blockchain is stale or not.
1019#[derive(Debug, Encodable, Decodable)]
1020pub struct Heartbeat {
1021    /// the block hash of the blockchain tip
1022    pub chain_tip: bitcoin::BlockHash,
1023    /// the height of the blockchain tip
1024    pub chain_height: u32,
1025    /// the block timestamp of the tip of the blockchain
1026    pub chain_timestamp: u32,
1027    /// the current time
1028    pub current_timestamp: u32,
1029}
1030
1031impl Heartbeat {
1032    /// Compute heartbeat hash
1033    pub fn sighash(&self) -> Message {
1034        let mut sha = Sha256Hash::engine();
1035        sha.input(b"vls");
1036        sha.input(b"heartbeat");
1037        sha.input(self.chain_tip.as_byte_array());
1038        sha.input(&self.chain_height.to_be_bytes());
1039        sha.input(&self.chain_timestamp.to_be_bytes());
1040        sha.input(&self.current_timestamp.to_be_bytes());
1041        let hash = Sha256Hash::from_engine(sha);
1042        Message::from_digest(hash.to_byte_array())
1043    }
1044}
1045
1046/// A signed heartbeat message.
1047#[derive(Encodable, Decodable)]
1048pub struct SignedHeartbeat {
1049    /// the schnorr signature of the heartbeat
1050    pub signature: Vec<u8>,
1051    /// the heartbeat
1052    pub heartbeat: Heartbeat,
1053}
1054
1055impl Debug for SignedHeartbeat {
1056    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1057        f.debug_struct("SignedHeartbeat")
1058            .field("signature", &DebugBytes(&self.signature))
1059            .field("heartbeat", &self.heartbeat)
1060            .finish()
1061    }
1062}
1063
1064impl SignedHeartbeat {
1065    /// Get the hash of the heartbeat for signing
1066    pub fn sighash(&self) -> Message {
1067        self.heartbeat.sighash()
1068    }
1069
1070    /// Verify the heartbeat signature
1071    pub fn verify(&self, pubkey: &PublicKey, secp: &Secp256k1<secp256k1::All>) -> bool {
1072        match schnorr::Signature::from_slice(&self.signature) {
1073            Ok(signature) => {
1074                let xpubkey = XOnlyPublicKey::from(pubkey.clone());
1075                secp.verify_schnorr(&signature, &self.sighash(), &xpubkey).is_ok()
1076            }
1077            Err(_) => false,
1078        }
1079    }
1080}
1081
1082/// A signer for one Lightning node.
1083///
1084/// ```rust
1085/// use std::sync::Arc;
1086///
1087/// use lightning_signer::channel::{ChannelSlot, ChannelBase};
1088/// use lightning_signer::node::{Node, NodeConfig, NodeServices, SyncLogger};
1089/// use lightning_signer::persist::{DummyPersister, Persist};
1090/// use lightning_signer::policy::simple_validator::SimpleValidatorFactory;
1091/// use lightning_signer::signer::ClockStartingTimeFactory;
1092/// use lightning_signer::signer::derive::KeyDerivationStyle;
1093/// use lightning_signer::util::clock::StandardClock;
1094/// use lightning_signer::bitcoin;
1095/// use bitcoin::Network;
1096///
1097/// let persister: Arc<dyn Persist> = Arc::new(DummyPersister {});
1098/// let seed = [0; 32];
1099/// let config = NodeConfig {
1100///     network: Network::Testnet,
1101///     key_derivation_style: KeyDerivationStyle::Native,
1102///     use_checkpoints: true,
1103///     allow_deep_reorgs: true, // not for production
1104/// };
1105/// let validator_factory = Arc::new(SimpleValidatorFactory::new());
1106/// let starting_time_factory = ClockStartingTimeFactory::new();
1107/// let clock = Arc::new(StandardClock());
1108/// let services = NodeServices {
1109///     validator_factory,
1110///     starting_time_factory,
1111///     persister,
1112///     clock,
1113///     trusted_oracle_pubkeys: vec![],
1114/// };
1115/// let node = Arc::new(Node::new(config, &seed, vec![], services));
1116/// // TODO: persist the seed
1117/// let (channel_id, opt_stub) = node.new_channel_with_random_id(&node).expect("new channel");
1118/// assert!(opt_stub.is_some());
1119/// let channel_slot_mutex = node.get_channel(&channel_id).expect("get channel");
1120/// let channel_slot = channel_slot_mutex.lock().expect("lock");
1121/// match &*channel_slot {
1122///     ChannelSlot::Stub(stub) => {
1123///         // Do things with the stub, such as readying it or getting the points
1124///         let holder_basepoints = stub.get_channel_basepoints();
1125///     }
1126///     ChannelSlot::Ready(_) => panic!("expected a stub")
1127/// }
1128/// ```
1129pub struct Node {
1130    secp_ctx: Secp256k1<secp256k1::All>,
1131    pub(crate) node_config: NodeConfig,
1132    pub(crate) keys_manager: MyKeysManager,
1133    channels: Mutex<OrderedMap<ChannelId, Arc<Mutex<ChannelSlot>>>>,
1134    // This is Mutex because we want to be able to replace it on the fly
1135    pub(crate) validator_factory: Mutex<Arc<dyn ValidatorFactory>>,
1136    pub(crate) persister: Arc<dyn Persist>,
1137    pub(crate) clock: Arc<dyn Clock>,
1138    tracker: Mutex<ChainTracker<ChainMonitor>>,
1139    pub(crate) state: Mutex<NodeState>,
1140    node_id: PublicKey,
1141}
1142
1143/// Various services the Node uses
1144#[derive(Clone)]
1145pub struct NodeServices {
1146    /// The validator factory
1147    pub validator_factory: Arc<dyn ValidatorFactory>,
1148    /// The starting time factory
1149    pub starting_time_factory: Arc<dyn StartingTimeFactory>,
1150    /// The persister
1151    pub persister: Arc<dyn Persist>,
1152    /// Clock source
1153    pub clock: Arc<dyn Clock>,
1154    /// public keys of trusted TXO oracle
1155    pub trusted_oracle_pubkeys: Vec<PublicKey>,
1156}
1157
1158impl Wallet for Node {
1159    fn can_spend(
1160        &self,
1161        child_path: &DerivationPath,
1162        script_pubkey: &ScriptBuf,
1163    ) -> Result<bool, Status> {
1164        // If there is no path we can't spend it ...
1165        if child_path.len() == 0 {
1166            return Ok(false);
1167        }
1168
1169        let pubkey = self.get_wallet_pubkey(child_path)?;
1170
1171        // Lightning layer-1 wallets can spend native segwit or wrapped segwit addresses.
1172        // these can only fail with uncompressed keys, which we never generate
1173        let native_addr = Address::p2wpkh(&pubkey, self.network());
1174        let wrapped_addr = Address::p2shwpkh(&pubkey, self.network());
1175        let untweaked_pubkey = UntweakedPublicKey::from(pubkey.0);
1176
1177        // FIXME(520) it is not recommended to use the same xpub for both schnorr and ECDSA
1178        let taproot_addr = Address::p2tr(&self.secp_ctx, untweaked_pubkey, None, self.network());
1179
1180        Ok(*script_pubkey == native_addr.script_pubkey()
1181            || *script_pubkey == wrapped_addr.script_pubkey()
1182            || *script_pubkey == taproot_addr.script_pubkey())
1183    }
1184
1185    fn get_native_address(&self, child_path: &DerivationPath) -> Result<Address, Status> {
1186        if child_path.len() == 0 {
1187            return Err(invalid_argument("empty child path"));
1188        }
1189
1190        let pubkey = self.get_wallet_pubkey(child_path)?;
1191        // can only fail with uncompressed keys, which we never generate
1192        Ok(Address::p2wpkh(&pubkey, self.network()))
1193    }
1194
1195    fn get_taproot_address(&self, child_path: &DerivationPath) -> Result<Address, Status> {
1196        if child_path.len() == 0 {
1197            return Err(invalid_argument("empty child path"));
1198        }
1199
1200        let pubkey = self.get_wallet_pubkey(child_path)?;
1201        let untweaked_pubkey = UntweakedPublicKey::from(pubkey.0);
1202        Ok(Address::p2tr(&self.secp_ctx, untweaked_pubkey, None, self.network()))
1203    }
1204
1205    fn get_wrapped_address(&self, child_path: &DerivationPath) -> Result<Address, Status> {
1206        if child_path.len() == 0 {
1207            return Err(invalid_argument("empty child path"));
1208        }
1209
1210        let pubkey = self.get_wallet_pubkey(child_path)?;
1211        // can only fail with uncompressed keys, which we never generate
1212        Ok(Address::p2shwpkh(&pubkey, self.network()))
1213    }
1214
1215    fn allowlist_contains_payee(&self, payee: PublicKey) -> bool {
1216        self.get_state().allowlist.contains(&Allowable::Payee(payee))
1217    }
1218
1219    fn allowlist_contains(&self, script_pubkey: &ScriptBuf, path: &DerivationPath) -> bool {
1220        let state = self.get_state();
1221        if state.allowlist.contains(&Allowable::Script(script_pubkey.clone())) {
1222            return true;
1223        }
1224
1225        if path.is_empty() {
1226            return false;
1227        }
1228
1229        for a in state.allowlist.iter() {
1230            if let Allowable::XPub(xp) = a {
1231                // cannot fail because we did not generate hardened paths
1232                let pubkey =
1233                    CompressedPublicKey(xp.derive_pub(&Secp256k1::new(), path).unwrap().public_key);
1234
1235                // this is infallible because the pubkey is compressed
1236                if *script_pubkey == Address::p2wpkh(&pubkey, self.network()).script_pubkey() {
1237                    return true;
1238                }
1239
1240                if *script_pubkey == Address::p2pkh(&pubkey, self.network()).script_pubkey() {
1241                    return true;
1242                }
1243
1244                // FIXME(520) it is not recommended to use the same xpub for both schnorr and ECDSA
1245                let untweaked_pubkey = UntweakedPublicKey::from(pubkey.0);
1246                if *script_pubkey
1247                    == Address::p2tr(&self.secp_ctx, untweaked_pubkey, None, self.network())
1248                        .script_pubkey()
1249                {
1250                    return true;
1251                }
1252            }
1253        }
1254
1255        return false;
1256    }
1257
1258    fn network(&self) -> Network {
1259        self.node_config.network
1260    }
1261}
1262
1263impl Node {
1264    /// Create a node.
1265    ///
1266    /// NOTE: you must persist the node yourself if it is new.
1267    pub fn new(
1268        node_config: NodeConfig,
1269        seed: &[u8],
1270        allowlist: Vec<Allowable>,
1271        services: NodeServices,
1272    ) -> Node {
1273        let policy = services.validator_factory.policy(node_config.network);
1274        let global_velocity_control = Self::make_velocity_control(&policy);
1275        let fee_velocity_control = Self::make_fee_velocity_control(&policy);
1276        let state = NodeState::new(global_velocity_control, fee_velocity_control, allowlist);
1277
1278        let (keys_manager, node_id) = Self::make_keys_manager(&node_config, seed, &services);
1279        let mut tracker = if node_config.use_checkpoints {
1280            ChainTracker::for_network(
1281                node_config.network,
1282                node_id.clone(),
1283                services.validator_factory.clone(),
1284                services.trusted_oracle_pubkeys.clone(),
1285            )
1286        } else {
1287            ChainTracker::from_genesis(
1288                node_config.network,
1289                node_id.clone(),
1290                services.validator_factory.clone(),
1291                services.trusted_oracle_pubkeys.clone(),
1292            )
1293        };
1294        tracker.set_allow_deep_reorgs(node_config.allow_deep_reorgs);
1295
1296        Self::new_full(node_config, services, state, keys_manager, node_id, tracker)
1297    }
1298
1299    /// Update the velocity controls with any spec changes from the policy
1300    pub fn update_velocity_controls(&self) {
1301        let policy = self.validator_factory().policy(self.network());
1302        let mut state = self.get_state();
1303
1304        state.velocity_control.update_spec(&policy.global_velocity_control());
1305        state.fee_velocity_control.update_spec(&policy.fee_velocity_control());
1306        trace_node_state!(state);
1307    }
1308
1309    pub(crate) fn get_node_secret(&self) -> SecretKey {
1310        self.keys_manager.get_node_secret()
1311    }
1312
1313    /// Get an entropy source
1314    pub fn get_entropy_source(&self) -> &dyn EntropySource {
1315        &self.keys_manager
1316    }
1317
1318    /// Clock
1319    pub fn get_clock(&self) -> Arc<dyn Clock> {
1320        Arc::clone(&self.clock)
1321    }
1322
1323    /// Restore a node.
1324    pub fn new_from_persistence(
1325        node_config: NodeConfig,
1326        expected_node_id: &PublicKey,
1327        seed: &[u8],
1328        services: NodeServices,
1329        state: NodeState,
1330    ) -> Arc<Node> {
1331        let (keys_manager, node_id) = Self::make_keys_manager(&node_config, seed, &services);
1332        if node_id != *expected_node_id {
1333            panic!("persisted node_id mismatch: expected {} got {}", expected_node_id, node_id);
1334        }
1335        let (mut tracker, listener_entries) = services
1336            .persister
1337            .get_tracker(node_id.clone(), services.validator_factory.clone())
1338            .expect("tracker not found for node");
1339        tracker.trusted_oracle_pubkeys = services.trusted_oracle_pubkeys.clone();
1340
1341        tracker.set_allow_deep_reorgs(node_config.allow_deep_reorgs);
1342
1343        let persister = services.persister.clone();
1344
1345        let node =
1346            Arc::new(Self::new_full(node_config, services, state, keys_manager, node_id, tracker));
1347        let blockheight = node.get_tracker().height();
1348
1349        let mut listeners = OrderedMap::from_iter(listener_entries.into_iter().map(|e| (e.0, e.1)));
1350
1351        for (channel_id0, channel_entry) in
1352            persister.get_node_channels(&node_id).expect("channels not found for node")
1353        {
1354            let mut channels = node.channels.lock().unwrap();
1355            let channel_id = channel_entry.id;
1356            let enforcement_state = channel_entry.enforcement_state;
1357
1358            info!(
1359                "  Restore channel {} outpoint {:?}",
1360                channel_id0,
1361                channel_entry.channel_setup.as_ref().map(|s| s.funding_outpoint)
1362            );
1363            let (keys, payment_key) = node.keys_manager.get_channel_keys_with_id(
1364                channel_id0.clone(),
1365                channel_entry.channel_value_satoshis,
1366            );
1367            let setup_opt = channel_entry.channel_setup;
1368            match setup_opt {
1369                None => {
1370                    let stub = ChannelStub {
1371                        node: Arc::downgrade(&node),
1372                        secp_ctx: Secp256k1::new(),
1373                        keys,
1374                        payment_key,
1375                        id0: channel_id0.clone(),
1376                        blockheight: channel_entry.blockheight.unwrap_or(blockheight),
1377                    };
1378                    let slot = Arc::new(Mutex::new(ChannelSlot::Stub(stub)));
1379                    channels.insert(channel_id0, Arc::clone(&slot));
1380                    channel_id.map(|id| channels.insert(id, Arc::clone(&slot)));
1381                }
1382                Some(setup) => {
1383                    let funding_outpoint = setup.funding_outpoint;
1384                    // Clone the matching monitor from the chaintracker's listeners.
1385                    // Tracker is persisted with node, so this should not fail.
1386                    let (tracker_state, tracker_slot) =
1387                        listeners.remove(&funding_outpoint).unwrap_or_else(|| {
1388                            panic!("tracker not found for point {}", setup.funding_outpoint)
1389                        });
1390                    let monitor_base = ChainMonitorBase::new_from_persistence(
1391                        funding_outpoint.clone(),
1392                        tracker_state,
1393                        channel_id.as_ref().unwrap_or(&channel_id0),
1394                    );
1395                    let channel = Channel {
1396                        node: Arc::downgrade(&node),
1397                        secp_ctx: Secp256k1::new(),
1398                        keys,
1399                        payment_key,
1400                        enforcement_state,
1401                        setup,
1402                        id0: channel_id0.clone(),
1403                        id: channel_id.clone(),
1404                        monitor: monitor_base.clone(),
1405                    };
1406
1407                    channel.restore_payments();
1408                    let slot = Arc::new(Mutex::new(ChannelSlot::Ready(channel)));
1409                    let provider = Box::new(ChannelCommitmentPointProvider::new(slot.clone()));
1410                    let monitor = monitor_base.as_monitor(provider);
1411                    node.get_tracker().restore_listener(funding_outpoint, monitor, tracker_slot);
1412                    channels.insert(channel_id0, Arc::clone(&slot));
1413                    channel_id.map(|id| channels.insert(id, Arc::clone(&slot)));
1414                }
1415            };
1416            node.keys_manager.increment_channel_id_child_index();
1417        }
1418        if !listeners.is_empty() {
1419            panic!("some chain tracker listeners were not restored: {:?}", listeners);
1420        }
1421        node
1422    }
1423
1424    fn new_full(
1425        node_config: NodeConfig,
1426        services: NodeServices,
1427        state: NodeState,
1428        keys_manager: MyKeysManager,
1429        node_id: PublicKey,
1430        tracker: ChainTracker<ChainMonitor>,
1431    ) -> Node {
1432        let secp_ctx = Secp256k1::new();
1433        let log_prefix = &node_id.to_string()[0..4];
1434
1435        let persister = services.persister;
1436        let clock = services.clock;
1437        let validator_factory = services.validator_factory;
1438        let policy = validator_factory.policy(node_config.network);
1439        let global_velocity_control = Self::make_velocity_control(&policy);
1440        let fee_velocity_control = Self::make_fee_velocity_control(&policy);
1441
1442        let state = Mutex::new(state.with_log_prefix(
1443            global_velocity_control,
1444            fee_velocity_control,
1445            log_prefix.to_string(),
1446        ));
1447
1448        #[cfg(feature = "timeless_workaround")]
1449        {
1450            // WORKAROUND for #206, #339, #235 - If our implementation has no clock use the
1451            // latest BlockHeader timestamp.
1452            let old_now = clock.now();
1453            let new_now = tracker.tip_time();
1454            // Don't allow retrograde time updates ...
1455            if new_now > old_now {
1456                clock.set_workaround_time(new_now);
1457            }
1458        }
1459
1460        Node {
1461            secp_ctx,
1462            node_config,
1463            keys_manager,
1464            channels: Mutex::new(OrderedMap::new()),
1465            validator_factory: Mutex::new(validator_factory),
1466            persister,
1467            clock,
1468            tracker: Mutex::new(tracker),
1469            state,
1470            node_id,
1471        }
1472    }
1473
1474    /// Create a keys manager - useful for bootstrapping a node from persistence, so the
1475    /// persistence key can be derived.
1476    pub fn make_keys_manager(
1477        node_config: &NodeConfig,
1478        seed: &[u8],
1479        services: &NodeServices,
1480    ) -> (MyKeysManager, PublicKey) {
1481        let keys_manager = MyKeysManager::new(
1482            node_config.key_derivation_style,
1483            seed,
1484            node_config.network,
1485            services.starting_time_factory.borrow(),
1486        );
1487        // infallible with Recipient::Node
1488        let node_id = keys_manager.get_node_id(Recipient::Node).unwrap();
1489        (keys_manager, node_id)
1490    }
1491
1492    /// persister
1493    pub fn get_persister(&self) -> Arc<dyn Persist> {
1494        Arc::clone(&self.persister)
1495    }
1496
1497    /// onion reply secret
1498    pub fn get_onion_reply_secret(&self) -> [u8; 32] {
1499        self.keys_manager.get_onion_reply_secret()
1500    }
1501
1502    /// BOLT 12 x-only pubkey
1503    pub fn get_bolt12_pubkey(&self) -> PublicKey {
1504        self.keys_manager.get_bolt12_pubkey()
1505    }
1506
1507    /// persistence pubkey
1508    pub fn get_persistence_pubkey(&self) -> PublicKey {
1509        self.keys_manager.get_persistence_pubkey()
1510    }
1511
1512    /// persistence shared secret
1513    pub fn get_persistence_shared_secret(&self, server_pubkey: &PublicKey) -> [u8; 32] {
1514        self.keys_manager.get_persistence_shared_secret(server_pubkey)
1515    }
1516
1517    /// Persistence auth token
1518    pub fn get_persistence_auth_token(&self, server_pubkey: &PublicKey) -> [u8; 32] {
1519        self.keys_manager.get_persistence_auth_token(server_pubkey)
1520    }
1521
1522    /// BOLT 12 sign
1523    pub fn sign_bolt12(
1524        &self,
1525        messagename: &[u8],
1526        fieldname: &[u8],
1527        merkleroot: &[u8; 32],
1528        publictweak_opt: Option<&[u8]>,
1529    ) -> Result<schnorr::Signature, Status> {
1530        self.keys_manager
1531            .sign_bolt12(messagename, fieldname, merkleroot, publictweak_opt)
1532            .map_err(|_| internal_error("signature operation failed"))
1533    }
1534
1535    /// BOLT 12 sign
1536    pub fn sign_bolt12_2(
1537        &self,
1538        messagename: &[u8],
1539        fieldname: &[u8],
1540        merkleroot: &[u8; 32],
1541        info: &[u8],
1542        publictweak_opt: Option<&[u8]>,
1543    ) -> Result<schnorr::Signature, Status> {
1544        self.keys_manager
1545            .sign_bolt12_2(messagename, fieldname, merkleroot, info, publictweak_opt)
1546            .map_err(|_| internal_error("signature operation failed"))
1547    }
1548
1549    /// derive secret
1550    pub fn derive_secret(&self, info: &[u8]) -> SecretKey {
1551        self.keys_manager.derive_secret(info)
1552    }
1553
1554    /// Set the node's validator factory
1555    pub fn set_validator_factory(&self, validator_factory: Arc<dyn ValidatorFactory>) {
1556        let mut vfac = self.validator_factory();
1557        *vfac = validator_factory;
1558    }
1559
1560    /// Persist everything.
1561    /// This is normally not needed, as the node will persist itself,
1562    /// but may be useful if switching to a new persister.
1563    pub fn persist_all(&self) {
1564        let persister = &self.persister;
1565        // Lock order: state is taken and released on its own, before the channels
1566        // and tracker locks, so it is never held across a channel_slot (see LOCK
1567        // ORDERING). Both state-derived writes are read from one critical section
1568        // so they stay consistent with each other.
1569        let wlvec: Vec<String> = {
1570            let state = self.get_state();
1571            persister.new_node(&self.get_id(), &self.node_config, &*state).unwrap();
1572            state.allowlist.iter().map(|a| a.to_string(self.network())).collect()
1573        };
1574        for channel in self.get_channels().values() {
1575            let channel = channel.lock().unwrap();
1576            match &*channel {
1577                ChannelSlot::Stub(_) => {}
1578                ChannelSlot::Ready(chan) => {
1579                    persister.update_channel(&self.get_id(), &chan).unwrap();
1580                }
1581            }
1582        }
1583        persister.update_tracker(&self.get_id(), &self.get_tracker()).unwrap();
1584        self.persister.update_node_allowlist(&self.get_id(), wlvec).unwrap();
1585    }
1586
1587    /// Get the node ID, which is the same as the node public key
1588    pub fn get_id(&self) -> PublicKey {
1589        self.node_id
1590    }
1591
1592    /// Get suitable node identity string for logging
1593    pub fn log_prefix(&self) -> String {
1594        self.get_id().to_string()[0..4].to_string()
1595    }
1596
1597    /// Lock and return the node state
1598    pub fn get_state(&self) -> MutexGuard<'_, NodeState> {
1599        self.state.lock().unwrap()
1600    }
1601
1602    #[allow(dead_code)]
1603    pub(crate) fn get_secure_random_bytes(&self) -> [u8; 32] {
1604        self.keys_manager.get_secure_random_bytes()
1605    }
1606
1607    /// Get secret key material as bytes for use in encrypting and decrypting inbound payment data.
1608    ///
1609    /// This method must return the same value each time it is called.
1610    pub fn get_inbound_payment_key_material(&self) -> ExpandedKey {
1611        self.keys_manager.get_expanded_key()
1612    }
1613
1614    /// Get the 32-byte peer-storage encryption key derived from the seed. Used by
1615    /// LDK 0.2+ to encrypt our state backup sent to peers; the signer is the only
1616    /// component with the seed, so it's the source of truth for this key.
1617    pub fn get_peer_storage_key_bytes(&self) -> [u8; 32] {
1618        self.keys_manager.get_peer_storage_key().inner
1619    }
1620
1621    /// Seed for LDK's inbound-payment `ExpandedKey`. Only the signer holds the seed, so it is
1622    /// the source of truth; shipped to a remote client in `HsmdInit2Reply`.
1623    pub fn get_inbound_payment_key_bytes(&self) -> [u8; 32] {
1624        self.keys_manager.get_inbound_payment_key_bytes()
1625    }
1626
1627    /// Get the [Mutex] protected channel slot
1628    pub fn get_channel(&self, channel_id: &ChannelId) -> Result<Arc<Mutex<ChannelSlot>>, Status> {
1629        let mut guard = self.get_channels();
1630        let elem = guard.get_mut(channel_id);
1631        let slot_arc =
1632            elem.ok_or_else(|| invalid_argument(format!("no such channel: {}", &channel_id)))?;
1633        Ok(Arc::clone(slot_arc))
1634    }
1635
1636    /// Execute a function with an existing channel.
1637    ///
1638    /// The channel may be a stub or a ready channel.
1639    /// An invalid_argument [Status] will be returned if the channel does not exist.
1640    pub fn with_channel_base<F: Sized, T>(&self, channel_id: &ChannelId, f: F) -> Result<T, Status>
1641    where
1642        F: Fn(&mut dyn ChannelBase) -> Result<T, Status>,
1643    {
1644        let slot_mutex = self.get_channel(channel_id)?;
1645        let mut slot = slot_mutex.lock().unwrap();
1646        let base = match &mut *slot {
1647            ChannelSlot::Stub(stub) => stub as &mut dyn ChannelBase,
1648            ChannelSlot::Ready(chan) => chan as &mut dyn ChannelBase,
1649        };
1650        f(base)
1651    }
1652
1653    /// Execute a function with an existing configured channel.
1654    ///
1655    /// An invalid_argument [Status] will be returned if the channel does not exist.
1656    pub fn with_channel<F: Sized, T>(&self, channel_id: &ChannelId, f: F) -> Result<T, Status>
1657    where
1658        F: FnOnce(&mut Channel) -> Result<T, Status>,
1659    {
1660        let slot_arc = self.get_channel(channel_id)?;
1661        let mut slot = slot_arc.lock().unwrap();
1662        match &mut *slot {
1663            ChannelSlot::Stub(_) =>
1664                Err(invalid_argument(format!("channel not ready: {}", &channel_id))),
1665            ChannelSlot::Ready(chan) => f(chan),
1666        }
1667    }
1668
1669    /// Get a channel given its funding outpoint, or None if no such channel exists.
1670    pub fn find_channel_with_funding_outpoint(
1671        &self,
1672        outpoint: &OutPoint,
1673    ) -> Option<Arc<Mutex<ChannelSlot>>> {
1674        let channels_lock = self.get_channels();
1675        find_channel_with_funding_outpoint(&channels_lock, outpoint)
1676    }
1677
1678    /// Create a new channel, which starts out as a stub.
1679    ///
1680    /// Returns a generated channel ID and the stub.
1681    pub fn new_channel_with_random_id(
1682        &self,
1683        arc_self: &Arc<Node>,
1684    ) -> Result<(ChannelId, Option<ChannelSlot>), Status> {
1685        let channel_id = self.keys_manager.get_channel_id();
1686        self.find_or_create_channel(channel_id, arc_self)
1687    }
1688
1689    /// Create a new channel from a seed identifier (aka a dbid) and
1690    /// a peer node id
1691    ///
1692    /// The seed id must never be reused as revocation secrets may
1693    /// be publicly known. Rather than store all historical ids,
1694    /// this method requires seed ids to increase monotonically,
1695    /// checked against a high-water mark which is set when
1696    /// forgetting channels.
1697    ///
1698    /// Setting the high-water mark on forgetting rather than creating
1699    /// channels allows for some slack in the system to accomodate reordered
1700    /// requests.
1701    ///
1702    /// If the seed id is not monotonic the method returns an error.
1703    /// Otherwise, it returns the new channel id and stub.
1704    pub fn new_channel(
1705        &self,
1706        dbid: u64,
1707        peer_id: &[u8; 33], // TODO figure out a more specific type
1708        arc_self: &Arc<Node>,
1709    ) -> Result<(ChannelId, Option<ChannelSlot>), Status> {
1710        if self.get_state().dbid_high_water_mark >= dbid {
1711            return Err(policy_error(
1712                "policy-channel-original-channel-id-reuse",
1713                format!("original channel id {} is potentially being reused", dbid),
1714            )
1715            .into());
1716        }
1717
1718        let channel_id = ChannelId::new_from_peer_id_and_oid(peer_id, dbid);
1719        self.find_or_create_channel(channel_id, arc_self)
1720    }
1721
1722    /// Create a new channel with a specified channel id.
1723    /// Only used for testing.
1724    #[cfg(any(test, feature = "test_utils"))]
1725    pub(crate) fn new_channel_with_id(
1726        &self,
1727        channel_id: ChannelId,
1728        arc_self: &Arc<Node>,
1729    ) -> Result<(ChannelId, Option<ChannelSlot>), Status> {
1730        self.find_or_create_channel(channel_id, arc_self)
1731    }
1732
1733    fn find_or_create_channel(
1734        &self,
1735        channel_id: ChannelId,
1736        arc_self: &Arc<Node>,
1737    ) -> Result<(ChannelId, Option<ChannelSlot>), Status> {
1738        // Lock order: tracker -> channels (see LOCK ORDERING)
1739        let blockheight = arc_self.get_tracker().height();
1740        let mut channels = self.get_channels();
1741        let policy = self.policy();
1742        if channels.len() >= policy.max_channels() {
1743            // FIXME(3) we don't garbage collect channels
1744            return Err(failed_precondition(format!(
1745                "too many channels ({} >= {})",
1746                channels.len(),
1747                policy.max_channels()
1748            )));
1749        }
1750
1751        // Is there an existing channel slot?
1752        let maybe_slot = channels.get(&channel_id);
1753        if let Some(slot) = maybe_slot {
1754            let slot = slot.lock().unwrap().clone();
1755            return Ok((channel_id, Some(slot)));
1756        }
1757
1758        let channel_value_sat = 0; // Placeholder value, not known yet.
1759        let (keys, payment_key) =
1760            self.keys_manager.get_channel_keys_with_id(channel_id.clone(), channel_value_sat);
1761
1762        let stub = ChannelStub {
1763            node: Arc::downgrade(arc_self),
1764            secp_ctx: Secp256k1::new(),
1765            keys,
1766            payment_key,
1767            id0: channel_id.clone(),
1768            blockheight,
1769        };
1770        // TODO(507) this clone is expensive
1771        channels.insert(channel_id.clone(), Arc::new(Mutex::new(ChannelSlot::Stub(stub.clone()))));
1772        self.persister
1773            .new_channel(&self.get_id(), &stub)
1774            // Persist.new_channel should only fail if the channel was previously persisted.
1775            // So if it did fail, we have an internal error.
1776            .expect("channel was in storage but not in memory");
1777        Ok((channel_id.clone(), Some(ChannelSlot::Stub(stub))))
1778    }
1779
1780    /// Restore a node from a persisted [NodeEntry].
1781    ///
1782    /// You can get the [NodeEntry] from [Persist::get_nodes].
1783    ///
1784    /// The channels are also restored from the `persister`.
1785    // unit test coverage outside crate
1786    pub fn restore_node(
1787        node_id: &PublicKey,
1788        node_entry: NodeEntry,
1789        seed: &[u8],
1790        services: NodeServices,
1791    ) -> Result<Arc<Node>, Status> {
1792        let network = Network::from_str(node_entry.network.as_str())
1793            .expect("bad node network in persistence");
1794        let allow_deep_reorgs = if network == Network::Testnet { true } else { false };
1795        let key_derivation_style = KeyDerivationStyle::try_from(node_entry.key_derivation_style)
1796            .expect("bad key derivation in peristence");
1797        let config =
1798            NodeConfig { network, key_derivation_style, use_checkpoints: true, allow_deep_reorgs };
1799
1800        let persister = services.persister.clone();
1801        let allowlist: Vec<Allowable> = persister
1802            .get_node_allowlist(node_id)
1803            .expect("missing node allowlist in persistence")
1804            .iter()
1805            .map(|e| Allowable::from_str(e, network))
1806            .collect::<Result<_, _>>()
1807            .expect("persisted allowable could not be parsed");
1808
1809        let mut state = node_entry.state;
1810
1811        state.allowlist = allowlist.into_iter().collect();
1812
1813        // create a payment state for each invoice state
1814        for h in state.invoices.keys() {
1815            state.payments.insert(*h, RoutedPayment::new());
1816        }
1817
1818        let node = Node::new_from_persistence(config, node_id, seed, services, state);
1819        assert_eq!(&node.get_id(), node_id);
1820        info!("Restore node {} on {}", node_id, config.network);
1821        if let Some((height, _hash, filter_header, header)) = get_latest_checkpoint(network) {
1822            let mut tracker = node.get_tracker();
1823            if tracker.height() == 0 {
1824                // Fast-forward the tracker to the checkpoint
1825                tracker.headers = VecDeque::new();
1826                tracker.tip = Headers(header, filter_header);
1827                tracker.height = height;
1828            }
1829        }
1830
1831        node.maybe_sync_persister()?;
1832        Ok(node)
1833    }
1834
1835    fn maybe_sync_persister(&self) -> Result<(), Status> {
1836        if self.persister.on_initial_restore() {
1837            // write everything to persister, to ensure that any composite
1838            // persister has all sub-persisters in sync
1839            //
1840            // Lock order: state is released before the tracker and channels locks,
1841            // so it is never held across a channel_slot (see LOCK ORDERING).
1842            let wlvec: Vec<String> = {
1843                let state = self.get_state();
1844                // do a new_node here, because update_node doesn't store the entry,
1845                // only the state
1846                self.persister
1847                    .new_node(&self.get_id(), &self.node_config, &*state)
1848                    .map_err(|_| internal_error("sync persist failed"))?;
1849
1850                state.allowlist.iter().map(|a| a.to_string(self.network())).collect()
1851            };
1852            self.persister
1853                .update_node_allowlist(&self.get_id(), wlvec)
1854                .map_err(|_| internal_error("sync persist failed"))?;
1855
1856            {
1857                let tracker = self.get_tracker();
1858                self.persister
1859                    .update_tracker(&self.get_id(), &tracker)
1860                    .map_err(|_| internal_error("tracker persist failed"))?;
1861            }
1862            let channels = self.get_channels();
1863            for (_, slot) in channels.iter() {
1864                let channel = slot.lock().unwrap();
1865                match &*channel {
1866                    ChannelSlot::Stub(_) => {}
1867                    ChannelSlot::Ready(c) => {
1868                        self.persister
1869                            .update_channel(&self.get_id(), c)
1870                            .map_err(|_| internal_error("sync persist failed"))?;
1871                    }
1872                }
1873            }
1874        }
1875        Ok(())
1876    }
1877
1878    /// Restore all nodes from `persister`.
1879    ///
1880    /// The channels of each node are also restored.
1881    // unit test coverage outside crate
1882    pub fn restore_nodes(
1883        services: NodeServices,
1884        seed_persister: Arc<dyn SeedPersist>,
1885    ) -> Result<Map<PublicKey, Arc<Node>>, Status> {
1886        let mut nodes = Map::new();
1887        let persister = services.persister.clone();
1888        let mut seeds = OrderedSet::from_iter(seed_persister.list().into_iter());
1889        for (node_id, node_entry) in
1890            persister.get_nodes().expect("could not get nodes from persistence")
1891        {
1892            let seed = seed_persister
1893                .get(&node_id.serialize().to_hex())
1894                .expect(format!("no seed for node {:?}", node_id).as_str());
1895            let node = Node::restore_node(&node_id, node_entry, &seed, services.clone())?;
1896            nodes.insert(node_id, node);
1897            seeds.remove(&node_id.serialize().to_hex());
1898        }
1899        if !seeds.is_empty() {
1900            warn!("some seeds had no persisted node state: {:?}", seeds);
1901        }
1902        Ok(nodes)
1903    }
1904
1905    /// Setup a new channel, making it available for use.
1906    ///
1907    /// This populates fields that are known later in the channel creation flow,
1908    /// such as fields that are supplied by the counterparty and funding outpoint.
1909    ///
1910    /// * `channel_id0` - the original channel ID supplied to [`Node::new_channel`]
1911    /// * `opt_channel_id` - the permanent channel ID
1912    ///
1913    /// The channel is promoted from a [ChannelStub] to a [Channel].
1914    /// After this call, the channel may be referred to by either ID.
1915    pub fn setup_channel(
1916        &self,
1917        channel_id0: ChannelId,
1918        opt_channel_id: Option<ChannelId>,
1919        setup: ChannelSetup,
1920        holder_shutdown_key_path: &DerivationPath,
1921    ) -> Result<Channel, Status> {
1922        // Lock order: tracker -> channels -> channel_slot (see LOCK ORDERING)
1923        let mut tracker = self.get_tracker();
1924        let validator = self.validator_factory().make_validator(
1925            self.network(),
1926            self.get_id(),
1927            Some(channel_id0.clone()),
1928        );
1929
1930        // If a permanent channel_id was provided use it, otherwise
1931        // continue with the initial channel_id0.
1932        let chan_id = opt_channel_id.as_ref().unwrap_or(&channel_id0);
1933
1934        let chan = {
1935            let channels = self.get_channels();
1936            let arcobj = channels.get(&channel_id0).ok_or_else(|| {
1937                invalid_argument(format!("channel does not exist: {}", channel_id0))
1938            })?;
1939            let slot = arcobj.lock().unwrap();
1940            let stub: &ChannelStub = match &*slot {
1941                ChannelSlot::Stub(stub) => stub,
1942                ChannelSlot::Ready(c) => {
1943                    if c.setup != setup {
1944                        return Err(invalid_argument(format!(
1945                            "channel already ready with different setup: {}",
1946                            channel_id0
1947                        )));
1948                    }
1949                    return Ok(c.clone());
1950                }
1951            };
1952            let (keys, payment_key) = stub.channel_keys();
1953            let funding_outpoint = setup.funding_outpoint;
1954            let monitor = ChainMonitorBase::new(funding_outpoint, tracker.height(), chan_id);
1955            monitor.add_funding_outpoint(&funding_outpoint);
1956            let to_holder_msat = if setup.is_outbound {
1957                // This is also checked in the validator, but we have to check
1958                // here because we need it to create the validator
1959                (setup.channel_value_sat * 1000).checked_sub(setup.push_value_msat).ok_or_else(
1960                    || {
1961                        policy_error(
1962                            "policy-routing-balanced",
1963                            format!(
1964                                "beneficial channel value underflow: {} - {}",
1965                                setup.channel_value_sat * 1000,
1966                                setup.push_value_msat
1967                            ),
1968                        )
1969                    },
1970                )?
1971            } else {
1972                setup.push_value_msat
1973            };
1974            let initial_holder_value_sat = validator.minimum_initial_balance(to_holder_msat);
1975            let enforcement_state = EnforcementState::new(initial_holder_value_sat);
1976            Channel {
1977                node: Weak::clone(&stub.node),
1978                secp_ctx: stub.secp_ctx.clone(),
1979                keys,
1980                payment_key,
1981                enforcement_state,
1982                setup: setup.clone(),
1983                id0: channel_id0.clone(),
1984                id: opt_channel_id.clone(),
1985                monitor,
1986            }
1987        };
1988
1989        validator.validate_setup_channel(self, &setup, holder_shutdown_key_path)?;
1990
1991        let mut channels = self.get_channels();
1992
1993        // Wrap the ready channel with an arc so we can potentially
1994        // refer to it multiple times.
1995        // TODO(507) this clone is expensive
1996        let chan_arc = Arc::new(Mutex::new(ChannelSlot::Ready(chan.clone())));
1997
1998        let commitment_point_provider = ChannelCommitmentPointProvider::new(chan_arc.clone());
1999
2000        // Associate the new ready channel with the channel id.
2001        channels.insert(chan_id.clone(), chan_arc.clone());
2002
2003        // If we are using a new permanent channel_id additionally
2004        // associate the channel with the original (initial)
2005        // channel_id as well.
2006        if channel_id0 != *chan_id {
2007            channels.insert(channel_id0, chan_arc.clone());
2008        }
2009
2010        // Watch the funding outpoint, because we might not have any funding
2011        // inputs that are ours.
2012        // Note that the functional tests also have no inputs for the funder's tx
2013        // which might be a problem in the future with more validation.
2014        tracker.add_listener(
2015            chan.monitor.as_monitor(Box::new(commitment_point_provider)),
2016            OrderedSet::from_iter(vec![setup.funding_outpoint.txid]),
2017        );
2018
2019        dbgvals!(&chan.setup);
2020        trace_enforcement_state!(&chan);
2021        self.persister
2022            .update_tracker(&self.get_id(), &tracker)
2023            .map_err(|_| internal_error("tracker persist failed"))?;
2024        self.persister
2025            .update_channel(&self.get_id(), &chan)
2026            .map_err(|_| internal_error("persist failed"))?;
2027
2028        Ok(chan)
2029    }
2030
2031    /// Get a signed heartbeat message.
2032    /// The heartbeat is signed with the account master key.
2033    pub fn get_heartbeat(&self) -> SignedHeartbeat {
2034        // Lock order: state (released), then channels -> slot -> state via
2035        // channel_balance, then tracker -> channels (see LOCK ORDERING). Nothing
2036        // is nested across those steps, so no state/slot cycle can form here.
2037        // we get asked for a heartbeat on a regular basis, so use this
2038        // opportunity to prune invoices
2039        let mut state = self.get_state();
2040        let now = self.clock.now();
2041        let pruned1 = state.prune_invoices(now);
2042        let pruned2 = state.prune_issued_invoices(now);
2043        let pruned3 = state.prune_forwarded_payments();
2044        if pruned1 || pruned2 || pruned3 {
2045            trace_node_state!(state);
2046            self.persister
2047                .update_node(&self.get_id(), &state)
2048                .unwrap_or_else(|err| panic!("pruned node state persist failed: {:?}", err));
2049        }
2050        drop(state); // minimize lock time
2051
2052        // channel_balance() takes channels -> slot -> state; call it before
2053        // acquiring the tracker so the tracker is not held across it.
2054        info!("current channel balance: {:?}", self.channel_balance());
2055
2056        let mut tracker = self.get_tracker();
2057
2058        // pruned channels are persisted inside
2059        self.prune_channels(&mut tracker);
2060
2061        let tip = tracker.tip();
2062        let current_timestamp = self.clock.now().as_secs() as u32;
2063        let heartbeat = Heartbeat {
2064            chain_tip: tip.0.block_hash(),
2065            chain_height: tracker.height(),
2066            chain_timestamp: tip.0.time,
2067            current_timestamp,
2068        };
2069        let sig = self.keys_manager.sign_heartbeat(heartbeat.sighash());
2070        SignedHeartbeat { signature: sig[..].to_vec(), heartbeat }
2071    }
2072
2073    // Check and sign an onchain transaction
2074    #[cfg(any(test, feature = "test_utils"))]
2075    pub(crate) fn check_and_sign_onchain_tx(
2076        &self,
2077        tx: &Transaction,
2078        segwit_flags: &[bool],
2079        ipaths: &[DerivationPath],
2080        prev_outs: &[TxOut],
2081        uniclosekeys: Vec<Option<(SecretKey, Vec<Vec<u8>>)>>,
2082        opaths: &[DerivationPath],
2083    ) -> Result<Vec<Vec<Vec<u8>>>, Status> {
2084        self.check_onchain_tx(tx, segwit_flags, prev_outs, &uniclosekeys, opaths)?;
2085        self.unchecked_sign_onchain_tx(tx, ipaths, prev_outs, uniclosekeys)
2086    }
2087
2088    /// Sign an onchain transaction (funding tx or simple sweeps).
2089    ///
2090    /// `check_onchain_tx` must be called first to validate the transaction.
2091    /// The two are separate so that the caller can check for approval if
2092    /// there is an unknown destination.
2093    ///
2094    /// The transaction may fund multiple channels at once.
2095    ///
2096    /// Returns a witness stack for each input.  Inputs that are marked
2097    /// as [SpendType::Invalid] are not signed and get an empty witness stack.
2098    ///
2099    /// * `ipaths` - derivation path for the wallet key per input
2100    /// * `prev_outs` - the previous outputs used as inputs for this tx
2101    /// * `uniclosekeys` - an optional unilateral close key to use instead of the
2102    ///   wallet key.  Takes precedence over the `ipaths` entry.  This is used when
2103    ///   we are sweeping a unilateral close and funding a channel in a single tx.
2104    ///   The second item in the tuple is the witness stack suffix - zero or more
2105    ///   script parameters and the redeemscript.
2106    pub fn unchecked_sign_onchain_tx(
2107        &self,
2108        tx: &Transaction,
2109        ipaths: &[DerivationPath],
2110        prev_outs: &[TxOut],
2111        uniclosekeys: Vec<Option<(SecretKey, Vec<Vec<u8>>)>>,
2112    ) -> Result<Vec<Vec<Vec<u8>>>, Status> {
2113        // Funding transactions cannot be associated with just a single channel;
2114        // a single transaction may fund multiple channels
2115
2116        let txid = tx.compute_txid();
2117        debug!("{}: txid: {}", short_function!(), txid);
2118
2119        // Lock order: channels (released) -> tracker (see LOCK ORDERING)
2120        // Collect channel Arc refs, then release channels lock before acquiring tracker
2121        let channels: Vec<Option<Arc<Mutex<ChannelSlot>>>> = {
2122            let channels_lock = self.get_channels();
2123            (0..tx.output.len())
2124                .map(|ndx| {
2125                    let outpoint = OutPoint { txid, vout: ndx as u32 };
2126                    find_channel_with_funding_outpoint(&channels_lock, &outpoint)
2127                })
2128                .collect()
2129        }; // channels_lock released here
2130
2131        let mut witvec: Vec<Vec<Vec<u8>>> = Vec::new();
2132        for (idx, uck) in uniclosekeys.into_iter().enumerate() {
2133            let spend_type = SpendType::from_script_pubkey(&prev_outs[idx].script_pubkey);
2134            // if we don't recognize the script, or we are not told what the derivation path is, don't try to sign
2135            if spend_type == SpendType::Invalid || (uck.is_none() && ipaths[idx].is_empty()) {
2136                // If we are signing a PSBT some of the inputs may be
2137                // marked as SpendType::Invalid (we skip these), push
2138                // an empty witness element instead.
2139                witvec.push(vec![]);
2140            } else {
2141                let value_sat = prev_outs[idx].value;
2142                let (privkey, mut witness) = match uck {
2143                    // There was a unilateral_close_key.
2144                    Some((key, stack)) => (PrivateKey::new(key, self.network()), stack),
2145                    // Derive the HD key.
2146                    None => {
2147                        let key = self.get_wallet_privkey(&ipaths[idx])?;
2148                        let redeemscript = PublicKey::from_secret_key(&self.secp_ctx, &key.inner)
2149                            .serialize()
2150                            .to_vec();
2151                        (key, vec![redeemscript])
2152                    }
2153                };
2154                let pubkey = CompressedPublicKey(privkey.public_key(&self.secp_ctx).inner);
2155                // the unwraps below are infallible, because sighash is always 32 bytes
2156                let sigvec = match spend_type {
2157                    SpendType::P2pkh => {
2158                        let expected_scriptpubkey =
2159                            Address::p2pkh(&pubkey, self.network()).script_pubkey();
2160                        assert_eq!(
2161                            prev_outs[idx].script_pubkey, expected_scriptpubkey,
2162                            "scriptpubkey mismatch on index {}",
2163                            idx
2164                        );
2165                        let script_code = Address::p2pkh(&pubkey, self.network()).script_pubkey();
2166                        let sighash = SighashCache::new(tx)
2167                            .legacy_signature_hash(idx, &script_code, 0x01)
2168                            .map_err(|_| internal_error("sighash failed"))?;
2169                        signature_to_bitcoin_vec(ecdsa_sign(
2170                            &self.secp_ctx,
2171                            &privkey,
2172                            sighash.into(),
2173                        ))
2174                    }
2175                    SpendType::P2wpkh => {
2176                        let expected_scriptpubkey =
2177                            Address::p2wpkh(&pubkey, self.network()).script_pubkey();
2178                        assert_eq!(
2179                            prev_outs[idx].script_pubkey, expected_scriptpubkey,
2180                            "scriptpubkey mismatch on index {}",
2181                            idx
2182                        );
2183                        // unwrap cannot fail
2184                        let sighash = SighashCache::new(tx)
2185                            .p2wpkh_signature_hash(
2186                                idx,
2187                                &expected_scriptpubkey,
2188                                value_sat,
2189                                EcdsaSighashType::All,
2190                            )
2191                            .unwrap();
2192                        signature_to_bitcoin_vec(ecdsa_sign(
2193                            &self.secp_ctx,
2194                            &privkey,
2195                            sighash.into(),
2196                        ))
2197                    }
2198                    SpendType::P2shP2wpkh => {
2199                        // compressed pubkeys cannot fail
2200                        let expected_scriptpubkey =
2201                            Address::p2shwpkh(&pubkey, self.network()).script_pubkey();
2202                        assert_eq!(
2203                            prev_outs[idx].script_pubkey, expected_scriptpubkey,
2204                            "scriptpubkey mismatch on index {}",
2205                            idx
2206                        );
2207                        let nested_script =
2208                            Address::p2wpkh(&pubkey, self.network()).script_pubkey();
2209
2210                        // unwrap cannot fail
2211                        let sighash = SighashCache::new(tx)
2212                            .p2wpkh_signature_hash(
2213                                idx,
2214                                &nested_script,
2215                                value_sat,
2216                                EcdsaSighashType::All,
2217                            )
2218                            .unwrap();
2219                        signature_to_bitcoin_vec(ecdsa_sign(
2220                            &self.secp_ctx,
2221                            &privkey,
2222                            sighash.into(),
2223                        ))
2224                    }
2225                    SpendType::P2wsh => {
2226                        // TODO failfast here if the scriptpubkey doesn't match
2227                        let sighash = SighashCache::new(tx)
2228                            .p2wsh_signature_hash(
2229                                idx,
2230                                &ScriptBuf::from(witness[witness.len() - 1].clone()),
2231                                value_sat,
2232                                EcdsaSighashType::All,
2233                            )
2234                            .unwrap();
2235                        signature_to_bitcoin_vec(ecdsa_sign(
2236                            &self.secp_ctx,
2237                            &privkey,
2238                            sighash.into(),
2239                        ))
2240                    }
2241                    SpendType::P2tr => {
2242                        let wallet_addr = self.get_taproot_address(&ipaths[idx])?;
2243                        let script = &prev_outs[idx].script_pubkey;
2244                        let out_addr =
2245                            Address::from_script(&script, self.network()).map_err(|_| {
2246                                invalid_argument(format!(
2247                                    "script {} at output {} could not be converted to address",
2248                                    script, idx
2249                                ))
2250                            })?;
2251                        trace!(
2252                            "signing p2tr, idx {}, ipath {:?} out addr {:?}, wallet addr {} prev outs {:?}",
2253                            idx, ipaths[idx], out_addr, wallet_addr, prev_outs
2254                        );
2255                        if wallet_addr != out_addr {
2256                            return Err(invalid_argument(format!(
2257                                "wallet address @{:?} {} does not match output address {}",
2258                                ipaths[idx], wallet_addr, out_addr
2259                            )));
2260                        }
2261                        let prevouts = Prevouts::All(&prev_outs);
2262                        // unwrap cannot fail
2263                        let sighash = SighashCache::new(tx)
2264                            .taproot_signature_hash(
2265                                idx,
2266                                &prevouts,
2267                                None,
2268                                None,
2269                                TapSighashType::Default,
2270                            )
2271                            .unwrap();
2272                        let aux_rand = self.keys_manager.get_secure_random_bytes();
2273                        schnorr_signature_to_bitcoin_vec(taproot_sign(
2274                            &self.secp_ctx,
2275                            &privkey,
2276                            sighash,
2277                            &aux_rand,
2278                        ))
2279                    }
2280                    st => return Err(invalid_argument(format!("unsupported spend_type={:?}", st))),
2281                };
2282                // if taproot, clear out the witness, since taproot doesn't use a redeemscript for key path
2283                if spend_type == SpendType::P2tr {
2284                    witness.clear();
2285                }
2286                witness.insert(0, sigvec);
2287
2288                witvec.push(witness);
2289            }
2290        }
2291
2292        // The tracker may be updated for multiple channels.
2293        let mut tracker = self.get_tracker();
2294
2295        // Re-acquire channels lock to serialize access to the slot-locking loop,
2296        // preventing deadlock when multiple threads lock overlapping channel slots.
2297        // TODO(511) consider sorting instead
2298        let _channels_lock = self.get_channels();
2299        for (vout, slot_opt) in channels.iter().enumerate() {
2300            if let Some(slot_mutex) = slot_opt {
2301                let slot = slot_mutex.lock().unwrap();
2302                match &*slot {
2303                    ChannelSlot::Stub(_) => panic!("this can't happen"),
2304                    ChannelSlot::Ready(chan) => {
2305                        let inputs =
2306                            OrderedSet::from_iter(tx.input.iter().map(|i| i.previous_output));
2307                        tracker.add_listener_watches(&chan.monitor.funding_outpoint, inputs);
2308                        chan.funding_signed(tx, vout as u32);
2309                        self.persister
2310                            .update_channel(&self.get_id(), &chan)
2311                            .map_err(|_| internal_error("persist failed"))?;
2312                    }
2313                }
2314            }
2315        }
2316
2317        // the channels added some watches - persist
2318        self.persister
2319            .update_tracker(&self.get_id(), &tracker)
2320            .map_err(|_| internal_error("tracker persist failed"))?;
2321
2322        Ok(witvec)
2323    }
2324
2325    /// Check an onchain transaction (funding tx or simple sweeps).
2326    ///
2327    /// This is normally followed by a call to `unchecked_sign_onchain_tx`.
2328    ///
2329    /// If the result is ValidationError::UncheckedDestinations, the caller
2330    /// could still ask for manual approval and then sign the transaction.
2331    ///
2332    /// The transaction may fund multiple channels at once.
2333    ///
2334    /// * `input_txs` - previous tx for inputs when funding channel
2335    /// * `prev_outs` - the previous outputs used as inputs for this tx
2336    /// * `uniclosekeys` - an optional unilateral close key to use instead of the
2337    ///   wallet key.  Takes precedence over the `ipaths` entry.  This is used when
2338    ///   we are sweeping a unilateral close and funding a channel in a single tx.
2339    ///   The second item in the tuple is the witness stack suffix - zero or more
2340    ///   script parameters and the redeemscript.
2341    /// * `opaths` - derivation path per output.  Empty for non-wallet/non-xpub-whitelist
2342    ///   outputs.
2343    pub fn check_onchain_tx(
2344        &self,
2345        tx: &Transaction,
2346        segwit_flags: &[bool],
2347        prev_outs: &[TxOut],
2348        uniclosekeys: &[Option<(SecretKey, Vec<Vec<u8>>)>],
2349        opaths: &[DerivationPath],
2350    ) -> Result<(), ValidationError> {
2351        let channels_lock = self.get_channels();
2352
2353        // Funding transactions cannot be associated with just a single channel;
2354        // a single transaction may fund multiple channels
2355
2356        let txid = tx.compute_txid();
2357        debug!("{}: txid: {}", short_function!(), txid);
2358
2359        let channels: Vec<Option<Arc<Mutex<ChannelSlot>>>> = (0..tx.output.len())
2360            .map(|ndx| {
2361                let outpoint = OutPoint { txid, vout: ndx as u32 };
2362                find_channel_with_funding_outpoint(&channels_lock, &outpoint)
2363            })
2364            .collect();
2365
2366        let validator = self.validator();
2367
2368        // Compute a lower bound for the tx weight for feerate checking.
2369        // TODO(dual-funding) - This estimate does not include witnesses for inputs we don't sign.
2370        let mut weight_lower_bound = tx.weight().to_wu() as usize;
2371        for (idx, uck) in uniclosekeys.iter().enumerate() {
2372            let spend_type = SpendType::from_script_pubkey(&prev_outs[idx].script_pubkey);
2373            if spend_type == SpendType::Invalid {
2374                weight_lower_bound += 0;
2375            } else {
2376                let wit_len = match uck {
2377                    // length-byte + witness-element
2378                    Some((_key, stack)) => stack.iter().map(|v| 1 + v.len()).sum(),
2379                    None => 33,
2380                };
2381                // witness-header + element-count + length + sig + len + redeemscript
2382                weight_lower_bound += 2 + 1 + 1 + 72 + 1 + wit_len;
2383            }
2384        }
2385        debug!("weight_lower_bound: {}", weight_lower_bound);
2386
2387        let values_sat = prev_outs.iter().map(|o| o.value.to_sat()).collect::<Vec<_>>();
2388        let non_beneficial_sat = validator.validate_onchain_tx(
2389            self,
2390            channels,
2391            tx,
2392            segwit_flags,
2393            &values_sat,
2394            opaths,
2395            weight_lower_bound,
2396        )?;
2397
2398        // be conservative about holding multiple locks, so we don't worry about order
2399        drop(channels_lock);
2400
2401        let validator = self.validator();
2402        defer! { trace_node_state!(self.get_state()); }
2403        let mut state = self.get_state();
2404        let now = self.clock.now().as_secs();
2405        if !state.fee_velocity_control.insert(now, non_beneficial_sat * 1000) {
2406            policy_err!(
2407                validator,
2408                "policy-onchain-fee-range",
2409                "fee velocity would be exceeded {} + {} > {}",
2410                state.fee_velocity_control.velocity(),
2411                non_beneficial_sat * 1000,
2412                state.fee_velocity_control.limit
2413            );
2414        }
2415
2416        Ok(())
2417    }
2418
2419    fn validator(&self) -> Arc<dyn Validator> {
2420        self.validator_factory().make_validator(self.network(), self.get_id(), None)
2421    }
2422
2423    pub(crate) fn get_wallet_privkey(
2424        &self,
2425        derivation_path: &DerivationPath,
2426    ) -> Result<PrivateKey, Status> {
2427        let key_path_len = self.node_config.key_derivation_style.get_key_path_len();
2428        if key_path_len.is_some() && derivation_path.len() != key_path_len.unwrap() {
2429            return Err(invalid_argument(format!(
2430                "get_wallet_key: bad child_path len : {}",
2431                derivation_path.len()
2432            )));
2433        }
2434
2435        let xkey =
2436            self.get_account_extended_key().derive_priv(&self.secp_ctx, &derivation_path).unwrap();
2437        Ok(PrivateKey::new(xkey.private_key, self.network()))
2438    }
2439
2440    pub(crate) fn get_wallet_pubkey(
2441        &self,
2442        child_path: &DerivationPath,
2443    ) -> Result<CompressedPublicKey, Status> {
2444        Ok(CompressedPublicKey(
2445            self.get_wallet_privkey(child_path)?.public_key(&self.secp_ctx).inner,
2446        ))
2447    }
2448
2449    /// Check the submitted wallet pubkey
2450    pub fn check_wallet_pubkey(
2451        &self,
2452        child_path: &DerivationPath,
2453        pubkey: bitcoin::PublicKey,
2454    ) -> Result<bool, Status> {
2455        Ok(self.get_wallet_pubkey(child_path)?.0 == pubkey.inner)
2456    }
2457
2458    /// Get shutdown_pubkey to use as PublicKey at channel closure
2459    // FIXME(75) - this method is deprecated
2460    pub fn get_ldk_shutdown_scriptpubkey(&self) -> ShutdownScript {
2461        self.keys_manager.get_shutdown_scriptpubkey().unwrap()
2462    }
2463
2464    /// Get the layer-1 xprv
2465    pub fn get_account_extended_key(&self) -> &Xpriv {
2466        self.keys_manager.get_account_extended_key()
2467    }
2468
2469    /// Get the layer-1 xpub
2470    pub fn get_account_extended_pubkey(&self) -> Xpub {
2471        let secp_ctx = Secp256k1::signing_only();
2472        Xpub::from_priv(&secp_ctx, &self.get_account_extended_key())
2473    }
2474
2475    /// Sign a node announcement using the node key
2476    pub fn sign_node_announcement(&self, na: &[u8]) -> Result<Signature, Status> {
2477        self.do_sign_gossip_message(na)
2478    }
2479
2480    /// Sign a channel update or announcement using the node key
2481    pub fn sign_channel_update(&self, cu: &[u8]) -> Result<Signature, Status> {
2482        self.do_sign_gossip_message(cu)
2483    }
2484
2485    /// Sign gossip messages
2486    pub fn sign_gossip_message(&self, msg: &UnsignedGossipMessage) -> Result<Signature, Status> {
2487        let encoded = &msg.encode()[..];
2488        self.do_sign_gossip_message(encoded)
2489    }
2490
2491    fn do_sign_gossip_message(&self, encoded: &[u8]) -> Result<Signature, Status> {
2492        let secp_ctx = Secp256k1::signing_only();
2493        let msg_hash = Sha256dHash::hash(encoded);
2494        let encmsg = Message::from_digest(msg_hash.to_byte_array());
2495        let sig = secp_ctx.sign_ecdsa(&encmsg, &self.get_node_secret());
2496        Ok(sig)
2497    }
2498
2499    /// Sign a BOLT-11 invoice and start tracking incoming payment for its payment hash
2500    pub fn sign_bolt11_invoice(
2501        &self,
2502        invoice: RawBolt11Invoice,
2503    ) -> Result<RecoverableSignature, Status> {
2504        let signed_raw_invoice = self.do_sign_invoice(invoice)?;
2505
2506        let sig = signed_raw_invoice.signature().0;
2507        let (hash, payment_state, invoice_hash) = Self::payment_state_from_invoice(
2508            &signed_raw_invoice.try_into().map_err(|e: Status| invalid_argument(e.to_string()))?,
2509        )?;
2510        info!(
2511            "{} signing an invoice {} -> {}",
2512            self.log_prefix(),
2513            hash.0.to_hex(),
2514            payment_state.amount_msat
2515        );
2516
2517        defer! { trace_node_state!(self.get_state()); }
2518        let mut state = self.get_state();
2519        let policy = self.policy();
2520        if state.issued_invoices.len() >= policy.max_invoices() {
2521            return Err(failed_precondition(format!(
2522                "too many invoices {} (max {})",
2523                state.issued_invoices.len(),
2524                policy.max_invoices()
2525            )));
2526        }
2527        if let Some(payment_state) = state.issued_invoices.get(&hash) {
2528            return if payment_state.invoice_hash == invoice_hash {
2529                Ok(sig)
2530            } else {
2531                Err(failed_precondition(
2532                    "sign_invoice: already have a different invoice for same secret".to_string(),
2533                ))
2534            };
2535        }
2536
2537        // We don't care about zero amount invoices, since they can be considered
2538        // already fullfilled, and we could give out the preimage for free without
2539        // any risk.  These are generated, for example, when the node is receiving
2540        // a keysend.
2541        if payment_state.amount_msat > 0 {
2542            state.issued_invoices.insert(hash, payment_state);
2543        }
2544
2545        Ok(sig)
2546    }
2547
2548    /// Sign a BOLT-12 invoice after enforcing signer-side policy checks.
2549    ///
2550    /// Issued-invoice accounting intentionally mirrors BOLT-11: `max_invoices`
2551    /// is an absolute limit checked before duplicate lookup, and zero-amount
2552    /// invoices are signed but not tracked in `issued_invoices`.
2553    pub fn sign_bolt12_invoice(
2554        &self,
2555        invoice: &UnsignedBolt12Invoice,
2556    ) -> Result<schnorr::Signature, Status> {
2557        let validator = self.validator();
2558        let now = self.clock.now();
2559        validator.validate_bolt12_invoice_unsigned(invoice, now, self.get_bolt12_pubkey())?;
2560
2561        let sig = self
2562            .keys_manager
2563            .sign_bolt12_invoice(invoice)
2564            .map_err(|_| internal_error("failed to sign bolt12 invoice"))?;
2565
2566        let sig_copy = sig;
2567        let signed_invoice = invoice
2568            .clone()
2569            .sign(move |_message: &UnsignedBolt12Invoice| Ok(sig_copy))
2570            .map_err(|_| internal_error("failed to assemble signed bolt12 invoice"))?;
2571        let (payment_hash, payment_state, invoice_hash) =
2572            Self::payment_state_from_invoice(&Invoice::Bolt12(signed_invoice))?;
2573
2574        defer! { trace_node_state!(self.get_state()); }
2575        let mut state = self.get_state();
2576        let policy = self.policy();
2577        if state.issued_invoices.len() >= policy.max_invoices() {
2578            return Err(failed_precondition(format!(
2579                "too many invoices {} (max {})",
2580                state.issued_invoices.len(),
2581                policy.max_invoices()
2582            )));
2583        }
2584
2585        if let Some(existing_state) = state.issued_invoices.get(&payment_hash) {
2586            return if existing_state.invoice_hash == invoice_hash {
2587                Ok(sig)
2588            } else {
2589                Err(failed_precondition(
2590                    "sign_bolt12_invoice: already have a different invoice for same payment hash"
2591                        .to_string(),
2592                ))
2593            };
2594        }
2595
2596        if payment_state.amount_msat > 0 {
2597            state.issued_invoices.insert(payment_hash, payment_state);
2598        }
2599        Ok(sig)
2600    }
2601
2602    fn policy(&self) -> Box<dyn Policy> {
2603        self.validator_factory().policy(self.network())
2604    }
2605
2606    pub(crate) fn validator_factory(&self) -> MutexGuard<'_, Arc<dyn ValidatorFactory>> {
2607        self.validator_factory.lock().unwrap()
2608    }
2609
2610    // Sign a BOLT-11 invoice
2611    pub(crate) fn do_sign_invoice(
2612        &self,
2613        raw_invoice: RawBolt11Invoice,
2614    ) -> Result<SignedRawBolt11Invoice, Status> {
2615        let hash = raw_invoice.signable_hash();
2616        let secp_ctx = Secp256k1::signing_only();
2617        let message = Message::from_digest(hash);
2618        let sig = secp_ctx.sign_ecdsa_recoverable(&message, &self.get_node_secret());
2619
2620        raw_invoice
2621            .sign::<_, ()>(|_| Ok(sig))
2622            .map_err(|()| internal_error("failed to sign invoice"))
2623    }
2624
2625    /// Sign a message, with the specified tag. Notice that you most likely are looking for
2626    /// `sign_message` which adds the lightning message tag, so the signature cannot be reused for
2627    /// unintended use-cases. The `tag` specifies the domain in which the signature should be
2628    /// usable. It is up to the caller to ensure that tags are prefix-free.
2629    pub fn sign_tagged_message(&self, tag: &[u8], message: &[u8]) -> Result<Vec<u8>, Status> {
2630        let mut buffer = tag.to_vec().clone();
2631        buffer.extend(message);
2632        let secp_ctx = Secp256k1::signing_only();
2633        let hash = Sha256dHash::hash(&buffer);
2634        let encmsg = Message::from_digest(hash.to_byte_array());
2635        let sig = secp_ctx.sign_ecdsa_recoverable(&encmsg, &self.get_node_secret());
2636        let (rid, sig) = sig.serialize_compact();
2637        let mut res = sig.to_vec();
2638        res.push(rid.to_i32() as u8);
2639        Ok(res)
2640    }
2641
2642    /// Sign a Lightning message
2643    pub fn sign_message(&self, message: &[u8]) -> Result<Vec<u8>, Status> {
2644        let tag: Vec<u8> = "Lightning Signed Message:".into();
2645        self.sign_tagged_message(&tag, message)
2646    }
2647
2648    /// Lock and return all the channels this node knows about.
2649    pub fn get_channels(&self) -> MutexGuard<'_, OrderedMap<ChannelId, Arc<Mutex<ChannelSlot>>>> {
2650        self.channels.lock().unwrap()
2651    }
2652
2653    /// Perform an ECDH operation between the node key and a public key
2654    /// This can be used for onion packet decoding
2655    pub fn ecdh(&self, other_key: &PublicKey) -> Vec<u8> {
2656        let our_key = self.keys_manager.get_node_secret();
2657        let ss = SharedSecret::new(&other_key, &our_key);
2658        ss.as_ref().to_vec()
2659    }
2660
2661    /// See [`MyKeysManager::spend_spendable_outputs`].
2662    ///
2663    /// For LDK compatibility.
2664    pub fn spend_spendable_outputs(
2665        &self,
2666        descriptors: &[&SpendableOutputDescriptor],
2667        outputs: Vec<TxOut>,
2668        change_destination_script: ScriptBuf,
2669        feerate_sat_per_1000_weight: u32,
2670    ) -> Result<Transaction, ()> {
2671        self.keys_manager.spend_spendable_outputs(
2672            descriptors,
2673            outputs,
2674            change_destination_script,
2675            feerate_sat_per_1000_weight,
2676            &self.secp_ctx,
2677        )
2678    }
2679
2680    /// Returns the node's current allowlist.
2681    pub fn allowlist(&self) -> Result<Vec<String>, Status> {
2682        let state = self.get_state();
2683        state
2684            .allowlist
2685            .iter()
2686            .map(|allowable| Ok(allowable.to_string(self.network())))
2687            .collect::<Result<Vec<String>, Status>>()
2688    }
2689
2690    /// Returns the node's current allowlist.
2691    pub fn allowables(&self) -> Vec<Allowable> {
2692        self.get_state().allowlist.iter().cloned().collect()
2693    }
2694
2695    /// Adds addresses to the node's current allowlist.
2696    pub fn add_allowlist(&self, adds: &[String]) -> Result<(), Status> {
2697        let mut state = self.get_state();
2698        for a in adds.iter() {
2699            let allowable = Allowable::from_str(a, self.node_config.network)
2700                .map_err(|e| invalid_argument(format!("could not parse {}", e)))?;
2701            state.allowlist.insert(allowable);
2702        }
2703        self.update_allowlist(&state)?;
2704        Ok(())
2705    }
2706
2707    /// Replace the node's allowlist with the provided allowlist.
2708    pub fn set_allowlist(&self, list: &[String]) -> Result<(), Status> {
2709        let mut state = self.get_state();
2710        state.allowlist.clear();
2711        for a in list.iter() {
2712            let allowable = Allowable::from_str(a, self.node_config.network)
2713                .map_err(|e| invalid_argument(format!("could not parse {}", e)))?;
2714            state.allowlist.insert(allowable);
2715        }
2716        self.update_allowlist(&state)?;
2717        Ok(())
2718    }
2719
2720    fn update_allowlist(&self, state: &MutexGuard<NodeState>) -> Result<(), Status> {
2721        let wlvec = state.allowlist.iter().map(|a| a.to_string(self.network())).collect();
2722        self.persister
2723            .update_node_allowlist(&self.get_id(), wlvec)
2724            .map_err(|_| internal_error("persist failed"))
2725    }
2726
2727    /// Removes addresses from the node's current allowlist.
2728    pub fn remove_allowlist(&self, removes: &[String]) -> Result<(), Status> {
2729        let mut state = self.get_state();
2730        for r in removes.iter() {
2731            let allowable = Allowable::from_str(r, self.node_config.network)
2732                .map_err(|e| invalid_argument(format!("could not parse {}", e)))?;
2733            state.allowlist.remove(&allowable);
2734        }
2735        self.update_allowlist(&state)?;
2736        Ok(())
2737    }
2738
2739    /// Chain tracker with lock
2740    pub fn get_tracker(&self) -> MutexGuard<'_, ChainTracker<ChainMonitor>> {
2741        self.tracker.lock().unwrap()
2742    }
2743
2744    /// Height of chain
2745    pub fn get_chain_height(&self) -> u32 {
2746        self.get_tracker().height()
2747    }
2748
2749    // Process payment preimages for offered HTLCs.
2750    // Any invoice with a payment hash that matches a preimage is marked
2751    // as paid, so that the offered HTLC can be removed and our balance
2752    // adjusted downwards.
2753    pub(crate) fn htlcs_fulfilled(
2754        &self,
2755        channel_id: &ChannelId,
2756        preimages: Vec<PaymentPreimage>,
2757        validator: Arc<dyn Validator>,
2758    ) {
2759        let mut state = self.get_state();
2760        let mut fulfilled = false;
2761        for preimage in preimages.into_iter() {
2762            fulfilled =
2763                state.htlc_fulfilled(channel_id, preimage, Arc::clone(&validator)) || fulfilled;
2764        }
2765        if fulfilled {
2766            trace_node_state!(state);
2767        }
2768    }
2769
2770    /// Add an invoice.
2771    /// Used by the signer to map HTLCs to destination payees, so that payee
2772    /// public keys can be allowlisted for policy control. Returns true
2773    /// if the invoice was added, false otherwise.
2774    pub fn add_invoice(&self, invoice: Invoice) -> Result<bool, Status> {
2775        let validator = self.validator();
2776        let now = self.clock.now();
2777
2778        validator.validate_invoice(&invoice, now)?;
2779
2780        let (hash, payment_state, invoice_hash) = Self::payment_state_from_invoice(&invoice)?;
2781
2782        info!(
2783            "{} adding invoice {} -> {}",
2784            self.log_prefix(),
2785            hash.0.to_hex(),
2786            payment_state.amount_msat
2787        );
2788        defer! { trace_node_state!(self.get_state()); }
2789        let mut state = self.get_state();
2790        let policy = self.policy();
2791        if state.invoices.len() >= policy.max_invoices() {
2792            return Err(failed_precondition(format!(
2793                "too many invoices ({} >= {})",
2794                state.invoices.len(),
2795                policy.max_invoices()
2796            )));
2797        }
2798        if let Some(payment_state) = state.invoices.get(&hash) {
2799            return if payment_state.invoice_hash == invoice_hash {
2800                Ok(true)
2801            } else {
2802                Err(failed_precondition(
2803                    "add_invoice: already have a different invoice for same payment_hash",
2804                ))
2805            };
2806        }
2807        if !state.velocity_control.insert(now.as_secs(), payment_state.amount_msat) {
2808            warn!(
2809                "policy-commitment-payment-velocity velocity would be exceeded - += {} = {} > {}",
2810                payment_state.amount_msat,
2811                state.velocity_control.velocity(),
2812                state.velocity_control.limit
2813            );
2814            return Ok(false);
2815        }
2816        state.invoices.insert(hash, payment_state);
2817        state.payments.entry(hash).or_insert_with(RoutedPayment::new);
2818        self.persister.update_node(&self.get_id(), &*state).expect("node persistence failure");
2819
2820        Ok(true)
2821    }
2822
2823    /// Add a keysend payment.
2824    ///
2825    /// Returns true if the keysend was added, false otherwise.
2826    ///
2827    /// The payee is currently not validated.
2828    pub fn add_keysend(
2829        &self,
2830        payee: PublicKey,
2831        payment_hash: PaymentHash,
2832        amount_msat: u64,
2833    ) -> Result<bool, Status> {
2834        let (payment_state, invoice_hash) =
2835            Node::payment_state_from_keysend(payee, payment_hash, amount_msat, self.clock.now())?;
2836
2837        info!(
2838            "{} adding keysend {} -> {}",
2839            self.log_prefix(),
2840            payment_hash.0.to_hex(),
2841            payment_state.amount_msat
2842        );
2843        defer! { trace_node_state!(self.get_state()); }
2844        let mut state = self.get_state();
2845        let policy = self.policy();
2846        if state.invoices.len() >= policy.max_invoices() {
2847            return Err(failed_precondition(format!(
2848                "too many invoices ({} >= {})",
2849                state.invoices.len(),
2850                policy.max_invoices()
2851            )));
2852        }
2853
2854        if let Some(payment_state) = state.invoices.get(&payment_hash) {
2855            return if payment_state.invoice_hash == invoice_hash {
2856                Ok(true)
2857            } else {
2858                Err(failed_precondition(
2859                    "add_keysend: already have a different keysend for same payment_hash",
2860                ))
2861            };
2862        }
2863        let now = self.clock.now().as_secs();
2864        if !state.velocity_control.insert(now, payment_state.amount_msat) {
2865            warn!(
2866                "policy-commitment-payment-velocity velocity would be exceeded - += {} = {} > {}",
2867                payment_state.amount_msat,
2868                state.velocity_control.velocity(),
2869                state.velocity_control.limit
2870            );
2871            return Ok(false);
2872        }
2873        state.invoices.insert(payment_hash, payment_state);
2874        state.payments.entry(payment_hash).or_insert_with(RoutedPayment::new);
2875        self.persister.update_node(&self.get_id(), &*state).expect("node persistence failure");
2876
2877        Ok(true)
2878    }
2879
2880    /// Check to see if a payment has already been added
2881    pub fn has_payment(&self, hash: &PaymentHash, invoice_hash: &[u8; 32]) -> Result<bool, Status> {
2882        let mut state = self.get_state();
2883        let retval = if let Some(payment_state) = state.invoices.get(&*hash) {
2884            if payment_state.invoice_hash == *invoice_hash {
2885                Ok(true)
2886            } else {
2887                trace_node_state!(state);
2888                Err(failed_precondition(
2889                    "has_payment: already have a different invoice for same secret",
2890                ))
2891            }
2892        } else {
2893            Ok(false) // not found
2894        };
2895        debug!("{} has_payment {} {:?}", self.log_prefix(), hash.0.to_hex(), retval,);
2896        retval
2897    }
2898
2899    /// Create a tracking state for the invoice
2900    ///
2901    /// Returns the payment hash, payment state, and the hash of the raw invoice that was signed.
2902    pub fn payment_state_from_invoice(
2903        invoice: &Invoice,
2904    ) -> Result<(PaymentHash, PaymentState, [u8; 32]), Status> {
2905        let payment_hash = invoice.payment_hash();
2906        let invoice_hash = invoice.invoice_hash();
2907        let payment_state = PaymentState {
2908            invoice_hash,
2909            amount_msat: invoice.amount_milli_satoshis(),
2910            payee: invoice.payee_pub_key(),
2911            duration_since_epoch: invoice.duration_since_epoch(),
2912            expiry_duration: invoice.expiry_duration(),
2913            is_fulfilled: false,
2914            payment_type: PaymentType::Invoice,
2915        };
2916        Ok((payment_hash, payment_state, invoice_hash))
2917    }
2918
2919    /// Create tracking state for an ad-hoc payment (keysend).
2920    /// The payee is not validated yet.
2921    ///
2922    /// Returns the invoice state
2923    pub fn payment_state_from_keysend(
2924        payee: PublicKey,
2925        payment_hash: PaymentHash,
2926        amount_msat: u64,
2927        now: Duration,
2928    ) -> Result<(PaymentState, [u8; 32]), Status> {
2929        // TODO(281) validate the payee by generating the preimage ourselves and wrapping the inner layer
2930        // of the onion
2931        // TODO(281) once we validate the payee, check if payee public key is in allowlist
2932        let invoice_hash = payment_hash.0;
2933        let payment_state = PaymentState {
2934            invoice_hash,
2935            amount_msat,
2936            payee,
2937            duration_since_epoch: now,                // FIXME(329)
2938            expiry_duration: Duration::from_secs(60), // FIXME(329)
2939            is_fulfilled: false,
2940            payment_type: PaymentType::Keysend,
2941        };
2942        Ok((payment_state, invoice_hash))
2943    }
2944
2945    fn make_velocity_control(policy: &Box<dyn Policy>) -> VelocityControl {
2946        let velocity_control_spec = policy.global_velocity_control();
2947        VelocityControl::new(velocity_control_spec)
2948    }
2949
2950    fn make_fee_velocity_control(policy: &Box<dyn Policy>) -> VelocityControl {
2951        let velocity_control_spec = policy.fee_velocity_control();
2952        VelocityControl::new(velocity_control_spec)
2953    }
2954
2955    /// The node tells us that it is forgetting a channel.
2956    pub fn forget_channel(&self, channel_id: &ChannelId) -> Result<(), Status> {
2957        // Lock order: channels -> channel_slot -> state (see LOCK ORDERING)
2958        let mut stub_found = false;
2959        let mut channels = self.get_channels();
2960        let found = channels.get(channel_id);
2961        if let Some(slot) = found {
2962            {
2963                let channel = slot.lock().unwrap();
2964                match &*channel {
2965                    ChannelSlot::Stub(_) => {
2966                        info!("forget_channel stub {}", channel_id);
2967                        // We can't update the channels map here as it's immutably borrowed
2968                        // so we set a flag to remove it after the borrow is released.
2969                        stub_found = true;
2970                    }
2971                    ChannelSlot::Ready(chan) => {
2972                        info!("forget_channel {}", channel_id);
2973                        chan.forget()?;
2974                    }
2975                };
2976            } // release the slot before taking node state
2977
2978            // Potentially update the high water mark. This is the only place the high
2979            // water mark could be updated, so any changes to the node state since
2980            // acquiring the channels lock are irrelevant, and taking state after the
2981            // slot guard is dropped loses nothing.
2982            let mut node_state: MutexGuard<'_, NodeState> = self.get_state();
2983            if channel_id.oid() > node_state.dbid_high_water_mark {
2984                node_state.dbid_high_water_mark = channel_id.oid();
2985                self.persister
2986                    .update_node(&self.get_id(), &node_state)
2987                    .unwrap_or_else(|err| panic!("could not update node state: {:?}", err));
2988            }
2989        } else {
2990            debug!("forget_channel didn't find {}", channel_id);
2991        }
2992        if stub_found {
2993            channels.remove(&channel_id).unwrap();
2994            self.persister.delete_channel(&self.get_id(), &channel_id).unwrap_or_else(|err| {
2995                panic!("could not delete channel {}: {:?}", &channel_id, err)
2996            });
2997        }
2998        return Ok(());
2999    }
3000
3001    // Lock order: caller holds tracker, this acquires channels (see LOCK ORDERING)
3002    fn prune_channels(&self, tracker: &mut ChainTracker<ChainMonitor>) {
3003        // Prune stubs/channels which are no longer needed in memory.
3004        let mut channels = self.get_channels();
3005
3006        // unfortunately `btree_drain_filter` is unstable
3007        // Gather a list of all channels to prune
3008        let keys_to_remove: Vec<_> = channels
3009            .iter()
3010            .filter_map(|(key, slot_arc)| {
3011                let slot = slot_arc.lock().unwrap();
3012                match &*slot {
3013                    ChannelSlot::Ready(chan) => {
3014                        if chan.monitor.is_done() {
3015                            Some(key.clone()) // clone the channel_id0 for removal
3016                        } else {
3017                            None
3018                        }
3019                    }
3020                    ChannelSlot::Stub(stub) => {
3021                        // Stubs are priomordial channel placeholders. As soon as a commitment can
3022                        // be formed (and is subject to BOLT-2's 2016 block hold time) they are
3023                        // converted to channels.  Stubs are left behind when a channel open fails
3024                        // before a funding tx and commitment can be established.  LDK removes these
3025                        // after a few minutes.
3026                        let stub_prune_time = match self.network() {
3027                            // In the regtest network (CI) flurries of blocks are created;
3028                            // this is not realistic in the other networks.
3029                            Network::Regtest => CHANNEL_STUB_PRUNE_BLOCKS + 100,
3030                            _ => CHANNEL_STUB_PRUNE_BLOCKS,
3031                        };
3032                        if tracker.height().saturating_sub(stub.blockheight) > stub_prune_time {
3033                            Some(key.clone()) // clone the channel_id0 for removal
3034                        } else {
3035                            None
3036                        }
3037                    }
3038                }
3039            })
3040            .collect();
3041
3042        // Prune the channels
3043        let mut tracker_modified = false;
3044        for key in keys_to_remove {
3045            // checked presence above
3046            let slot = channels.remove(&key).unwrap();
3047            match &*slot.lock().unwrap() {
3048                ChannelSlot::Ready(chan) => {
3049                    info!("pruning channel {} because is_done", &key);
3050                    tracker.remove_listener(&chan.monitor.funding_outpoint);
3051                    tracker_modified = true;
3052                }
3053                ChannelSlot::Stub(_stub) => {
3054                    info!("pruning channel stub {}", &key);
3055                }
3056            };
3057            self.persister
3058                .delete_channel(&self.get_id(), &key)
3059                .unwrap_or_else(|err| panic!("could not delete channel {}: {:?}", &key, err));
3060        }
3061        if tracker_modified {
3062            self.persister
3063                .update_tracker(&self.get_id(), &tracker)
3064                .unwrap_or_else(|err| panic!("could not update tracker: {:?}", err));
3065        }
3066    }
3067
3068    /// Log channel information
3069    pub fn chaninfo(&self) -> Vec<SlotInfo> {
3070        // Gather the entries
3071        self.get_channels()
3072            .iter()
3073            .map(|(_, slot_arc)| slot_arc.lock().unwrap().chaninfo())
3074            .collect()
3075    }
3076}
3077
3078/// Trait to monitor read-only features of Node
3079pub trait NodeMonitor {
3080    ///Get the balance
3081    fn channel_balance(&self) -> ChannelBalance;
3082}
3083
3084impl NodeMonitor for Node {
3085    fn channel_balance(&self) -> ChannelBalance {
3086        let mut sum = ChannelBalance::zero();
3087        // Lock order: channels (released) -> channel_slot -> state (see LOCK
3088        // ORDERING). chan.balance() takes state under the slot, so state must
3089        // not be held here. Snapshot the slots so the channels lock is not held
3090        // while locking them either; this runs off the signing path (admin RPC,
3091        // heartbeat) and must not block it.
3092        let slot_arcs: Vec<Arc<Mutex<ChannelSlot>>> =
3093            self.get_channels().values().cloned().collect();
3094        for slot_arc in slot_arcs {
3095            let slot = slot_arc.lock().unwrap();
3096            let balance = match &*slot {
3097                ChannelSlot::Ready(chan) => chan.balance(),
3098                ChannelSlot::Stub(_stub) => ChannelBalance::stub(),
3099            };
3100            sum.accumulate(&balance);
3101        }
3102        sum
3103    }
3104}
3105
3106fn find_channel_with_funding_outpoint(
3107    channels_lock: &MutexGuard<OrderedMap<ChannelId, Arc<Mutex<ChannelSlot>>>>,
3108    outpoint: &OutPoint,
3109) -> Option<Arc<Mutex<ChannelSlot>>> {
3110    for (_, slot_arc) in channels_lock.iter() {
3111        let slot = slot_arc.lock().unwrap();
3112        match &*slot {
3113            ChannelSlot::Ready(chan) =>
3114                if chan.setup.funding_outpoint == *outpoint {
3115                    return Some(Arc::clone(slot_arc));
3116                },
3117            ChannelSlot::Stub(_stub) => {
3118                // ignore stubs ...
3119            }
3120        }
3121    }
3122    None
3123}
3124
3125impl Debug for Node {
3126    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
3127        f.write_str("node")
3128    }
3129}
3130
3131/// The type of address, for layer-1 input signing
3132#[derive(PartialEq, Clone, Copy, Debug)]
3133#[repr(i32)]
3134pub enum SpendType {
3135    /// To be signed by someone else
3136    Invalid = 0,
3137    /// Pay to public key hash
3138    P2pkh = 1,
3139    /// Pay to witness public key hash
3140    P2wpkh = 3,
3141    /// Pay to p2sh wrapped p2wpkh
3142    P2shP2wpkh = 4,
3143    /// Pay to witness script hash
3144    P2wsh = 5,
3145    /// Pay to taproot script
3146    P2tr = 6,
3147}
3148
3149impl TryFrom<i32> for SpendType {
3150    type Error = ();
3151
3152    fn try_from(i: i32) -> Result<Self, Self::Error> {
3153        let res = match i {
3154            x if x == SpendType::Invalid as i32 => SpendType::Invalid,
3155            x if x == SpendType::P2pkh as i32 => SpendType::P2pkh,
3156            x if x == SpendType::P2wpkh as i32 => SpendType::P2wpkh,
3157            x if x == SpendType::P2shP2wpkh as i32 => SpendType::P2shP2wpkh,
3158            x if x == SpendType::P2wsh as i32 => SpendType::P2wsh,
3159            x if x == SpendType::P2tr as i32 => SpendType::P2tr,
3160            _ => return Err(()),
3161        };
3162        Ok(res)
3163    }
3164}
3165
3166impl SpendType {
3167    /// Return the SpendType of a script pubkey
3168    pub fn from_script_pubkey(script: &Script) -> Self {
3169        if script.is_p2pkh() {
3170            SpendType::P2pkh
3171        } else if script.is_p2sh() {
3172            SpendType::P2shP2wpkh
3173        } else if script.is_p2wpkh() {
3174            SpendType::P2wpkh
3175        } else if script.is_p2wsh() {
3176            SpendType::P2wsh
3177        } else if script.is_p2tr() {
3178            SpendType::P2tr
3179        } else {
3180            SpendType::Invalid
3181        }
3182    }
3183}
3184
3185/// Marker trait for LDK compatible logger
3186pub trait SyncLogger: Logger + SendSync {}
3187
3188#[cfg(test)]
3189mod tests {
3190    use bitcoin::consensus::deserialize;
3191    use bitcoin::hashes::sha256d::Hash as Sha256dHash;
3192    use bitcoin::hashes::Hash;
3193    use bitcoin::secp256k1::ecdsa::{RecoverableSignature, RecoveryId};
3194    use bitcoin::secp256k1::SecretKey;
3195    use bitcoin::transaction::Version;
3196    use bitcoin::{secp256k1, BlockHash, Sequence, TxIn, Witness};
3197    use bitcoin::{Address, Amount, OutPoint};
3198    use lightning::ln::chan_utils;
3199    use lightning::ln::chan_utils::derive_private_key;
3200    use lightning::ln::channel_keys::{DelayedPaymentKey, RevocationKey};
3201    use lightning_invoice::PaymentSecret;
3202    use lightning_invoice::{Currency, InvoiceBuilder};
3203    use serde_bolt::to_vec;
3204    use std::time::{SystemTime, UNIX_EPOCH};
3205    use test_log::test;
3206    use vls_common::to_derivation_path;
3207
3208    use crate::channel::{ChannelBase, CommitmentType};
3209    use crate::policy::filter::{FilterRule, PolicyFilter};
3210    use crate::policy::simple_validator::{
3211        make_default_simple_policy, SimpleValidatorFactory, TestSimpleValidatorBuilder,
3212    };
3213    use crate::util::clock::{ManualClock, StandardClock};
3214    use crate::util::test_utils::htlc::{
3215        make_commit_info_with_htlcs, make_counterparty_commit_info_with_htlcs, make_htlc,
3216    };
3217    use crate::util::test_utils::invoice::{
3218        make_test_bolt12_invoice, make_test_unsigned_bolt12_invoice_with_params,
3219    };
3220    use crate::util::test_utils::key::make_test_pubkey;
3221    use bitcoin::hashes::sha256::Hash as Sha256Hash;
3222    use lightning::offers::offer::Quantity;
3223
3224    use crate::tx::tx::ANCHOR_SAT;
3225    use crate::util::status::{internal_error, invalid_argument, Code, Status};
3226    use crate::util::test_utils::*;
3227    use crate::util::velocity::{VelocityControlIntervalType, VelocityControlSpec};
3228    use crate::CommitmentPointProvider;
3229
3230    use core::sync::atomic::AtomicUsize;
3231    use core::sync::atomic::Ordering::Relaxed;
3232
3233    use super::*;
3234
3235    #[test]
3236    fn channel_debug_test() {
3237        let (node, channel_id) =
3238            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3239        let _status: Result<(), Status> = node.with_channel(&channel_id, |chan| {
3240            assert_eq!(format!("{:?}", chan), "channel");
3241            Ok(())
3242        });
3243    }
3244
3245    #[test]
3246    fn node_debug_test() {
3247        let (node, _channel_id) =
3248            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3249        assert_eq!(format!("{:?}", node), "node");
3250    }
3251
3252    #[test]
3253    fn node_invalid_argument_test() {
3254        let err = invalid_argument("testing invalid_argument");
3255        assert_eq!(err.code(), Code::InvalidArgument);
3256        assert_eq!(err.message(), "testing invalid_argument");
3257    }
3258
3259    #[test]
3260    fn node_internal_error_test() {
3261        let err = internal_error("testing internal_error");
3262        assert_eq!(err.code(), Code::Internal);
3263        assert_eq!(err.message(), "testing internal_error");
3264    }
3265
3266    #[test]
3267    fn new_channel_test() {
3268        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3269
3270        let (channel_id, _) = node.new_channel_with_random_id(&node).unwrap();
3271        assert!(node.get_channel(&channel_id).is_ok());
3272    }
3273
3274    #[test]
3275    fn new_channel_with_dbid_test() {
3276        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3277        let dbid: u64 = 1234;
3278        let peer_id: [u8; 33] = [0; 33];
3279
3280        let (channel_id, _) = node.new_channel(dbid, &peer_id, &node).unwrap();
3281        assert!(node.get_channel(&channel_id).is_ok());
3282    }
3283
3284    #[test]
3285    fn new_channel_with_dbid_should_fail_for_forgotten_channel_test() {
3286        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3287        let dbid = 1234;
3288        let peer_id: [u8; 33] = [0; 33];
3289
3290        let (channel_id, _) = node.new_channel(dbid, &peer_id, &node).unwrap();
3291        let _ = node.forget_channel(&channel_id);
3292
3293        let res = node.new_channel(dbid, &peer_id, &node);
3294        assert!(res.is_err());
3295        let error_msg = res.unwrap_err().to_string();
3296        assert!(error_msg
3297            .contains("policy failure: original channel id 1234 is potentially being reused"));
3298    }
3299
3300    #[test]
3301    fn new_channel_with_dbid_should_fail_for_dbid_below_previously_forgotten_dbid_test() {
3302        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3303        let dbid = 1234;
3304        let peer_id: [u8; 33] = [0; 33];
3305
3306        let (channel_id, _) = node.new_channel(dbid, &peer_id, &node).unwrap();
3307        let _ = node.forget_channel(&channel_id);
3308
3309        let res = node.new_channel(dbid - 1, &peer_id, &node);
3310        assert!(res.is_err());
3311        let error_msg = res.unwrap_err().to_string();
3312        assert!(error_msg
3313            .contains("policy failure: original channel id 1233 is potentially being reused"));
3314    }
3315
3316    #[test]
3317    fn new_channel_with_dbid_should_work_for_dbid_below_highest_but_above_last_forgotten_test() {
3318        let node: Arc<Node> = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3319        let dbid_1 = 1000;
3320        let dbid_2 = 1001;
3321        let dbid_3 = 1002;
3322        let peer_id: [u8; 33] = [0; 33];
3323
3324        let (channel_id_1, _) = node.new_channel(dbid_1, &peer_id, &node).unwrap();
3325        let _ = node.new_channel(dbid_3, &peer_id, &node);
3326        let _ = node.forget_channel(&channel_id_1);
3327
3328        let res = node.new_channel(dbid_2, &peer_id, &node);
3329        assert!(res.is_ok());
3330    }
3331
3332    #[test]
3333    fn forget_channel_should_remove_stubs_from_the_channels_map_test() {
3334        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3335        let (channel_id, _) = node.new_channel_with_random_id(&node).unwrap();
3336        let _ = node.forget_channel(&channel_id);
3337
3338        let channels = node.get_channels();
3339        assert!(channels.get(&channel_id).is_none());
3340    }
3341
3342    #[test]
3343    fn commitment_point_provider_test() {
3344        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3345        let node1 = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
3346        let (channel_id, _) = node.new_channel_with_random_id(&node).unwrap();
3347        let (channel_id1, _) = node1.new_channel_with_random_id(&node1).unwrap();
3348        let points =
3349            node.get_channel(&channel_id).unwrap().lock().unwrap().get_channel_basepoints();
3350        let points1 =
3351            node1.get_channel(&channel_id1).unwrap().lock().unwrap().get_channel_basepoints();
3352        let holder_shutdown_key_path = DerivationPath::master();
3353
3354        // note that these channels are clones of the ones in the node, so the ones in the nodes
3355        // will not be updated in this test
3356        let mut channel = node
3357            .setup_channel(
3358                channel_id.clone(),
3359                None,
3360                make_test_channel_setup_with_points(true, points1),
3361                &holder_shutdown_key_path,
3362            )
3363            .expect("setup_channel");
3364        let mut channel1 = node1
3365            .setup_channel(
3366                channel_id1.clone(),
3367                None,
3368                make_test_channel_setup_with_points(false, points),
3369                &holder_shutdown_key_path,
3370            )
3371            .expect("setup_channel 1");
3372        let commit_num = 0;
3373        next_state(&mut channel, &mut channel1, commit_num, 2_999_000, 0, vec![], vec![]);
3374
3375        let holder_point = channel.get_per_commitment_point(0).unwrap();
3376        let cp_point = channel.get_counterparty_commitment_point(0).unwrap();
3377
3378        let channel_slot = Arc::new(Mutex::new(ChannelSlot::Ready(channel)));
3379        let commitment_point_provider = ChannelCommitmentPointProvider::new(channel_slot);
3380
3381        assert_eq!(commitment_point_provider.get_holder_commitment_point(0), holder_point);
3382        assert_eq!(
3383            commitment_point_provider.get_counterparty_commitment_point(0).unwrap(),
3384            cp_point
3385        );
3386    }
3387
3388    #[test]
3389    fn bad_channel_lookup_test() -> Result<(), ()> {
3390        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3391        let channel_id = ChannelId::new(&hex_decode(TEST_CHANNEL_ID[0]).unwrap());
3392        assert!(node.get_channel(&channel_id).is_err());
3393        Ok(())
3394    }
3395
3396    #[test]
3397    fn keysend_test() {
3398        let payee_node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3399        let payee_node_id = payee_node.node_id.clone();
3400        let (node, _channel_id) =
3401            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3402        let hash = PaymentHash([2; 32]);
3403        assert!(node.add_keysend(payee_node_id.clone(), hash, 1234).unwrap());
3404        assert!(node.add_keysend(payee_node.node_id.clone(), hash, 1234).unwrap());
3405        let (_, invoice_hash) =
3406            Node::payment_state_from_keysend(payee_node_id, hash, 1234, node.clock.now()).unwrap();
3407        assert!(node.has_payment(&hash, &invoice_hash).unwrap());
3408        assert!(!node.has_payment(&PaymentHash([5; 32]), &invoice_hash).unwrap());
3409    }
3410
3411    #[test]
3412    fn invoice_test() {
3413        let payee_node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3414        let (node, channel_id) =
3415            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3416        let hash = PaymentHash([2; 32]);
3417        // TODO check currency matches
3418        let invoice1 = make_test_invoice(&payee_node, "invoice1", hash);
3419        let invoice2 = make_test_invoice(&payee_node, "invoice2", hash);
3420        assert_eq!(node.add_invoice(invoice1.clone()).expect("add invoice"), true);
3421        assert_eq!(node.add_invoice(invoice1.clone()).expect("add invoice"), true);
3422        node.add_invoice(invoice2.clone())
3423            .expect_err("add a different invoice with same payment hash");
3424
3425        let mut state = node.get_state();
3426        let hash1 = PaymentHash([1; 32]);
3427        let channel_id2 = ChannelId::new(&hex_decode(TEST_CHANNEL_ID[1]).unwrap());
3428
3429        // Create a strict invoice validator
3430        let strict_policy = make_default_simple_policy(Network::Testnet);
3431        let max_fee = strict_policy.max_routing_fee_msat / 1000;
3432        let strict_validator = SimpleValidatorFactory::new_with_policy(strict_policy)
3433            .make_validator(Network::Testnet, node.get_id(), None);
3434
3435        // Create a lenient invoice validator
3436        let mut lenient_policy = make_default_simple_policy(Network::Testnet);
3437        let lenient_filter = PolicyFilter {
3438            rules: vec![FilterRule::new_warn("policy-commitment-htlc-routing-balance")],
3439        };
3440        lenient_policy.filter.merge(lenient_filter);
3441        let lenient_validator = SimpleValidatorFactory::new_with_policy(lenient_policy)
3442            .make_validator(Network::Testnet, node.get_id(), None);
3443
3444        // Now there's an invoice
3445        assert_eq!(state.summary(), ("NodeState::summary 022d: 1 invoices, 0 issued_invoices, 1 payments, excess_amount 0, dbid_high_water_mark 0".to_string(), false));
3446
3447        state
3448            .validate_and_apply_payments(
3449                &channel_id2,
3450                &Map::new(),
3451                &vec![(hash, 99)].into_iter().collect(),
3452                &Default::default(),
3453                strict_validator.clone(),
3454            )
3455            .expect("channel1");
3456
3457        assert_eq!(state.summary(), ("NodeState::summary 022d: 1 invoices, 0 issued_invoices, 1 payments, excess_amount 0, dbid_high_water_mark 0".to_string(), false));
3458
3459        let result = state.validate_and_apply_payments(
3460            &channel_id,
3461            &Map::new(),
3462            &vec![(hash, max_fee + 2)].into_iter().collect(),
3463            &Default::default(),
3464            strict_validator.clone(),
3465        );
3466        assert_eq!(result, Err(policy_error("policy-commitment-htlc-routing-balance", "validate_payments: unbalanced payments on channel 0100000000000000000000000000000000000000000000000000000000000000: [\"0202020202020202020202020202020202020202020202020202020202020202\"]")));
3467
3468        assert_eq!(state.summary(), ("NodeState::summary 022d: 1 invoices, 0 issued_invoices, 1 payments, excess_amount 0, dbid_high_water_mark 0".to_string(), false));
3469
3470        // we should decrease the `max_fee` value otherwise we overpay in fee percentage
3471        // in this case we take the 5% of the max_fee
3472        let percentage_max_fee = (max_fee * 5) / 100;
3473        let result = state.validate_and_apply_payments(
3474            &channel_id,
3475            &Map::new(),
3476            &vec![(hash, percentage_max_fee)].into_iter().collect(),
3477            &Default::default(),
3478            strict_validator.clone(),
3479        );
3480        assert_validation_ok!(result);
3481
3482        assert_eq!(state.summary(), ("NodeState::summary 022d: 1 invoices, 0 issued_invoices, 1 payments, excess_amount 0, dbid_high_water_mark 0".to_string(), false));
3483
3484        // hash1 has no invoice, fails with strict validator, but only initially
3485        let result = state.validate_and_apply_payments(
3486            &channel_id,
3487            &Map::new(),
3488            &vec![(hash1, 5)].into_iter().collect(),
3489            &Default::default(),
3490            strict_validator.clone(),
3491        );
3492        assert_policy_err!(result, "policy-commitment-htlc-routing-balance", "validate_payments: unbalanced payments on channel 0100000000000000000000000000000000000000000000000000000000000000: [\"0101010101010101010101010101010101010101010101010101010101010101\"]");
3493
3494        assert_eq!(state.summary(), ("NodeState::summary 022d: 1 invoices, 0 issued_invoices, 1 payments, excess_amount 0, dbid_high_water_mark 0".to_string(), false));
3495
3496        // hash1 has no invoice, ok with lenient validator
3497        let result = state.validate_and_apply_payments(
3498            &channel_id,
3499            &Map::new(),
3500            &vec![(hash1, 5)].into_iter().collect(),
3501            &Default::default(),
3502            lenient_validator.clone(),
3503        );
3504        assert_validation_ok!(result);
3505
3506        assert_eq!(state.summary(), ("NodeState::summary 022d: 1 invoices, 0 issued_invoices, 2 payments, excess_amount 0, dbid_high_water_mark 0".to_string(), false));
3507
3508        // TODO(331) hash1 has no invoice, passes with strict validator once the payment exists
3509        let result = state.validate_and_apply_payments(
3510            &channel_id,
3511            &Map::new(),
3512            &vec![(hash1, 6)].into_iter().collect(),
3513            &Default::default(),
3514            strict_validator.clone(),
3515        );
3516        assert_validation_ok!(result);
3517
3518        assert_eq!(state.summary(), ("NodeState::summary 022d: 1 invoices, 0 issued_invoices, 2 payments, excess_amount 0, dbid_high_water_mark 0".to_string(), false));
3519
3520        // pretend this payment failed and went away
3521        let result = state.validate_and_apply_payments(
3522            &channel_id,
3523            &Map::new(),
3524            &vec![(hash1, 0)].into_iter().collect(),
3525            &Default::default(),
3526            strict_validator.clone(),
3527        );
3528        assert_validation_ok!(result);
3529
3530        // payment is still there
3531        assert_eq!(state.payments.len(), 2);
3532        assert_eq!(state.summary(), ("NodeState::summary 022d: 1 invoices, 0 issued_invoices, 2 payments, excess_amount 0, dbid_high_water_mark 0".to_string(), false));
3533
3534        // have to drop the state over the heartbeat because deadlock
3535        drop(state);
3536
3537        // heartbeat triggers pruning
3538        let _ = node.get_heartbeat();
3539
3540        let mut state = node.get_state();
3541
3542        // payment is pruned
3543        assert_eq!(state.payments.len(), 1);
3544        assert_eq!(state.summary(), ("NodeState::summary 022d: 1 invoices, 0 issued_invoices, 1 payments, excess_amount 0, dbid_high_water_mark 0".to_string(), false));
3545    }
3546
3547    fn make_test_invoice(
3548        payee_node: &Node,
3549        description: &str,
3550        payment_hash: PaymentHash,
3551    ) -> Invoice {
3552        sign_invoice(payee_node, build_test_invoice(description, &payment_hash))
3553    }
3554
3555    fn sign_invoice(payee_node: &Node, raw_invoice: RawBolt11Invoice) -> Invoice {
3556        payee_node.do_sign_invoice(raw_invoice).unwrap().try_into().unwrap()
3557    }
3558
3559    fn build_test_invoice(description: &str, payment_hash: &PaymentHash) -> RawBolt11Invoice {
3560        let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("time");
3561        build_test_invoice_with_time(description, payment_hash, now)
3562    }
3563
3564    fn build_test_invoice_with_time(
3565        description: &str,
3566        payment_hash: &PaymentHash,
3567        now: Duration,
3568    ) -> RawBolt11Invoice {
3569        let amount = 100_000;
3570        build_test_invoice_with_time_and_amount(description, payment_hash, now, amount)
3571    }
3572
3573    fn build_test_invoice_with_time_and_amount(
3574        description: &str,
3575        payment_hash: &PaymentHash,
3576        now: Duration,
3577        amount: u64,
3578    ) -> RawBolt11Invoice {
3579        InvoiceBuilder::new(Currency::Bitcoin)
3580            .duration_since_epoch(now)
3581            .amount_milli_satoshis(amount)
3582            .payment_hash(Sha256Hash::from_slice(&payment_hash.0).unwrap())
3583            .payment_secret(PaymentSecret([0; 32]))
3584            .description(description.to_string())
3585            .build_raw()
3586            .expect("build")
3587    }
3588
3589    #[test]
3590    fn with_channel_test() {
3591        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3592        let channel_id = ChannelId::new(&hex_decode(TEST_CHANNEL_ID[0]).unwrap());
3593        node.new_channel_with_id(channel_id.clone(), &node).expect("new_channel");
3594        assert!(node
3595            .with_channel(&channel_id, |_channel| {
3596                panic!("should not be called");
3597                #[allow(unreachable_code)]
3598                Ok(())
3599            })
3600            .is_err());
3601        assert!(node.with_channel_base(&channel_id, |_channel| { Ok(()) }).is_ok());
3602    }
3603
3604    #[test]
3605    fn too_many_channels_test() {
3606        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3607        for _ in 0..node.policy().max_channels() {
3608            node.new_channel_with_random_id(&node).expect("new_channel");
3609        }
3610        assert!(node.new_channel_with_random_id(&node).is_err());
3611    }
3612
3613    #[test]
3614    fn percentage_fee_exceeded_test() {
3615        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3616        let policy = make_default_simple_policy(Network::Testnet);
3617        let validator = SimpleValidatorFactory::new_with_policy(policy).make_validator(
3618            Network::Testnet,
3619            node.get_id(),
3620            None,
3621        );
3622
3623        // We are paying an invoice of 10 msat and the outcome of this payment is 20 msat.
3624        // This mean that the route fee 10 msat of routing fee. So this violate the policy
3625        // regarding the max routing feee percentage.
3626        let result = validator.validate_payment_balance(0, 20, Some(10));
3627
3628        // we are overpaying in percentage fee
3629        assert_eq!(
3630            result,
3631            Err(policy_error(
3632                "policy-htlc-fee-range",
3633                "validate_payment_balance: fee_percentage > max_feerate_percentage: 100% > 10%"
3634            )),
3635            "{:?}",
3636            result
3637        );
3638    }
3639
3640    #[test]
3641    fn too_many_invoices_test() {
3642        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3643        let payee_node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
3644
3645        for i in 0..node.policy().max_invoices() {
3646            let mut hash = [1u8; 32];
3647            hash[0..8].copy_from_slice(&i.to_be_bytes());
3648            let invoice =
3649                make_test_invoice(&payee_node, &format!("invoice {}", i), PaymentHash(hash));
3650            assert_eq!(node.add_invoice(invoice).expect("add invoice"), true);
3651        }
3652
3653        let invoice = make_test_invoice(&payee_node, "invoice", PaymentHash([2u8; 32]));
3654        node.add_invoice(invoice).expect_err("expected too many invoices");
3655    }
3656
3657    #[test]
3658    fn prune_invoice_test() {
3659        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3660        let invoice = make_test_invoice(&node, "invoice", PaymentHash([0; 32]));
3661        node.add_invoice(invoice.clone()).unwrap();
3662        let mut state = node.get_state();
3663        assert_eq!(state.invoices.len(), 1);
3664        assert_eq!(state.payments.len(), 1);
3665        println!("now: {:?}", node.clock.now());
3666        println!("invoice time: {:?}", invoice.duration_since_epoch());
3667        state.prune_invoices(node.clock.now());
3668        assert_eq!(state.invoices.len(), 1);
3669        assert_eq!(state.payments.len(), 1);
3670        state.prune_invoices(node.clock.now() + Duration::from_secs(3600 * 23));
3671        assert_eq!(state.invoices.len(), 1);
3672        assert_eq!(state.payments.len(), 1);
3673        state.prune_invoices(node.clock.now() + Duration::from_secs(3600 * 25));
3674        assert_eq!(state.invoices.len(), 0);
3675        assert_eq!(state.payments.len(), 0);
3676    }
3677
3678    #[test]
3679    fn prune_invoice_incomplete_test() {
3680        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3681        let invoice = make_test_invoice(&node, "invoice", PaymentHash([0; 32]));
3682        node.add_invoice(invoice.clone()).unwrap();
3683        let mut state = node.get_state();
3684        assert_eq!(state.invoices.len(), 1);
3685        assert_eq!(state.payments.len(), 1);
3686        let chan_id = ChannelId::new(&[0; 32]);
3687        state.payments.get_mut(&PaymentHash([0; 32])).unwrap().outgoing.insert(chan_id, 100);
3688        state.prune_invoices(node.clock.now());
3689        assert_eq!(state.invoices.len(), 1);
3690        assert_eq!(state.payments.len(), 1);
3691        state.prune_invoices(node.clock.now() + Duration::from_secs(3600 * 25));
3692        assert_eq!(state.invoices.len(), 1);
3693        assert_eq!(state.payments.len(), 1);
3694        state.payments.get_mut(&PaymentHash([0; 32])).unwrap().preimage =
3695            Some(PaymentPreimage([0; 32]));
3696        state.prune_invoices(node.clock.now() + Duration::from_secs(3600 * 25));
3697        assert_eq!(state.invoices.len(), 0);
3698        assert_eq!(state.payments.len(), 0);
3699    }
3700
3701    #[test]
3702    fn prune_issued_invoice_test() {
3703        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3704        let raw_invoice = build_test_invoice("invoice", &PaymentHash([0; 32]));
3705        node.sign_bolt11_invoice(raw_invoice).unwrap();
3706        let mut state = node.get_state();
3707        assert_eq!(state.issued_invoices.len(), 1);
3708        state.prune_issued_invoices(node.clock.now());
3709        assert_eq!(state.issued_invoices.len(), 1);
3710        state.prune_issued_invoices(node.clock.now() + Duration::from_secs(3600 * 23));
3711        assert_eq!(state.issued_invoices.len(), 1);
3712        state.prune_issued_invoices(node.clock.now() + Duration::from_secs(3600 * 25));
3713        assert_eq!(state.issued_invoices.len(), 0);
3714    }
3715
3716    #[test]
3717    fn drop_zero_amount_issued_invoice_test() {
3718        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3719        let raw_invoice = build_test_invoice_with_time_and_amount(
3720            "invoice",
3721            &PaymentHash([0; 32]),
3722            SystemTime::now().duration_since(UNIX_EPOCH).expect("time"),
3723            0,
3724        );
3725        node.sign_bolt11_invoice(raw_invoice).unwrap();
3726        let state = node.get_state();
3727        assert_eq!(state.issued_invoices.len(), 0);
3728    }
3729
3730    #[test]
3731    fn add_expired_invoice_test() {
3732        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3733
3734        let future =
3735            SystemTime::now().duration_since(UNIX_EPOCH).expect("time") + Duration::from_secs(3600);
3736        let invoice = sign_invoice(
3737            &*node,
3738            build_test_invoice_with_time("invoice", &PaymentHash([0; 32]), future),
3739        );
3740        assert!(node
3741            .add_invoice(invoice)
3742            .unwrap_err()
3743            .message()
3744            .starts_with("policy failure: validate_invoice: invoice is not yet valid"));
3745
3746        let past =
3747            SystemTime::now().duration_since(UNIX_EPOCH).expect("time") - Duration::from_secs(7200);
3748        let invoice = sign_invoice(
3749            &*node,
3750            build_test_invoice_with_time("invoice", &PaymentHash([0; 32]), past),
3751        );
3752        assert!(node
3753            .add_invoice(invoice)
3754            .unwrap_err()
3755            .message()
3756            .starts_with("policy failure: validate_invoice: invoice is expired"));
3757    }
3758
3759    #[test]
3760    fn too_many_issued_invoices_test() {
3761        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3762
3763        for i in 0..node.policy().max_invoices() {
3764            let mut hash = [1u8; 32];
3765            hash[0..8].copy_from_slice(&i.to_be_bytes());
3766            let raw_invoice = build_test_invoice("invoice", &PaymentHash(hash));
3767            node.sign_bolt11_invoice(raw_invoice).unwrap();
3768        }
3769
3770        let raw_invoice = build_test_invoice("invoice", &PaymentHash([2u8; 32]));
3771        node.sign_bolt11_invoice(raw_invoice).expect_err("expected too many issued invoics");
3772    }
3773
3774    #[test]
3775    fn sign_bolt12_invoice_rejects_future_timestamp_test() {
3776        let now = Duration::from_secs(10_000);
3777        let clock: Arc<dyn Clock> = Arc::new(ManualClock::new(now));
3778        let node = init_node_with_policy_and_clock(
3779            TEST_NODE_CONFIG,
3780            TEST_SEED[0],
3781            make_default_simple_policy(Network::Testnet),
3782            clock,
3783        );
3784        let invoice = make_test_unsigned_bolt12_invoice_with_params(
3785            node.get_bolt12_pubkey(),
3786            PaymentHash([21; 32]),
3787            Some(2_000),
3788            None,
3789            None,
3790            Quantity::One,
3791            now + Duration::from_secs(61),
3792            None,
3793            Some(Network::Testnet),
3794        );
3795
3796        assert!(node
3797            .sign_bolt12_invoice(&invoice)
3798            .unwrap_err()
3799            .message()
3800            .contains("not yet valid"));
3801    }
3802
3803    #[test]
3804    fn sign_bolt12_invoice_rejects_expired_test() {
3805        let now = Duration::from_secs(10_000);
3806        let clock: Arc<dyn Clock> = Arc::new(ManualClock::new(now));
3807        let node = init_node_with_policy_and_clock(
3808            TEST_NODE_CONFIG,
3809            TEST_SEED[0],
3810            make_default_simple_policy(Network::Testnet),
3811            clock,
3812        );
3813        let invoice = make_test_unsigned_bolt12_invoice_with_params(
3814            node.get_bolt12_pubkey(),
3815            PaymentHash([22; 32]),
3816            Some(2_000),
3817            None,
3818            None,
3819            Quantity::One,
3820            now - Duration::from_secs(7_201),
3821            None,
3822            Some(Network::Testnet),
3823        );
3824
3825        assert!(node.sign_bolt12_invoice(&invoice).unwrap_err().message().contains("expired"));
3826    }
3827
3828    #[test]
3829    fn sign_bolt12_invoice_tracks_issued_invoices_test() {
3830        let now = Duration::from_secs(10_000);
3831        let clock: Arc<dyn Clock> = Arc::new(ManualClock::new(now));
3832        let mut policy = make_default_simple_policy(Network::Testnet);
3833        policy.max_invoices = 1;
3834        let node = init_node_with_policy_and_clock(TEST_NODE_CONFIG, TEST_SEED[0], policy, clock);
3835
3836        let invoice1 = make_test_unsigned_bolt12_invoice_with_params(
3837            node.get_bolt12_pubkey(),
3838            PaymentHash([28; 32]),
3839            Some(2_000),
3840            None,
3841            None,
3842            Quantity::One,
3843            now,
3844            None,
3845            Some(Network::Testnet),
3846        );
3847        node.sign_bolt12_invoice(&invoice1).unwrap();
3848        assert!(node.sign_bolt12_invoice(&invoice1).is_err());
3849        assert_eq!(node.get_state().issued_invoices.len(), 1);
3850
3851        let invoice2 = make_test_unsigned_bolt12_invoice_with_params(
3852            node.get_bolt12_pubkey(),
3853            PaymentHash([29; 32]),
3854            Some(2_000),
3855            None,
3856            None,
3857            Quantity::One,
3858            now,
3859            None,
3860            Some(Network::Testnet),
3861        );
3862        assert!(node.sign_bolt12_invoice(&invoice2).is_err());
3863    }
3864
3865    #[test]
3866    fn sign_bolt12_invoice_drops_zero_amount_issued_invoice_test() {
3867        let now = Duration::from_secs(10_000);
3868        let clock: Arc<dyn Clock> = Arc::new(ManualClock::new(now));
3869        let mut policy = make_default_simple_policy(Network::Testnet);
3870        policy.max_invoices = 1;
3871        let node = init_node_with_policy_and_clock(TEST_NODE_CONFIG, TEST_SEED[0], policy, clock);
3872
3873        // LDK 0.2 drops a zero offer amount to `None`, so the invoice request would otherwise
3874        // fail to build with `MissingAmount`. Supply the zero amount on the request instead to
3875        // construct the zero-amount invoice this test needs.
3876        let zero_amount_invoice = make_test_unsigned_bolt12_invoice_with_params(
3877            node.get_bolt12_pubkey(),
3878            PaymentHash([30; 32]),
3879            Some(0),
3880            Some(0),
3881            None,
3882            Quantity::One,
3883            now,
3884            None,
3885            Some(Network::Testnet),
3886        );
3887        node.sign_bolt12_invoice(&zero_amount_invoice).unwrap();
3888        assert_eq!(node.get_state().issued_invoices.len(), 0);
3889
3890        let invoice = make_test_unsigned_bolt12_invoice_with_params(
3891            node.get_bolt12_pubkey(),
3892            PaymentHash([31; 32]),
3893            Some(2_000),
3894            None,
3895            None,
3896            Quantity::One,
3897            now,
3898            None,
3899            Some(Network::Testnet),
3900        );
3901        node.sign_bolt12_invoice(&invoice).unwrap();
3902        assert_eq!(node.get_state().issued_invoices.len(), 1);
3903    }
3904
3905    #[test]
3906    fn fulfill_test() {
3907        let payee_node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3908        let (node, channel_id) =
3909            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3910        // TODO check currency matches
3911        let preimage = PaymentPreimage([0; 32]);
3912        let hash = PaymentHash(Sha256Hash::hash(&preimage.0).to_byte_array());
3913
3914        let invoice = make_test_invoice(&payee_node, "invoice", hash);
3915
3916        assert_eq!(node.add_invoice(invoice).expect("add invoice"), true);
3917
3918        let mut policy = make_default_simple_policy(Network::Testnet);
3919        policy.enforce_balance = true;
3920        let factory = SimpleValidatorFactory::new_with_policy(policy);
3921        let invoice_validator = factory.make_validator(Network::Testnet, node.get_id(), None);
3922        node.set_validator_factory(Arc::new(factory));
3923
3924        {
3925            let mut state = node.get_state();
3926            assert_status_ok!(state.validate_and_apply_payments(
3927                &channel_id,
3928                &Map::new(),
3929                &vec![(hash, 110)].into_iter().collect(),
3930                &Default::default(),
3931                invoice_validator.clone()
3932            ));
3933        }
3934        node.with_channel(&channel_id, |chan| {
3935            chan.htlcs_fulfilled(vec![preimage]);
3936            Ok(())
3937        })
3938        .unwrap();
3939    }
3940
3941    #[test]
3942    fn fulfill_bolt12_test() {
3943        let (node, channel_id) =
3944            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3945        // TODO check currency matches
3946        let preimage = PaymentPreimage([0; 32]);
3947        let hash = PaymentHash(Sha256Hash::hash(&preimage.0).to_byte_array());
3948
3949        let invoice = make_test_bolt12_invoice("This is the invoice description", hash);
3950
3951        assert_eq!(invoice.description(), Some("This is the invoice description".to_string()));
3952
3953        assert_eq!(node.add_invoice(invoice).expect("add invoice"), true);
3954
3955        let mut policy = make_default_simple_policy(Network::Testnet);
3956        policy.enforce_balance = true;
3957        let factory = SimpleValidatorFactory::new_with_policy(policy);
3958        let invoice_validator = factory.make_validator(Network::Testnet, node.get_id(), None);
3959        node.set_validator_factory(Arc::new(factory));
3960
3961        {
3962            let mut state = node.get_state();
3963            assert_status_ok!(state.validate_and_apply_payments(
3964                &channel_id,
3965                &Map::new(),
3966                &vec![(hash, 110)].into_iter().collect(),
3967                &Default::default(),
3968                invoice_validator.clone()
3969            ));
3970        }
3971        node.with_channel(&channel_id, |chan| {
3972            chan.htlcs_fulfilled(vec![preimage]);
3973            Ok(())
3974        })
3975        .unwrap();
3976    }
3977
3978    #[test]
3979    fn overpay_test() {
3980        let payee_node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3981        let (node, channel_id) =
3982            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3983
3984        let preimage = PaymentPreimage([0; 32]);
3985        let hash = PaymentHash(Sha256Hash::hash(&preimage.0).to_byte_array());
3986
3987        let invoice = make_test_invoice(&payee_node, "invoice", hash);
3988
3989        assert_eq!(node.add_invoice(invoice).expect("add invoice"), true);
3990
3991        let mut policy = make_default_simple_policy(Network::Testnet);
3992        policy.enforce_balance = true;
3993        let max_fee = policy.max_routing_fee_msat / 1000;
3994        let factory = SimpleValidatorFactory::new_with_policy(policy);
3995        let invoice_validator = factory.make_validator(Network::Testnet, node.get_id(), None);
3996        node.set_validator_factory(Arc::new(factory));
3997
3998        {
3999            let mut state = node.get_state();
4000            assert_eq!(
4001                state.validate_and_apply_payments(
4002                    &channel_id,
4003                    &Map::new(),
4004                    &vec![(hash, 100 + max_fee + 1)].into_iter().collect(),
4005                    &Default::default(),
4006                    invoice_validator.clone()
4007                ),
4008                Err(policy_error("policy-commitment-htlc-routing-balance", "validate_payments: unbalanced payments on channel 0100000000000000000000000000000000000000000000000000000000000000: [\"66687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925\"]"))
4009            );
4010        }
4011    }
4012
4013    #[test]
4014    fn htlc_fail_test() {
4015        let payee_node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
4016        let (node, channel_id) =
4017            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
4018        // another channel ID
4019        let channel_id2 = ChannelId::new(&[1; 32]);
4020
4021        let preimage = PaymentPreimage([0; 32]);
4022        let hash = PaymentHash(Sha256Hash::hash(&preimage.0).to_byte_array());
4023
4024        let invoice = make_test_invoice(&payee_node, "invoice", hash);
4025
4026        assert_eq!(node.add_invoice(invoice).expect("add invoice"), true);
4027
4028        let policy = make_default_simple_policy(Network::Testnet);
4029        let factory = SimpleValidatorFactory::new_with_policy(policy);
4030        let invoice_validator = factory.make_validator(Network::Testnet, node.get_id(), None);
4031        node.set_validator_factory(Arc::new(factory));
4032
4033        let empty = Map::new();
4034        {
4035            let mut state = node.get_state();
4036            state
4037                .validate_and_apply_payments(
4038                    &channel_id,
4039                    &empty,
4040                    &vec![(hash, 90)].into_iter().collect(),
4041                    &Default::default(),
4042                    invoice_validator.clone(),
4043                )
4044                .unwrap();
4045            // payment summarizer now generates a zero for failed HTLCs
4046            state
4047                .validate_and_apply_payments(
4048                    &channel_id,
4049                    &empty,
4050                    &vec![(hash, 0)].into_iter().collect(),
4051                    &Default::default(),
4052                    invoice_validator.clone(),
4053                )
4054                .unwrap();
4055            state
4056                .validate_and_apply_payments(
4057                    &channel_id2,
4058                    &empty,
4059                    &vec![(hash, 90)].into_iter().collect(),
4060                    &Default::default(),
4061                    invoice_validator.clone(),
4062                )
4063                .unwrap();
4064        }
4065    }
4066
4067    // policy-routing-deltas-only-htlc
4068    #[test]
4069    fn shortfall_test() {
4070        let (node, channel_id) =
4071            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
4072
4073        let mut policy = make_default_simple_policy(Network::Testnet);
4074        policy.enforce_balance = true;
4075        let factory = SimpleValidatorFactory::new_with_policy(policy);
4076        let invoice_validator = factory.make_validator(Network::Testnet, node.get_id(), None);
4077        node.set_validator_factory(Arc::new(factory));
4078
4079        {
4080            let mut state = node.get_state();
4081            assert_eq!(
4082                state.validate_and_apply_payments(
4083                    &channel_id,
4084                    &Map::new(),
4085                    &Map::new(),
4086                    &BalanceDelta(0, 0),
4087                    invoice_validator.clone()
4088                ),
4089                Ok(())
4090            );
4091            assert_eq!(
4092                state.validate_and_apply_payments(
4093                    &channel_id,
4094                    &Map::new(),
4095                    &Map::new(),
4096                    &BalanceDelta(1, 0),
4097                    invoice_validator.clone()
4098                ),
4099                Err(policy_error("policy-routing-balanced", "shortfall 0 + 0 - 1"))
4100            );
4101        }
4102    }
4103
4104    #[test]
4105    fn sign_invoice_no_amount_test() {
4106        let (node, _channel_id) =
4107            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
4108        let preimage = PaymentPreimage([0; 32]);
4109        let hash = PaymentHash(Sha256Hash::hash(&preimage.0).to_byte_array());
4110        let raw_invoice = InvoiceBuilder::new(Currency::Bitcoin)
4111            .duration_since_epoch(Duration::from_secs(123456789))
4112            .payment_hash(Sha256Hash::from_slice(&hash.0).unwrap())
4113            .payment_secret(PaymentSecret([0; 32]))
4114            .description("".to_string())
4115            .build_raw()
4116            .expect("build");
4117
4118        // This records the issued invoice
4119        node.sign_bolt11_invoice(raw_invoice).unwrap();
4120    }
4121
4122    #[test]
4123    fn incoming_payment_test() {
4124        let (node, channel_id) =
4125            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
4126        // TODO check currency matches
4127        let preimage = PaymentPreimage([0; 32]);
4128        let hash = PaymentHash(Sha256Hash::hash(&preimage.0).to_byte_array());
4129
4130        let raw_invoice = build_test_invoice("invoice", &hash);
4131        // This records the issued invoice
4132        node.sign_bolt11_invoice(raw_invoice).unwrap();
4133
4134        let mut policy = make_default_simple_policy(Network::Testnet);
4135        policy.enforce_balance = true;
4136        let factory = SimpleValidatorFactory::new_with_policy(policy);
4137        let invoice_validator = factory.make_validator(Network::Testnet, node.get_id(), None);
4138
4139        {
4140            let mut state = node.get_state();
4141            assert!(!state.issued_invoices.get(&hash).unwrap().is_fulfilled);
4142            // Underpaid
4143            state
4144                .validate_and_apply_payments(
4145                    &channel_id,
4146                    &vec![(hash, 99)].into_iter().collect(),
4147                    &Map::new(),
4148                    &Default::default(),
4149                    invoice_validator.clone(),
4150                )
4151                .expect("ok");
4152            assert!(!state.payments.get(&hash).unwrap().is_fulfilled());
4153            assert!(!state.issued_invoices.get(&hash).unwrap().is_fulfilled);
4154            // Paid
4155            state
4156                .validate_and_apply_payments(
4157                    &channel_id,
4158                    &vec![(hash, 100)].into_iter().collect(),
4159                    &Map::new(),
4160                    &Default::default(),
4161                    invoice_validator.clone(),
4162                )
4163                .expect("ok");
4164            assert!(state.payments.get(&hash).unwrap().is_fulfilled());
4165            assert!(state.issued_invoices.get(&hash).unwrap().is_fulfilled);
4166            // Already paid
4167            state
4168                .validate_and_apply_payments(
4169                    &channel_id,
4170                    &vec![(hash, 100)].into_iter().collect(),
4171                    &Map::new(),
4172                    &Default::default(),
4173                    invoice_validator.clone(),
4174                )
4175                .expect("ok");
4176            assert!(state.payments.get(&hash).unwrap().is_fulfilled());
4177            assert!(state.issued_invoices.get(&hash).unwrap().is_fulfilled);
4178        }
4179    }
4180
4181    #[test]
4182    fn issued_invoice_fulfilled_on_preimage_test() {
4183        let (node, channel_id) =
4184            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
4185        let preimage = PaymentPreimage([1; 32]);
4186        let hash = PaymentHash(Sha256Hash::hash(&preimage.0).to_byte_array());
4187
4188        let raw_invoice = build_test_invoice("invoice", &hash);
4189        node.sign_bolt11_invoice(raw_invoice).unwrap();
4190
4191        let mut policy = make_default_simple_policy(Network::Testnet);
4192        policy.enforce_balance = true;
4193        let factory = SimpleValidatorFactory::new_with_policy(policy);
4194        let invoice_validator = factory.make_validator(Network::Testnet, node.get_id(), None);
4195
4196        {
4197            let mut state = node.get_state();
4198            assert!(!state.issued_invoices.get(&hash).unwrap().is_fulfilled);
4199            state.htlc_fulfilled(&channel_id, preimage, invoice_validator.clone());
4200            assert!(state.issued_invoices.get(&hash).unwrap().is_fulfilled);
4201        }
4202    }
4203
4204    #[test]
4205    fn get_per_commitment_point_and_secret_test() {
4206        let (node, channel_id) =
4207            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
4208
4209        let commit_num = 23;
4210
4211        let (point, secret) = node
4212            .with_channel(&channel_id, |chan| {
4213                // The channel next_holder_commit_num must be 2 past the
4214                // requested commit_num for get_per_commitment_secret.
4215                chan.enforcement_state.set_next_holder_commit_num_for_testing(commit_num + 2);
4216                let point = chan.get_per_commitment_point(commit_num)?;
4217                let secret = chan.get_per_commitment_secret(commit_num)?;
4218
4219                assert_eq!(chan.get_per_commitment_secret_or_none(commit_num), Some(secret));
4220                assert_eq!(chan.get_per_commitment_secret_or_none(commit_num + 1), None);
4221
4222                Ok((point, secret))
4223            })
4224            .expect("point");
4225
4226        let derived_point = PublicKey::from_secret_key(&Secp256k1::new(), &secret);
4227
4228        assert_eq!(point, derived_point);
4229    }
4230
4231    #[test]
4232    fn get_check_future_secret_test() {
4233        let (node, channel_id) =
4234            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
4235
4236        let n: u64 = 10;
4237
4238        let suggested = SecretKey::from_slice(
4239            hex_decode("2f87fef68f2bafdb3c6425921894af44da9a984075c70c7ba31ccd551b3585db")
4240                .unwrap()
4241                .as_slice(),
4242        )
4243        .unwrap();
4244
4245        let correct = node
4246            .with_channel_base(&channel_id, |base| base.check_future_secret(n, &suggested))
4247            .unwrap();
4248        assert_eq!(correct, true);
4249
4250        let notcorrect = node
4251            .with_channel_base(&channel_id, |base| base.check_future_secret(n + 1, &suggested))
4252            .unwrap();
4253        assert_eq!(notcorrect, false);
4254    }
4255
4256    #[test]
4257    fn sign_channel_announcement_with_funding_key_test() {
4258        let (node, channel_id) =
4259            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
4260
4261        let ann = hex_decode("0123456789abcdef").unwrap();
4262        let bsig = node
4263            .with_channel(&channel_id, |chan| {
4264                Ok(chan.sign_channel_announcement_with_funding_key(&ann))
4265            })
4266            .unwrap();
4267
4268        let ca_hash = Sha256dHash::hash(&ann);
4269        let encmsg = Message::from_digest(ca_hash.to_byte_array());
4270        let secp_ctx = Secp256k1::new();
4271        node.with_channel(&channel_id, |chan| {
4272            let funding_pubkey =
4273                PublicKey::from_secret_key(&secp_ctx, &chan.keys.funding_key(None));
4274            Ok(secp_ctx.verify_ecdsa(&encmsg, &bsig, &funding_pubkey).expect("verify bsig"))
4275        })
4276        .unwrap();
4277    }
4278
4279    #[test]
4280    fn sign_node_announcement_test() -> Result<(), ()> {
4281        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4282        let ann = hex_decode("000302aaa25e445fef0265b6ab5ec860cd257865d61ef0bbf5b3339c36cbda8b26b74e7f1dca490b65180265b64c4f554450484f544f2d2e302d3139392d67613237336639642d6d6f646465640000").unwrap();
4283        let sigvec = node.sign_node_announcement(&ann).unwrap().serialize_der().to_vec();
4284        assert_eq!(sigvec, hex_decode("30450221008ef1109b95f127a7deec63b190b72180f0c2692984eaf501c44b6bfc5c4e915502207a6fa2f250c5327694967be95ff42a94a9c3d00b7fa0fbf7daa854ceb872e439").unwrap());
4285        Ok(())
4286    }
4287
4288    #[test]
4289    fn sign_channel_update_test() -> Result<(), ()> {
4290        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4291        let cu = hex_decode("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f00006700000100015e42ddc6010000060000000000000000000000010000000a000000003b023380").unwrap();
4292        let sigvec = node.sign_channel_update(&cu).unwrap().serialize_der().to_vec();
4293        assert_eq!(sigvec, hex_decode("3045022100be9840696c868b161aaa997f9fa91a899e921ea06c8083b2e1ea32b8b511948d0220352eec7a74554f97c2aed26950b8538ca7d7d7568b42fd8c6f195bd749763fa5").unwrap());
4294        Ok(())
4295    }
4296
4297    #[test]
4298    fn sign_invoice_test() -> Result<(), ()> {
4299        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4300        let human_readable_part = String::from("lnbcrt1230n");
4301        let data_part = hex_decode("010f0418090a010101141917110f01040e050f06100003021e1b0e13161c150301011415060204130c0018190d07070a18070a1c1101111e111f130306000d00120c11121706181b120d051807081a0b0f0d18060004120e140018000105100114000b130b01110c001a05041a181716020007130c091d11170d10100d0b1a1b00030e05190208171e16080d00121a00110719021005000405001000").unwrap().check_base32().unwrap();
4302        let raw_invoice = RawBolt11Invoice::from_raw(&human_readable_part, &data_part).unwrap();
4303        let (rid, rsig) = node.sign_bolt11_invoice(raw_invoice).unwrap().serialize_compact();
4304        assert_eq!(rsig.to_vec(), hex_decode("739ffb91aa7c0b3d3c92de1600f7a9afccedc5597977095228232ee4458685531516451b84deb35efad27a311ea99175d10c6cdb458cd27ce2ed104eb6cf8064").unwrap());
4305        assert_eq!(rid.to_i32(), 0);
4306        Ok(())
4307    }
4308
4309    #[test]
4310    fn sign_invoice_with_overhang_test() -> Result<(), ()> {
4311        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4312        let human_readable_part = String::from("lnbcrt2m");
4313        let data_part = hex_decode("010f0a001d051e0101140c0c000006140009160c09051a0d1a190708020d17141106171f0f07131616111f1910070b0d0e150c0c0c0d010d1a01181c15100d010009181a06101a0a0309181b040a111a0a06111705100c0b18091909030e151b14060004120e14001800010510011419080f1307000a0a0517021c171410101a1e101605050a08180d0d110e13150409051d02091d181502020f050e1a1f161a09130005000405001000").unwrap().check_base32().unwrap();
4314        // The data_part is 170 bytes.
4315        // overhang = (data_part.len() * 5) % 8 = 2
4316        // looking for a verified invoice where overhang is in 1..3
4317        let raw_invoice = RawBolt11Invoice::from_raw(&human_readable_part, &data_part).unwrap();
4318        let (rid, rsig) = node.sign_bolt11_invoice(raw_invoice).unwrap().serialize_compact();
4319        assert_eq!(rsig.to_vec(), hex_decode("f278cdba3fd4a37abf982cee5a66f52e142090631ef57763226f1232eead78b43da7962fcfe29ffae9bd918c588df71d6d7b92a4787de72801594b22f0e7e62a").unwrap());
4320        assert_eq!(rid.to_i32(), 0);
4321        Ok(())
4322    }
4323
4324    #[test]
4325    fn ecdh_test() {
4326        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4327        let pointvec =
4328            hex_decode("0330febba06ba074378dec994669cf5ebf6b15e24a04ec190fb93a9482e841a0ca")
4329                .unwrap();
4330        let other_key = PublicKey::from_slice(pointvec.as_slice()).unwrap();
4331
4332        let ssvec = node.ecdh(&other_key);
4333        assert_eq!(
4334            ssvec,
4335            hex_decode("48db1582f4b42a0068b5727fd37090a65fbf1f9bd842f4393afc2e794719ae47").unwrap()
4336        );
4337    }
4338
4339    #[test]
4340    fn spend_anchor_test() {
4341        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
4342        let node1 = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4343        let (channel_id, _) = node.new_channel_with_random_id(&node).unwrap();
4344        let (channel_id1, _) = node1.new_channel_with_random_id(&node1).unwrap();
4345        let points =
4346            node.get_channel(&channel_id).unwrap().lock().unwrap().get_channel_basepoints();
4347        let points1 =
4348            node1.get_channel(&channel_id1).unwrap().lock().unwrap().get_channel_basepoints();
4349        let holder_shutdown_key_path = DerivationPath::master();
4350
4351        // note that these channels are clones of the ones in the node, so the ones in the nodes
4352        // will not be updated in this test
4353        let mut channel = node
4354            .setup_channel(
4355                channel_id.clone(),
4356                None,
4357                make_test_channel_setup_with_points(true, points1),
4358                &holder_shutdown_key_path,
4359            )
4360            .expect("setup_channel");
4361        let mut channel1 = node1
4362            .setup_channel(
4363                channel_id1.clone(),
4364                None,
4365                make_test_channel_setup_with_points(false, points),
4366                &holder_shutdown_key_path,
4367            )
4368            .expect("setup_channel 1");
4369        let commit_num = 0;
4370        next_state(&mut channel, &mut channel1, commit_num, 2_999_000, 0, vec![], vec![]);
4371
4372        let txs = channel.sign_holder_commitment_tx_for_recovery(&[], None).unwrap();
4373        let holder_tx = txs.0;
4374        // find anchor output by value
4375        let idx =
4376            holder_tx.output.iter().position(|o| o.value == ANCHOR_SAT).expect("anchor output");
4377        // spend the anchor
4378        let mut spend_tx = Transaction {
4379            version: Version::TWO,
4380            lock_time: bitcoin::absolute::LockTime::ZERO,
4381            input: vec![TxIn {
4382                previous_output: OutPoint { txid: holder_tx.compute_txid(), vout: idx as u32 },
4383                sequence: Sequence::MAX,
4384                witness: Witness::new(),
4385                script_sig: ScriptBuf::new(),
4386            }],
4387            output: vec![TxOut { value: ANCHOR_SAT, script_pubkey: ScriptBuf::new() }],
4388        };
4389        // sign the spend
4390        let sig = channel.sign_holder_anchor_input(&spend_tx, idx).unwrap();
4391        let anchor_redeemscript = channel.get_keyed_anchor_redeemscript();
4392        let witness = vec![signature_to_bitcoin_vec(sig), anchor_redeemscript.to_bytes()];
4393        spend_tx.input[0].witness = Witness::from_slice(&witness);
4394        // verify the transaction
4395        spend_tx
4396            .verify(|point| Some(holder_tx.output[point.vout as usize].clone()))
4397            .expect("verify");
4398    }
4399
4400    #[test]
4401    fn get_unilateral_close_key_anchors_test() {
4402        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
4403        let (channel_id, chan) = node.new_channel_with_random_id(&node).unwrap();
4404
4405        let mut setup = make_test_channel_setup();
4406        setup.commitment_type = CommitmentType::AnchorsZeroFeeHtlc;
4407
4408        node.setup_channel(channel_id.clone(), None, setup, &DerivationPath::master())
4409            .expect("ready channel");
4410
4411        let uck = node
4412            .with_channel(&channel_id, |chan| chan.get_unilateral_close_key(&None, &None))
4413            .unwrap();
4414        let keys = &chan.as_ref().unwrap().unwrap_stub().keys;
4415        let secp_ctx = Secp256k1::new();
4416        let pubkey = keys.pubkeys(&secp_ctx).payment_point;
4417        let redeem_script = chan_utils::get_to_countersigner_keyed_anchor_redeemscript(&pubkey);
4418
4419        assert_eq!(
4420            uck,
4421            (
4422                SecretKey::from_slice(
4423                    &hex_decode("e6eb522940c9d1dcffc82f4eaff5b81ad318bdaa952061fa73fd6f717f73e160")
4424                        .unwrap()[..]
4425                )
4426                .unwrap(),
4427                vec![redeem_script.to_bytes()]
4428            )
4429        );
4430    }
4431
4432    #[test]
4433    fn get_unilateral_close_key_test() {
4434        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
4435        let (channel_id, chan) = node.new_channel_with_random_id(&node).unwrap();
4436
4437        node.setup_channel(
4438            channel_id.clone(),
4439            None,
4440            make_test_channel_setup(),
4441            &DerivationPath::master(),
4442        )
4443        .expect("ready channel");
4444
4445        let uck = node
4446            .with_channel(&channel_id, |chan| chan.get_unilateral_close_key(&None, &None))
4447            .unwrap();
4448        let keys = &chan.as_ref().unwrap().unwrap_stub().keys;
4449        let secp_ctx = Secp256k1::new();
4450        let key = keys.pubkeys(&secp_ctx).payment_point;
4451
4452        assert_eq!(
4453            uck,
4454            (
4455                SecretKey::from_slice(
4456                    &hex_decode("e6eb522940c9d1dcffc82f4eaff5b81ad318bdaa952061fa73fd6f717f73e160")
4457                        .unwrap()[..]
4458                )
4459                .unwrap(),
4460                vec![key.serialize().to_vec()]
4461            )
4462        );
4463
4464        let secp_ctx = Secp256k1::new();
4465        let revocation_secret = SecretKey::from_slice(
4466            hex_decode("0101010101010101010101010101010101010101010101010101010101010101")
4467                .unwrap()
4468                .as_slice(),
4469        )
4470        .unwrap();
4471        let revocation_point = PublicKey::from_secret_key(&secp_ctx, &revocation_secret);
4472        let revocation_point = RevocationKey(revocation_point);
4473        let commitment_secret = SecretKey::from_slice(
4474            hex_decode("0101010101010101010101010101010101010101010101010101010101010102")
4475                .unwrap()
4476                .as_slice(),
4477        )
4478        .unwrap();
4479        let commitment_point = PublicKey::from_secret_key(&secp_ctx, &commitment_secret);
4480        let uck = node
4481            .with_channel(&channel_id, |chan| {
4482                chan.get_unilateral_close_key(&Some(commitment_point), &Some(revocation_point))
4483            })
4484            .unwrap();
4485
4486        let seckey =
4487            derive_private_key(&secp_ctx, &commitment_point, &keys.delayed_payment_base_key);
4488        let pubkey = PublicKey::from_secret_key(&secp_ctx, &seckey);
4489
4490        let redeem_script = chan_utils::get_revokeable_redeemscript(
4491            &revocation_point,
4492            7,
4493            &DelayedPaymentKey(pubkey),
4494        );
4495
4496        assert_eq!(
4497            uck,
4498            (
4499                SecretKey::from_slice(
4500                    &hex_decode("fd5f03ea7b42be9a045097dfa1ef007a430f576302c76e6e6265812f1d1ce18f")
4501                        .unwrap()[..]
4502                )
4503                .unwrap(),
4504                vec![vec![], redeem_script.to_bytes()]
4505            )
4506        );
4507    }
4508
4509    #[test]
4510    fn get_account_ext_pub_key_test() {
4511        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4512        let xpub = node.get_account_extended_pubkey();
4513        assert_eq!(format!("{}", xpub), "tpubDAu312RD7nE6R9qyB4xJk9QAMyi3ppq3UJ4MMUGpB9frr6eNDd8FJVPw27zTVvWAfYFVUtJamgfh5ZLwT23EcymYgLx7MHsU8zZxc9L3GKk");
4514    }
4515
4516    #[test]
4517    fn check_wallet_pubkey_test() {
4518        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4519        assert_eq!(
4520            node.check_wallet_pubkey(
4521                &to_derivation_path(&[1u32]),
4522                bitcoin::PublicKey::from_slice(
4523                    hex_decode(
4524                        "0330febba06ba074378dec994669cf5ebf6b15e24a04ec190fb93a9482e841a0ca"
4525                    )
4526                    .unwrap()
4527                    .as_slice()
4528                )
4529                .unwrap()
4530            )
4531            .unwrap(),
4532            false,
4533        );
4534        assert_eq!(
4535            node.check_wallet_pubkey(
4536                &to_derivation_path(&[1u32]),
4537                bitcoin::PublicKey::from_slice(
4538                    hex_decode(
4539                        "0207ec2b35534712d86ae030dd9bfaec08e2ddea1ec1cecffb9725ed7acb12ab66"
4540                    )
4541                    .unwrap()
4542                    .as_slice()
4543                )
4544                .unwrap()
4545            )
4546            .unwrap(),
4547            true,
4548        );
4549    }
4550
4551    #[test]
4552    fn sign_bolt12_test() {
4553        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4554        node.sign_bolt12("name".as_bytes(), "field".as_bytes(), &[0; 32], None).unwrap();
4555    }
4556
4557    #[test]
4558    fn sign_message_test() {
4559        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4560        let message = String::from("Testing 1 2 3").into_bytes();
4561        let mut rsigvec = node.sign_message(&message).unwrap();
4562        let rid = rsigvec.pop().unwrap() as i32;
4563        let rsig =
4564            RecoverableSignature::from_compact(&rsigvec[..], RecoveryId::from_i32(rid).unwrap())
4565                .unwrap();
4566        let secp_ctx = secp256k1::Secp256k1::new();
4567        let mut buffer = String::from("Lightning Signed Message:").into_bytes();
4568        buffer.extend(message);
4569        let hash = Sha256dHash::hash(&buffer);
4570        let encmsg = Message::from_digest(hash.to_byte_array());
4571        let sig = Signature::from_compact(&rsig.to_standard().serialize_compact()).unwrap();
4572        let pubkey = secp_ctx.recover_ecdsa(&encmsg, &rsig).unwrap();
4573        assert!(secp_ctx.verify_ecdsa(&encmsg, &sig, &pubkey).is_ok());
4574        assert_eq!(pubkey.serialize().to_vec(), node.get_id().serialize().to_vec());
4575    }
4576
4577    #[test]
4578    fn peer_storage_key_bytes_test() {
4579        use lightning::sign::NodeSigner;
4580        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4581        let bytes = node.get_peer_storage_key_bytes();
4582        // The signer is the source of truth; this is shipped to the client in HsmdInit2Reply.
4583        assert_eq!(bytes, node.keys_manager.get_peer_storage_key().inner);
4584        // A real derived key is not a constant.
4585        assert_ne!(bytes, [0u8; 32]);
4586        assert_ne!(bytes, [1u8; 32]);
4587    }
4588
4589    #[test]
4590    fn inbound_payment_key_bytes_test() {
4591        use lightning::ln::inbound_payment::ExpandedKey;
4592        use lightning::sign::NodeSigner;
4593        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4594        let bytes = node.get_inbound_payment_key_bytes();
4595        // The signer is the source of truth; this seed ships to the client in HsmdInit2Reply,
4596        // where `ExpandedKey::new(bytes)` must reconstruct the signer's own expanded key.
4597        assert_eq!(ExpandedKey::new(bytes), node.keys_manager.get_expanded_key());
4598        // A real derived key is not a constant.
4599        assert_ne!(bytes, [0u8; 32]);
4600        assert_ne!(bytes, [1u8; 32]);
4601    }
4602
4603    // TODO move this elsewhere
4604    #[test]
4605    fn transaction_verify_test() {
4606        // a random recent segwit transaction from blockchain using both old and segwit inputs
4607        let spending: Transaction = deserialize(hex_decode("020000000001031cfbc8f54fbfa4a33a30068841371f80dbfe166211242213188428f437445c91000000006a47304402206fbcec8d2d2e740d824d3d36cc345b37d9f65d665a99f5bd5c9e8d42270a03a8022013959632492332200c2908459547bf8dbf97c65ab1a28dec377d6f1d41d3d63e012103d7279dfb90ce17fe139ba60a7c41ddf605b25e1c07a4ddcb9dfef4e7d6710f48feffffff476222484f5e35b3f0e43f65fc76e21d8be7818dd6a989c160b1e5039b7835fc00000000171600140914414d3c94af70ac7e25407b0689e0baa10c77feffffffa83d954a62568bbc99cc644c62eb7383d7c2a2563041a0aeb891a6a4055895570000000017160014795d04cc2d4f31480d9a3710993fbd80d04301dffeffffff06fef72f000000000017a91476fd7035cd26f1a32a5ab979e056713aac25796887a5000f00000000001976a914b8332d502a529571c6af4be66399cd33379071c588ac3fda0500000000001976a914fc1d692f8de10ae33295f090bea5fe49527d975c88ac522e1b00000000001976a914808406b54d1044c429ac54c0e189b0d8061667e088ac6eb68501000000001976a914dfab6085f3a8fb3e6710206a5a959313c5618f4d88acbba20000000000001976a914eb3026552d7e3f3073457d0bee5d4757de48160d88ac0002483045022100bee24b63212939d33d513e767bc79300051f7a0d433c3fcf1e0e3bf03b9eb1d70220588dc45a9ce3a939103b4459ce47500b64e23ab118dfc03c9caa7d6bfc32b9c601210354fd80328da0f9ae6eef2b3a81f74f9a6f66761fadf96f1d1d22b1fd6845876402483045022100e29c7e3a5efc10da6269e5fc20b6a1cb8beb92130cc52c67e46ef40aaa5cac5f0220644dd1b049727d991aece98a105563416e10a5ac4221abac7d16931842d5c322012103960b87412d6e169f30e12106bdf70122aabb9eb61f455518322a18b920a4dfa887d30700")
4608            .unwrap().as_slice()).unwrap();
4609        let spent1: Transaction = deserialize(hex_decode("020000000001040aacd2c49f5f3c0968cfa8caf9d5761436d95385252e3abb4de8f5dcf8a582f20000000017160014bcadb2baea98af0d9a902e53a7e9adff43b191e9feffffff96cd3c93cac3db114aafe753122bd7d1afa5aa4155ae04b3256344ecca69d72001000000171600141d9984579ceb5c67ebfbfb47124f056662fe7adbfeffffffc878dd74d3a44072eae6178bb94b9253177db1a5aaa6d068eb0e4db7631762e20000000017160014df2a48cdc53dae1aba7aa71cb1f9de089d75aac3feffffffe49f99275bc8363f5f593f4eec371c51f62c34ff11cc6d8d778787d340d6896c0100000017160014229b3b297a0587e03375ab4174ef56eeb0968735feffffff03360d0f00000000001976a9149f44b06f6ee92ddbc4686f71afe528c09727a5c788ac24281b00000000001976a9140277b4f68ff20307a2a9f9b4487a38b501eb955888ac227c0000000000001976a9148020cd422f55eef8747a9d418f5441030f7c9c7788ac0247304402204aa3bd9682f9a8e101505f6358aacd1749ecf53a62b8370b97d59243b3d6984f02200384ad449870b0e6e89c92505880411285ecd41cf11e7439b973f13bad97e53901210205b392ffcb83124b1c7ce6dd594688198ef600d34500a7f3552d67947bbe392802473044022033dfd8d190a4ae36b9f60999b217c775b96eb10dee3a1ff50fb6a75325719106022005872e4e36d194e49ced2ebcf8bb9d843d842e7b7e0eb042f4028396088d292f012103c9d7cbf369410b090480de2aa15c6c73d91b9ffa7d88b90724614b70be41e98e0247304402207d952de9e59e4684efed069797e3e2d993e9f98ec8a9ccd599de43005fe3f713022076d190cc93d9513fc061b1ba565afac574e02027c9efbfa1d7b71ab8dbb21e0501210313ad44bc030cc6cb111798c2bf3d2139418d751c1e79ec4e837ce360cc03b97a024730440220029e75edb5e9413eb98d684d62a077b17fa5b7cc19349c1e8cc6c4733b7b7452022048d4b9cae594f03741029ff841e35996ef233701c1ea9aa55c301362ea2e2f68012103590657108a72feb8dc1dec022cf6a230bb23dc7aaa52f4032384853b9f8388baf9d20700")
4610            .unwrap().as_slice()).unwrap();
4611        let spent2: Transaction = deserialize(hex_decode("0200000000010166c3d39490dc827a2594c7b17b7d37445e1f4b372179649cd2ce4475e3641bbb0100000017160014e69aa750e9bff1aca1e32e57328b641b611fc817fdffffff01e87c5d010000000017a914f3890da1b99e44cd3d52f7bcea6a1351658ea7be87024830450221009eb97597953dc288de30060ba02d4e91b2bde1af2ecf679c7f5ab5989549aa8002202a98f8c3bd1a5a31c0d72950dd6e2e3870c6c5819a6c3db740e91ebbbc5ef4800121023f3d3b8e74b807e32217dea2c75c8d0bd46b8665b3a2d9b3cb310959de52a09bc9d20700")
4612            .unwrap().as_slice()).unwrap();
4613        let spent3: Transaction = deserialize(hex_decode("01000000027a1120a30cef95422638e8dab9dedf720ec614b1b21e451a4957a5969afb869d000000006a47304402200ecc318a829a6cad4aa9db152adbf09b0cd2de36f47b53f5dade3bc7ef086ca702205722cda7404edd6012eedd79b2d6f24c0a0c657df1a442d0a2166614fb164a4701210372f4b97b34e9c408741cd1fc97bcc7ffdda6941213ccfde1cb4075c0f17aab06ffffffffc23b43e5a18e5a66087c0d5e64d58e8e21fcf83ce3f5e4f7ecb902b0e80a7fb6010000006b483045022100f10076a0ea4b4cf8816ed27a1065883efca230933bf2ff81d5db6258691ff75202206b001ef87624e76244377f57f0c84bc5127d0dd3f6e0ef28b276f176badb223a01210309a3a61776afd39de4ed29b622cd399d99ecd942909c36a8696cfd22fc5b5a1affffffff0200127a000000000017a914f895e1dd9b29cb228e9b06a15204e3b57feaf7cc8769311d09000000001976a9144d00da12aaa51849d2583ae64525d4a06cd70fde88ac00000000")
4614            .unwrap().as_slice()).unwrap();
4615
4616        println!("{:?}", &spending.compute_txid());
4617        println!("{:?}", &spent1.compute_txid());
4618        println!("{:?}", &spent2.compute_txid());
4619        println!("{:?}", &spent3.compute_txid());
4620        println!("{:?}", &spent1.output[0].script_pubkey);
4621        println!("{:?}", &spent2.output[0].script_pubkey);
4622        println!("{:?}", &spent3.output[0].script_pubkey);
4623
4624        let mut spent = Map::new();
4625        spent.insert(spent1.compute_txid(), spent1);
4626        spent.insert(spent2.compute_txid(), spent2);
4627        spent.insert(spent3.compute_txid(), spent3);
4628        spending
4629            .verify(|point: &OutPoint| {
4630                if let Some(tx) = spent.remove(&point.txid) {
4631                    return tx.output.get(point.vout as usize).cloned();
4632                }
4633                None
4634            })
4635            .unwrap();
4636    }
4637
4638    // TODO move this elsewhere
4639    #[test]
4640    fn bip143_p2wpkh_test() {
4641        let tx: Transaction = deserialize(hex_decode("0100000002fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f0000000000eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac11000000")
4642            .unwrap().as_slice()).unwrap();
4643        let secp_ctx = Secp256k1::signing_only();
4644        let priv2 = SecretKey::from_slice(
4645            hex_decode("619c335025c7f4012e556c2a58b2506e30b8511b53ade95ea316fd8c3286feb9")
4646                .unwrap()
4647                .as_slice(),
4648        )
4649        .unwrap();
4650        let pub2 = bitcoin::PublicKey::from_slice(
4651            &PublicKey::from_secret_key(&secp_ctx, &priv2).serialize(),
4652        )
4653        .unwrap();
4654
4655        let script_code =
4656            Address::p2wpkh(&CompressedPublicKey(pub2.inner), Network::Testnet).script_pubkey();
4657        let value = 600_000_000;
4658
4659        let sighash = &SighashCache::new(&tx)
4660            .p2wpkh_signature_hash(1, &script_code, Amount::from_sat(value), EcdsaSighashType::All)
4661            .unwrap()[..];
4662        assert_eq!(
4663            hex_encode(sighash),
4664            "c37af31116d1b27caf68aae9e3ac82f1477929014d5b917657d0eb49478cb670"
4665        );
4666    }
4667
4668    fn vecs_match<T: PartialEq + Ord>(mut a: Vec<T>, mut b: Vec<T>) -> bool {
4669        a.sort();
4670        b.sort();
4671        let matching = a.iter().zip(b.iter()).filter(|&(a, b)| a == b).count();
4672        matching == a.len() && matching == b.len()
4673    }
4674
4675    #[test]
4676    fn allowlist_test() {
4677        assert!(Allowable::from_str(
4678            "address:mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB",
4679            Network::Bitcoin
4680        )
4681        .is_err());
4682
4683        assert!(Allowable::from_str("xpub:tpubDEQBfiy13hMZzGT4NWqNnaSWwVqYQ58kuu2pDYjkrf8F6DLKAprm8c65Pyh7PrzodXHtJuEXFu5yf6JbvYaL8rz7v28zapwbuzZzr7z4UvR", Network::Bitcoin).is_err());
4684        assert!(Allowable::from_str("xxx:mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB", Network::Regtest)
4685            .is_err());
4686        let a = Allowable::from_str("address:mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB", Network::Testnet)
4687            .unwrap();
4688        assert_eq!(a.to_script().unwrap().to_string(), "OP_DUP OP_HASH160 OP_PUSHBYTES_20 9f9a7abd600c0caa03983a77c8c3df8e062cb2fa OP_EQUALVERIFY OP_CHECKSIG");
4689        let x = Allowable::from_str("xpub:tpubDEQBfiy13hMZzGT4NWqNnaSWwVqYQ58kuu2pDYjkrf8F6DLKAprm8c65Pyh7PrzodXHtJuEXFu5yf6JbvYaL8rz7v28zapwbuzZzr7z4UvR", Network::Testnet).unwrap();
4690        assert!(x.to_script().is_err());
4691    }
4692
4693    #[test]
4694    fn node_wallet_test() {
4695        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4696        let derivation_path = to_derivation_path(&[0u32]);
4697        let a = node.get_native_address(&derivation_path).unwrap();
4698        assert_eq!(a.to_string(), "tb1qr8j660jqglj0x2axua26u0qcyuxhanycx4sr49");
4699        assert!(node.can_spend(&derivation_path, &a.script_pubkey()).unwrap());
4700        assert!(!node.can_spend(&to_derivation_path(&[1u32]), &a.script_pubkey()).unwrap());
4701        #[allow(deprecated)]
4702        let a = node.get_wrapped_address(&derivation_path).unwrap();
4703        assert_eq!(a.to_string(), "2NBaG2jeH1ahh6cMcYBF1RAcZRZsTPqLNLZ");
4704    }
4705
4706    #[test]
4707    fn node_allowlist_contains_test() {
4708        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4709        let payee_sec = SecretKey::from_slice(&[42; 32]).unwrap();
4710        let payee_pub = PublicKey::from_secret_key(&Secp256k1::new(), &payee_sec);
4711        let xpub_str = "tpubDEQBfiy13hMZzGT4NWqNnaSWwVqYQ58kuu2pDYjkrf8F6DLKAprm8c65Pyh7PrzodXHtJuEXFu5yf6JbvYaL8rz7v28zapwbuzZzr7z4UvR";
4712        // let xpub = Xpub::from_str(xpub_str).unwrap();
4713        // println!("XXX {}", Address::p2wpkh(&xpub.derive_pub(&Secp256k1::new(), &[ChildNumber::from_normal_idx(2).unwrap()]).unwrap().to_pub(), Network::Testnet).unwrap());
4714        // xpub is "abandon* about" external account 0
4715        node.add_allowlist(&[
4716            "address:mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB".to_string(),
4717            format!("xpub:{}", xpub_str),
4718            format!("payee:{}", payee_pub.to_string()),
4719        ])
4720        .unwrap();
4721        // check if second child matches the xpub in the allowlist
4722        let script2 = Address::from_str("mnTkxhNkgx7TsZrEdRcPti564yQTzynGJp")
4723            .unwrap()
4724            .require_network(Network::Testnet)
4725            .unwrap()
4726            .script_pubkey();
4727        let derivation_path = to_derivation_path(&[2u32]);
4728        assert!(node.allowlist_contains(&script2, &derivation_path));
4729        // check if third child matches the xpub in the allowlist with wrong index
4730        let script2 = Address::from_str("mpW3iVi2Td1vqDK8Nfie29ddZXf9spmZkX")
4731            .unwrap()
4732            .require_network(Network::Testnet)
4733            .unwrap()
4734            .script_pubkey();
4735        assert!(!node.allowlist_contains(&script2, &derivation_path));
4736        let p2wpkh_script = Address::from_str("tb1qfshzhu5qdyz94r4kylyrnlerq6mnhw3sjz7w8p")
4737            .unwrap()
4738            .require_network(Network::Testnet)
4739            .unwrap()
4740            .script_pubkey();
4741        assert!(node.allowlist_contains(&p2wpkh_script, &derivation_path));
4742    }
4743
4744    #[test]
4745    fn node_allowlist_test() {
4746        fn prefix(a: &String) -> String {
4747            format!("address:{}", a)
4748        }
4749
4750        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4751
4752        // initial allowlist should be empty
4753        assert!(node.allowlist().expect("allowlist").len() == 0);
4754
4755        // can insert some entries
4756        let adds0: Vec<String> = vec![
4757            "mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB",
4758            "2N6i2gfgTonx88yvYm32PRhnHxqxtEfocbt",
4759            "tb1qhetd7l0rv6kca6wvmt25ax5ej05eaat9q29z7z",
4760            "tb1qycu764qwuvhn7u0enpg0x8gwumyuw565f3mspnn58rsgar5hkjmqtjegrh",
4761        ]
4762        .iter()
4763        .map(|s| s.to_string())
4764        .collect();
4765        let prefixed_adds: Vec<String> = adds0.iter().cloned().map(|s| prefix(&s)).collect();
4766        assert_status_ok!(node.add_allowlist(&adds0));
4767
4768        // now allowlist should have the added entries
4769        assert!(vecs_match(node.allowlist().expect("allowlist").clone(), prefixed_adds.clone()));
4770
4771        // adding duplicates shouldn't change the node allowlist
4772        assert_status_ok!(node.add_allowlist(&adds0));
4773        assert!(vecs_match(node.allowlist().expect("allowlist").clone(), prefixed_adds.clone()));
4774
4775        // can remove some elements from the allowlist
4776        let removes0 = vec![adds0[0].clone(), adds0[3].clone()];
4777        assert_status_ok!(node.remove_allowlist(&removes0));
4778        assert!(vecs_match(
4779            node.allowlist().expect("allowlist").clone(),
4780            vec![prefix(&adds0[1]), prefix(&adds0[2])]
4781        ));
4782
4783        // set should replace the elements
4784        assert_status_ok!(node.set_allowlist(&removes0));
4785        assert!(vecs_match(
4786            node.allowlist().expect("allowlist").clone(),
4787            removes0.iter().map(|e| prefix(e)).collect()
4788        ));
4789
4790        // can't add bogus addresses
4791        assert_invalid_argument_err!(
4792            node.add_allowlist(&vec!["1234567890".to_string()]),
4793            "could not parse 1234567890"
4794        );
4795
4796        // can't add w/ wrong network
4797        assert_invalid_argument_err!(
4798            node.add_allowlist(&vec!["1287uUybCYgf7Tb76qnfPf8E1ohCgSZATp".to_string()]),
4799            "could not parse 1287uUybCYgf7Tb76qnfPf8E1ohCgSZATp: expected network testnet"
4800        );
4801
4802        // can't remove w/ wrong network
4803        assert_invalid_argument_err!(
4804            node.remove_allowlist(&vec!["1287uUybCYgf7Tb76qnfPf8E1ohCgSZATp".to_string()]),
4805            "could not parse 1287uUybCYgf7Tb76qnfPf8E1ohCgSZATp: expected network testnet"
4806        );
4807    }
4808
4809    #[test]
4810    fn node_heartbeat_test() {
4811        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4812        let heartbeat = node.get_heartbeat();
4813        let secp = Secp256k1::new();
4814        assert!(heartbeat.verify(&node.get_account_extended_pubkey().public_key, &secp));
4815    }
4816
4817    #[test]
4818    fn heartbeat_sighash_test() {
4819        let heartbeat = Heartbeat {
4820            chain_tip: BlockHash::from_byte_array([0x11; 32]),
4821            chain_height: 0x12345678,
4822            chain_timestamp: 0x9abcdef0,
4823            current_timestamp: 0xcafebabe,
4824        };
4825        assert_eq!(
4826            hex::encode(heartbeat.sighash().as_ref()),
4827            "bd57eb2bd6eabc85ac72c04e27163db9c9ee0282a8dfab8fc1fa8c84dcf7756e"
4828        );
4829    }
4830
4831    #[test]
4832    fn cln_node_param_compatibility() {
4833        // This test compares to known values generated by CLN's native hsmd
4834        let node = init_node(
4835            NodeConfig::new(Network::Regtest),
4836            "6c696768746e696e672d31000000000000000000000000000000000000000000",
4837        );
4838        assert_eq!(
4839            hex::encode(node.get_id().serialize()),
4840            "0266e4598d1d3c415f572a8488830b60f7e744ed9235eb0b1ba93283b315c03518"
4841        );
4842        assert_eq!(
4843            node.get_account_extended_pubkey().to_string(),
4844            "tpubDBrTnjDZwRM6jznHEmo1sYqJWU9so1HRsGEWWjMKLRhVLtuCKYKaHPE3NzqFY3ZdTd64t65T8YrXZZ8Ugwkb7oNzQVBtokaAvtC8Km6EM2G");
4845        assert_eq!(
4846            hex::encode(node.get_bolt12_pubkey().serialize()),
4847            "02e25c37f1af7cb00984e594eae0f4d1d03537ffe202b7a6b2ebc1e5fcf1dfd9f4"
4848        );
4849        assert_eq!(
4850            hex::encode(node.get_onion_reply_secret()),
4851            "cfd1fb341180bf3fa2f624ed7d4a809aedf388e3ba363c589faf341018cb83e1"
4852        );
4853    }
4854
4855    #[test]
4856    fn serialize_heartbeat_test() {
4857        let hb = SignedHeartbeat {
4858            signature: vec![1, 2, 3, 4],
4859            heartbeat: Heartbeat {
4860                chain_tip: BlockHash::all_zeros(),
4861                chain_height: 0,
4862                chain_timestamp: 0,
4863                current_timestamp: 0,
4864            },
4865        };
4866        let mut ser_hb = to_vec(&hb).expect("heartbeat");
4867        let de_hb: SignedHeartbeat = serde_bolt::from_vec(&mut ser_hb).expect("bad heartbeat");
4868        assert_eq!(format!("{:?}", hb), format!("{:?}", de_hb));
4869    }
4870
4871    #[test]
4872    fn update_velocity_spec_test() {
4873        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4874        {
4875            let mut state = node.get_state();
4876            state.velocity_control.insert(0, 1);
4877            assert_eq!(state.velocity_control.velocity(), 1);
4878        }
4879
4880        // this should not change anything, since the specs didn't change
4881        node.update_velocity_controls();
4882
4883        {
4884            let state = node.get_state();
4885            assert_eq!(state.velocity_control.velocity(), 1);
4886            assert!(state.velocity_control.is_unlimited());
4887        }
4888
4889        let mut validator_factory = SimpleValidatorFactory::new();
4890        let mut policy = make_default_simple_policy(Network::Testnet);
4891        let spec = VelocityControlSpec {
4892            limit_msat: 100,
4893            interval_type: VelocityControlIntervalType::Hourly,
4894        };
4895        policy.global_velocity_control = spec.clone();
4896        validator_factory.policy = Some(policy);
4897
4898        node.set_validator_factory(Arc::new(validator_factory));
4899        node.update_velocity_controls();
4900
4901        {
4902            let state = node.get_state();
4903            assert_eq!(state.velocity_control.velocity(), 0);
4904            assert!(!state.velocity_control.is_unlimited());
4905            assert!(state.velocity_control.spec_matches(&spec));
4906        }
4907    }
4908
4909    #[test]
4910    fn prune_failed_stubs() {
4911        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4912
4913        // Create a channel stub
4914        let (channel_id, _) = node.new_channel_with_random_id(&node).unwrap();
4915        assert!(node.get_channel(&channel_id).is_ok());
4916
4917        // Do a heartbeat
4918        let heartbeat = node.get_heartbeat();
4919        let secp = Secp256k1::new();
4920        assert!(heartbeat.verify(&node.get_account_extended_pubkey().public_key, &secp));
4921
4922        // Channel stub is still there
4923        assert!(node.get_channel(&channel_id).is_ok());
4924
4925        // Pretend some blocks have gone by
4926        assert_eq!(node.get_tracker().height(), 0);
4927        node.get_tracker().height = 20;
4928
4929        // Do a heartbeat
4930        let heartbeat = node.get_heartbeat();
4931        let secp = Secp256k1::new();
4932        assert!(heartbeat.verify(&node.get_account_extended_pubkey().public_key, &secp));
4933
4934        // Channel stub is no longer there
4935        assert!(node.get_channel(&channel_id).is_err());
4936    }
4937
4938    #[test]
4939    fn test_apply_payments_cltv_min() {
4940        let (node, channel_id) =
4941            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
4942        let mut state = node.get_state();
4943        let validator = Arc::new(
4944            TestSimpleValidatorBuilder::new()
4945                .cltv_delta(40)
4946                .enforce_balance(true)
4947                .node_id(make_test_pubkey(0x42))
4948                .build(),
4949        );
4950        let hash1 = PaymentHash(Sha256Hash::hash(&[1u8; 32]).to_byte_array());
4951        let commit_info1 = make_commit_info_with_htlcs(
4952            // offered (outgoing)
4953            vec![make_htlc(hash1, 70_000, 1000)],
4954            // received (incoming)
4955            vec![make_htlc(hash1, 50_000, 1200), make_htlc(hash1, 30_000, 1050)],
4956        );
4957
4958        state.apply_payments(
4959            &channel_id,
4960            &vec![(hash1, 80)].into_iter().collect(),
4961            &vec![(hash1, 70)].into_iter().collect(),
4962            &Default::default(),
4963            validator,
4964            Some(&commit_info1),
4965        );
4966
4967        let payment1 = state.payments.get(&hash1).unwrap();
4968        assert_eq!(payment1.incoming_cltv_min, Some(1050));
4969        assert_eq!(payment1.outgoing_cltv_max, Some(1000));
4970    }
4971
4972    #[test]
4973    fn test_apply_payments_cltv_counterparty_commitment() {
4974        let (node, channel_id) =
4975            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
4976        let mut state = node.get_state();
4977        let validator = Arc::new(
4978            TestSimpleValidatorBuilder::new()
4979                .cltv_delta(40)
4980                .enforce_balance(true)
4981                .node_id(make_test_pubkey(0x42))
4982                .build(),
4983        );
4984        let hash1 = PaymentHash(Sha256Hash::hash(&[1u8; 32]).to_byte_array());
4985
4986        let commit_info1 = make_counterparty_commit_info_with_htlcs(
4987            vec![make_htlc(hash1, 50_000, 1200), make_htlc(hash1, 30_000, 1050)],
4988            vec![make_htlc(hash1, 70_000, 1000)],
4989        );
4990
4991        state.apply_payments(
4992            &channel_id,
4993            &vec![(hash1, 80)].into_iter().collect(),
4994            &vec![(hash1, 70)].into_iter().collect(),
4995            &Default::default(),
4996            validator,
4997            Some(&commit_info1),
4998        );
4999
5000        let payment1 = state.payments.get(&hash1).unwrap();
5001        assert_eq!(payment1.incoming_cltv_min, Some(1050));
5002        assert_eq!(payment1.outgoing_cltv_max, Some(1000));
5003    }
5004
5005    #[test]
5006    fn test_multi_channel_multi_payment_sufficient_cltv() {
5007        let (node, _channel_id) =
5008            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
5009        let mut state = node.get_state();
5010        let hash1 = PaymentHash(Sha256Hash::hash(&[1u8; 32]).to_byte_array());
5011        let hash2 = PaymentHash(Sha256Hash::hash(&[2u8; 32]).to_byte_array());
5012        let hash3 = PaymentHash(Sha256Hash::hash(&[3u8; 32]).to_byte_array());
5013        let validator = Arc::new(
5014            TestSimpleValidatorBuilder::new()
5015                .cltv_delta(40)
5016                .enforce_balance(true)
5017                .node_id(make_test_pubkey(0x42))
5018                .build(),
5019        );
5020
5021        let channel_id1 = ChannelId::new(&[1; 32]);
5022        let channel_id2 = ChannelId::new(&[2; 32]);
5023        let channel_id3 = ChannelId::new(&[3; 32]);
5024
5025        // delta=50
5026        let mut payment1 = RoutedPayment::new();
5027        payment1.apply(&channel_id1, 50, 0, Some(1050), None);
5028        payment1.apply(&channel_id2, 30, 70, Some(1100), Some(1000));
5029        state.payments.insert(hash1, payment1);
5030
5031        // delta=50
5032        let mut payment2 = RoutedPayment::new();
5033        payment2.apply(&channel_id1, 100, 0, Some(1100), None);
5034        payment2.apply(&channel_id2, 50, 80, Some(1200), Some(1050));
5035        payment2.apply(&channel_id3, 0, 60, None, Some(1040));
5036        state.payments.insert(hash2, payment2);
5037
5038        // delta=50
5039        let mut payment3 = RoutedPayment::new();
5040        payment3.apply(&channel_id1, 60, 55, Some(1300), Some(1250));
5041        state.payments.insert(hash3, payment3);
5042
5043        let result = state.validate_payments(
5044            &channel_id1,
5045            &vec![(hash1, 50), (hash2, 100), (hash3, 60)].into_iter().collect(),
5046            &vec![(hash1, 0), (hash2, 0), (hash3, 55)].into_iter().collect(),
5047            &Default::default(),
5048            validator,
5049        );
5050
5051        assert!(result.is_ok());
5052    }
5053
5054    #[test]
5055    fn test_multi_channel_multi_payment_one_insufficient_cltv() {
5056        let (node, _channel_id) =
5057            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
5058
5059        let hash1 = PaymentHash(Sha256Hash::hash(&[1u8; 32]).to_byte_array());
5060        let hash2 = PaymentHash(Sha256Hash::hash(&[2u8; 32]).to_byte_array());
5061        let hash3 = PaymentHash(Sha256Hash::hash(&[3u8; 32]).to_byte_array());
5062
5063        let validator = Arc::new(
5064            TestSimpleValidatorBuilder::new()
5065                .cltv_delta(40)
5066                .enforce_balance(true)
5067                .node_id(make_test_pubkey(0x42))
5068                .build(),
5069        );
5070
5071        let channel_id1 = ChannelId::new(&[1; 32]);
5072        let channel_id2 = ChannelId::new(&[2; 32]);
5073
5074        let mut state = node.get_state();
5075
5076        // Payment 1: delta=50 (valid)
5077        let mut payment1 = RoutedPayment::new();
5078        payment1.apply(&channel_id1, 50, 0, Some(1200), None);
5079        payment1.apply(&channel_id2, 30, 70, Some(1050), Some(1000));
5080        state.payments.insert(hash1, payment1);
5081
5082        // Payment 2: delta=20 (invalid)
5083        let mut payment2 = RoutedPayment::new();
5084        payment2.apply(&channel_id1, 100, 80, Some(1100), Some(1000));
5085        payment2.apply(&channel_id2, 50, 60, Some(1020), Some(990));
5086        state.payments.insert(hash2, payment2);
5087
5088        // Payment 3: delta=50 (valid)
5089        let mut payment3 = RoutedPayment::new();
5090        payment3.apply(&channel_id1, 60, 55, Some(1300), Some(1250));
5091        state.payments.insert(hash3, payment3);
5092
5093        let result = state.validate_payments(
5094            &channel_id1,
5095            &vec![(hash1, 50), (hash2, 100), (hash3, 60)].into_iter().collect(),
5096            &vec![(hash1, 0), (hash2, 80), (hash3, 55)].into_iter().collect(),
5097            &Default::default(),
5098            validator.clone(),
5099        );
5100
5101        assert!(result.is_err());
5102        let err = result.unwrap_err();
5103        assert_eq!(err.tag, "policy-routing-cltv-delta");
5104        assert!(
5105            err.to_string().contains("CLTV delta 20 is less than minimum 40"),
5106            "Error should mention delta=20 < minimum=40"
5107        );
5108    }
5109
5110    #[test]
5111    fn test_multi_payment_originating_and_terminal_no_cltv_validation() {
5112        let (node, _channel_id) =
5113            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
5114        let validator = Arc::new(
5115            TestSimpleValidatorBuilder::new()
5116                .cltv_delta(40)
5117                .enforce_balance(true)
5118                .node_id(make_test_pubkey(0x42))
5119                .build(),
5120        );
5121
5122        let channel_id = ChannelId::new(&[1; 32]);
5123        let mut state = node.get_state();
5124
5125        // only incoming (multiple HTLCs)
5126        let terminal_hash1 = PaymentHash(Sha256Hash::hash(&[10u8; 32]).to_byte_array());
5127        let mut terminal1 = RoutedPayment::new();
5128        terminal1.apply(&channel_id, 100, 0, Some(1000), None);
5129        terminal1.apply(&channel_id, 50, 0, Some(1100), None);
5130        terminal1.apply(&channel_id, 75, 0, Some(1050), None);
5131        state.payments.insert(terminal_hash1, terminal1);
5132
5133        // only outgoing (multiple HTLCs)
5134        let orig_hash1 = PaymentHash(Sha256Hash::hash(&[30u8; 32]).to_byte_array());
5135        let mut orig1 = RoutedPayment::new();
5136        orig1.apply(&channel_id, 0, 60, None, Some(950));
5137        orig1.apply(&channel_id, 0, 40, None, Some(1000));
5138        orig1.apply(&channel_id, 0, 50, None, Some(980));
5139        state.payments.insert(orig_hash1, orig1);
5140
5141        let terminal1 = state.payments.get(&terminal_hash1).unwrap();
5142        assert_eq!(terminal1.incoming_cltv_min, Some(1000));
5143        assert_eq!(terminal1.outgoing_cltv_max, None);
5144        assert!(terminal1.get_cltv_bounds().is_none());
5145
5146        let orig1 = state.payments.get(&orig_hash1).unwrap();
5147        assert_eq!(orig1.incoming_cltv_min, None);
5148        assert_eq!(orig1.outgoing_cltv_max, Some(1000));
5149        assert!(orig1.get_cltv_bounds().is_none());
5150
5151        let result = state.validate_payments(
5152            &channel_id,
5153            &vec![(terminal_hash1, 225)].into_iter().collect(),
5154            &vec![(orig_hash1, 150)].into_iter().collect(),
5155            &Default::default(),
5156            validator.clone(),
5157        );
5158
5159        assert!(result.is_ok());
5160    }
5161
5162    /// A Persist that counts the writes we care about, so a test can assert that
5163    /// a bulk-persist method actually wrote something. Everything else mirrors
5164    /// DummyPersister.
5165    struct RecordingPersister {
5166        initial_restore: bool,
5167        new_node: AtomicUsize,
5168        update_channel: AtomicUsize,
5169        update_tracker: AtomicUsize,
5170        update_node_allowlist: AtomicUsize,
5171    }
5172
5173    impl RecordingPersister {
5174        fn new(initial_restore: bool) -> Self {
5175            Self {
5176                initial_restore,
5177                new_node: AtomicUsize::new(0),
5178                update_channel: AtomicUsize::new(0),
5179                update_tracker: AtomicUsize::new(0),
5180                update_node_allowlist: AtomicUsize::new(0),
5181            }
5182        }
5183
5184        /// Forget writes made while building the node under test.
5185        fn reset(&self) {
5186            self.new_node.store(0, Relaxed);
5187            self.update_channel.store(0, Relaxed);
5188            self.update_tracker.store(0, Relaxed);
5189            self.update_node_allowlist.store(0, Relaxed);
5190        }
5191
5192        fn counts(&self) -> (usize, usize, usize, usize) {
5193            (
5194                self.new_node.load(Relaxed),
5195                self.update_channel.load(Relaxed),
5196                self.update_tracker.load(Relaxed),
5197                self.update_node_allowlist.load(Relaxed),
5198            )
5199        }
5200    }
5201
5202    impl SendSync for RecordingPersister {}
5203
5204    #[allow(unused_variables)]
5205    impl Persist for RecordingPersister {
5206        fn new_node(
5207            &self,
5208            node_id: &PublicKey,
5209            config: &NodeConfig,
5210            state: &NodeState,
5211        ) -> Result<(), crate::persist::Error> {
5212            self.new_node.fetch_add(1, Relaxed);
5213            Ok(())
5214        }
5215
5216        fn update_node(
5217            &self,
5218            node_id: &PublicKey,
5219            state: &NodeState,
5220        ) -> Result<(), crate::persist::Error> {
5221            Ok(())
5222        }
5223
5224        fn delete_node(&self, node_id: &PublicKey) -> Result<(), crate::persist::Error> {
5225            Ok(())
5226        }
5227
5228        fn new_channel(
5229            &self,
5230            node_id: &PublicKey,
5231            stub: &ChannelStub,
5232        ) -> Result<(), crate::persist::Error> {
5233            Ok(())
5234        }
5235
5236        fn delete_channel(
5237            &self,
5238            node_id: &PublicKey,
5239            channel_id: &ChannelId,
5240        ) -> Result<(), crate::persist::Error> {
5241            Ok(())
5242        }
5243
5244        fn new_tracker(
5245            &self,
5246            node_id: &PublicKey,
5247            tracker: &ChainTracker<ChainMonitor>,
5248        ) -> Result<(), crate::persist::Error> {
5249            Ok(())
5250        }
5251
5252        fn update_tracker(
5253            &self,
5254            node_id: &PublicKey,
5255            tracker: &ChainTracker<ChainMonitor>,
5256        ) -> Result<(), crate::persist::Error> {
5257            self.update_tracker.fetch_add(1, Relaxed);
5258            Ok(())
5259        }
5260
5261        fn get_tracker(
5262            &self,
5263            node_id: PublicKey,
5264            validator_factory: Arc<dyn ValidatorFactory>,
5265        ) -> Result<
5266            (ChainTracker<ChainMonitor>, Vec<crate::persist::ChainTrackerListenerEntry>),
5267            crate::persist::Error,
5268        > {
5269            Err(crate::persist::Error::Internal("get_tracker unimplemented".to_string()))
5270        }
5271
5272        fn update_channel(
5273            &self,
5274            node_id: &PublicKey,
5275            channel: &Channel,
5276        ) -> Result<(), crate::persist::Error> {
5277            self.update_channel.fetch_add(1, Relaxed);
5278            Ok(())
5279        }
5280
5281        fn get_channel(
5282            &self,
5283            node_id: &PublicKey,
5284            channel_id: &ChannelId,
5285        ) -> Result<crate::persist::model::ChannelEntry, crate::persist::Error> {
5286            Err(crate::persist::Error::Internal("get_channel unimplemented".to_string()))
5287        }
5288
5289        fn get_node_channels(
5290            &self,
5291            node_id: &PublicKey,
5292        ) -> Result<Vec<(ChannelId, crate::persist::model::ChannelEntry)>, crate::persist::Error>
5293        {
5294            Ok(Vec::new())
5295        }
5296
5297        fn update_node_allowlist(
5298            &self,
5299            node_id: &PublicKey,
5300            allowlist: Vec<String>,
5301        ) -> Result<(), crate::persist::Error> {
5302            self.update_node_allowlist.fetch_add(1, Relaxed);
5303            Ok(())
5304        }
5305
5306        fn get_node_allowlist(
5307            &self,
5308            node_id: &PublicKey,
5309        ) -> Result<Vec<String>, crate::persist::Error> {
5310            Ok(Vec::new())
5311        }
5312
5313        fn get_nodes(
5314            &self,
5315        ) -> Result<Vec<(PublicKey, crate::persist::model::NodeEntry)>, crate::persist::Error>
5316        {
5317            Ok(Vec::new())
5318        }
5319
5320        fn clear_database(&self) -> Result<(), crate::persist::Error> {
5321            Ok(())
5322        }
5323
5324        fn on_initial_restore(&self) -> bool {
5325            self.initial_restore
5326        }
5327
5328        fn signer_id(&self) -> [u8; 16] {
5329            [0; 16]
5330        }
5331    }
5332
5333    fn make_node_with_persister(persister: Arc<RecordingPersister>) -> Arc<Node> {
5334        let services = NodeServices {
5335            validator_factory: Arc::new(SimpleValidatorFactory::new()),
5336            starting_time_factory: make_genesis_starting_time_factory(TEST_NODE_CONFIG.network),
5337            persister,
5338            clock: Arc::new(StandardClock()),
5339            trusted_oracle_pubkeys: vec![],
5340        };
5341        init_node_with_services(TEST_NODE_CONFIG, TEST_SEED[1], services)
5342    }
5343
5344    #[test]
5345    fn test_persist_all_writes_node_channels_tracker_and_allowlist() {
5346        let persister = Arc::new(RecordingPersister::new(false));
5347        let node = make_node_with_persister(persister.clone());
5348        // a Ready channel, so persist_all reaches update_channel; stubs are skipped
5349        init_channel(make_test_channel_setup(), node.clone());
5350
5351        persister.reset();
5352        node.persist_all();
5353
5354        let (new_node, update_channel, update_tracker, allowlist) = persister.counts();
5355        assert!(new_node > 0, "persist_all did not write the node entry");
5356        assert!(update_channel > 0, "persist_all did not write the ready channel");
5357        assert!(update_tracker > 0, "persist_all did not write the tracker");
5358        assert!(allowlist > 0, "persist_all did not write the allowlist");
5359    }
5360
5361    #[test]
5362    fn test_maybe_sync_persister_writes_when_restoring() {
5363        let persister = Arc::new(RecordingPersister::new(true));
5364        let node = make_node_with_persister(persister.clone());
5365        init_channel(make_test_channel_setup(), node.clone());
5366
5367        persister.reset();
5368        node.maybe_sync_persister().expect("sync persist");
5369
5370        let (new_node, update_channel, update_tracker, allowlist) = persister.counts();
5371        assert!(new_node > 0, "maybe_sync_persister did not write the node entry");
5372        assert!(update_channel > 0, "maybe_sync_persister did not write the ready channel");
5373        assert!(update_tracker > 0, "maybe_sync_persister did not write the tracker");
5374        assert!(allowlist > 0, "maybe_sync_persister did not write the allowlist");
5375    }
5376
5377    #[test]
5378    fn test_maybe_sync_persister_is_a_noop_when_not_restoring() {
5379        let persister = Arc::new(RecordingPersister::new(false));
5380        let node = make_node_with_persister(persister.clone());
5381        init_channel(make_test_channel_setup(), node.clone());
5382
5383        persister.reset();
5384        node.maybe_sync_persister().expect("sync persist");
5385
5386        assert_eq!(persister.counts(), (0, 0, 0, 0));
5387    }
5388}