lightning_signer/
node.rs

1use alloc::collections::VecDeque;
2use core::borrow::Borrow;
3use core::fmt::{self, Debug, Formatter};
4use core::str::FromStr;
5use core::time::Duration;
6
7use scopeguard::defer;
8
9use bitcoin::bip32::{DerivationPath, Xpriv, Xpub};
10use bitcoin::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(
544                        "policy-routing-balanced",
545                        format!(
546                            "shortfall {} + {} - {}",
547                            self.excess_amount, balance_delta.1, balance_delta.0
548                        ),
549                    )
550                })?;
551        }
552        *debug_on_return = false;
553        Ok(())
554    }
555
556    /// Apply outgoing in-flight payment amounts as a result of a new commitment tx.
557    /// Must call [NodeState::validate_payments] first.
558    pub fn apply_payments(
559        &mut self,
560        channel_id: &ChannelId,
561        incoming_payment_summary: &Map<PaymentHash, u64>,
562        outgoing_payment_summary: &Map<PaymentHash, u64>,
563        balance_delta: &BalanceDelta,
564        validator: Arc<dyn Validator>,
565    ) {
566        debug!("applying payments on channel {}", channel_id);
567
568        let mut hashes: UnorderedSet<&PaymentHash> = UnorderedSet::new();
569        hashes.extend(incoming_payment_summary.keys());
570        hashes.extend(outgoing_payment_summary.keys());
571
572        let mut fulfilled_issued_invoices = Vec::new();
573
574        // Preflight check
575        for hash_r in hashes.iter() {
576            let hash = **hash_r;
577            let payment = self.payments.entry(hash).or_insert_with(|| RoutedPayment::new());
578            if let Some(issued) = self.issued_invoices.get(&hash) {
579                if !payment.is_fulfilled() {
580                    let incoming_for_chan_sat =
581                        incoming_payment_summary.get(&hash).map(|a| *a).unwrap_or(0);
582                    let outgoing_for_chan_sat =
583                        outgoing_payment_summary.get(&hash).map(|a| *a).unwrap_or(0);
584                    let (incoming_sat, outgoing_sat) = payment.updated_incoming_outgoing(
585                        channel_id,
586                        incoming_for_chan_sat,
587                        outgoing_for_chan_sat,
588                    );
589                    if incoming_sat >= outgoing_sat + issued.amount_msat / 1000 {
590                        fulfilled_issued_invoices.push(hash);
591                    }
592                }
593            }
594        }
595
596        if validator.enforce_balance() {
597            info!(
598                "{} apply payments adjust excess {} +{} -{}",
599                self.log_prefix, self.excess_amount, balance_delta.1, balance_delta.0
600            );
601            let excess_amount = self
602                .excess_amount
603                .checked_add(balance_delta.1)
604                .expect("overflow")
605                .checked_sub(balance_delta.0)
606                .expect("validation didn't catch underflow");
607            for hash in fulfilled_issued_invoices.iter() {
608                debug!("mark issued invoice {} as fulfilled", hash.0.to_hex());
609                let payment = self.payments.get_mut(&*hash).expect("already checked");
610                // Mark as fulfilled by setting a dummy preimage.
611                // This has the side-effect of the payment amount not being added
612                // to the excess_amount, because we set the preimage after the balance
613                // delta has already been calculated.
614                payment.preimage = Some(PaymentPreimage([0; 32]));
615            }
616            self.excess_amount = excess_amount;
617        }
618
619        debug!(
620            "applying incoming payments from channel {} - {:?}",
621            channel_id, incoming_payment_summary
622        );
623
624        for hash_r in hashes.iter() {
625            let hash = **hash_r;
626            let incoming_sat = incoming_payment_summary.get(&hash).map(|a| *a).unwrap_or(0);
627            let outgoing_sat = outgoing_payment_summary.get(&hash).map(|a| *a).unwrap_or(0);
628            let payment = self.payments.get_mut(&hash).expect("created above");
629            payment.apply(channel_id, incoming_sat, outgoing_sat);
630        }
631
632        trace_node_state!(self);
633    }
634
635    /// Fulfills an HTLC.
636    /// Performs bookkeeping on any invoice or routed payment with this payment hash.
637    pub fn htlc_fulfilled(
638        &mut self,
639        channel_id: &ChannelId,
640        preimage: PaymentPreimage,
641        validator: Arc<dyn Validator>,
642    ) -> bool {
643        let payment_hash = PaymentHash(Sha256Hash::hash(&preimage.0).to_byte_array());
644        let mut fulfilled = false;
645        if let Some(payment) = self.payments.get_mut(&payment_hash) {
646            // Getting an HTLC preimage moves HTLC values to the virtual balance of the recipient
647            // on both input and output.
648            // We gain the difference between the input and the output amounts,
649            // so record that in the excess_amount register.
650            // However, when we pay an invoice, the excess_amount is not
651            // updated.
652            if payment.preimage.is_some() {
653                info!(
654                    "{} duplicate preimage {} on channel {}",
655                    self.log_prefix,
656                    payment_hash.0.to_hex(),
657                    channel_id
658                );
659            } else {
660                let (incoming, outgoing) = payment.incoming_outgoing();
661                if self.invoices.contains_key(&payment_hash) {
662                    if incoming > 0 {
663                        info!(
664                            "{} preimage invoice+routing {} +{} -{} msat",
665                            self.log_prefix,
666                            payment_hash.0.to_hex(),
667                            incoming,
668                            outgoing
669                        )
670                    } else {
671                        info!(
672                            "{} preimage invoice {} -{} msat",
673                            self.log_prefix,
674                            payment_hash.0.to_hex(),
675                            outgoing
676                        )
677                    }
678                } else {
679                    info!(
680                        "{} preimage routing {} adjust excess {} +{} -{} msat",
681                        self.log_prefix,
682                        payment_hash.0.to_hex(),
683                        self.excess_amount,
684                        incoming,
685                        outgoing
686                    );
687                    if validator.enforce_balance() {
688                        self.excess_amount =
689                            self.excess_amount.checked_add(incoming).expect("overflow");
690                        // TODO(519) convert to checked error
691                        self.excess_amount =
692                            self.excess_amount.checked_sub(outgoing).expect("underflow");
693                    }
694                }
695                payment.preimage = Some(preimage);
696                fulfilled = true;
697            }
698        }
699        fulfilled
700    }
701
702    fn prune_time(pstate: &PaymentState) -> Duration {
703        let mut prune = Duration::from_secs(0);
704        prune += match pstate.payment_type {
705            PaymentType::Invoice => INVOICE_PRUNE_TIME,
706            PaymentType::Keysend => KEYSEND_PRUNE_TIME,
707        };
708        #[cfg(feature = "timeless_workaround")]
709        {
710            // When we are using block headers our now() could be 2 hours ahead
711            prune += Duration::from_secs(2 * 60 * 60);
712        }
713        prune
714    }
715
716    fn prune_issued_invoices(&mut self, now: Duration) -> bool {
717        let mut modified = false;
718        self.issued_invoices.retain(|hash, issued| {
719            let keep =
720                issued.duration_since_epoch + issued.expiry_duration + Self::prune_time(issued)
721                    > now;
722            if !keep {
723                info!(
724                    "pruning {} {:?} from issued_invoices",
725                    issued.payment_type.to_string(),
726                    DebugBytes(&hash.0)
727                );
728                modified = true;
729            }
730            keep
731        });
732        modified
733    }
734
735    fn prune_invoices(&mut self, now: Duration) -> bool {
736        let invoices = &mut self.invoices;
737        let payments = &mut self.payments;
738        let prune: UnorderedSet<_> = invoices
739            .iter_mut()
740            .filter_map(|(hash, payment_state)| {
741                let payments =
742                    payments.get(hash).unwrap_or_else(|| {
743                        // we create a payment struct for each invoice
744                        panic!(
745                            "missing payments struct for {}",
746                            payment_state.payment_type.to_string(),
747                        )
748                    });
749                if Self::is_invoice_prunable(now, hash, payment_state, payments) {
750                    Some(*hash)
751                } else {
752                    None
753                }
754            })
755            .collect();
756
757        let mut modified = false;
758        invoices.retain(|hash, state| {
759            let keep = !prune.contains(hash);
760            if !keep {
761                info!(
762                    "pruning {} {:?} from invoices",
763                    state.payment_type.to_string(),
764                    DebugBytes(&hash.0)
765                );
766                modified = true;
767            }
768            keep
769        });
770        payments.retain(|hash, _| {
771            let keep = !prune.contains(hash);
772            if !keep {
773                info!(
774                    "pruning {:?} from payments because invoice/keysend expired",
775                    DebugBytes(&hash.0)
776                );
777                modified = true;
778            }
779            keep
780        });
781        modified
782    }
783
784    fn prune_forwarded_payments(&mut self) -> bool {
785        let payments = &mut self.payments;
786        let invoices = &self.invoices;
787        let issued_invoices = &self.issued_invoices;
788        let mut modified = false;
789        payments.retain(|hash, payment| {
790            let keep =
791                !Self::is_forwarded_payment_prunable(hash, invoices, issued_invoices, payment);
792            if !keep {
793                info!("pruning {:?} from payments because forward has ended", DebugBytes(&hash.0));
794                modified = true;
795            }
796            keep
797        });
798        modified
799    }
800
801    fn is_invoice_prunable(
802        now: Duration,
803        hash: &PaymentHash,
804        state: &PaymentState,
805        payment: &RoutedPayment,
806    ) -> bool {
807        let is_payment_complete = payment.is_fulfilled() || payment.is_no_outgoing();
808        let is_past_prune_time =
809            now > state.duration_since_epoch + state.expiry_duration + Self::prune_time(state);
810        // warn if past prune time but incomplete
811        if is_past_prune_time && !is_payment_complete {
812            warn!(
813                "{} {:?} is past prune time but there are still pending outgoing payments",
814                state.payment_type.to_string(),
815                DebugBytes(&hash.0)
816            );
817        }
818        is_past_prune_time && is_payment_complete
819    }
820
821    fn is_forwarded_payment_prunable(
822        hash: &PaymentHash,
823        invoices: &Map<PaymentHash, PaymentState>,
824        issued_invoices: &Map<PaymentHash, PaymentState>,
825        payment: &RoutedPayment,
826    ) -> bool {
827        invoices.get(hash).is_none()
828            && issued_invoices.get(hash).is_none()
829            && payment.is_no_incoming()
830            && payment.is_no_outgoing()
831    }
832}
833
834/// Allowlist entry
835#[derive(Eq, PartialEq, Hash, Clone, PartialOrd, Ord)]
836pub enum Allowable {
837    /// A layer-1 destination
838    Script(ScriptBuf),
839    /// A layer-1 xpub destination
840    XPub(Xpub),
841    /// A layer-2 payee (node_id)
842    Payee(PublicKey),
843}
844
845/// Convert to String for a specified Bitcoin network type
846pub trait ToStringForNetwork {
847    /// Convert to String for a specified Bitcoin network type
848    fn to_string(&self, network: Network) -> String;
849}
850
851impl ToStringForNetwork for Allowable {
852    fn to_string(&self, network: Network) -> String {
853        match self {
854            Allowable::Script(script) => {
855                let addr_res = Address::from_script(&script, network);
856                addr_res
857                    .map(|a| format!("address:{}", a.to_string()))
858                    .unwrap_or_else(|_| format!("invalid_script:{}", script.to_hex_string()))
859            }
860            Allowable::Payee(pubkey) => format!("payee:{}", pubkey.to_string()),
861            Allowable::XPub(xpub) => {
862                format!("xpub:{}", xpub.to_string())
863            }
864        }
865    }
866}
867
868impl Allowable {
869    /// Convert from string, while checking that the network matches
870    pub fn from_str(s: &str, network: Network) -> Result<Allowable, String> {
871        let mut splits = s.splitn(2, ":");
872        let prefix = splits.next().ok_or_else(|| "empty Allowable")?;
873        if let Some(body) = splits.next() {
874            if prefix == "address" {
875                let address = Address::from_str(body)
876                    .map_err(|_| s.to_string())?
877                    .require_network(network)
878                    .map_err(|_| format!("{}: expected network {}", s, network))?;
879                Ok(Allowable::Script(address.script_pubkey()))
880            } else if prefix == "payee" {
881                let pubkey = PublicKey::from_str(body).map_err(|_| s.to_string())?;
882                Ok(Allowable::Payee(pubkey))
883            } else if prefix == "xpub" {
884                let xpub = Xpub::from_str(body).map_err(|_| s.to_string())?;
885                if xpub.network != network.into() {
886                    return Err(format!("{}: expected network {}", s, network));
887                }
888                Ok(Allowable::XPub(xpub))
889            } else {
890                Err(s.to_string())
891            }
892        } else {
893            let address = Address::from_str(prefix)
894                .map_err(|_| s.to_string())?
895                .require_network(network)
896                .map_err(|_| format!("{}: expected network {}", s, network))?;
897            Ok(Allowable::Script(address.script_pubkey()))
898        }
899    }
900
901    /// Convert to a scriptpubkey
902    /// Will error if this is a bare pubkey (Lightning payee)
903    pub fn to_script(self) -> Result<ScriptBuf, ()> {
904        match self {
905            Allowable::Script(script) => Ok(script),
906            _ => Err(()),
907        }
908    }
909}
910
911/// A signer heartbeat message.
912///
913/// This includes information that determines if we think our
914/// view of the blockchain is stale or not.
915#[derive(Debug, Encodable, Decodable)]
916pub struct Heartbeat {
917    /// the block hash of the blockchain tip
918    pub chain_tip: bitcoin::BlockHash,
919    /// the height of the blockchain tip
920    pub chain_height: u32,
921    /// the block timestamp of the tip of the blockchain
922    pub chain_timestamp: u32,
923    /// the current time
924    pub current_timestamp: u32,
925}
926
927impl Heartbeat {
928    /// Serialize with serde_bolt
929    pub fn encode(&self) -> Vec<u8> {
930        to_vec(&self).expect("serialize Heartbeat")
931    }
932}
933
934/// A signed heartbeat message.
935#[derive(Encodable, Decodable)]
936pub struct SignedHeartbeat {
937    /// the schnorr signature of the heartbeat
938    pub signature: Vec<u8>,
939    /// the heartbeat
940    pub heartbeat: Heartbeat,
941}
942
943impl Debug for SignedHeartbeat {
944    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
945        f.debug_struct("SignedHeartbeat")
946            .field("signature", &DebugBytes(&self.signature))
947            .field("heartbeat", &self.heartbeat)
948            .finish()
949    }
950}
951
952impl SignedHeartbeat {
953    /// Get the hash of the heartbeat for signing
954    pub fn sighash(&self) -> Message {
955        sighash_from_heartbeat(&self.heartbeat.encode())
956    }
957
958    /// Verify the heartbeat signature
959    pub fn verify(&self, pubkey: &PublicKey, secp: &Secp256k1<secp256k1::All>) -> bool {
960        match schnorr::Signature::from_slice(&self.signature) {
961            Ok(signature) => {
962                let xpubkey = XOnlyPublicKey::from(pubkey.clone());
963                secp.verify_schnorr(&signature, &self.sighash(), &xpubkey).is_ok()
964            }
965            Err(_) => false,
966        }
967    }
968}
969
970/// A signer for one Lightning node.
971///
972/// ```rust
973/// use std::sync::Arc;
974///
975/// use lightning_signer::channel::{ChannelSlot, ChannelBase};
976/// use lightning_signer::node::{Node, NodeConfig, NodeServices, SyncLogger};
977/// use lightning_signer::persist::{DummyPersister, Persist};
978/// use lightning_signer::policy::simple_validator::SimpleValidatorFactory;
979/// use lightning_signer::signer::ClockStartingTimeFactory;
980/// use lightning_signer::signer::derive::KeyDerivationStyle;
981/// use lightning_signer::util::clock::StandardClock;
982/// use lightning_signer::bitcoin;
983/// use bitcoin::Network;
984///
985/// let persister: Arc<dyn Persist> = Arc::new(DummyPersister {});
986/// let seed = [0; 32];
987/// let config = NodeConfig {
988///     network: Network::Testnet,
989///     key_derivation_style: KeyDerivationStyle::Native,
990///     use_checkpoints: true,
991///     allow_deep_reorgs: true, // not for production
992/// };
993/// let validator_factory = Arc::new(SimpleValidatorFactory::new());
994/// let starting_time_factory = ClockStartingTimeFactory::new();
995/// let clock = Arc::new(StandardClock());
996/// let services = NodeServices {
997///     validator_factory,
998///     starting_time_factory,
999///     persister,
1000///     clock,
1001///     trusted_oracle_pubkeys: vec![],
1002/// };
1003/// let node = Arc::new(Node::new(config, &seed, vec![], services));
1004/// // TODO: persist the seed
1005/// let (channel_id, opt_stub) = node.new_channel_with_random_id(&node).expect("new channel");
1006/// assert!(opt_stub.is_some());
1007/// let channel_slot_mutex = node.get_channel(&channel_id).expect("get channel");
1008/// let channel_slot = channel_slot_mutex.lock().expect("lock");
1009/// match &*channel_slot {
1010///     ChannelSlot::Stub(stub) => {
1011///         // Do things with the stub, such as readying it or getting the points
1012///         let holder_basepoints = stub.get_channel_basepoints();
1013///     }
1014///     ChannelSlot::Ready(_) => panic!("expected a stub")
1015/// }
1016/// ```
1017pub struct Node {
1018    secp_ctx: Secp256k1<secp256k1::All>,
1019    pub(crate) node_config: NodeConfig,
1020    pub(crate) keys_manager: MyKeysManager,
1021    channels: Mutex<OrderedMap<ChannelId, Arc<Mutex<ChannelSlot>>>>,
1022    // This is Mutex because we want to be able to replace it on the fly
1023    pub(crate) validator_factory: Mutex<Arc<dyn ValidatorFactory>>,
1024    pub(crate) persister: Arc<dyn Persist>,
1025    pub(crate) clock: Arc<dyn Clock>,
1026    tracker: Mutex<ChainTracker<ChainMonitor>>,
1027    pub(crate) state: Mutex<NodeState>,
1028    node_id: PublicKey,
1029}
1030
1031/// Various services the Node uses
1032#[derive(Clone)]
1033pub struct NodeServices {
1034    /// The validator factory
1035    pub validator_factory: Arc<dyn ValidatorFactory>,
1036    /// The starting time factory
1037    pub starting_time_factory: Arc<dyn StartingTimeFactory>,
1038    /// The persister
1039    pub persister: Arc<dyn Persist>,
1040    /// Clock source
1041    pub clock: Arc<dyn Clock>,
1042    /// public keys of trusted TXO oracle
1043    pub trusted_oracle_pubkeys: Vec<PublicKey>,
1044}
1045
1046impl Wallet for Node {
1047    fn can_spend(
1048        &self,
1049        child_path: &DerivationPath,
1050        script_pubkey: &ScriptBuf,
1051    ) -> Result<bool, Status> {
1052        // If there is no path we can't spend it ...
1053        if child_path.len() == 0 {
1054            return Ok(false);
1055        }
1056
1057        let pubkey = self.get_wallet_pubkey(child_path)?;
1058
1059        // Lightning layer-1 wallets can spend native segwit or wrapped segwit addresses.
1060        // these can only fail with uncompressed keys, which we never generate
1061        let native_addr = Address::p2wpkh(&pubkey, self.network());
1062        let wrapped_addr = Address::p2shwpkh(&pubkey, self.network());
1063        let untweaked_pubkey = UntweakedPublicKey::from(pubkey.0);
1064
1065        // FIXME(520) it is not recommended to use the same xpub for both schnorr and ECDSA
1066        let taproot_addr = Address::p2tr(&self.secp_ctx, untweaked_pubkey, None, self.network());
1067
1068        Ok(*script_pubkey == native_addr.script_pubkey()
1069            || *script_pubkey == wrapped_addr.script_pubkey()
1070            || *script_pubkey == taproot_addr.script_pubkey())
1071    }
1072
1073    fn get_native_address(&self, child_path: &DerivationPath) -> Result<Address, Status> {
1074        if child_path.len() == 0 {
1075            return Err(invalid_argument("empty child path"));
1076        }
1077
1078        let pubkey = self.get_wallet_pubkey(child_path)?;
1079        // can only fail with uncompressed keys, which we never generate
1080        Ok(Address::p2wpkh(&pubkey, self.network()))
1081    }
1082
1083    fn get_taproot_address(&self, child_path: &DerivationPath) -> Result<Address, Status> {
1084        if child_path.len() == 0 {
1085            return Err(invalid_argument("empty child path"));
1086        }
1087
1088        let pubkey = self.get_wallet_pubkey(child_path)?;
1089        let untweaked_pubkey = UntweakedPublicKey::from(pubkey.0);
1090        Ok(Address::p2tr(&self.secp_ctx, untweaked_pubkey, None, self.network()))
1091    }
1092
1093    fn get_wrapped_address(&self, child_path: &DerivationPath) -> Result<Address, Status> {
1094        if child_path.len() == 0 {
1095            return Err(invalid_argument("empty child path"));
1096        }
1097
1098        let pubkey = self.get_wallet_pubkey(child_path)?;
1099        // can only fail with uncompressed keys, which we never generate
1100        Ok(Address::p2shwpkh(&pubkey, self.network()))
1101    }
1102
1103    fn allowlist_contains_payee(&self, payee: PublicKey) -> bool {
1104        self.get_state().allowlist.contains(&Allowable::Payee(payee))
1105    }
1106
1107    fn allowlist_contains(&self, script_pubkey: &ScriptBuf, path: &DerivationPath) -> bool {
1108        let state = self.get_state();
1109        if state.allowlist.contains(&Allowable::Script(script_pubkey.clone())) {
1110            return true;
1111        }
1112
1113        if path.is_empty() {
1114            return false;
1115        }
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 =
1121                    CompressedPublicKey(xp.derive_pub(&Secp256k1::new(), path).unwrap().public_key);
1122
1123                // this is infallible because the pubkey is compressed
1124                if *script_pubkey == Address::p2wpkh(&pubkey, self.network()).script_pubkey() {
1125                    return true;
1126                }
1127
1128                if *script_pubkey == Address::p2pkh(&pubkey, self.network()).script_pubkey() {
1129                    return true;
1130                }
1131
1132                // FIXME(520) it is not recommended to use the same xpub for both schnorr and ECDSA
1133                let untweaked_pubkey = UntweakedPublicKey::from(pubkey.0);
1134                if *script_pubkey
1135                    == Address::p2tr(&self.secp_ctx, untweaked_pubkey, None, self.network())
1136                        .script_pubkey()
1137                {
1138                    return true;
1139                }
1140            }
1141        }
1142
1143        return false;
1144    }
1145
1146    fn network(&self) -> Network {
1147        self.node_config.network
1148    }
1149}
1150
1151impl Node {
1152    /// Create a node.
1153    ///
1154    /// NOTE: you must persist the node yourself if it is new.
1155    pub fn new(
1156        node_config: NodeConfig,
1157        seed: &[u8],
1158        allowlist: Vec<Allowable>,
1159        services: NodeServices,
1160    ) -> Node {
1161        let policy = services.validator_factory.policy(node_config.network);
1162        let global_velocity_control = Self::make_velocity_control(&policy);
1163        let fee_velocity_control = Self::make_fee_velocity_control(&policy);
1164        let state = NodeState::new(global_velocity_control, fee_velocity_control, allowlist);
1165
1166        let (keys_manager, node_id) = Self::make_keys_manager(&node_config, seed, &services);
1167        let mut tracker = if node_config.use_checkpoints {
1168            ChainTracker::for_network(
1169                node_config.network,
1170                node_id.clone(),
1171                services.validator_factory.clone(),
1172                services.trusted_oracle_pubkeys.clone(),
1173            )
1174        } else {
1175            ChainTracker::from_genesis(
1176                node_config.network,
1177                node_id.clone(),
1178                services.validator_factory.clone(),
1179                services.trusted_oracle_pubkeys.clone(),
1180            )
1181        };
1182        tracker.set_allow_deep_reorgs(node_config.allow_deep_reorgs);
1183
1184        Self::new_full(node_config, services, state, keys_manager, node_id, tracker)
1185    }
1186
1187    /// Update the velocity controls with any spec changes from the policy
1188    pub fn update_velocity_controls(&self) {
1189        let policy = self.validator_factory().policy(self.network());
1190        let mut state = self.get_state();
1191
1192        state.velocity_control.update_spec(&policy.global_velocity_control());
1193        state.fee_velocity_control.update_spec(&policy.fee_velocity_control());
1194        trace_node_state!(state);
1195    }
1196
1197    pub(crate) fn get_node_secret(&self) -> SecretKey {
1198        self.keys_manager.get_node_secret()
1199    }
1200
1201    /// Get an entropy source
1202    pub fn get_entropy_source(&self) -> &dyn EntropySource {
1203        &self.keys_manager
1204    }
1205
1206    /// Clock
1207    pub fn get_clock(&self) -> Arc<dyn Clock> {
1208        Arc::clone(&self.clock)
1209    }
1210
1211    /// Restore a node.
1212    pub fn new_from_persistence(
1213        node_config: NodeConfig,
1214        expected_node_id: &PublicKey,
1215        seed: &[u8],
1216        services: NodeServices,
1217        state: NodeState,
1218    ) -> Arc<Node> {
1219        let (keys_manager, node_id) = Self::make_keys_manager(&node_config, seed, &services);
1220        if node_id != *expected_node_id {
1221            panic!("persisted node_id mismatch: expected {} got {}", expected_node_id, node_id);
1222        }
1223        let (mut tracker, listener_entries) = services
1224            .persister
1225            .get_tracker(node_id.clone(), services.validator_factory.clone())
1226            .expect("tracker not found for node");
1227        tracker.trusted_oracle_pubkeys = services.trusted_oracle_pubkeys.clone();
1228
1229        tracker.set_allow_deep_reorgs(node_config.allow_deep_reorgs);
1230
1231        let persister = services.persister.clone();
1232
1233        let node =
1234            Arc::new(Self::new_full(node_config, services, state, keys_manager, node_id, tracker));
1235        let blockheight = node.get_tracker().height();
1236
1237        let mut listeners = OrderedMap::from_iter(listener_entries.into_iter().map(|e| (e.0, e.1)));
1238
1239        for (channel_id0, channel_entry) in
1240            persister.get_node_channels(&node_id).expect("channels not found for node")
1241        {
1242            let mut channels = node.channels.lock().unwrap();
1243            let channel_id = channel_entry.id;
1244            let enforcement_state = channel_entry.enforcement_state;
1245
1246            info!(
1247                "  Restore channel {} outpoint {:?}",
1248                channel_id0,
1249                channel_entry.channel_setup.as_ref().map(|s| s.funding_outpoint)
1250            );
1251            let mut keys = node.keys_manager.get_channel_keys_with_id(
1252                channel_id0.clone(),
1253                channel_entry.channel_value_satoshis,
1254            );
1255            let setup_opt = channel_entry.channel_setup;
1256            match setup_opt {
1257                None => {
1258                    let stub = ChannelStub {
1259                        node: Arc::downgrade(&node),
1260                        secp_ctx: Secp256k1::new(),
1261                        keys,
1262                        id0: channel_id0.clone(),
1263                        blockheight: channel_entry.blockheight.unwrap_or(blockheight),
1264                    };
1265                    let slot = Arc::new(Mutex::new(ChannelSlot::Stub(stub)));
1266                    channels.insert(channel_id0, Arc::clone(&slot));
1267                    channel_id.map(|id| channels.insert(id, Arc::clone(&slot)));
1268                }
1269                Some(setup) => {
1270                    let channel_transaction_parameters =
1271                        Node::channel_setup_to_channel_transaction_parameters(
1272                            &setup,
1273                            keys.pubkeys(),
1274                        );
1275                    keys.provide_channel_parameters(&channel_transaction_parameters);
1276                    let funding_outpoint = setup.funding_outpoint;
1277                    // Clone the matching monitor from the chaintracker's listeners.
1278                    // Tracker is persisted with node, so this should not fail.
1279                    let (tracker_state, tracker_slot) =
1280                        listeners.remove(&funding_outpoint).unwrap_or_else(|| {
1281                            panic!("tracker not found for point {}", setup.funding_outpoint)
1282                        });
1283                    let monitor_base = ChainMonitorBase::new_from_persistence(
1284                        funding_outpoint.clone(),
1285                        tracker_state,
1286                        channel_id.as_ref().unwrap_or(&channel_id0),
1287                    );
1288                    let channel = Channel {
1289                        node: Arc::downgrade(&node),
1290                        secp_ctx: Secp256k1::new(),
1291                        keys,
1292                        enforcement_state,
1293                        setup,
1294                        id0: channel_id0.clone(),
1295                        id: channel_id.clone(),
1296                        monitor: monitor_base.clone(),
1297                    };
1298
1299                    channel.restore_payments();
1300                    let slot = Arc::new(Mutex::new(ChannelSlot::Ready(channel)));
1301                    let provider = Box::new(ChannelCommitmentPointProvider::new(slot.clone()));
1302                    let monitor = monitor_base.as_monitor(provider);
1303                    node.get_tracker().restore_listener(funding_outpoint, monitor, tracker_slot);
1304                    channels.insert(channel_id0, Arc::clone(&slot));
1305                    channel_id.map(|id| channels.insert(id, Arc::clone(&slot)));
1306                }
1307            };
1308            node.keys_manager.increment_channel_id_child_index();
1309        }
1310        if !listeners.is_empty() {
1311            panic!("some chain tracker listeners were not restored: {:?}", listeners);
1312        }
1313        node
1314    }
1315
1316    fn new_full(
1317        node_config: NodeConfig,
1318        services: NodeServices,
1319        state: NodeState,
1320        keys_manager: MyKeysManager,
1321        node_id: PublicKey,
1322        tracker: ChainTracker<ChainMonitor>,
1323    ) -> Node {
1324        let secp_ctx = Secp256k1::new();
1325        let log_prefix = &node_id.to_string()[0..4];
1326
1327        let persister = services.persister;
1328        let clock = services.clock;
1329        let validator_factory = services.validator_factory;
1330        let policy = validator_factory.policy(node_config.network);
1331        let global_velocity_control = Self::make_velocity_control(&policy);
1332        let fee_velocity_control = Self::make_fee_velocity_control(&policy);
1333
1334        let state = Mutex::new(state.with_log_prefix(
1335            global_velocity_control,
1336            fee_velocity_control,
1337            log_prefix.to_string(),
1338        ));
1339
1340        #[cfg(feature = "timeless_workaround")]
1341        {
1342            // WORKAROUND for #206, #339, #235 - If our implementation has no clock use the
1343            // latest BlockHeader timestamp.
1344            let old_now = clock.now();
1345            let new_now = tracker.tip_time();
1346            // Don't allow retrograde time updates ...
1347            if new_now > old_now {
1348                clock.set_workaround_time(new_now);
1349            }
1350        }
1351
1352        Node {
1353            secp_ctx,
1354            node_config,
1355            keys_manager,
1356            channels: Mutex::new(OrderedMap::new()),
1357            validator_factory: Mutex::new(validator_factory),
1358            persister,
1359            clock,
1360            tracker: Mutex::new(tracker),
1361            state,
1362            node_id,
1363        }
1364    }
1365
1366    /// Create a keys manager - useful for bootstrapping a node from persistence, so the
1367    /// persistence key can be derived.
1368    pub fn make_keys_manager(
1369        node_config: &NodeConfig,
1370        seed: &[u8],
1371        services: &NodeServices,
1372    ) -> (MyKeysManager, PublicKey) {
1373        let keys_manager = MyKeysManager::new(
1374            node_config.key_derivation_style,
1375            seed,
1376            node_config.network,
1377            services.starting_time_factory.borrow(),
1378        );
1379        // infallible with Recipient::Node
1380        let node_id = keys_manager.get_node_id(Recipient::Node).unwrap();
1381        (keys_manager, node_id)
1382    }
1383
1384    /// persister
1385    pub fn get_persister(&self) -> Arc<dyn Persist> {
1386        Arc::clone(&self.persister)
1387    }
1388
1389    /// onion reply secret
1390    pub fn get_onion_reply_secret(&self) -> [u8; 32] {
1391        self.keys_manager.get_onion_reply_secret()
1392    }
1393
1394    /// BOLT 12 x-only pubkey
1395    pub fn get_bolt12_pubkey(&self) -> PublicKey {
1396        self.keys_manager.get_bolt12_pubkey()
1397    }
1398
1399    /// persistence pubkey
1400    pub fn get_persistence_pubkey(&self) -> PublicKey {
1401        self.keys_manager.get_persistence_pubkey()
1402    }
1403
1404    /// persistence shared secret
1405    pub fn get_persistence_shared_secret(&self, server_pubkey: &PublicKey) -> [u8; 32] {
1406        self.keys_manager.get_persistence_shared_secret(server_pubkey)
1407    }
1408
1409    /// Persistence auth token
1410    pub fn get_persistence_auth_token(&self, server_pubkey: &PublicKey) -> [u8; 32] {
1411        self.keys_manager.get_persistence_auth_token(server_pubkey)
1412    }
1413
1414    /// BOLT 12 sign
1415    pub fn sign_bolt12(
1416        &self,
1417        messagename: &[u8],
1418        fieldname: &[u8],
1419        merkleroot: &[u8; 32],
1420        publictweak_opt: Option<&[u8]>,
1421    ) -> Result<schnorr::Signature, Status> {
1422        self.keys_manager
1423            .sign_bolt12(messagename, fieldname, merkleroot, publictweak_opt)
1424            .map_err(|_| internal_error("signature operation failed"))
1425    }
1426
1427    /// BOLT 12 sign
1428    pub fn sign_bolt12_2(
1429        &self,
1430        messagename: &[u8],
1431        fieldname: &[u8],
1432        merkleroot: &[u8; 32],
1433        info: &[u8],
1434        publictweak_opt: Option<&[u8]>,
1435    ) -> Result<schnorr::Signature, Status> {
1436        self.keys_manager
1437            .sign_bolt12_2(messagename, fieldname, merkleroot, info, publictweak_opt)
1438            .map_err(|_| internal_error("signature operation failed"))
1439    }
1440
1441    /// derive secret
1442    pub fn derive_secret(&self, info: &[u8]) -> SecretKey {
1443        self.keys_manager.derive_secret(info)
1444    }
1445
1446    /// Set the node's validator factory
1447    pub fn set_validator_factory(&self, validator_factory: Arc<dyn ValidatorFactory>) {
1448        let mut vfac = self.validator_factory();
1449        *vfac = validator_factory;
1450    }
1451
1452    /// Persist everything.
1453    /// This is normally not needed, as the node will persist itself,
1454    /// but may be useful if switching to a new persister.
1455    pub fn persist_all(&self) {
1456        let persister = &self.persister;
1457        let state = self.get_state();
1458        persister.new_node(&self.get_id(), &self.node_config, &*state).unwrap();
1459        for channel in self.get_channels().values() {
1460            let channel = channel.lock().unwrap();
1461            match &*channel {
1462                ChannelSlot::Stub(_) => {}
1463                ChannelSlot::Ready(chan) => {
1464                    persister.update_channel(&self.get_id(), &chan).unwrap();
1465                }
1466            }
1467        }
1468        persister.update_tracker(&self.get_id(), &self.get_tracker()).unwrap();
1469        let wlvec = state.allowlist.iter().map(|a| a.to_string(self.network())).collect();
1470        self.persister.update_node_allowlist(&self.get_id(), wlvec).unwrap();
1471    }
1472
1473    /// Get the node ID, which is the same as the node public key
1474    pub fn get_id(&self) -> PublicKey {
1475        self.node_id
1476    }
1477
1478    /// Get suitable node identity string for logging
1479    pub fn log_prefix(&self) -> String {
1480        self.get_id().to_string()[0..4].to_string()
1481    }
1482
1483    /// Lock and return the node state
1484    pub fn get_state(&self) -> MutexGuard<NodeState> {
1485        self.state.lock().unwrap()
1486    }
1487
1488    #[allow(dead_code)]
1489    pub(crate) fn get_secure_random_bytes(&self) -> [u8; 32] {
1490        self.keys_manager.get_secure_random_bytes()
1491    }
1492
1493    /// Get secret key material as bytes for use in encrypting and decrypting inbound payment data.
1494    ///
1495    /// This method must return the same value each time it is called.
1496    pub fn get_inbound_payment_key_material(&self) -> ExpandedKey {
1497        self.keys_manager.get_inbound_payment_key()
1498    }
1499
1500    /// Get the [Mutex] protected channel slot
1501    pub fn get_channel(&self, channel_id: &ChannelId) -> Result<Arc<Mutex<ChannelSlot>>, Status> {
1502        let mut guard = self.get_channels();
1503        let elem = guard.get_mut(channel_id);
1504        let slot_arc =
1505            elem.ok_or_else(|| invalid_argument(format!("no such channel: {}", &channel_id)))?;
1506        Ok(Arc::clone(slot_arc))
1507    }
1508
1509    /// Execute a function with an existing channel.
1510    ///
1511    /// The channel may be a stub or a ready channel.
1512    /// An invalid_argument [Status] will be returned if the channel does not exist.
1513    pub fn with_channel_base<F: Sized, T>(&self, channel_id: &ChannelId, f: F) -> Result<T, Status>
1514    where
1515        F: Fn(&mut dyn ChannelBase) -> Result<T, Status>,
1516    {
1517        let slot_mutex = self.get_channel(channel_id)?;
1518        let mut slot = slot_mutex.lock().unwrap();
1519        let base = match &mut *slot {
1520            ChannelSlot::Stub(stub) => stub as &mut dyn ChannelBase,
1521            ChannelSlot::Ready(chan) => chan as &mut dyn ChannelBase,
1522        };
1523        f(base)
1524    }
1525
1526    /// Execute a function with an existing configured channel.
1527    ///
1528    /// An invalid_argument [Status] will be returned if the channel does not exist.
1529    pub fn with_channel<F: Sized, T>(&self, channel_id: &ChannelId, f: F) -> Result<T, Status>
1530    where
1531        F: FnOnce(&mut Channel) -> Result<T, Status>,
1532    {
1533        let slot_arc = self.get_channel(channel_id)?;
1534        let mut slot = slot_arc.lock().unwrap();
1535        match &mut *slot {
1536            ChannelSlot::Stub(_) =>
1537                Err(invalid_argument(format!("channel not ready: {}", &channel_id))),
1538            ChannelSlot::Ready(chan) => f(chan),
1539        }
1540    }
1541
1542    /// Get a channel given its funding outpoint, or None if no such channel exists.
1543    pub fn find_channel_with_funding_outpoint(
1544        &self,
1545        outpoint: &OutPoint,
1546    ) -> Option<Arc<Mutex<ChannelSlot>>> {
1547        let channels_lock = self.get_channels();
1548        find_channel_with_funding_outpoint(&channels_lock, outpoint)
1549    }
1550
1551    /// Create a new channel, which starts out as a stub.
1552    ///
1553    /// Returns a generated channel ID and the stub.
1554    pub fn new_channel_with_random_id(
1555        &self,
1556        arc_self: &Arc<Node>,
1557    ) -> Result<(ChannelId, Option<ChannelSlot>), Status> {
1558        let channel_id = self.keys_manager.get_channel_id();
1559        self.find_or_create_channel(channel_id, arc_self)
1560    }
1561
1562    /// Create a new channel from a seed identifier (aka a dbid) and
1563    /// a peer node id
1564    ///
1565    /// The seed id must never be reused as revocation secrets may
1566    /// be publicly known. Rather than store all historical ids,
1567    /// this method requires seed ids to increase monotonically,
1568    /// checked against a high-water mark which is set when
1569    /// forgetting channels.
1570    ///
1571    /// Setting the high-water mark on forgetting rather than creating
1572    /// channels allows for some slack in the system to accomodate reordered
1573    /// requests.
1574    ///
1575    /// If the seed id is not monotonic the method returns an error.
1576    /// Otherwise, it returns the new channel id and stub.
1577    pub fn new_channel(
1578        &self,
1579        dbid: u64,
1580        peer_id: &[u8; 33], // TODO figure out a more specific type
1581        arc_self: &Arc<Node>,
1582    ) -> Result<(ChannelId, Option<ChannelSlot>), Status> {
1583        if self.get_state().dbid_high_water_mark >= dbid {
1584            return Err(Status::invalid_argument("dbid not above the high water mark"));
1585        }
1586
1587        let channel_id = ChannelId::new_from_peer_id_and_oid(peer_id, dbid);
1588        self.find_or_create_channel(channel_id, arc_self)
1589    }
1590
1591    /// Create a new channel with a specified channel id.
1592    /// Only used for testing.
1593    #[cfg(any(test, feature = "test_utils"))]
1594    pub(crate) fn new_channel_with_id(
1595        &self,
1596        channel_id: ChannelId,
1597        arc_self: &Arc<Node>,
1598    ) -> Result<(ChannelId, Option<ChannelSlot>), Status> {
1599        self.find_or_create_channel(channel_id, arc_self)
1600    }
1601
1602    fn find_or_create_channel(
1603        &self,
1604        channel_id: ChannelId,
1605        arc_self: &Arc<Node>,
1606    ) -> Result<(ChannelId, Option<ChannelSlot>), Status> {
1607        let mut channels = self.get_channels();
1608        let policy = self.policy();
1609        if channels.len() >= policy.max_channels() {
1610            // FIXME(3) we don't garbage collect channels
1611            return Err(failed_precondition(format!(
1612                "too many channels ({} >= {})",
1613                channels.len(),
1614                policy.max_channels()
1615            )));
1616        }
1617
1618        // Is there an existing channel slot?
1619        let maybe_slot = channels.get(&channel_id);
1620        if let Some(slot) = maybe_slot {
1621            let slot = slot.lock().unwrap().clone();
1622            return Ok((channel_id, Some(slot)));
1623        }
1624
1625        let channel_value_sat = 0; // Placeholder value, not known yet.
1626        let keys =
1627            self.keys_manager.get_channel_keys_with_id(channel_id.clone(), channel_value_sat);
1628
1629        let blockheight = arc_self.get_tracker().height();
1630        let stub = ChannelStub {
1631            node: Arc::downgrade(arc_self),
1632            secp_ctx: Secp256k1::new(),
1633            keys,
1634            id0: channel_id.clone(),
1635            blockheight,
1636        };
1637        // TODO(507) this clone is expensive
1638        channels.insert(channel_id.clone(), Arc::new(Mutex::new(ChannelSlot::Stub(stub.clone()))));
1639        self.persister
1640            .new_channel(&self.get_id(), &stub)
1641            // Persist.new_channel should only fail if the channel was previously persisted.
1642            // So if it did fail, we have an internal error.
1643            .expect("channel was in storage but not in memory");
1644        Ok((channel_id.clone(), Some(ChannelSlot::Stub(stub))))
1645    }
1646
1647    /// Restore a node from a persisted [NodeEntry].
1648    ///
1649    /// You can get the [NodeEntry] from [Persist::get_nodes].
1650    ///
1651    /// The channels are also restored from the `persister`.
1652    // unit test coverage outside crate
1653    pub fn restore_node(
1654        node_id: &PublicKey,
1655        node_entry: NodeEntry,
1656        seed: &[u8],
1657        services: NodeServices,
1658    ) -> Result<Arc<Node>, Status> {
1659        let network = Network::from_str(node_entry.network.as_str())
1660            .expect("bad node network in persistence");
1661        let allow_deep_reorgs = if network == Network::Testnet { true } else { false };
1662        let key_derivation_style = KeyDerivationStyle::try_from(node_entry.key_derivation_style)
1663            .expect("bad key derivation in peristence");
1664        let config =
1665            NodeConfig { network, key_derivation_style, use_checkpoints: true, allow_deep_reorgs };
1666
1667        let persister = services.persister.clone();
1668        let allowlist: Vec<Allowable> = persister
1669            .get_node_allowlist(node_id)
1670            .expect("missing node allowlist in persistence")
1671            .iter()
1672            .map(|e| Allowable::from_str(e, network))
1673            .collect::<Result<_, _>>()
1674            .expect("persisted allowable could not be parsed");
1675
1676        let mut state = node_entry.state;
1677
1678        state.allowlist = allowlist.into_iter().collect();
1679
1680        // create a payment state for each invoice state
1681        for h in state.invoices.keys() {
1682            state.payments.insert(*h, RoutedPayment::new());
1683        }
1684
1685        let node = Node::new_from_persistence(config, node_id, seed, services, state);
1686        assert_eq!(&node.get_id(), node_id);
1687        info!("Restore node {} on {}", node_id, config.network);
1688        if let Some((height, _hash, filter_header, header)) = get_latest_checkpoint(network) {
1689            let mut tracker = node.get_tracker();
1690            if tracker.height() == 0 {
1691                // Fast-forward the tracker to the checkpoint
1692                tracker.headers = VecDeque::new();
1693                tracker.tip = Headers(header, filter_header);
1694                tracker.height = height;
1695            }
1696        }
1697
1698        node.maybe_sync_persister()?;
1699        Ok(node)
1700    }
1701
1702    fn maybe_sync_persister(&self) -> Result<(), Status> {
1703        if self.persister.on_initial_restore() {
1704            // write everything to persister, to ensure that any composite
1705            // persister has all sub-persisters in sync
1706            let state = self.get_state();
1707            // do a new_node here, because update_node doesn't store the entry,
1708            // only the state
1709            self.persister
1710                .new_node(&self.get_id(), &self.node_config, &*state)
1711                .map_err(|_| internal_error("sync persist failed"))?;
1712
1713            let wlvec = state.allowlist.iter().map(|a| a.to_string(self.network())).collect();
1714            self.persister
1715                .update_node_allowlist(&self.get_id(), wlvec)
1716                .map_err(|_| internal_error("sync persist failed"))?;
1717
1718            {
1719                let tracker = self.get_tracker();
1720                self.persister
1721                    .update_tracker(&self.get_id(), &tracker)
1722                    .map_err(|_| internal_error("tracker persist failed"))?;
1723            }
1724            let channels = self.get_channels();
1725            for (_, slot) in channels.iter() {
1726                let channel = slot.lock().unwrap();
1727                match &*channel {
1728                    ChannelSlot::Stub(_) => {}
1729                    ChannelSlot::Ready(c) => {
1730                        self.persister
1731                            .update_channel(&self.get_id(), c)
1732                            .map_err(|_| internal_error("sync persist failed"))?;
1733                    }
1734                }
1735            }
1736        }
1737        Ok(())
1738    }
1739
1740    /// Restore all nodes from `persister`.
1741    ///
1742    /// The channels of each node are also restored.
1743    // unit test coverage outside crate
1744    pub fn restore_nodes(
1745        services: NodeServices,
1746        seed_persister: Arc<dyn SeedPersist>,
1747    ) -> Result<Map<PublicKey, Arc<Node>>, Status> {
1748        let mut nodes = Map::new();
1749        let persister = services.persister.clone();
1750        let mut seeds = OrderedSet::from_iter(seed_persister.list().into_iter());
1751        for (node_id, node_entry) in
1752            persister.get_nodes().expect("could not get nodes from persistence")
1753        {
1754            let seed = seed_persister
1755                .get(&node_id.serialize().to_hex())
1756                .expect(format!("no seed for node {:?}", node_id).as_str());
1757            let node = Node::restore_node(&node_id, node_entry, &seed, services.clone())?;
1758            nodes.insert(node_id, node);
1759            seeds.remove(&node_id.serialize().to_hex());
1760        }
1761        if !seeds.is_empty() {
1762            warn!("some seeds had no persisted node state: {:?}", seeds);
1763        }
1764        Ok(nodes)
1765    }
1766
1767    /// Setup a new channel, making it available for use.
1768    ///
1769    /// This populates fields that are known later in the channel creation flow,
1770    /// such as fields that are supplied by the counterparty and funding outpoint.
1771    ///
1772    /// * `channel_id0` - the original channel ID supplied to [`Node::new_channel`]
1773    /// * `opt_channel_id` - the permanent channel ID
1774    ///
1775    /// The channel is promoted from a [ChannelStub] to a [Channel].
1776    /// After this call, the channel may be referred to by either ID.
1777    pub fn setup_channel(
1778        &self,
1779        channel_id0: ChannelId,
1780        opt_channel_id: Option<ChannelId>,
1781        setup: ChannelSetup,
1782        holder_shutdown_key_path: &DerivationPath,
1783    ) -> Result<Channel, Status> {
1784        let mut tracker = self.get_tracker();
1785        let validator = self.validator_factory().make_validator(
1786            self.network(),
1787            self.get_id(),
1788            Some(channel_id0.clone()),
1789        );
1790
1791        // If a permanent channel_id was provided use it, otherwise
1792        // continue with the initial channel_id0.
1793        let chan_id = opt_channel_id.as_ref().unwrap_or(&channel_id0);
1794
1795        let chan = {
1796            let channels = self.get_channels();
1797            let arcobj = channels.get(&channel_id0).ok_or_else(|| {
1798                invalid_argument(format!("channel does not exist: {}", channel_id0))
1799            })?;
1800            let slot = arcobj.lock().unwrap();
1801            let stub: &ChannelStub = match &*slot {
1802                ChannelSlot::Stub(stub) => stub,
1803                ChannelSlot::Ready(c) => {
1804                    if c.setup != setup {
1805                        return Err(invalid_argument(format!(
1806                            "channel already ready with different setup: {}",
1807                            channel_id0
1808                        )));
1809                    }
1810                    return Ok(c.clone());
1811                }
1812            };
1813            let mut keys = stub.channel_keys_with_channel_value(setup.channel_value_sat);
1814            let holder_pubkeys = keys.pubkeys();
1815            let channel_transaction_parameters =
1816                Node::channel_setup_to_channel_transaction_parameters(&setup, holder_pubkeys);
1817            keys.provide_channel_parameters(&channel_transaction_parameters);
1818            let funding_outpoint = setup.funding_outpoint;
1819            let monitor = ChainMonitorBase::new(funding_outpoint, tracker.height(), chan_id);
1820            monitor.add_funding_outpoint(&funding_outpoint);
1821            let to_holder_msat = if setup.is_outbound {
1822                // This is also checked in the validator, but we have to check
1823                // here because we need it to create the validator
1824                (setup.channel_value_sat * 1000).checked_sub(setup.push_value_msat).ok_or_else(
1825                    || {
1826                        policy_error(
1827                            "policy-routing-balanced",
1828                            format!(
1829                                "beneficial channel value underflow: {} - {}",
1830                                setup.channel_value_sat * 1000,
1831                                setup.push_value_msat
1832                            ),
1833                        )
1834                    },
1835                )?
1836            } else {
1837                setup.push_value_msat
1838            };
1839            let initial_holder_value_sat = validator.minimum_initial_balance(to_holder_msat);
1840            let enforcement_state = EnforcementState::new(initial_holder_value_sat);
1841            Channel {
1842                node: Weak::clone(&stub.node),
1843                secp_ctx: stub.secp_ctx.clone(),
1844                keys,
1845                enforcement_state,
1846                setup: setup.clone(),
1847                id0: channel_id0.clone(),
1848                id: opt_channel_id.clone(),
1849                monitor,
1850            }
1851        };
1852
1853        validator.validate_setup_channel(self, &setup, holder_shutdown_key_path)?;
1854
1855        let mut channels = self.get_channels();
1856
1857        // Wrap the ready channel with an arc so we can potentially
1858        // refer to it multiple times.
1859        // TODO(507) this clone is expensive
1860        let chan_arc = Arc::new(Mutex::new(ChannelSlot::Ready(chan.clone())));
1861
1862        let commitment_point_provider = ChannelCommitmentPointProvider::new(chan_arc.clone());
1863
1864        // Associate the new ready channel with the channel id.
1865        channels.insert(chan_id.clone(), chan_arc.clone());
1866
1867        // If we are using a new permanent channel_id additionally
1868        // associate the channel with the original (initial)
1869        // channel_id as well.
1870        if channel_id0 != *chan_id {
1871            channels.insert(channel_id0, chan_arc.clone());
1872        }
1873
1874        // Watch the funding outpoint, because we might not have any funding
1875        // inputs that are ours.
1876        // Note that the functional tests also have no inputs for the funder's tx
1877        // which might be a problem in the future with more validation.
1878        tracker.add_listener(
1879            chan.monitor.as_monitor(Box::new(commitment_point_provider)),
1880            OrderedSet::from_iter(vec![setup.funding_outpoint.txid]),
1881        );
1882
1883        dbgvals!(&chan.setup);
1884        trace_enforcement_state!(&chan);
1885        self.persister
1886            .update_tracker(&self.get_id(), &tracker)
1887            .map_err(|_| internal_error("tracker persist failed"))?;
1888        self.persister
1889            .update_channel(&self.get_id(), &chan)
1890            .map_err(|_| internal_error("persist failed"))?;
1891
1892        Ok(chan)
1893    }
1894
1895    /// Get a signed heartbeat message
1896    /// The heartbeat is signed with the account master key.
1897    pub fn get_heartbeat(&self) -> SignedHeartbeat {
1898        // we get asked for a heartbeat on a regular basis, so use this
1899        // opportunity to prune invoices
1900        let mut state = self.get_state();
1901        let now = self.clock.now();
1902        let pruned1 = state.prune_invoices(now);
1903        let pruned2 = state.prune_issued_invoices(now);
1904        let pruned3 = state.prune_forwarded_payments();
1905        if pruned1 || pruned2 || pruned3 {
1906            trace_node_state!(state);
1907            self.persister
1908                .update_node(&self.get_id(), &state)
1909                .unwrap_or_else(|err| panic!("pruned node state persist failed: {:?}", err));
1910        }
1911        drop(state); // minimize lock time
1912
1913        let mut tracker = self.get_tracker();
1914
1915        // pruned channels are persisted inside
1916        self.prune_channels(&mut tracker);
1917
1918        info!("current channel balance: {:?}", self.channel_balance());
1919
1920        let tip = tracker.tip();
1921        let current_timestamp = self.clock.now().as_secs() as u32;
1922        let heartbeat = Heartbeat {
1923            chain_tip: tip.0.block_hash(),
1924            chain_height: tracker.height(),
1925            chain_timestamp: tip.0.time,
1926            current_timestamp,
1927        };
1928        let ser_heartbeat = heartbeat.encode();
1929        let sig = self.keys_manager.sign_heartbeat(&ser_heartbeat);
1930        SignedHeartbeat { signature: sig[..].to_vec(), heartbeat }
1931    }
1932
1933    // Check and sign an onchain transaction
1934    #[cfg(any(test, feature = "test_utils"))]
1935    pub(crate) fn check_and_sign_onchain_tx(
1936        &self,
1937        tx: &Transaction,
1938        segwit_flags: &[bool],
1939        ipaths: &[DerivationPath],
1940        prev_outs: &[TxOut],
1941        uniclosekeys: Vec<Option<(SecretKey, Vec<Vec<u8>>)>>,
1942        opaths: &[DerivationPath],
1943    ) -> Result<Vec<Vec<Vec<u8>>>, Status> {
1944        self.check_onchain_tx(tx, segwit_flags, prev_outs, &uniclosekeys, opaths)?;
1945        self.unchecked_sign_onchain_tx(tx, ipaths, prev_outs, uniclosekeys)
1946    }
1947
1948    /// Sign an onchain transaction (funding tx or simple sweeps).
1949    ///
1950    /// `check_onchain_tx` must be called first to validate the transaction.
1951    /// The two are separate so that the caller can check for approval if
1952    /// there is an unknown destination.
1953    ///
1954    /// The transaction may fund multiple channels at once.
1955    ///
1956    /// Returns a witness stack for each input.  Inputs that are marked
1957    /// as [SpendType::Invalid] are not signed and get an empty witness stack.
1958    ///
1959    /// * `ipaths` - derivation path for the wallet key per input
1960    /// * `prev_outs` - the previous outputs used as inputs for this tx
1961    /// * `uniclosekeys` - an optional unilateral close key to use instead of the
1962    ///   wallet key.  Takes precedence over the `ipaths` entry.  This is used when
1963    ///   we are sweeping a unilateral close and funding a channel in a single tx.
1964    ///   The second item in the tuple is the witness stack suffix - zero or more
1965    ///   script parameters and the redeemscript.
1966    pub fn unchecked_sign_onchain_tx(
1967        &self,
1968        tx: &Transaction,
1969        ipaths: &[DerivationPath],
1970        prev_outs: &[TxOut],
1971        uniclosekeys: Vec<Option<(SecretKey, Vec<Vec<u8>>)>>,
1972    ) -> Result<Vec<Vec<Vec<u8>>>, Status> {
1973        let channels_lock = self.get_channels();
1974
1975        // Funding transactions cannot be associated with just a single channel;
1976        // a single transaction may fund multiple channels
1977
1978        let txid = tx.compute_txid();
1979        debug!("{}: txid: {}", short_function!(), txid);
1980
1981        let channels: Vec<Option<Arc<Mutex<ChannelSlot>>>> = (0..tx.output.len())
1982            .map(|ndx| {
1983                let outpoint = OutPoint { txid, vout: ndx as u32 };
1984                find_channel_with_funding_outpoint(&channels_lock, &outpoint)
1985            })
1986            .collect();
1987
1988        let mut witvec: Vec<Vec<Vec<u8>>> = Vec::new();
1989        for (idx, uck) in uniclosekeys.into_iter().enumerate() {
1990            let spend_type = SpendType::from_script_pubkey(&prev_outs[idx].script_pubkey);
1991            // if we don't recognize the script, or we are not told what the derivation path is, don't try to sign
1992            if spend_type == SpendType::Invalid || (uck.is_none() && ipaths[idx].is_empty()) {
1993                // If we are signing a PSBT some of the inputs may be
1994                // marked as SpendType::Invalid (we skip these), push
1995                // an empty witness element instead.
1996                witvec.push(vec![]);
1997            } else {
1998                let value_sat = prev_outs[idx].value;
1999                let (privkey, mut witness) = match uck {
2000                    // There was a unilateral_close_key.
2001                    Some((key, stack)) => (PrivateKey::new(key, self.network()), stack),
2002                    // Derive the HD key.
2003                    None => {
2004                        let key = self.get_wallet_privkey(&ipaths[idx])?;
2005                        let redeemscript = PublicKey::from_secret_key(&self.secp_ctx, &key.inner)
2006                            .serialize()
2007                            .to_vec();
2008                        (key, vec![redeemscript])
2009                    }
2010                };
2011                let pubkey = CompressedPublicKey(privkey.public_key(&self.secp_ctx).inner);
2012                // the unwraps below are infallible, because sighash is always 32 bytes
2013                let sigvec = match spend_type {
2014                    SpendType::P2pkh => {
2015                        let expected_scriptpubkey =
2016                            Address::p2pkh(&pubkey, self.network()).script_pubkey();
2017                        assert_eq!(
2018                            prev_outs[idx].script_pubkey, expected_scriptpubkey,
2019                            "scriptpubkey mismatch on index {}",
2020                            idx
2021                        );
2022                        let script_code = Address::p2pkh(&pubkey, self.network()).script_pubkey();
2023                        let sighash = SighashCache::new(tx)
2024                            .legacy_signature_hash(idx, &script_code, 0x01)
2025                            .map_err(|_| internal_error("sighash failed"))?;
2026                        signature_to_bitcoin_vec(ecdsa_sign(
2027                            &self.secp_ctx,
2028                            &privkey,
2029                            sighash.into(),
2030                        ))
2031                    }
2032                    SpendType::P2wpkh => {
2033                        let expected_scriptpubkey =
2034                            Address::p2wpkh(&pubkey, self.network()).script_pubkey();
2035                        assert_eq!(
2036                            prev_outs[idx].script_pubkey, expected_scriptpubkey,
2037                            "scriptpubkey mismatch on index {}",
2038                            idx
2039                        );
2040                        // unwrap cannot fail
2041                        let sighash = SighashCache::new(tx)
2042                            .p2wpkh_signature_hash(
2043                                idx,
2044                                &expected_scriptpubkey,
2045                                value_sat,
2046                                EcdsaSighashType::All,
2047                            )
2048                            .unwrap();
2049                        signature_to_bitcoin_vec(ecdsa_sign(
2050                            &self.secp_ctx,
2051                            &privkey,
2052                            sighash.into(),
2053                        ))
2054                    }
2055                    SpendType::P2shP2wpkh => {
2056                        // compressed pubkeys cannot fail
2057                        let expected_scriptpubkey =
2058                            Address::p2shwpkh(&pubkey, self.network()).script_pubkey();
2059                        assert_eq!(
2060                            prev_outs[idx].script_pubkey, expected_scriptpubkey,
2061                            "scriptpubkey mismatch on index {}",
2062                            idx
2063                        );
2064                        let nested_script =
2065                            Address::p2wpkh(&pubkey, self.network()).script_pubkey();
2066
2067                        // unwrap cannot fail
2068                        let sighash = SighashCache::new(tx)
2069                            .p2wpkh_signature_hash(
2070                                idx,
2071                                &nested_script,
2072                                value_sat,
2073                                EcdsaSighashType::All,
2074                            )
2075                            .unwrap();
2076                        signature_to_bitcoin_vec(ecdsa_sign(
2077                            &self.secp_ctx,
2078                            &privkey,
2079                            sighash.into(),
2080                        ))
2081                    }
2082                    SpendType::P2wsh => {
2083                        // TODO failfast here if the scriptpubkey doesn't match
2084                        let sighash = SighashCache::new(tx)
2085                            .p2wsh_signature_hash(
2086                                idx,
2087                                &ScriptBuf::from(witness[witness.len() - 1].clone()),
2088                                value_sat,
2089                                EcdsaSighashType::All,
2090                            )
2091                            .unwrap();
2092                        signature_to_bitcoin_vec(ecdsa_sign(
2093                            &self.secp_ctx,
2094                            &privkey,
2095                            sighash.into(),
2096                        ))
2097                    }
2098                    SpendType::P2tr => {
2099                        let wallet_addr = self.get_taproot_address(&ipaths[idx])?;
2100                        let script = &prev_outs[idx].script_pubkey;
2101                        let out_addr =
2102                            Address::from_script(&script, self.network()).map_err(|_| {
2103                                invalid_argument(format!(
2104                                    "script {} at output {} could not be converted to address",
2105                                    script, idx
2106                                ))
2107                            })?;
2108                        trace!(
2109                            "signing p2tr, idx {}, ipath {:?} out addr {:?}, wallet addr {} prev outs {:?}",
2110                            idx, ipaths[idx], out_addr, wallet_addr, prev_outs
2111                        );
2112                        if wallet_addr != out_addr {
2113                            return Err(invalid_argument(format!(
2114                                "wallet address @{:?} {} does not match output address {}",
2115                                ipaths[idx], wallet_addr, out_addr
2116                            )));
2117                        }
2118                        let prevouts = Prevouts::All(&prev_outs);
2119                        // unwrap cannot fail
2120                        let sighash = SighashCache::new(tx)
2121                            .taproot_signature_hash(
2122                                idx,
2123                                &prevouts,
2124                                None,
2125                                None,
2126                                TapSighashType::Default,
2127                            )
2128                            .unwrap();
2129                        let aux_rand = self.keys_manager.get_secure_random_bytes();
2130                        schnorr_signature_to_bitcoin_vec(taproot_sign(
2131                            &self.secp_ctx,
2132                            &privkey,
2133                            sighash,
2134                            &aux_rand,
2135                        ))
2136                    }
2137                    st => return Err(invalid_argument(format!("unsupported spend_type={:?}", st))),
2138                };
2139                // if taproot, clear out the witness, since taproot doesn't use a redeemscript for key path
2140                if spend_type == SpendType::P2tr {
2141                    witness.clear();
2142                }
2143                witness.insert(0, sigvec);
2144
2145                witvec.push(witness);
2146            }
2147        }
2148
2149        // The tracker may be updated for multiple channels
2150        let mut tracker = self.get_tracker();
2151
2152        // This locks channels in a random order, so we have to keep a global
2153        // lock to ensure no deadlock.  We grab the self.channels mutex above
2154        // for this purpose.
2155        // TODO(511) consider sorting instead
2156        for (vout, slot_opt) in channels.iter().enumerate() {
2157            if let Some(slot_mutex) = slot_opt {
2158                let slot = slot_mutex.lock().unwrap();
2159                match &*slot {
2160                    ChannelSlot::Stub(_) => panic!("this can't happen"),
2161                    ChannelSlot::Ready(chan) => {
2162                        let inputs =
2163                            OrderedSet::from_iter(tx.input.iter().map(|i| i.previous_output));
2164                        tracker.add_listener_watches(&chan.monitor.funding_outpoint, inputs);
2165                        chan.funding_signed(tx, vout as u32);
2166                        self.persister
2167                            .update_channel(&self.get_id(), &chan)
2168                            .map_err(|_| internal_error("persist failed"))?;
2169                    }
2170                }
2171            }
2172        }
2173
2174        // the channels added some watches - persist
2175        self.persister
2176            .update_tracker(&self.get_id(), &tracker)
2177            .map_err(|_| internal_error("tracker persist failed"))?;
2178
2179        Ok(witvec)
2180    }
2181
2182    /// Check an onchain transaction (funding tx or simple sweeps).
2183    ///
2184    /// This is normally followed by a call to `unchecked_sign_onchain_tx`.
2185    ///
2186    /// If the result is ValidationError::UncheckedDestinations, the caller
2187    /// could still ask for manual approval and then sign the transaction.
2188    ///
2189    /// The transaction may fund multiple channels at once.
2190    ///
2191    /// * `input_txs` - previous tx for inputs when funding channel
2192    /// * `prev_outs` - the previous outputs used as inputs for this tx
2193    /// * `uniclosekeys` - an optional unilateral close key to use instead of the
2194    ///   wallet key.  Takes precedence over the `ipaths` entry.  This is used when
2195    ///   we are sweeping a unilateral close and funding a channel in a single tx.
2196    ///   The second item in the tuple is the witness stack suffix - zero or more
2197    ///   script parameters and the redeemscript.
2198    /// * `opaths` - derivation path per output.  Empty for non-wallet/non-xpub-whitelist
2199    ///   outputs.
2200    pub fn check_onchain_tx(
2201        &self,
2202        tx: &Transaction,
2203        segwit_flags: &[bool],
2204        prev_outs: &[TxOut],
2205        uniclosekeys: &[Option<(SecretKey, Vec<Vec<u8>>)>],
2206        opaths: &[DerivationPath],
2207    ) -> Result<(), ValidationError> {
2208        let channels_lock = self.get_channels();
2209
2210        // Funding transactions cannot be associated with just a single channel;
2211        // a single transaction may fund multiple channels
2212
2213        let txid = tx.compute_txid();
2214        debug!("{}: txid: {}", short_function!(), txid);
2215
2216        let channels: Vec<Option<Arc<Mutex<ChannelSlot>>>> = (0..tx.output.len())
2217            .map(|ndx| {
2218                let outpoint = OutPoint { txid, vout: ndx as u32 };
2219                find_channel_with_funding_outpoint(&channels_lock, &outpoint)
2220            })
2221            .collect();
2222
2223        let validator = self.validator();
2224
2225        // Compute a lower bound for the tx weight for feerate checking.
2226        // TODO(dual-funding) - This estimate does not include witnesses for inputs we don't sign.
2227        let mut weight_lower_bound = tx.weight().to_wu() as usize;
2228        for (idx, uck) in uniclosekeys.iter().enumerate() {
2229            let spend_type = SpendType::from_script_pubkey(&prev_outs[idx].script_pubkey);
2230            if spend_type == SpendType::Invalid {
2231                weight_lower_bound += 0;
2232            } else {
2233                let wit_len = match uck {
2234                    // length-byte + witness-element
2235                    Some((_key, stack)) => stack.iter().map(|v| 1 + v.len()).sum(),
2236                    None => 33,
2237                };
2238                // witness-header + element-count + length + sig + len + redeemscript
2239                weight_lower_bound += 2 + 1 + 1 + 72 + 1 + wit_len;
2240            }
2241        }
2242        debug!("weight_lower_bound: {}", weight_lower_bound);
2243
2244        let values_sat = prev_outs.iter().map(|o| o.value.to_sat()).collect::<Vec<_>>();
2245        let non_beneficial_sat = validator.validate_onchain_tx(
2246            self,
2247            channels,
2248            tx,
2249            segwit_flags,
2250            &values_sat,
2251            opaths,
2252            weight_lower_bound,
2253        )?;
2254
2255        // be conservative about holding multiple locks, so we don't worry about order
2256        drop(channels_lock);
2257
2258        let validator = self.validator();
2259        defer! { trace_node_state!(self.get_state()); }
2260        let mut state = self.get_state();
2261        let now = self.clock.now().as_secs();
2262        if !state.fee_velocity_control.insert(now, non_beneficial_sat * 1000) {
2263            policy_err!(
2264                validator,
2265                "policy-onchain-fee-range",
2266                "fee velocity would be exceeded {} + {} > {}",
2267                state.fee_velocity_control.velocity(),
2268                non_beneficial_sat * 1000,
2269                state.fee_velocity_control.limit
2270            );
2271        }
2272
2273        Ok(())
2274    }
2275
2276    fn validator(&self) -> Arc<dyn Validator> {
2277        self.validator_factory().make_validator(self.network(), self.get_id(), None)
2278    }
2279
2280    fn channel_setup_to_channel_transaction_parameters(
2281        setup: &ChannelSetup,
2282        holder_pubkeys: &ChannelPublicKeys,
2283    ) -> ChannelTransactionParameters {
2284        let funding_outpoint = Some(chain::transaction::OutPoint {
2285            txid: setup.funding_outpoint.txid,
2286            index: setup.funding_outpoint.vout as u16,
2287        });
2288
2289        let channel_transaction_parameters = ChannelTransactionParameters {
2290            holder_pubkeys: holder_pubkeys.clone(),
2291            holder_selected_contest_delay: setup.holder_selected_contest_delay,
2292            is_outbound_from_holder: setup.is_outbound,
2293            counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
2294                pubkeys: setup.counterparty_points.clone(),
2295                selected_contest_delay: setup.counterparty_selected_contest_delay,
2296            }),
2297            funding_outpoint,
2298            channel_type_features: setup.features(),
2299        };
2300        channel_transaction_parameters
2301    }
2302
2303    pub(crate) fn get_wallet_privkey(
2304        &self,
2305        derivation_path: &DerivationPath,
2306    ) -> Result<PrivateKey, Status> {
2307        let key_path_len = self.node_config.key_derivation_style.get_key_path_len();
2308        if key_path_len.is_some() && derivation_path.len() != key_path_len.unwrap() {
2309            return Err(invalid_argument(format!(
2310                "get_wallet_key: bad child_path len : {}",
2311                derivation_path.len()
2312            )));
2313        }
2314
2315        let xkey =
2316            self.get_account_extended_key().derive_priv(&self.secp_ctx, &derivation_path).unwrap();
2317        Ok(PrivateKey::new(xkey.private_key, self.network()))
2318    }
2319
2320    pub(crate) fn get_wallet_pubkey(
2321        &self,
2322        child_path: &DerivationPath,
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: &DerivationPath,
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    use vls_common::to_derivation_path;
3022
3023    use crate::channel::{ChannelBase, CommitmentType};
3024    use crate::policy::filter::{FilterRule, PolicyFilter};
3025    use crate::policy::simple_validator::{make_default_simple_policy, SimpleValidatorFactory};
3026    use crate::tx::tx::ANCHOR_SAT;
3027    use crate::util::status::{internal_error, invalid_argument, Code, Status};
3028    use crate::util::test_utils::invoice::make_test_bolt12_invoice;
3029    use crate::util::test_utils::*;
3030    use crate::util::velocity::{VelocityControlIntervalType, VelocityControlSpec};
3031    use crate::CommitmentPointProvider;
3032
3033    use super::*;
3034
3035    #[test]
3036    fn channel_debug_test() {
3037        let (node, channel_id) =
3038            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3039        let _status: Result<(), Status> = node.with_channel(&channel_id, |chan| {
3040            assert_eq!(format!("{:?}", chan), "channel");
3041            Ok(())
3042        });
3043    }
3044
3045    #[test]
3046    fn node_debug_test() {
3047        let (node, _channel_id) =
3048            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3049        assert_eq!(format!("{:?}", node), "node");
3050    }
3051
3052    #[test]
3053    fn node_invalid_argument_test() {
3054        let err = invalid_argument("testing invalid_argument");
3055        assert_eq!(err.code(), Code::InvalidArgument);
3056        assert_eq!(err.message(), "testing invalid_argument");
3057    }
3058
3059    #[test]
3060    fn node_internal_error_test() {
3061        let err = internal_error("testing internal_error");
3062        assert_eq!(err.code(), Code::Internal);
3063        assert_eq!(err.message(), "testing internal_error");
3064    }
3065
3066    #[test]
3067    fn new_channel_test() {
3068        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3069
3070        let (channel_id, _) = node.new_channel_with_random_id(&node).unwrap();
3071        assert!(node.get_channel(&channel_id).is_ok());
3072    }
3073
3074    #[test]
3075    fn new_channel_with_dbid_test() {
3076        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3077        let dbid: u64 = 1234;
3078        let peer_id: [u8; 33] = [0; 33];
3079
3080        let (channel_id, _) = node.new_channel(dbid, &peer_id, &node).unwrap();
3081        assert!(node.get_channel(&channel_id).is_ok());
3082    }
3083
3084    #[test]
3085    fn new_channel_with_dbid_should_fail_for_forgotten_channel_test() {
3086        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3087        let dbid = 1234;
3088        let peer_id: [u8; 33] = [0; 33];
3089
3090        let (channel_id, _) = node.new_channel(dbid, &peer_id, &node).unwrap();
3091        let _ = node.forget_channel(&channel_id);
3092
3093        let res = node.new_channel(dbid, &peer_id, &node);
3094        assert!(res.is_err());
3095    }
3096
3097    #[test]
3098    fn new_channel_with_dbid_should_fail_for_dbid_below_previously_forgotten_dbid_test() {
3099        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3100        let dbid = 1234;
3101        let peer_id: [u8; 33] = [0; 33];
3102
3103        let (channel_id, _) = node.new_channel(dbid, &peer_id, &node).unwrap();
3104        let _ = node.forget_channel(&channel_id);
3105
3106        let res = node.new_channel(dbid - 1, &peer_id, &node);
3107        assert!(res.is_err());
3108    }
3109
3110    #[test]
3111    fn new_channel_with_dbid_should_work_for_dbid_below_highest_but_above_last_forgotten_test() {
3112        let node: Arc<Node> = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3113        let dbid_1 = 1000;
3114        let dbid_2 = 1001;
3115        let dbid_3 = 1002;
3116        let peer_id: [u8; 33] = [0; 33];
3117
3118        let (channel_id_1, _) = node.new_channel(dbid_1, &peer_id, &node).unwrap();
3119        let _ = node.new_channel(dbid_3, &peer_id, &node);
3120        let _ = node.forget_channel(&channel_id_1);
3121
3122        let res = node.new_channel(dbid_2, &peer_id, &node);
3123        assert!(res.is_ok());
3124    }
3125
3126    #[test]
3127    fn forget_channel_should_remove_stubs_from_the_channels_map_test() {
3128        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3129        let (channel_id, _) = node.new_channel_with_random_id(&node).unwrap();
3130        let _ = node.forget_channel(&channel_id);
3131
3132        let channels = node.get_channels();
3133        assert!(channels.get(&channel_id).is_none());
3134    }
3135
3136    #[test]
3137    fn commitment_point_provider_test() {
3138        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3139        let node1 = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
3140        let (channel_id, _) = node.new_channel_with_random_id(&node).unwrap();
3141        let (channel_id1, _) = node1.new_channel_with_random_id(&node1).unwrap();
3142        let points =
3143            node.get_channel(&channel_id).unwrap().lock().unwrap().get_channel_basepoints();
3144        let points1 =
3145            node1.get_channel(&channel_id1).unwrap().lock().unwrap().get_channel_basepoints();
3146        let holder_shutdown_key_path = DerivationPath::master();
3147
3148        // note that these channels are clones of the ones in the node, so the ones in the nodes
3149        // will not be updated in this test
3150        let mut channel = node
3151            .setup_channel(
3152                channel_id.clone(),
3153                None,
3154                make_test_channel_setup_with_points(true, points1),
3155                &holder_shutdown_key_path,
3156            )
3157            .expect("setup_channel");
3158        let mut channel1 = node1
3159            .setup_channel(
3160                channel_id1.clone(),
3161                None,
3162                make_test_channel_setup_with_points(false, points),
3163                &holder_shutdown_key_path,
3164            )
3165            .expect("setup_channel 1");
3166        let commit_num = 0;
3167        next_state(&mut channel, &mut channel1, commit_num, 2_999_000, 0, vec![], vec![]);
3168
3169        let holder_point = channel.get_per_commitment_point(0).unwrap();
3170        let cp_point = channel.get_counterparty_commitment_point(0).unwrap();
3171
3172        let channel_slot = Arc::new(Mutex::new(ChannelSlot::Ready(channel)));
3173        let commitment_point_provider = ChannelCommitmentPointProvider::new(channel_slot);
3174
3175        assert_eq!(commitment_point_provider.get_holder_commitment_point(0), holder_point);
3176        assert_eq!(
3177            commitment_point_provider.get_counterparty_commitment_point(0).unwrap(),
3178            cp_point
3179        );
3180    }
3181
3182    #[test]
3183    fn bad_channel_lookup_test() -> Result<(), ()> {
3184        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3185        let channel_id = ChannelId::new(&hex_decode(TEST_CHANNEL_ID[0]).unwrap());
3186        assert!(node.get_channel(&channel_id).is_err());
3187        Ok(())
3188    }
3189
3190    #[test]
3191    fn keysend_test() {
3192        let payee_node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3193        let payee_node_id = payee_node.node_id.clone();
3194        let (node, _channel_id) =
3195            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3196        let hash = PaymentHash([2; 32]);
3197        assert!(node.add_keysend(payee_node_id.clone(), hash, 1234).unwrap());
3198        assert!(node.add_keysend(payee_node.node_id.clone(), hash, 1234).unwrap());
3199        let (_, invoice_hash) =
3200            Node::payment_state_from_keysend(payee_node_id, hash, 1234, node.clock.now()).unwrap();
3201        assert!(node.has_payment(&hash, &invoice_hash).unwrap());
3202        assert!(!node.has_payment(&PaymentHash([5; 32]), &invoice_hash).unwrap());
3203    }
3204
3205    #[test]
3206    fn invoice_test() {
3207        let payee_node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3208        let (node, channel_id) =
3209            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3210        let hash = PaymentHash([2; 32]);
3211        // TODO check currency matches
3212        let invoice1 = make_test_invoice(&payee_node, "invoice1", hash);
3213        let invoice2 = make_test_invoice(&payee_node, "invoice2", hash);
3214        assert_eq!(node.add_invoice(invoice1.clone()).expect("add invoice"), true);
3215        assert_eq!(node.add_invoice(invoice1.clone()).expect("add invoice"), true);
3216        node.add_invoice(invoice2.clone())
3217            .expect_err("add a different invoice with same payment hash");
3218
3219        let mut state = node.get_state();
3220        let hash1 = PaymentHash([1; 32]);
3221        let channel_id2 = ChannelId::new(&hex_decode(TEST_CHANNEL_ID[1]).unwrap());
3222
3223        // Create a strict invoice validator
3224        let strict_policy = make_default_simple_policy(Network::Testnet);
3225        let max_fee = strict_policy.max_routing_fee_msat / 1000;
3226        let strict_validator = SimpleValidatorFactory::new_with_policy(strict_policy)
3227            .make_validator(Network::Testnet, node.get_id(), None);
3228
3229        // Create a lenient invoice validator
3230        let mut lenient_policy = make_default_simple_policy(Network::Testnet);
3231        let lenient_filter = PolicyFilter {
3232            rules: vec![FilterRule::new_warn("policy-commitment-htlc-routing-balance")],
3233        };
3234        lenient_policy.filter.merge(lenient_filter);
3235        let lenient_validator = SimpleValidatorFactory::new_with_policy(lenient_policy)
3236            .make_validator(Network::Testnet, node.get_id(), None);
3237
3238        // Now there's an invoice
3239        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));
3240
3241        state
3242            .validate_and_apply_payments(
3243                &channel_id2,
3244                &Map::new(),
3245                &vec![(hash, 99)].into_iter().collect(),
3246                &Default::default(),
3247                strict_validator.clone(),
3248            )
3249            .expect("channel1");
3250
3251        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));
3252
3253        let result = state.validate_and_apply_payments(
3254            &channel_id,
3255            &Map::new(),
3256            &vec![(hash, max_fee + 2)].into_iter().collect(),
3257            &Default::default(),
3258            strict_validator.clone(),
3259        );
3260        assert_eq!(result, Err(policy_error("policy-commitment-htlc-routing-balance", "validate_payments: unbalanced payments on channel 0100000000000000000000000000000000000000000000000000000000000000: [\"0202020202020202020202020202020202020202020202020202020202020202\"]")));
3261
3262        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));
3263
3264        // we should decrease the `max_fee` value otherwise we overpay in fee percentage
3265        // in this case we take the 5% of the max_fee
3266        let percentage_max_fee = (max_fee * 5) / 100;
3267        let result = state.validate_and_apply_payments(
3268            &channel_id,
3269            &Map::new(),
3270            &vec![(hash, percentage_max_fee)].into_iter().collect(),
3271            &Default::default(),
3272            strict_validator.clone(),
3273        );
3274        assert_validation_ok!(result);
3275
3276        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));
3277
3278        // hash1 has no invoice, fails with strict validator, but only initially
3279        let result = state.validate_and_apply_payments(
3280            &channel_id,
3281            &Map::new(),
3282            &vec![(hash1, 5)].into_iter().collect(),
3283            &Default::default(),
3284            strict_validator.clone(),
3285        );
3286        assert_policy_err!(result, "policy-commitment-htlc-routing-balance", "validate_payments: unbalanced payments on channel 0100000000000000000000000000000000000000000000000000000000000000: [\"0101010101010101010101010101010101010101010101010101010101010101\"]");
3287
3288        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));
3289
3290        // hash1 has no invoice, ok with lenient validator
3291        let result = state.validate_and_apply_payments(
3292            &channel_id,
3293            &Map::new(),
3294            &vec![(hash1, 5)].into_iter().collect(),
3295            &Default::default(),
3296            lenient_validator.clone(),
3297        );
3298        assert_validation_ok!(result);
3299
3300        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));
3301
3302        // TODO(331) hash1 has no invoice, passes with strict validator once the payment exists
3303        let result = state.validate_and_apply_payments(
3304            &channel_id,
3305            &Map::new(),
3306            &vec![(hash1, 6)].into_iter().collect(),
3307            &Default::default(),
3308            strict_validator.clone(),
3309        );
3310        assert_validation_ok!(result);
3311
3312        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));
3313
3314        // pretend this payment failed and went away
3315        let result = state.validate_and_apply_payments(
3316            &channel_id,
3317            &Map::new(),
3318            &vec![(hash1, 0)].into_iter().collect(),
3319            &Default::default(),
3320            strict_validator.clone(),
3321        );
3322        assert_validation_ok!(result);
3323
3324        // payment is still there
3325        assert_eq!(state.payments.len(), 2);
3326        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));
3327
3328        // have to drop the state over the heartbeat because deadlock
3329        drop(state);
3330
3331        // heartbeat triggers pruning
3332        let _ = node.get_heartbeat();
3333
3334        let mut state = node.get_state();
3335
3336        // payment is pruned
3337        assert_eq!(state.payments.len(), 1);
3338        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));
3339    }
3340
3341    fn make_test_invoice(
3342        payee_node: &Node,
3343        description: &str,
3344        payment_hash: PaymentHash,
3345    ) -> Invoice {
3346        sign_invoice(payee_node, build_test_invoice(description, &payment_hash))
3347    }
3348
3349    fn sign_invoice(payee_node: &Node, raw_invoice: RawBolt11Invoice) -> Invoice {
3350        payee_node.do_sign_invoice(raw_invoice).unwrap().try_into().unwrap()
3351    }
3352
3353    fn build_test_invoice(description: &str, payment_hash: &PaymentHash) -> RawBolt11Invoice {
3354        let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("time");
3355        build_test_invoice_with_time(description, payment_hash, now)
3356    }
3357
3358    fn build_test_invoice_with_time(
3359        description: &str,
3360        payment_hash: &PaymentHash,
3361        now: Duration,
3362    ) -> RawBolt11Invoice {
3363        let amount = 100_000;
3364        build_test_invoice_with_time_and_amount(description, payment_hash, now, amount)
3365    }
3366
3367    fn build_test_invoice_with_time_and_amount(
3368        description: &str,
3369        payment_hash: &PaymentHash,
3370        now: Duration,
3371        amount: u64,
3372    ) -> RawBolt11Invoice {
3373        InvoiceBuilder::new(Currency::Bitcoin)
3374            .duration_since_epoch(now)
3375            .amount_milli_satoshis(amount)
3376            .payment_hash(Sha256Hash::from_slice(&payment_hash.0).unwrap())
3377            .payment_secret(PaymentSecret([0; 32]))
3378            .description(description.to_string())
3379            .build_raw()
3380            .expect("build")
3381    }
3382
3383    #[test]
3384    fn with_channel_test() {
3385        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3386        let channel_id = ChannelId::new(&hex_decode(TEST_CHANNEL_ID[0]).unwrap());
3387        node.new_channel_with_id(channel_id.clone(), &node).expect("new_channel");
3388        assert!(node
3389            .with_channel(&channel_id, |_channel| {
3390                panic!("should not be called");
3391                #[allow(unreachable_code)]
3392                Ok(())
3393            })
3394            .is_err());
3395        assert!(node.with_channel_base(&channel_id, |_channel| { Ok(()) }).is_ok());
3396    }
3397
3398    #[test]
3399    fn too_many_channels_test() {
3400        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3401        for _ in 0..node.policy().max_channels() {
3402            node.new_channel_with_random_id(&node).expect("new_channel");
3403        }
3404        assert!(node.new_channel_with_random_id(&node).is_err());
3405    }
3406
3407    #[test]
3408    fn percentage_fee_exceeded_test() {
3409        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3410        let policy = make_default_simple_policy(Network::Testnet);
3411        let validator = SimpleValidatorFactory::new_with_policy(policy).make_validator(
3412            Network::Testnet,
3413            node.get_id(),
3414            None,
3415        );
3416
3417        // We are paying an invoice of 10 msat and the outcome of this payment is 20 msat.
3418        // This mean that the route fee 10 msat of routing fee. So this violate the policy
3419        // regarding the max routing feee percentage.
3420        let result = validator.validate_payment_balance(0, 20, Some(10));
3421
3422        // we are overpaying in percentage fee
3423        assert_eq!(
3424            result,
3425            Err(policy_error(
3426                "policy-htlc-fee-range",
3427                "validate_payment_balance: fee_percentage > max_feerate_percentage: 100% > 10%"
3428            )),
3429            "{:?}",
3430            result
3431        );
3432    }
3433
3434    #[test]
3435    fn too_many_invoices_test() {
3436        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3437        let payee_node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
3438
3439        for i in 0..node.policy().max_invoices() {
3440            let mut hash = [1u8; 32];
3441            hash[0..8].copy_from_slice(&i.to_be_bytes());
3442            let invoice =
3443                make_test_invoice(&payee_node, &format!("invoice {}", i), PaymentHash(hash));
3444            assert_eq!(node.add_invoice(invoice).expect("add invoice"), true);
3445        }
3446
3447        let invoice = make_test_invoice(&payee_node, "invoice", PaymentHash([2u8; 32]));
3448        node.add_invoice(invoice).expect_err("expected too many invoices");
3449    }
3450
3451    #[test]
3452    fn prune_invoice_test() {
3453        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3454        let invoice = make_test_invoice(&node, "invoice", PaymentHash([0; 32]));
3455        node.add_invoice(invoice.clone()).unwrap();
3456        let mut state = node.get_state();
3457        assert_eq!(state.invoices.len(), 1);
3458        assert_eq!(state.payments.len(), 1);
3459        println!("now: {:?}", node.clock.now());
3460        println!("invoice time: {:?}", invoice.duration_since_epoch());
3461        state.prune_invoices(node.clock.now());
3462        assert_eq!(state.invoices.len(), 1);
3463        assert_eq!(state.payments.len(), 1);
3464        state.prune_invoices(node.clock.now() + Duration::from_secs(3600 * 23));
3465        assert_eq!(state.invoices.len(), 1);
3466        assert_eq!(state.payments.len(), 1);
3467        state.prune_invoices(node.clock.now() + Duration::from_secs(3600 * 25));
3468        assert_eq!(state.invoices.len(), 0);
3469        assert_eq!(state.payments.len(), 0);
3470    }
3471
3472    #[test]
3473    fn prune_invoice_incomplete_test() {
3474        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3475        let invoice = make_test_invoice(&node, "invoice", PaymentHash([0; 32]));
3476        node.add_invoice(invoice.clone()).unwrap();
3477        let mut state = node.get_state();
3478        assert_eq!(state.invoices.len(), 1);
3479        assert_eq!(state.payments.len(), 1);
3480        let chan_id = ChannelId::new(&[0; 32]);
3481        state.payments.get_mut(&PaymentHash([0; 32])).unwrap().outgoing.insert(chan_id, 100);
3482        state.prune_invoices(node.clock.now());
3483        assert_eq!(state.invoices.len(), 1);
3484        assert_eq!(state.payments.len(), 1);
3485        state.prune_invoices(node.clock.now() + Duration::from_secs(3600 * 25));
3486        assert_eq!(state.invoices.len(), 1);
3487        assert_eq!(state.payments.len(), 1);
3488        state.payments.get_mut(&PaymentHash([0; 32])).unwrap().preimage =
3489            Some(PaymentPreimage([0; 32]));
3490        state.prune_invoices(node.clock.now() + Duration::from_secs(3600 * 25));
3491        assert_eq!(state.invoices.len(), 0);
3492        assert_eq!(state.payments.len(), 0);
3493    }
3494
3495    #[test]
3496    fn prune_issued_invoice_test() {
3497        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3498        let raw_invoice = build_test_invoice("invoice", &PaymentHash([0; 32]));
3499        node.sign_bolt11_invoice(raw_invoice).unwrap();
3500        let mut state = node.get_state();
3501        assert_eq!(state.issued_invoices.len(), 1);
3502        state.prune_issued_invoices(node.clock.now());
3503        assert_eq!(state.issued_invoices.len(), 1);
3504        state.prune_issued_invoices(node.clock.now() + Duration::from_secs(3600 * 23));
3505        assert_eq!(state.issued_invoices.len(), 1);
3506        state.prune_issued_invoices(node.clock.now() + Duration::from_secs(3600 * 25));
3507        assert_eq!(state.issued_invoices.len(), 0);
3508    }
3509
3510    #[test]
3511    fn drop_zero_amount_issued_invoice_test() {
3512        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3513        let raw_invoice = build_test_invoice_with_time_and_amount(
3514            "invoice",
3515            &PaymentHash([0; 32]),
3516            SystemTime::now().duration_since(UNIX_EPOCH).expect("time"),
3517            0,
3518        );
3519        node.sign_bolt11_invoice(raw_invoice).unwrap();
3520        let state = node.get_state();
3521        assert_eq!(state.issued_invoices.len(), 0);
3522    }
3523
3524    #[test]
3525    fn add_expired_invoice_test() {
3526        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3527
3528        let future =
3529            SystemTime::now().duration_since(UNIX_EPOCH).expect("time") + Duration::from_secs(3600);
3530        let invoice = sign_invoice(
3531            &*node,
3532            build_test_invoice_with_time("invoice", &PaymentHash([0; 32]), future),
3533        );
3534        assert!(node
3535            .add_invoice(invoice)
3536            .unwrap_err()
3537            .message()
3538            .starts_with("policy failure: validate_invoice: invoice is not yet valid"));
3539
3540        let past =
3541            SystemTime::now().duration_since(UNIX_EPOCH).expect("time") - Duration::from_secs(7200);
3542        let invoice = sign_invoice(
3543            &*node,
3544            build_test_invoice_with_time("invoice", &PaymentHash([0; 32]), past),
3545        );
3546        assert!(node
3547            .add_invoice(invoice)
3548            .unwrap_err()
3549            .message()
3550            .starts_with("policy failure: validate_invoice: invoice is expired"));
3551    }
3552
3553    #[test]
3554    fn too_many_issued_invoices_test() {
3555        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3556
3557        for i in 0..node.policy().max_invoices() {
3558            let mut hash = [1u8; 32];
3559            hash[0..8].copy_from_slice(&i.to_be_bytes());
3560            let raw_invoice = build_test_invoice("invoice", &PaymentHash(hash));
3561            node.sign_bolt11_invoice(raw_invoice).unwrap();
3562        }
3563
3564        let raw_invoice = build_test_invoice("invoice", &PaymentHash([2u8; 32]));
3565        node.sign_bolt11_invoice(raw_invoice).expect_err("expected too many issued invoics");
3566    }
3567
3568    #[test]
3569    fn fulfill_test() {
3570        let payee_node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3571        let (node, channel_id) =
3572            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3573        // TODO check currency matches
3574        let preimage = PaymentPreimage([0; 32]);
3575        let hash = PaymentHash(Sha256Hash::hash(&preimage.0).to_byte_array());
3576
3577        let invoice = make_test_invoice(&payee_node, "invoice", hash);
3578
3579        assert_eq!(node.add_invoice(invoice).expect("add invoice"), true);
3580
3581        let mut policy = make_default_simple_policy(Network::Testnet);
3582        policy.enforce_balance = true;
3583        let factory = SimpleValidatorFactory::new_with_policy(policy);
3584        let invoice_validator = factory.make_validator(Network::Testnet, node.get_id(), None);
3585        node.set_validator_factory(Arc::new(factory));
3586
3587        {
3588            let mut state = node.get_state();
3589            assert_status_ok!(state.validate_and_apply_payments(
3590                &channel_id,
3591                &Map::new(),
3592                &vec![(hash, 110)].into_iter().collect(),
3593                &Default::default(),
3594                invoice_validator.clone()
3595            ));
3596        }
3597        node.with_channel(&channel_id, |chan| {
3598            chan.htlcs_fulfilled(vec![preimage]);
3599            Ok(())
3600        })
3601        .unwrap();
3602    }
3603
3604    #[test]
3605    fn fulfill_bolt12_test() {
3606        let (node, channel_id) =
3607            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3608        // TODO check currency matches
3609        let preimage = PaymentPreimage([0; 32]);
3610        let hash = PaymentHash(Sha256Hash::hash(&preimage.0).to_byte_array());
3611
3612        let invoice = make_test_bolt12_invoice("This is the invoice description", hash);
3613
3614        assert_eq!(invoice.description(), Some("This is the invoice description".to_string()));
3615
3616        assert_eq!(node.add_invoice(invoice).expect("add invoice"), true);
3617
3618        let mut policy = make_default_simple_policy(Network::Testnet);
3619        policy.enforce_balance = true;
3620        let factory = SimpleValidatorFactory::new_with_policy(policy);
3621        let invoice_validator = factory.make_validator(Network::Testnet, node.get_id(), None);
3622        node.set_validator_factory(Arc::new(factory));
3623
3624        {
3625            let mut state = node.get_state();
3626            assert_status_ok!(state.validate_and_apply_payments(
3627                &channel_id,
3628                &Map::new(),
3629                &vec![(hash, 110)].into_iter().collect(),
3630                &Default::default(),
3631                invoice_validator.clone()
3632            ));
3633        }
3634        node.with_channel(&channel_id, |chan| {
3635            chan.htlcs_fulfilled(vec![preimage]);
3636            Ok(())
3637        })
3638        .unwrap();
3639    }
3640
3641    #[test]
3642    fn overpay_test() {
3643        let payee_node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3644        let (node, channel_id) =
3645            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3646
3647        let preimage = PaymentPreimage([0; 32]);
3648        let hash = PaymentHash(Sha256Hash::hash(&preimage.0).to_byte_array());
3649
3650        let invoice = make_test_invoice(&payee_node, "invoice", hash);
3651
3652        assert_eq!(node.add_invoice(invoice).expect("add invoice"), true);
3653
3654        let mut policy = make_default_simple_policy(Network::Testnet);
3655        policy.enforce_balance = true;
3656        let max_fee = policy.max_routing_fee_msat / 1000;
3657        let factory = SimpleValidatorFactory::new_with_policy(policy);
3658        let invoice_validator = factory.make_validator(Network::Testnet, node.get_id(), None);
3659        node.set_validator_factory(Arc::new(factory));
3660
3661        {
3662            let mut state = node.get_state();
3663            assert_eq!(
3664                state.validate_and_apply_payments(
3665                    &channel_id,
3666                    &Map::new(),
3667                    &vec![(hash, 100 + max_fee + 1)].into_iter().collect(),
3668                    &Default::default(),
3669                    invoice_validator.clone()
3670                ),
3671                Err(policy_error("policy-commitment-htlc-routing-balance", "validate_payments: unbalanced payments on channel 0100000000000000000000000000000000000000000000000000000000000000: [\"66687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925\"]"))
3672            );
3673        }
3674    }
3675
3676    #[test]
3677    fn htlc_fail_test() {
3678        let payee_node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3679        let (node, channel_id) =
3680            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3681        // another channel ID
3682        let channel_id2 = ChannelId::new(&[1; 32]);
3683
3684        let preimage = PaymentPreimage([0; 32]);
3685        let hash = PaymentHash(Sha256Hash::hash(&preimage.0).to_byte_array());
3686
3687        let invoice = make_test_invoice(&payee_node, "invoice", hash);
3688
3689        assert_eq!(node.add_invoice(invoice).expect("add invoice"), true);
3690
3691        let policy = make_default_simple_policy(Network::Testnet);
3692        let factory = SimpleValidatorFactory::new_with_policy(policy);
3693        let invoice_validator = factory.make_validator(Network::Testnet, node.get_id(), None);
3694        node.set_validator_factory(Arc::new(factory));
3695
3696        let empty = Map::new();
3697        {
3698            let mut state = node.get_state();
3699            state
3700                .validate_and_apply_payments(
3701                    &channel_id,
3702                    &empty,
3703                    &vec![(hash, 90)].into_iter().collect(),
3704                    &Default::default(),
3705                    invoice_validator.clone(),
3706                )
3707                .unwrap();
3708            // payment summarizer now generates a zero for failed HTLCs
3709            state
3710                .validate_and_apply_payments(
3711                    &channel_id,
3712                    &empty,
3713                    &vec![(hash, 0)].into_iter().collect(),
3714                    &Default::default(),
3715                    invoice_validator.clone(),
3716                )
3717                .unwrap();
3718            state
3719                .validate_and_apply_payments(
3720                    &channel_id2,
3721                    &empty,
3722                    &vec![(hash, 90)].into_iter().collect(),
3723                    &Default::default(),
3724                    invoice_validator.clone(),
3725                )
3726                .unwrap();
3727        }
3728    }
3729
3730    // policy-routing-deltas-only-htlc
3731    #[test]
3732    fn shortfall_test() {
3733        let (node, channel_id) =
3734            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3735
3736        let mut policy = make_default_simple_policy(Network::Testnet);
3737        policy.enforce_balance = true;
3738        let factory = SimpleValidatorFactory::new_with_policy(policy);
3739        let invoice_validator = factory.make_validator(Network::Testnet, node.get_id(), None);
3740        node.set_validator_factory(Arc::new(factory));
3741
3742        {
3743            let mut state = node.get_state();
3744            assert_eq!(
3745                state.validate_and_apply_payments(
3746                    &channel_id,
3747                    &Map::new(),
3748                    &Map::new(),
3749                    &BalanceDelta(0, 0),
3750                    invoice_validator.clone()
3751                ),
3752                Ok(())
3753            );
3754            assert_eq!(
3755                state.validate_and_apply_payments(
3756                    &channel_id,
3757                    &Map::new(),
3758                    &Map::new(),
3759                    &BalanceDelta(1, 0),
3760                    invoice_validator.clone()
3761                ),
3762                Err(policy_error("policy-routing-balanced", "shortfall 0 + 0 - 1"))
3763            );
3764        }
3765    }
3766
3767    #[test]
3768    fn sign_invoice_no_amount_test() {
3769        let (node, _channel_id) =
3770            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3771        let preimage = PaymentPreimage([0; 32]);
3772        let hash = PaymentHash(Sha256Hash::hash(&preimage.0).to_byte_array());
3773        let raw_invoice = InvoiceBuilder::new(Currency::Bitcoin)
3774            .duration_since_epoch(Duration::from_secs(123456789))
3775            .payment_hash(Sha256Hash::from_slice(&hash.0).unwrap())
3776            .payment_secret(PaymentSecret([0; 32]))
3777            .description("".to_string())
3778            .build_raw()
3779            .expect("build");
3780
3781        // This records the issued invoice
3782        node.sign_bolt11_invoice(raw_invoice).unwrap();
3783    }
3784
3785    #[test]
3786    fn incoming_payment_test() {
3787        let (node, channel_id) =
3788            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3789        // TODO check currency matches
3790        let preimage = PaymentPreimage([0; 32]);
3791        let hash = PaymentHash(Sha256Hash::hash(&preimage.0).to_byte_array());
3792
3793        let raw_invoice = build_test_invoice("invoice", &hash);
3794        // This records the issued invoice
3795        node.sign_bolt11_invoice(raw_invoice).unwrap();
3796
3797        let mut policy = make_default_simple_policy(Network::Testnet);
3798        policy.enforce_balance = true;
3799        let factory = SimpleValidatorFactory::new_with_policy(policy);
3800        let invoice_validator = factory.make_validator(Network::Testnet, node.get_id(), None);
3801
3802        {
3803            let mut state = node.get_state();
3804            // Underpaid
3805            state
3806                .validate_and_apply_payments(
3807                    &channel_id,
3808                    &vec![(hash, 99)].into_iter().collect(),
3809                    &Map::new(),
3810                    &Default::default(),
3811                    invoice_validator.clone(),
3812                )
3813                .expect("ok");
3814            assert!(!state.payments.get(&hash).unwrap().is_fulfilled());
3815            // Paid
3816            state
3817                .validate_and_apply_payments(
3818                    &channel_id,
3819                    &vec![(hash, 100)].into_iter().collect(),
3820                    &Map::new(),
3821                    &Default::default(),
3822                    invoice_validator.clone(),
3823                )
3824                .expect("ok");
3825            assert!(state.payments.get(&hash).unwrap().is_fulfilled());
3826            // Already paid
3827            state
3828                .validate_and_apply_payments(
3829                    &channel_id,
3830                    &vec![(hash, 100)].into_iter().collect(),
3831                    &Map::new(),
3832                    &Default::default(),
3833                    invoice_validator.clone(),
3834                )
3835                .expect("ok");
3836            assert!(state.payments.get(&hash).unwrap().is_fulfilled());
3837        }
3838    }
3839
3840    #[test]
3841    fn get_per_commitment_point_and_secret_test() {
3842        let (node, channel_id) =
3843            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3844
3845        let commit_num = 23;
3846
3847        let (point, secret) = node
3848            .with_channel(&channel_id, |chan| {
3849                // The channel next_holder_commit_num must be 2 past the
3850                // requested commit_num for get_per_commitment_secret.
3851                chan.enforcement_state.set_next_holder_commit_num_for_testing(commit_num + 2);
3852                let point = chan.get_per_commitment_point(commit_num)?;
3853                let secret = chan.get_per_commitment_secret(commit_num)?;
3854
3855                assert_eq!(chan.get_per_commitment_secret_or_none(commit_num), Some(secret));
3856                assert_eq!(chan.get_per_commitment_secret_or_none(commit_num + 1), None);
3857
3858                Ok((point, secret))
3859            })
3860            .expect("point");
3861
3862        let derived_point = PublicKey::from_secret_key(&Secp256k1::new(), &secret);
3863
3864        assert_eq!(point, derived_point);
3865    }
3866
3867    #[test]
3868    fn get_check_future_secret_test() {
3869        let (node, channel_id) =
3870            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3871
3872        let n: u64 = 10;
3873
3874        let suggested = SecretKey::from_slice(
3875            hex_decode("2f87fef68f2bafdb3c6425921894af44da9a984075c70c7ba31ccd551b3585db")
3876                .unwrap()
3877                .as_slice(),
3878        )
3879        .unwrap();
3880
3881        let correct = node
3882            .with_channel_base(&channel_id, |base| base.check_future_secret(n, &suggested))
3883            .unwrap();
3884        assert_eq!(correct, true);
3885
3886        let notcorrect = node
3887            .with_channel_base(&channel_id, |base| base.check_future_secret(n + 1, &suggested))
3888            .unwrap();
3889        assert_eq!(notcorrect, false);
3890    }
3891
3892    #[test]
3893    fn sign_channel_announcement_with_funding_key_test() {
3894        let (node, channel_id) =
3895            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], make_test_channel_setup());
3896
3897        let ann = hex_decode("0123456789abcdef").unwrap();
3898        let bsig = node
3899            .with_channel(&channel_id, |chan| {
3900                Ok(chan.sign_channel_announcement_with_funding_key(&ann))
3901            })
3902            .unwrap();
3903
3904        let ca_hash = Sha256dHash::hash(&ann);
3905        let encmsg = Message::from_digest(ca_hash.to_byte_array());
3906        let secp_ctx = Secp256k1::new();
3907        node.with_channel(&channel_id, |chan| {
3908            let funding_pubkey = PublicKey::from_secret_key(&secp_ctx, &chan.keys.funding_key);
3909            Ok(secp_ctx.verify_ecdsa(&encmsg, &bsig, &funding_pubkey).expect("verify bsig"))
3910        })
3911        .unwrap();
3912    }
3913
3914    #[test]
3915    fn sign_node_announcement_test() -> Result<(), ()> {
3916        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
3917        let ann = hex_decode("000302aaa25e445fef0265b6ab5ec860cd257865d61ef0bbf5b3339c36cbda8b26b74e7f1dca490b65180265b64c4f554450484f544f2d2e302d3139392d67613237336639642d6d6f646465640000").unwrap();
3918        let sigvec = node.sign_node_announcement(&ann).unwrap().serialize_der().to_vec();
3919        assert_eq!(sigvec, hex_decode("30450221008ef1109b95f127a7deec63b190b72180f0c2692984eaf501c44b6bfc5c4e915502207a6fa2f250c5327694967be95ff42a94a9c3d00b7fa0fbf7daa854ceb872e439").unwrap());
3920        Ok(())
3921    }
3922
3923    #[test]
3924    fn sign_channel_update_test() -> Result<(), ()> {
3925        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
3926        let cu = hex_decode("06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f00006700000100015e42ddc6010000060000000000000000000000010000000a000000003b023380").unwrap();
3927        let sigvec = node.sign_channel_update(&cu).unwrap().serialize_der().to_vec();
3928        assert_eq!(sigvec, hex_decode("3045022100be9840696c868b161aaa997f9fa91a899e921ea06c8083b2e1ea32b8b511948d0220352eec7a74554f97c2aed26950b8538ca7d7d7568b42fd8c6f195bd749763fa5").unwrap());
3929        Ok(())
3930    }
3931
3932    #[test]
3933    fn sign_invoice_test() -> Result<(), ()> {
3934        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
3935        let human_readable_part = String::from("lnbcrt1230n");
3936        let data_part = hex_decode("010f0418090a010101141917110f01040e050f06100003021e1b0e13161c150301011415060204130c0018190d07070a18070a1c1101111e111f130306000d00120c11121706181b120d051807081a0b0f0d18060004120e140018000105100114000b130b01110c001a05041a181716020007130c091d11170d10100d0b1a1b00030e05190208171e16080d00121a00110719021005000405001000").unwrap().check_base32().unwrap();
3937        let raw_invoice = RawBolt11Invoice::from_raw(&human_readable_part, &data_part).unwrap();
3938        let (rid, rsig) = node.sign_bolt11_invoice(raw_invoice).unwrap().serialize_compact();
3939        assert_eq!(rsig.to_vec(), hex_decode("739ffb91aa7c0b3d3c92de1600f7a9afccedc5597977095228232ee4458685531516451b84deb35efad27a311ea99175d10c6cdb458cd27ce2ed104eb6cf8064").unwrap());
3940        assert_eq!(rid.to_i32(), 0);
3941        Ok(())
3942    }
3943
3944    #[test]
3945    fn sign_invoice_with_overhang_test() -> Result<(), ()> {
3946        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
3947        let human_readable_part = String::from("lnbcrt2m");
3948        let data_part = hex_decode("010f0a001d051e0101140c0c000006140009160c09051a0d1a190708020d17141106171f0f07131616111f1910070b0d0e150c0c0c0d010d1a01181c15100d010009181a06101a0a0309181b040a111a0a06111705100c0b18091909030e151b14060004120e14001800010510011419080f1307000a0a0517021c171410101a1e101605050a08180d0d110e13150409051d02091d181502020f050e1a1f161a09130005000405001000").unwrap().check_base32().unwrap();
3949        // The data_part is 170 bytes.
3950        // overhang = (data_part.len() * 5) % 8 = 2
3951        // looking for a verified invoice where overhang is in 1..3
3952        let raw_invoice = RawBolt11Invoice::from_raw(&human_readable_part, &data_part).unwrap();
3953        let (rid, rsig) = node.sign_bolt11_invoice(raw_invoice).unwrap().serialize_compact();
3954        assert_eq!(rsig.to_vec(), hex_decode("f278cdba3fd4a37abf982cee5a66f52e142090631ef57763226f1232eead78b43da7962fcfe29ffae9bd918c588df71d6d7b92a4787de72801594b22f0e7e62a").unwrap());
3955        assert_eq!(rid.to_i32(), 0);
3956        Ok(())
3957    }
3958
3959    #[test]
3960    fn ecdh_test() {
3961        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
3962        let pointvec =
3963            hex_decode("0330febba06ba074378dec994669cf5ebf6b15e24a04ec190fb93a9482e841a0ca")
3964                .unwrap();
3965        let other_key = PublicKey::from_slice(pointvec.as_slice()).unwrap();
3966
3967        let ssvec = node.ecdh(&other_key);
3968        assert_eq!(
3969            ssvec,
3970            hex_decode("48db1582f4b42a0068b5727fd37090a65fbf1f9bd842f4393afc2e794719ae47").unwrap()
3971        );
3972    }
3973
3974    #[test]
3975    fn spend_anchor_test() {
3976        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
3977        let node1 = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
3978        let (channel_id, _) = node.new_channel_with_random_id(&node).unwrap();
3979        let (channel_id1, _) = node1.new_channel_with_random_id(&node1).unwrap();
3980        let points =
3981            node.get_channel(&channel_id).unwrap().lock().unwrap().get_channel_basepoints();
3982        let points1 =
3983            node1.get_channel(&channel_id1).unwrap().lock().unwrap().get_channel_basepoints();
3984        let holder_shutdown_key_path = DerivationPath::master();
3985
3986        // note that these channels are clones of the ones in the node, so the ones in the nodes
3987        // will not be updated in this test
3988        let mut channel = node
3989            .setup_channel(
3990                channel_id.clone(),
3991                None,
3992                make_test_channel_setup_with_points(true, points1),
3993                &holder_shutdown_key_path,
3994            )
3995            .expect("setup_channel");
3996        let mut channel1 = node1
3997            .setup_channel(
3998                channel_id1.clone(),
3999                None,
4000                make_test_channel_setup_with_points(false, points),
4001                &holder_shutdown_key_path,
4002            )
4003            .expect("setup_channel 1");
4004        let commit_num = 0;
4005        next_state(&mut channel, &mut channel1, commit_num, 2_999_000, 0, vec![], vec![]);
4006
4007        let txs = channel.sign_holder_commitment_tx_for_recovery().unwrap();
4008        let holder_tx = txs.0;
4009        // find anchor output by value
4010        let idx =
4011            holder_tx.output.iter().position(|o| o.value == ANCHOR_SAT).expect("anchor output");
4012        // spend the anchor
4013        let mut spend_tx = Transaction {
4014            version: Version::TWO,
4015            lock_time: bitcoin::absolute::LockTime::ZERO,
4016            input: vec![TxIn {
4017                previous_output: OutPoint { txid: holder_tx.compute_txid(), vout: idx as u32 },
4018                sequence: Sequence::MAX,
4019                witness: Witness::new(),
4020                script_sig: ScriptBuf::new(),
4021            }],
4022            output: vec![TxOut { value: ANCHOR_SAT, script_pubkey: ScriptBuf::new() }],
4023        };
4024        // sign the spend
4025        let sig = channel.sign_holder_anchor_input(&spend_tx, idx).unwrap();
4026        let anchor_redeemscript = channel.get_anchor_redeemscript();
4027        let witness = vec![signature_to_bitcoin_vec(sig), anchor_redeemscript.to_bytes()];
4028        spend_tx.input[0].witness = Witness::from_slice(&witness);
4029        // verify the transaction
4030        spend_tx
4031            .verify(|point| Some(holder_tx.output[point.vout as usize].clone()))
4032            .expect("verify");
4033    }
4034
4035    #[test]
4036    fn get_unilateral_close_key_anchors_test() {
4037        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
4038        let (channel_id, chan) = node.new_channel_with_random_id(&node).unwrap();
4039
4040        let mut setup = make_test_channel_setup();
4041        setup.commitment_type = CommitmentType::AnchorsZeroFeeHtlc;
4042
4043        node.setup_channel(channel_id.clone(), None, setup, &DerivationPath::master())
4044            .expect("ready channel");
4045
4046        let uck = node
4047            .with_channel(&channel_id, |chan| chan.get_unilateral_close_key(&None, &None))
4048            .unwrap();
4049        let keys = &chan.as_ref().unwrap().unwrap_stub().keys;
4050        let pubkey = keys.pubkeys().payment_point;
4051        let redeem_script = chan_utils::get_to_countersignatory_with_anchors_redeemscript(&pubkey);
4052
4053        assert_eq!(
4054            uck,
4055            (
4056                SecretKey::from_slice(
4057                    &hex_decode("e6eb522940c9d1dcffc82f4eaff5b81ad318bdaa952061fa73fd6f717f73e160")
4058                        .unwrap()[..]
4059                )
4060                .unwrap(),
4061                vec![redeem_script.to_bytes()]
4062            )
4063        );
4064    }
4065
4066    #[test]
4067    fn get_unilateral_close_key_test() {
4068        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[0]);
4069        let (channel_id, chan) = node.new_channel_with_random_id(&node).unwrap();
4070
4071        node.setup_channel(
4072            channel_id.clone(),
4073            None,
4074            make_test_channel_setup(),
4075            &DerivationPath::master(),
4076        )
4077        .expect("ready channel");
4078
4079        let uck = node
4080            .with_channel(&channel_id, |chan| chan.get_unilateral_close_key(&None, &None))
4081            .unwrap();
4082        let keys = &chan.as_ref().unwrap().unwrap_stub().keys;
4083        let key = keys.pubkeys().payment_point;
4084
4085        assert_eq!(
4086            uck,
4087            (
4088                SecretKey::from_slice(
4089                    &hex_decode("e6eb522940c9d1dcffc82f4eaff5b81ad318bdaa952061fa73fd6f717f73e160")
4090                        .unwrap()[..]
4091                )
4092                .unwrap(),
4093                vec![key.serialize().to_vec()]
4094            )
4095        );
4096
4097        let secp_ctx = Secp256k1::new();
4098        let revocation_secret = SecretKey::from_slice(
4099            hex_decode("0101010101010101010101010101010101010101010101010101010101010101")
4100                .unwrap()
4101                .as_slice(),
4102        )
4103        .unwrap();
4104        let revocation_point = PublicKey::from_secret_key(&secp_ctx, &revocation_secret);
4105        let revocation_point = RevocationKey(revocation_point);
4106        let commitment_secret = SecretKey::from_slice(
4107            hex_decode("0101010101010101010101010101010101010101010101010101010101010102")
4108                .unwrap()
4109                .as_slice(),
4110        )
4111        .unwrap();
4112        let commitment_point = PublicKey::from_secret_key(&secp_ctx, &commitment_secret);
4113        let uck = node
4114            .with_channel(&channel_id, |chan| {
4115                chan.get_unilateral_close_key(&Some(commitment_point), &Some(revocation_point))
4116            })
4117            .unwrap();
4118
4119        let seckey =
4120            derive_private_key(&secp_ctx, &commitment_point, &keys.delayed_payment_base_key);
4121        let pubkey = PublicKey::from_secret_key(&secp_ctx, &seckey);
4122
4123        let redeem_script = chan_utils::get_revokeable_redeemscript(
4124            &revocation_point,
4125            7,
4126            &DelayedPaymentKey(pubkey),
4127        );
4128
4129        assert_eq!(
4130            uck,
4131            (
4132                SecretKey::from_slice(
4133                    &hex_decode("fd5f03ea7b42be9a045097dfa1ef007a430f576302c76e6e6265812f1d1ce18f")
4134                        .unwrap()[..]
4135                )
4136                .unwrap(),
4137                vec![vec![], redeem_script.to_bytes()]
4138            )
4139        );
4140    }
4141
4142    #[test]
4143    fn get_account_ext_pub_key_test() {
4144        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4145        let xpub = node.get_account_extended_pubkey();
4146        assert_eq!(format!("{}", xpub), "tpubDAu312RD7nE6R9qyB4xJk9QAMyi3ppq3UJ4MMUGpB9frr6eNDd8FJVPw27zTVvWAfYFVUtJamgfh5ZLwT23EcymYgLx7MHsU8zZxc9L3GKk");
4147    }
4148
4149    #[test]
4150    fn check_wallet_pubkey_test() {
4151        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4152        assert_eq!(
4153            node.check_wallet_pubkey(
4154                &to_derivation_path(&[1u32]),
4155                bitcoin::PublicKey::from_slice(
4156                    hex_decode(
4157                        "0330febba06ba074378dec994669cf5ebf6b15e24a04ec190fb93a9482e841a0ca"
4158                    )
4159                    .unwrap()
4160                    .as_slice()
4161                )
4162                .unwrap()
4163            )
4164            .unwrap(),
4165            false,
4166        );
4167        assert_eq!(
4168            node.check_wallet_pubkey(
4169                &to_derivation_path(&[1u32]),
4170                bitcoin::PublicKey::from_slice(
4171                    hex_decode(
4172                        "0207ec2b35534712d86ae030dd9bfaec08e2ddea1ec1cecffb9725ed7acb12ab66"
4173                    )
4174                    .unwrap()
4175                    .as_slice()
4176                )
4177                .unwrap()
4178            )
4179            .unwrap(),
4180            true,
4181        );
4182    }
4183
4184    #[test]
4185    fn sign_bolt12_test() {
4186        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4187        node.sign_bolt12("name".as_bytes(), "field".as_bytes(), &[0; 32], None).unwrap();
4188    }
4189
4190    #[test]
4191    fn sign_message_test() {
4192        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4193        let message = String::from("Testing 1 2 3").into_bytes();
4194        let mut rsigvec = node.sign_message(&message).unwrap();
4195        let rid = rsigvec.pop().unwrap() as i32;
4196        let rsig =
4197            RecoverableSignature::from_compact(&rsigvec[..], RecoveryId::from_i32(rid).unwrap())
4198                .unwrap();
4199        let secp_ctx = secp256k1::Secp256k1::new();
4200        let mut buffer = String::from("Lightning Signed Message:").into_bytes();
4201        buffer.extend(message);
4202        let hash = Sha256dHash::hash(&buffer);
4203        let encmsg = Message::from_digest(hash.to_byte_array());
4204        let sig = Signature::from_compact(&rsig.to_standard().serialize_compact()).unwrap();
4205        let pubkey = secp_ctx.recover_ecdsa(&encmsg, &rsig).unwrap();
4206        assert!(secp_ctx.verify_ecdsa(&encmsg, &sig, &pubkey).is_ok());
4207        assert_eq!(pubkey.serialize().to_vec(), node.get_id().serialize().to_vec());
4208    }
4209
4210    // TODO move this elsewhere
4211    #[test]
4212    fn transaction_verify_test() {
4213        // a random recent segwit transaction from blockchain using both old and segwit inputs
4214        let spending: Transaction = deserialize(hex_decode("020000000001031cfbc8f54fbfa4a33a30068841371f80dbfe166211242213188428f437445c91000000006a47304402206fbcec8d2d2e740d824d3d36cc345b37d9f65d665a99f5bd5c9e8d42270a03a8022013959632492332200c2908459547bf8dbf97c65ab1a28dec377d6f1d41d3d63e012103d7279dfb90ce17fe139ba60a7c41ddf605b25e1c07a4ddcb9dfef4e7d6710f48feffffff476222484f5e35b3f0e43f65fc76e21d8be7818dd6a989c160b1e5039b7835fc00000000171600140914414d3c94af70ac7e25407b0689e0baa10c77feffffffa83d954a62568bbc99cc644c62eb7383d7c2a2563041a0aeb891a6a4055895570000000017160014795d04cc2d4f31480d9a3710993fbd80d04301dffeffffff06fef72f000000000017a91476fd7035cd26f1a32a5ab979e056713aac25796887a5000f00000000001976a914b8332d502a529571c6af4be66399cd33379071c588ac3fda0500000000001976a914fc1d692f8de10ae33295f090bea5fe49527d975c88ac522e1b00000000001976a914808406b54d1044c429ac54c0e189b0d8061667e088ac6eb68501000000001976a914dfab6085f3a8fb3e6710206a5a959313c5618f4d88acbba20000000000001976a914eb3026552d7e3f3073457d0bee5d4757de48160d88ac0002483045022100bee24b63212939d33d513e767bc79300051f7a0d433c3fcf1e0e3bf03b9eb1d70220588dc45a9ce3a939103b4459ce47500b64e23ab118dfc03c9caa7d6bfc32b9c601210354fd80328da0f9ae6eef2b3a81f74f9a6f66761fadf96f1d1d22b1fd6845876402483045022100e29c7e3a5efc10da6269e5fc20b6a1cb8beb92130cc52c67e46ef40aaa5cac5f0220644dd1b049727d991aece98a105563416e10a5ac4221abac7d16931842d5c322012103960b87412d6e169f30e12106bdf70122aabb9eb61f455518322a18b920a4dfa887d30700")
4215            .unwrap().as_slice()).unwrap();
4216        let spent1: Transaction = deserialize(hex_decode("020000000001040aacd2c49f5f3c0968cfa8caf9d5761436d95385252e3abb4de8f5dcf8a582f20000000017160014bcadb2baea98af0d9a902e53a7e9adff43b191e9feffffff96cd3c93cac3db114aafe753122bd7d1afa5aa4155ae04b3256344ecca69d72001000000171600141d9984579ceb5c67ebfbfb47124f056662fe7adbfeffffffc878dd74d3a44072eae6178bb94b9253177db1a5aaa6d068eb0e4db7631762e20000000017160014df2a48cdc53dae1aba7aa71cb1f9de089d75aac3feffffffe49f99275bc8363f5f593f4eec371c51f62c34ff11cc6d8d778787d340d6896c0100000017160014229b3b297a0587e03375ab4174ef56eeb0968735feffffff03360d0f00000000001976a9149f44b06f6ee92ddbc4686f71afe528c09727a5c788ac24281b00000000001976a9140277b4f68ff20307a2a9f9b4487a38b501eb955888ac227c0000000000001976a9148020cd422f55eef8747a9d418f5441030f7c9c7788ac0247304402204aa3bd9682f9a8e101505f6358aacd1749ecf53a62b8370b97d59243b3d6984f02200384ad449870b0e6e89c92505880411285ecd41cf11e7439b973f13bad97e53901210205b392ffcb83124b1c7ce6dd594688198ef600d34500a7f3552d67947bbe392802473044022033dfd8d190a4ae36b9f60999b217c775b96eb10dee3a1ff50fb6a75325719106022005872e4e36d194e49ced2ebcf8bb9d843d842e7b7e0eb042f4028396088d292f012103c9d7cbf369410b090480de2aa15c6c73d91b9ffa7d88b90724614b70be41e98e0247304402207d952de9e59e4684efed069797e3e2d993e9f98ec8a9ccd599de43005fe3f713022076d190cc93d9513fc061b1ba565afac574e02027c9efbfa1d7b71ab8dbb21e0501210313ad44bc030cc6cb111798c2bf3d2139418d751c1e79ec4e837ce360cc03b97a024730440220029e75edb5e9413eb98d684d62a077b17fa5b7cc19349c1e8cc6c4733b7b7452022048d4b9cae594f03741029ff841e35996ef233701c1ea9aa55c301362ea2e2f68012103590657108a72feb8dc1dec022cf6a230bb23dc7aaa52f4032384853b9f8388baf9d20700")
4217            .unwrap().as_slice()).unwrap();
4218        let spent2: Transaction = deserialize(hex_decode("0200000000010166c3d39490dc827a2594c7b17b7d37445e1f4b372179649cd2ce4475e3641bbb0100000017160014e69aa750e9bff1aca1e32e57328b641b611fc817fdffffff01e87c5d010000000017a914f3890da1b99e44cd3d52f7bcea6a1351658ea7be87024830450221009eb97597953dc288de30060ba02d4e91b2bde1af2ecf679c7f5ab5989549aa8002202a98f8c3bd1a5a31c0d72950dd6e2e3870c6c5819a6c3db740e91ebbbc5ef4800121023f3d3b8e74b807e32217dea2c75c8d0bd46b8665b3a2d9b3cb310959de52a09bc9d20700")
4219            .unwrap().as_slice()).unwrap();
4220        let spent3: Transaction = deserialize(hex_decode("01000000027a1120a30cef95422638e8dab9dedf720ec614b1b21e451a4957a5969afb869d000000006a47304402200ecc318a829a6cad4aa9db152adbf09b0cd2de36f47b53f5dade3bc7ef086ca702205722cda7404edd6012eedd79b2d6f24c0a0c657df1a442d0a2166614fb164a4701210372f4b97b34e9c408741cd1fc97bcc7ffdda6941213ccfde1cb4075c0f17aab06ffffffffc23b43e5a18e5a66087c0d5e64d58e8e21fcf83ce3f5e4f7ecb902b0e80a7fb6010000006b483045022100f10076a0ea4b4cf8816ed27a1065883efca230933bf2ff81d5db6258691ff75202206b001ef87624e76244377f57f0c84bc5127d0dd3f6e0ef28b276f176badb223a01210309a3a61776afd39de4ed29b622cd399d99ecd942909c36a8696cfd22fc5b5a1affffffff0200127a000000000017a914f895e1dd9b29cb228e9b06a15204e3b57feaf7cc8769311d09000000001976a9144d00da12aaa51849d2583ae64525d4a06cd70fde88ac00000000")
4221            .unwrap().as_slice()).unwrap();
4222
4223        println!("{:?}", &spending.compute_txid());
4224        println!("{:?}", &spent1.compute_txid());
4225        println!("{:?}", &spent2.compute_txid());
4226        println!("{:?}", &spent3.compute_txid());
4227        println!("{:?}", &spent1.output[0].script_pubkey);
4228        println!("{:?}", &spent2.output[0].script_pubkey);
4229        println!("{:?}", &spent3.output[0].script_pubkey);
4230
4231        let mut spent = Map::new();
4232        spent.insert(spent1.compute_txid(), spent1);
4233        spent.insert(spent2.compute_txid(), spent2);
4234        spent.insert(spent3.compute_txid(), spent3);
4235        spending
4236            .verify(|point: &OutPoint| {
4237                if let Some(tx) = spent.remove(&point.txid) {
4238                    return tx.output.get(point.vout as usize).cloned();
4239                }
4240                None
4241            })
4242            .unwrap();
4243    }
4244
4245    // TODO move this elsewhere
4246    #[test]
4247    fn bip143_p2wpkh_test() {
4248        let tx: Transaction = deserialize(hex_decode("0100000002fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f0000000000eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac11000000")
4249            .unwrap().as_slice()).unwrap();
4250        let secp_ctx = Secp256k1::signing_only();
4251        let priv2 = SecretKey::from_slice(
4252            hex_decode("619c335025c7f4012e556c2a58b2506e30b8511b53ade95ea316fd8c3286feb9")
4253                .unwrap()
4254                .as_slice(),
4255        )
4256        .unwrap();
4257        let pub2 = bitcoin::PublicKey::from_slice(
4258            &PublicKey::from_secret_key(&secp_ctx, &priv2).serialize(),
4259        )
4260        .unwrap();
4261
4262        let script_code =
4263            Address::p2wpkh(&CompressedPublicKey(pub2.inner), Network::Testnet).script_pubkey();
4264        let value = 600_000_000;
4265
4266        let sighash = &SighashCache::new(&tx)
4267            .p2wpkh_signature_hash(1, &script_code, Amount::from_sat(value), EcdsaSighashType::All)
4268            .unwrap()[..];
4269        assert_eq!(
4270            hex_encode(sighash),
4271            "c37af31116d1b27caf68aae9e3ac82f1477929014d5b917657d0eb49478cb670"
4272        );
4273    }
4274
4275    fn vecs_match<T: PartialEq + Ord>(mut a: Vec<T>, mut b: Vec<T>) -> bool {
4276        a.sort();
4277        b.sort();
4278        let matching = a.iter().zip(b.iter()).filter(|&(a, b)| a == b).count();
4279        matching == a.len() && matching == b.len()
4280    }
4281
4282    #[test]
4283    fn allowlist_test() {
4284        assert!(Allowable::from_str(
4285            "address:mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB",
4286            Network::Bitcoin
4287        )
4288        .is_err());
4289
4290        assert!(Allowable::from_str("xpub:tpubDEQBfiy13hMZzGT4NWqNnaSWwVqYQ58kuu2pDYjkrf8F6DLKAprm8c65Pyh7PrzodXHtJuEXFu5yf6JbvYaL8rz7v28zapwbuzZzr7z4UvR", Network::Bitcoin).is_err());
4291        assert!(Allowable::from_str("xxx:mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB", Network::Regtest)
4292            .is_err());
4293        let a = Allowable::from_str("address:mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB", Network::Testnet)
4294            .unwrap();
4295        assert_eq!(a.to_script().unwrap().to_string(), "OP_DUP OP_HASH160 OP_PUSHBYTES_20 9f9a7abd600c0caa03983a77c8c3df8e062cb2fa OP_EQUALVERIFY OP_CHECKSIG");
4296        let x = Allowable::from_str("xpub:tpubDEQBfiy13hMZzGT4NWqNnaSWwVqYQ58kuu2pDYjkrf8F6DLKAprm8c65Pyh7PrzodXHtJuEXFu5yf6JbvYaL8rz7v28zapwbuzZzr7z4UvR", Network::Testnet).unwrap();
4297        assert!(x.to_script().is_err());
4298    }
4299
4300    #[test]
4301    fn node_wallet_test() {
4302        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4303        let derivation_path = to_derivation_path(&[0u32]);
4304        let a = node.get_native_address(&derivation_path).unwrap();
4305        assert_eq!(a.to_string(), "tb1qr8j660jqglj0x2axua26u0qcyuxhanycx4sr49");
4306        assert!(node.can_spend(&derivation_path, &a.script_pubkey()).unwrap());
4307        assert!(!node.can_spend(&to_derivation_path(&[1u32]), &a.script_pubkey()).unwrap());
4308        #[allow(deprecated)]
4309        let a = node.get_wrapped_address(&derivation_path).unwrap();
4310        assert_eq!(a.to_string(), "2NBaG2jeH1ahh6cMcYBF1RAcZRZsTPqLNLZ");
4311    }
4312
4313    #[test]
4314    fn node_allowlist_contains_test() {
4315        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4316        let payee_sec = SecretKey::from_slice(&[42; 32]).unwrap();
4317        let payee_pub = PublicKey::from_secret_key(&Secp256k1::new(), &payee_sec);
4318        let xpub_str = "tpubDEQBfiy13hMZzGT4NWqNnaSWwVqYQ58kuu2pDYjkrf8F6DLKAprm8c65Pyh7PrzodXHtJuEXFu5yf6JbvYaL8rz7v28zapwbuzZzr7z4UvR";
4319        // let xpub = Xpub::from_str(xpub_str).unwrap();
4320        // println!("XXX {}", Address::p2wpkh(&xpub.derive_pub(&Secp256k1::new(), &[ChildNumber::from_normal_idx(2).unwrap()]).unwrap().to_pub(), Network::Testnet).unwrap());
4321        // xpub is "abandon* about" external account 0
4322        node.add_allowlist(&[
4323            "address:mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB".to_string(),
4324            format!("xpub:{}", xpub_str),
4325            format!("payee:{}", payee_pub.to_string()),
4326        ])
4327        .unwrap();
4328        // check if second child matches the xpub in the allowlist
4329        let script2 = Address::from_str("mnTkxhNkgx7TsZrEdRcPti564yQTzynGJp")
4330            .unwrap()
4331            .require_network(Network::Testnet)
4332            .unwrap()
4333            .script_pubkey();
4334        let derivation_path = to_derivation_path(&[2u32]);
4335        assert!(node.allowlist_contains(&script2, &derivation_path));
4336        // check if third child matches the xpub in the allowlist with wrong index
4337        let script2 = Address::from_str("mpW3iVi2Td1vqDK8Nfie29ddZXf9spmZkX")
4338            .unwrap()
4339            .require_network(Network::Testnet)
4340            .unwrap()
4341            .script_pubkey();
4342        assert!(!node.allowlist_contains(&script2, &derivation_path));
4343        let p2wpkh_script = Address::from_str("tb1qfshzhu5qdyz94r4kylyrnlerq6mnhw3sjz7w8p")
4344            .unwrap()
4345            .require_network(Network::Testnet)
4346            .unwrap()
4347            .script_pubkey();
4348        assert!(node.allowlist_contains(&p2wpkh_script, &derivation_path));
4349    }
4350
4351    #[test]
4352    fn node_allowlist_test() {
4353        fn prefix(a: &String) -> String {
4354            format!("address:{}", a)
4355        }
4356
4357        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4358
4359        // initial allowlist should be empty
4360        assert!(node.allowlist().expect("allowlist").len() == 0);
4361
4362        // can insert some entries
4363        let adds0: Vec<String> = vec![
4364            "mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB",
4365            "2N6i2gfgTonx88yvYm32PRhnHxqxtEfocbt",
4366            "tb1qhetd7l0rv6kca6wvmt25ax5ej05eaat9q29z7z",
4367            "tb1qycu764qwuvhn7u0enpg0x8gwumyuw565f3mspnn58rsgar5hkjmqtjegrh",
4368        ]
4369        .iter()
4370        .map(|s| s.to_string())
4371        .collect();
4372        let prefixed_adds: Vec<String> = adds0.iter().cloned().map(|s| prefix(&s)).collect();
4373        assert_status_ok!(node.add_allowlist(&adds0));
4374
4375        // now allowlist should have the added entries
4376        assert!(vecs_match(node.allowlist().expect("allowlist").clone(), prefixed_adds.clone()));
4377
4378        // adding duplicates shouldn't change the node allowlist
4379        assert_status_ok!(node.add_allowlist(&adds0));
4380        assert!(vecs_match(node.allowlist().expect("allowlist").clone(), prefixed_adds.clone()));
4381
4382        // can remove some elements from the allowlist
4383        let removes0 = vec![adds0[0].clone(), adds0[3].clone()];
4384        assert_status_ok!(node.remove_allowlist(&removes0));
4385        assert!(vecs_match(
4386            node.allowlist().expect("allowlist").clone(),
4387            vec![prefix(&adds0[1]), prefix(&adds0[2])]
4388        ));
4389
4390        // set should replace the elements
4391        assert_status_ok!(node.set_allowlist(&removes0));
4392        assert!(vecs_match(
4393            node.allowlist().expect("allowlist").clone(),
4394            removes0.iter().map(|e| prefix(e)).collect()
4395        ));
4396
4397        // can't add bogus addresses
4398        assert_invalid_argument_err!(
4399            node.add_allowlist(&vec!["1234567890".to_string()]),
4400            "could not parse 1234567890"
4401        );
4402
4403        // can't add w/ wrong network
4404        assert_invalid_argument_err!(
4405            node.add_allowlist(&vec!["1287uUybCYgf7Tb76qnfPf8E1ohCgSZATp".to_string()]),
4406            "could not parse 1287uUybCYgf7Tb76qnfPf8E1ohCgSZATp: expected network testnet"
4407        );
4408
4409        // can't remove w/ wrong network
4410        assert_invalid_argument_err!(
4411            node.remove_allowlist(&vec!["1287uUybCYgf7Tb76qnfPf8E1ohCgSZATp".to_string()]),
4412            "could not parse 1287uUybCYgf7Tb76qnfPf8E1ohCgSZATp: expected network testnet"
4413        );
4414    }
4415
4416    #[test]
4417    fn node_heartbeat_test() {
4418        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4419        let heartbeat = node.get_heartbeat();
4420        let secp = Secp256k1::new();
4421        assert!(heartbeat.verify(&node.get_account_extended_pubkey().public_key, &secp));
4422    }
4423
4424    #[test]
4425    fn cln_node_param_compatibility() {
4426        // This test compares to known values generated by CLN's native hsmd
4427        let node = init_node(
4428            NodeConfig::new(Network::Regtest),
4429            "6c696768746e696e672d31000000000000000000000000000000000000000000",
4430        );
4431        assert_eq!(
4432            hex::encode(node.get_id().serialize()),
4433            "0266e4598d1d3c415f572a8488830b60f7e744ed9235eb0b1ba93283b315c03518"
4434        );
4435        assert_eq!(
4436            node.get_account_extended_pubkey().to_string(),
4437            "tpubDBrTnjDZwRM6jznHEmo1sYqJWU9so1HRsGEWWjMKLRhVLtuCKYKaHPE3NzqFY3ZdTd64t65T8YrXZZ8Ugwkb7oNzQVBtokaAvtC8Km6EM2G");
4438        assert_eq!(
4439            hex::encode(node.get_bolt12_pubkey().serialize()),
4440            "02e25c37f1af7cb00984e594eae0f4d1d03537ffe202b7a6b2ebc1e5fcf1dfd9f4"
4441        );
4442        assert_eq!(
4443            hex::encode(node.get_onion_reply_secret()),
4444            "cfd1fb341180bf3fa2f624ed7d4a809aedf388e3ba363c589faf341018cb83e1"
4445        );
4446    }
4447
4448    #[test]
4449    fn serialize_heartbeat_test() {
4450        let hb = SignedHeartbeat {
4451            signature: vec![1, 2, 3, 4],
4452            heartbeat: Heartbeat {
4453                chain_tip: BlockHash::all_zeros(),
4454                chain_height: 0,
4455                chain_timestamp: 0,
4456                current_timestamp: 0,
4457            },
4458        };
4459        let mut ser_hb = to_vec(&hb).expect("heartbeat");
4460        let de_hb: SignedHeartbeat = serde_bolt::from_vec(&mut ser_hb).expect("bad heartbeat");
4461        assert_eq!(format!("{:?}", hb), format!("{:?}", de_hb));
4462    }
4463
4464    #[test]
4465    fn update_velocity_spec_test() {
4466        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4467        {
4468            let mut state = node.get_state();
4469            state.velocity_control.insert(0, 1);
4470            assert_eq!(state.velocity_control.velocity(), 1);
4471        }
4472
4473        // this should not change anything, since the specs didn't change
4474        node.update_velocity_controls();
4475
4476        {
4477            let state = node.get_state();
4478            assert_eq!(state.velocity_control.velocity(), 1);
4479            assert!(state.velocity_control.is_unlimited());
4480        }
4481
4482        let mut validator_factory = SimpleValidatorFactory::new();
4483        let mut policy = make_default_simple_policy(Network::Testnet);
4484        let spec = VelocityControlSpec {
4485            limit_msat: 100,
4486            interval_type: VelocityControlIntervalType::Hourly,
4487        };
4488        policy.global_velocity_control = spec.clone();
4489        validator_factory.policy = Some(policy);
4490
4491        node.set_validator_factory(Arc::new(validator_factory));
4492        node.update_velocity_controls();
4493
4494        {
4495            let state = node.get_state();
4496            assert_eq!(state.velocity_control.velocity(), 0);
4497            assert!(!state.velocity_control.is_unlimited());
4498            assert!(state.velocity_control.spec_matches(&spec));
4499        }
4500    }
4501
4502    #[test]
4503    fn prune_failed_stubs() {
4504        let node = init_node(TEST_NODE_CONFIG, TEST_SEED[1]);
4505
4506        // Create a channel stub
4507        let (channel_id, _) = node.new_channel_with_random_id(&node).unwrap();
4508        assert!(node.get_channel(&channel_id).is_ok());
4509
4510        // Do a heartbeat
4511        let heartbeat = node.get_heartbeat();
4512        let secp = Secp256k1::new();
4513        assert!(heartbeat.verify(&node.get_account_extended_pubkey().public_key, &secp));
4514
4515        // Channel stub is still there
4516        assert!(node.get_channel(&channel_id).is_ok());
4517
4518        // Pretend some blocks have gone by
4519        assert_eq!(node.get_tracker().height(), 0);
4520        node.get_tracker().height = 20;
4521
4522        // Do a heartbeat
4523        let heartbeat = node.get_heartbeat();
4524        let secp = Secp256k1::new();
4525        assert!(heartbeat.verify(&node.get_account_extended_pubkey().public_key, &secp));
4526
4527        // Channel stub is no longer there
4528        assert!(node.get_channel(&channel_id).is_err());
4529    }
4530}