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