lightning_signer/
node.rs

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