1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
extern crate scopeguard;

use core::cmp::{max, min};

use bitcoin::secp256k1::ecdsa::Signature;
use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
use bitcoin::{
    self, BlockHeader, EcdsaSighashType, FilterHeader, Network, OutPoint, Script, Sighash,
    Transaction,
};
use core::time::Duration;
use lightning::chain::keysinterface::InMemorySigner;
use lightning::ln::chan_utils::{ClosingTransaction, HTLCOutputInCommitment, TxCreationKeys};
use lightning::ln::PaymentHash;
use log::{debug, error};
use serde_derive::{Deserialize, Serialize};
use txoo::proof::{TxoProof, VerifyError};

use crate::channel::{ChannelBalance, ChannelId, ChannelSetup, ChannelSlot};
use crate::invoice::{Invoice, InvoiceAttributes};
use crate::policy::{Policy, MAX_CLOCK_SKEW, MIN_INVOICE_EXPIRY};
use crate::prelude::*;
use crate::sync::Arc;
use crate::tx::tx::{CommitmentInfo, CommitmentInfo2, HTLCInfo2, PreimageMap};
use crate::wallet::Wallet;

use super::error::ValidationError;

/// A policy checker
///
/// Called by Node / Channel as needed.
pub trait Validator {
    /// Validate ready channel parameters.
    /// The holder_shutdown_key_path should be an empty vector if the
    /// setup.holder_shutdown_script is not set or the address is in
    /// the allowlist.
    fn validate_ready_channel(
        &self,
        wallet: &Wallet,
        setup: &ChannelSetup,
        holder_shutdown_key_path: &[u32],
    ) -> Result<(), ValidationError>;

    /// Validate channel value after it is late-filled
    fn validate_channel_value(&self, setup: &ChannelSetup) -> Result<(), ValidationError>;

    /// Validate an onchain transaction (funding tx, simple sweeps).
    /// This transaction may fund multiple channels at the same time.
    ///
    /// * `channels` the funded channel for each funding output, or
    ///   None for change outputs
    /// * `input_txs` - previous tx for inputs when funding channel
    /// * `values_sat` - the amount in satoshi per input
    /// * `opaths` - derivation path per output.  Empty for non-wallet/non-xpub-whitelist
    ///   outputs.
    /// * `weight_lower_bound` - lower bound of tx size, for feerate checking
    ///
    /// Returns the total "non-beneficial value" (i.e. fees) in satoshi
    fn validate_onchain_tx(
        &self,
        wallet: &Wallet,
        channels: Vec<Option<Arc<Mutex<ChannelSlot>>>>,
        tx: &Transaction,
        input_txs: &[&Transaction],
        values_sat: &[u64],
        opaths: &[Vec<u32>],
        weight_lower_bound: usize,
    ) -> Result<u64, ValidationError>;

    /// Phase 1 CommitmentInfo
    fn decode_commitment_tx(
        &self,
        keys: &InMemorySigner,
        setup: &ChannelSetup,
        is_counterparty: bool,
        tx: &Transaction,
        output_witscripts: &[Vec<u8>],
    ) -> Result<CommitmentInfo, ValidationError>;

    /// Validate a counterparty commitment
    fn validate_counterparty_commitment_tx(
        &self,
        estate: &EnforcementState,
        commit_num: u64,
        commitment_point: &PublicKey,
        setup: &ChannelSetup,
        cstate: &ChainState,
        info2: &CommitmentInfo2,
    ) -> Result<(), ValidationError>;

    /// Validate a holder commitment
    fn validate_holder_commitment_tx(
        &self,
        estate: &EnforcementState,
        commit_num: u64,
        commitment_point: &PublicKey,
        setup: &ChannelSetup,
        cstate: &ChainState,
        info2: &CommitmentInfo2,
    ) -> Result<(), ValidationError>;

    /// Check a counterparty's revocation of an old state.
    /// This also makes a note that the counterparty has committed to their
    /// current commitment transaction.
    fn validate_counterparty_revocation(
        &self,
        state: &EnforcementState,
        revoke_num: u64,
        commitment_secret: &SecretKey,
    ) -> Result<(), ValidationError>;

    /// Phase 1 decoding of 2nd level HTLC tx and validation by recomposition
    fn decode_and_validate_htlc_tx(
        &self,
        is_counterparty: bool,
        setup: &ChannelSetup,
        txkeys: &TxCreationKeys,
        tx: &Transaction,
        redeemscript: &Script,
        htlc_amount_sat: u64,
        output_witscript: &Script,
    ) -> Result<(u32, HTLCOutputInCommitment, Sighash, EcdsaSighashType), ValidationError>;

    /// Phase 2 validation of 2nd level HTLC tx
    fn validate_htlc_tx(
        &self,
        setup: &ChannelSetup,
        cstate: &ChainState,
        is_counterparty: bool,
        htlc: &HTLCOutputInCommitment,
        feerate_per_kw: u32,
    ) -> Result<(), ValidationError>;

    /// Phase 1 decoding and recomposition of mutual_close
    fn decode_and_validate_mutual_close_tx(
        &self,
        wallet: &Wallet,
        setup: &ChannelSetup,
        state: &EnforcementState,
        tx: &Transaction,
        opaths: &[Vec<u32>],
    ) -> Result<ClosingTransaction, ValidationError>;

    /// Phase 2 Validatation of mutual_close
    fn validate_mutual_close_tx(
        &self,
        wallet: &Wallet,
        setup: &ChannelSetup,
        state: &EnforcementState,
        to_holder_value_sat: u64,
        to_counterparty_value_sat: u64,
        holder_shutdown_script: &Option<Script>,
        counterparty_shutdown_script: &Option<Script>,
        holder_wallet_path_hint: &[u32],
    ) -> Result<(), ValidationError>;

    /// Validation of delayed sweep transaction
    fn validate_delayed_sweep(
        &self,
        wallet: &Wallet,
        setup: &ChannelSetup,
        cstate: &ChainState,
        tx: &Transaction,
        input: usize,
        amount_sat: u64,
        key_path: &[u32],
    ) -> Result<(), ValidationError>;

    /// Validation of counterparty htlc sweep transaction (first level
    /// commitment htlc outputs)
    fn validate_counterparty_htlc_sweep(
        &self,
        wallet: &Wallet,
        setup: &ChannelSetup,
        cstate: &ChainState,
        tx: &Transaction,
        redeemscript: &Script,
        input: usize,
        amount_sat: u64,
        key_path: &[u32],
    ) -> Result<(), ValidationError>;

    /// Validation of justice sweep transaction
    fn validate_justice_sweep(
        &self,
        wallet: &Wallet,
        setup: &ChannelSetup,
        cstate: &ChainState,
        tx: &Transaction,
        input: usize,
        amount_sat: u64,
        key_path: &[u32],
    ) -> Result<(), ValidationError>;

    /// Validation of the payment state for a payment hash.
    /// This could include a payment routed through us, or a payment we
    /// are making, or both.  If we are not making a payment, then the incoming
    /// must be greater or equal to the outgoing.  Otherwise, the incoming
    /// minus outgoing should be enough to pay for the invoice and routing fees,
    /// but no larger.
    fn validate_payment_balance(
        &self,
        incoming_msat: u64,
        outgoing_msat: u64,
        invoiced_amount_msat: Option<u64>,
    ) -> Result<(), ValidationError>;

    /// Whether the policy specifies that holder balance should be tracked and
    /// enforced.
    fn enforce_balance(&self) -> bool {
        false
    }

    /// The minimum initial commitment transaction balance to us, given
    /// the funding amount.
    /// The result is in satoshi.
    fn minimum_initial_balance(&self, holder_value_msat: u64) -> u64;

    /// The associated policy
    fn policy(&self) -> Box<&dyn Policy>;

    /// Set next holder commitment number
    fn set_next_holder_commit_num(
        &self,
        estate: &mut EnforcementState,
        num: u64,
        current_commitment_info: CommitmentInfo2,
        counterparty_signatures: CommitmentSignatures,
    ) -> Result<(), ValidationError> {
        let current = estate.next_holder_commit_num;
        if num != current && num != current + 1 {
            // the tag is non-obvious, but jumping to an incorrect commitment number can mean that signing and revocation are out of sync
            policy_err!(
                self,
                "policy-revoke-new-commitment-signed",
                "invalid progression: {} to {}",
                current,
                num
            );
        }
        estate.set_next_holder_commit_num(num, current_commitment_info, counterparty_signatures);
        Ok(())
    }

    /// Get the current commitment info
    fn get_current_holder_commitment_info(
        &self,
        estate: &mut EnforcementState,
        commitment_number: u64,
    ) -> Result<CommitmentInfo2, ValidationError> {
        // Make sure they are asking for the correct commitment (in sync).
        if commitment_number + 1 != estate.next_holder_commit_num {
            policy_err!(
                self,
                "policy-other",
                "invalid next holder commitment number: {} != {}",
                commitment_number + 1,
                estate.next_holder_commit_num
            );
        }
        Ok(estate.get_current_holder_commitment_info())
    }

    /// Set next counterparty commitment number
    fn set_next_counterparty_commit_num(
        &self,
        estate: &mut EnforcementState,
        num: u64,
        current_point: PublicKey,
        current_commitment_info: CommitmentInfo2,
    ) -> Result<(), ValidationError> {
        if num == 0 {
            policy_err!(self, "policy-commitment-previous-revoked", "can't set next to 0");
        }

        // The initial commitment is special, it can advance even though next_revoke is 0.
        let delta = if num == 1 { 1 } else { 2 };

        // Ensure that next_commit is ok relative to next_revoke
        if num < estate.next_counterparty_revoke_num + delta {
            policy_err!(
                self,
                "policy-commitment-previous-revoked",
                "{} too small relative to next_counterparty_revoke_num {}",
                num,
                estate.next_counterparty_revoke_num
            );
        }
        if num > estate.next_counterparty_revoke_num + 2 {
            policy_err!(
                self,
                "policy-commitment-previous-revoked",
                "{} too large relative to next_counterparty_revoke_num {}",
                num,
                estate.next_counterparty_revoke_num
            );
        }

        let current = estate.next_counterparty_commit_num;
        if num == current {
            // This is a retry.
            assert!(
                estate.current_counterparty_point.is_some(),
                "retry {}: current_counterparty_point not set, this shouldn't be possible",
                num
            );
            // FIXME - need to compare current_commitment_info with current_counterparty_commit_info
            if current_point != estate.current_counterparty_point.unwrap() {
                debug!(
                    "current_point {} != prior {}",
                    current_point,
                    estate.current_counterparty_point.unwrap()
                );
                policy_err!(
                    self,
                    "policy-commitment-retry-same",
                    "retry {}: point different than prior",
                    num
                );
            }
        } else if num == current + 1 {
        } else {
            policy_err!(
                self,
                "policy-commitment-previous-revoked",
                "invalid progression: {} to {}",
                current,
                num
            );
        }

        estate.set_next_counterparty_commit_num(num, current_point, current_commitment_info);
        Ok(())
    }

    /// Set next counterparty revoked commitment number
    fn set_next_counterparty_revoke_num(
        &self,
        estate: &mut EnforcementState,
        num: u64,
    ) -> Result<(), ValidationError> {
        if num == 0 {
            policy_err!(self, "policy-other", "can't set next to 0");
        }

        // Ensure that next_revoke is ok relative to next_commit.
        if num + 2 < estate.next_counterparty_commit_num {
            policy_err!(
                self,
                "policy-commitment-previous-revoked",
                "{} too small relative to next_counterparty_commit_num {}",
                num,
                estate.next_counterparty_commit_num
            );
        }
        if num + 1 > estate.next_counterparty_commit_num {
            policy_err!(
                self,
                "policy-commitment-previous-revoked",
                "{} too large relative to next_counterparty_commit_num {}",
                num,
                estate.next_counterparty_commit_num
            );
        }

        let current = estate.next_counterparty_revoke_num;
        if num != current && num != current + 1 {
            policy_err!(
                self,
                "policy-commitment-previous-revoked",
                "invalid progression: {} to {}",
                current,
                num
            );
        }

        estate.set_next_counterparty_revoke_num(num);
        debug!("next_counterparty_revoke_num {} -> {}", current, num);
        Ok(())
    }

    /// Validate a block and a TXOO proof for spent/unspent watched outputs
    fn validate_block(
        &self,
        proof: &TxoProof,
        height: u32,
        header: &BlockHeader,
        prev_filter_header: &FilterHeader,
        outpoint_watches: &[OutPoint],
    ) -> Result<(), ValidationError> {
        let secp = Secp256k1::new();
        let result = proof.verify(height, header, prev_filter_header, outpoint_watches, &secp);
        match result {
            Ok(()) => {}
            Err(VerifyError::InvalidAttestation) => {
                for (pubkey, attestation) in &proof.attestations {
                    error!(
                        "invalid attestation for oracle {} at height {} block hash {} - {:?}",
                        pubkey,
                        height,
                        header.block_hash(),
                        &attestation.attestation
                    );
                }
                policy_err!(self, "policy-chain-validated", "invalid attestation");
            }
            Err(_) => {
                policy_err!(self, "policy-chain-validated", "invalid proof {:?}", result);
            }
        }
        // TODO validate attestation is by configured oracle
        // TODO validate filter header chain
        Ok(())
    }

    /// Validate an invoice
    fn validate_invoice(&self, invoice: &Invoice, now: Duration) -> Result<(), ValidationError> {
        // invoice must not have been created in the future
        if now + MAX_CLOCK_SKEW < invoice.duration_since_epoch() {
            policy_err!(
                self,
                "policy-invoice-not-expired",
                "invoice is not yet valid ({} < {})",
                now.as_secs(),
                invoice.duration_since_epoch().as_secs()
            );
        }

        // new invoices must not expire too soon
        if now + MIN_INVOICE_EXPIRY
            > (invoice.duration_since_epoch() + invoice.expiry_duration()) + MAX_CLOCK_SKEW
        {
            policy_err!(
                self,
                "policy-invoice-not-expired",
                "invoice is expired ({} + {} (buffer) > {})",
                now.as_secs(),
                MIN_INVOICE_EXPIRY.as_secs(),
                (invoice.duration_since_epoch() + invoice.expiry_duration()).as_secs()
            );
        }

        Ok(())
    }
}

/// Blockchain state used by the validator
#[derive(Debug)]
pub struct ChainState {
    /// The current blockchain height
    pub current_height: u32,
    /// Zero or the number of confirmation of the funding tx
    pub funding_depth: u32,
    /// Zero or the number of confirmation of a double-spend of the funding tx
    pub funding_double_spent_depth: u32,
    /// Zero or the number of confirmations of a closing tx
    pub closing_depth: u32,
}

/// A factory for validators
pub trait ValidatorFactory: Send + Sync {
    /// Construct a validator
    fn make_validator(
        &self,
        network: Network,
        node_id: PublicKey,
        channel_id: Option<ChannelId>,
    ) -> Arc<dyn Validator>;

    /// Get the policy
    fn policy(&self, network: Network) -> Box<dyn Policy>;
}

/// Signatures for a commitment transaction
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CommitmentSignatures(pub Signature, pub Vec<Signature>);

/// Enforcement state for a channel
///
/// This keeps track of commitments on both sides and whether the channel
/// was closed.
#[allow(missing_docs)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EnforcementState {
    // the next commitment number we expect to see signed by the counterparty
    // (set by validate_holder_commitment_tx)
    pub next_holder_commit_num: u64,
    // the next commitment number we expect to sign
    // (set by sign_counterparty_commitment_tx)
    pub next_counterparty_commit_num: u64,
    // the next commitment number we expect the counterparty to revoke
    // (set by validate_counterparty_revocation)
    pub next_counterparty_revoke_num: u64,

    // (set by sign_counterparty_commitment_tx)
    pub current_counterparty_point: Option<PublicKey>, // next_counterparty_commit_num - 1
    // (set by sign_counterparty_commitment_tx)
    pub previous_counterparty_point: Option<PublicKey>, // next_counterparty_commit_num - 2

    // (set by validate_holder_commitment_tx)
    pub current_holder_commit_info: Option<CommitmentInfo2>,
    /// Counterparty signatures on holder's commitment
    pub current_counterparty_signatures: Option<CommitmentSignatures>,

    // (set by sign_counterparty_commitment_tx)
    pub current_counterparty_commit_info: Option<CommitmentInfo2>,
    // (set by sign_counterparty_commitment_tx)
    pub previous_counterparty_commit_info: Option<CommitmentInfo2>,

    pub channel_closed: bool,
    pub initial_holder_value: u64,
}

impl EnforcementState {
    /// Create state for a new channel.
    ///
    /// `initial_holder_value` is in satoshi and represents the lowest value
    /// that we expect the initial commitment to send to us.
    pub fn new(initial_holder_value: u64) -> EnforcementState {
        EnforcementState {
            next_holder_commit_num: 0,
            next_counterparty_commit_num: 0,
            next_counterparty_revoke_num: 0,
            current_counterparty_point: None,
            previous_counterparty_point: None,
            current_holder_commit_info: None,
            current_counterparty_signatures: None,
            current_counterparty_commit_info: None,
            previous_counterparty_commit_info: None,
            channel_closed: false,
            initial_holder_value,
        }
    }

    /// Returns the minimum amount to_holder from both commitments or
    /// None if the amounts are not within epsilon_sat.
    pub fn minimum_to_holder_value(&self, epsilon_sat: u64) -> Option<u64> {
        if let Some(hinfo) = &self.current_holder_commit_info {
            if let Some(cinfo) = &self.current_counterparty_commit_info {
                let hval = hinfo.to_broadcaster_value_sat;
                let cval = cinfo.to_countersigner_value_sat;
                debug!("min to_holder: hval={}, cval={}", hval, cval);
                if hval > cval {
                    if hval - cval <= epsilon_sat {
                        return Some(cval);
                    }
                } else
                /* cval >= hval */
                {
                    if cval - hval <= epsilon_sat {
                        return Some(hval);
                    }
                }
            }
        }
        None
    }

    /// Returns the minimum amount to_counterparty from both commitments or
    /// None if the amounts are not within epsilon_sat.
    pub fn minimum_to_counterparty_value(&self, epsilon_sat: u64) -> Option<u64> {
        if let Some(hinfo) = &self.current_holder_commit_info {
            if let Some(cinfo) = &self.current_counterparty_commit_info {
                let hval = hinfo.to_countersigner_value_sat;
                let cval = cinfo.to_broadcaster_value_sat;
                debug!("min to_cparty: hval={}, cval={}", hval, cval);
                if hval > cval {
                    if hval - cval <= epsilon_sat {
                        return Some(cval);
                    }
                } else
                /* cval >= hval */
                {
                    if cval - hval <= epsilon_sat {
                        return Some(hval);
                    }
                }
            }
        }
        None
    }

    /// Set next holder commitment number
    /// Policy enforcement must be performed by the caller
    pub fn set_next_holder_commit_num(
        &mut self,
        num: u64,
        current_commitment_info: CommitmentInfo2,
        counterparty_signatures: CommitmentSignatures,
    ) {
        let current = self.next_holder_commit_num;
        // TODO - should we enforce policy-v2-commitment-retry-same here?
        debug!("next_holder_commit_num {} -> {}", current, num);
        self.next_holder_commit_num = num;
        self.current_holder_commit_info = Some(current_commitment_info);
        self.current_counterparty_signatures = Some(counterparty_signatures);
    }

    /// Get the current commitment info
    pub fn get_current_holder_commitment_info(&self) -> CommitmentInfo2 {
        self.current_holder_commit_info.as_ref().unwrap().clone()
    }

    /// Set next counterparty commitment number
    pub fn set_next_counterparty_commit_num(
        &mut self,
        num: u64,
        current_point: PublicKey,
        current_commitment_info: CommitmentInfo2,
    ) {
        assert!(num > 0);
        let current = self.next_counterparty_commit_num;

        if num == current + 1 {
            // normal progression, move current to previous
            self.previous_counterparty_point = self.current_counterparty_point;
            self.previous_counterparty_commit_info = self.current_counterparty_commit_info.take();
        } else if num > current + 1 || num < current {
            // we jumped ahead or back, clear out previous info
            self.previous_counterparty_point = None;
            self.previous_counterparty_commit_info = None;
        }

        if num >= current + 1 {
            // we progressed, set current
            self.current_counterparty_point = Some(current_point);
            self.current_counterparty_commit_info = Some(current_commitment_info);
        }

        self.next_counterparty_commit_num = num;
        debug!("next_counterparty_commit_num {} -> {} current {}", current, num, current_point);
    }

    /// Previous counterparty commitment point, or None if unknown
    pub fn get_previous_counterparty_point(&self, num: u64) -> Option<PublicKey> {
        if num + 1 == self.next_counterparty_commit_num {
            self.current_counterparty_point
        } else if num + 2 == self.next_counterparty_commit_num {
            self.previous_counterparty_point
        } else {
            None
        }
    }

    /// Previous counterparty commitment info
    pub fn get_previous_counterparty_commit_info(&self, num: u64) -> Option<CommitmentInfo2> {
        if num + 1 == self.next_counterparty_commit_num {
            self.current_counterparty_commit_info.clone()
        } else if num + 2 == self.next_counterparty_commit_num {
            self.previous_counterparty_commit_info.clone()
        } else {
            None
        }
    }

    /// Set next counterparty revoked commitment number
    pub fn set_next_counterparty_revoke_num(&mut self, num: u64) {
        assert_ne!(num, 0);
        let current = self.next_counterparty_revoke_num;

        // Remove any revoked commitment state.
        if num + 1 >= self.next_counterparty_commit_num {
            // We can't remove the previous_counterparty_point, needed for retries.
            self.previous_counterparty_commit_info = None;
        }

        self.next_counterparty_revoke_num = num;
        debug!("next_counterparty_revoke_num {} -> {}", current, num);
    }

    #[allow(missing_docs)]
    #[cfg(any(test, feature = "test_utils"))]
    pub fn set_next_holder_commit_num_for_testing(&mut self, num: u64) {
        debug!(
            "set_next_holder_commit_num_for_testing: {} -> {}",
            self.next_holder_commit_num, num
        );
        self.next_holder_commit_num = num;
    }

    #[allow(missing_docs)]
    #[cfg(any(test, feature = "test_utils"))]
    pub fn set_next_counterparty_commit_num_for_testing(
        &mut self,
        num: u64,
        current_point: PublicKey,
    ) {
        debug!(
            "set_next_counterparty_commit_num_for_testing: {} -> {}",
            self.next_counterparty_commit_num, num
        );
        self.previous_counterparty_point = self.current_counterparty_point;
        self.current_counterparty_point = Some(current_point);
        self.next_counterparty_commit_num = num;
    }

    #[allow(missing_docs)]
    #[cfg(any(test, feature = "test_utils"))]
    pub fn set_next_counterparty_revoke_num_for_testing(&mut self, num: u64) {
        debug!(
            "set_next_counterparty_revoke_num_for_testing: {} -> {}",
            self.next_counterparty_revoke_num, num
        );
        self.next_counterparty_revoke_num = num;
    }

    /// Summarize in-flight outgoing payments, possibly with new
    /// holder offered or counterparty received commitment tx.
    /// The amounts are in satoshi.
    /// HTLCs belonging to a payment are summed for each of the
    /// holder and counterparty txs. The greater value is taken as the actual
    /// in-flight value.
    pub fn payments_summary(
        &self,
        new_holder_tx: Option<&CommitmentInfo2>,
        new_counterparty_tx: Option<&CommitmentInfo2>,
    ) -> Map<PaymentHash, u64> {
        let holder_offered =
            new_holder_tx.or(self.current_holder_commit_info.as_ref()).map(|h| &h.offered_htlcs);
        let counterparty_received = new_counterparty_tx
            .or(self.current_counterparty_commit_info.as_ref())
            .map(|c| &c.received_htlcs);
        let holder_summary =
            holder_offered.map(|h| Self::summarize_payments(h)).unwrap_or_else(|| Map::new());
        let counterparty_summary = counterparty_received
            .map(|h| Self::summarize_payments(h))
            .unwrap_or_else(|| Map::new());
        // Union the two summaries
        let mut summary = holder_summary;
        for (k, v) in counterparty_summary {
            // Choose higher amount if already there, or insert if not
            summary.entry(k).and_modify(|e| *e = max(*e, v)).or_insert(v);
        }
        summary
    }

    /// Summarize in-flight incoming payments, possibly with new
    /// holder offered or counterparty received commitment tx.
    /// The amounts are in satoshi.
    /// HTLCs belonging to a payment are summed for each of the
    /// holder and counterparty txs. The smaller value is taken as the actual
    /// in-flight value.
    //
    // The smaller value is taken because we should only consider an invoice paid
    // when both txs contain the payment.
    pub fn incoming_payments_summary(
        &self,
        new_holder_tx: Option<&CommitmentInfo2>,
        new_counterparty_tx: Option<&CommitmentInfo2>,
    ) -> Map<PaymentHash, u64> {
        let holder_received =
            new_holder_tx.or(self.current_holder_commit_info.as_ref()).map(|h| &h.received_htlcs);
        let counterparty_offered = new_counterparty_tx
            .or(self.current_counterparty_commit_info.as_ref())
            .map(|c| &c.offered_htlcs);
        let holder_summary =
            holder_received.map(|h| Self::summarize_payments(h)).unwrap_or_else(|| Map::new());
        let counterparty_summary =
            counterparty_offered.map(|h| Self::summarize_payments(h)).unwrap_or_else(|| Map::new());
        // Intersect the holder and counterparty summaries, because we don't
        // consider a payment until it is present in both commitment transactions.
        let mut summary = holder_summary;
        summary.retain(|k, _| counterparty_summary.contains_key(k));
        for (k, v) in counterparty_summary {
            // Choose lower amount
            summary.entry(k).and_modify(|e| *e = min(*e, v));
        }
        summary
    }

    fn summarize_payments(htlcs: &[HTLCInfo2]) -> Map<PaymentHash, u64> {
        let mut summary = Map::new();
        for h in htlcs {
            // If there are multiple HTLCs for the same payment, sum them
            summary.entry(h.payment_hash).and_modify(|e| *e += h.value_sat).or_insert(h.value_sat);
        }
        summary
    }

    /// The claimable balance before and after a new commitment tx
    ///
    /// See [`CommitmentInfo2::claimable_balance`]
    pub fn claimable_balances<T: PreimageMap>(
        &self,
        preimage_map: &T,
        new_holder_tx: Option<&CommitmentInfo2>,
        new_counterparty_tx: Option<&CommitmentInfo2>,
        channel_setup: &ChannelSetup,
    ) -> BalanceDelta {
        assert!(
            new_holder_tx.is_some() || new_counterparty_tx.is_some(),
            "must have at least one new tx"
        );
        assert!(
            new_holder_tx.is_none() || new_counterparty_tx.is_none(),
            "must have at most one new tx"
        );
        // Our balance in the holder commitment tx
        let cur_holder_bal = self.current_holder_commit_info.as_ref().map(|tx| {
            tx.claimable_balance(
                preimage_map,
                channel_setup.is_outbound,
                channel_setup.channel_value_sat,
            )
        });
        // Our balance in the counterparty commitment tx
        let cur_cp_bal = self.current_counterparty_commit_info.as_ref().map(|tx| {
            tx.claimable_balance(
                preimage_map,
                channel_setup.is_outbound,
                channel_setup.channel_value_sat,
            )
        });
        // Our overall balance is the lower of the two
        let cur_bal_opt = min_opt(cur_holder_bal, cur_cp_bal);

        // Perform balance calculations given the new transaction
        let new_holder_bal = new_holder_tx.or(self.current_holder_commit_info.as_ref()).map(|tx| {
            tx.claimable_balance(
                preimage_map,
                channel_setup.is_outbound,
                channel_setup.channel_value_sat,
            )
        });
        let new_cp_bal =
            new_counterparty_tx.or(self.current_counterparty_commit_info.as_ref()).map(|tx| {
                tx.claimable_balance(
                    preimage_map,
                    channel_setup.is_outbound,
                    channel_setup.channel_value_sat,
                )
            });
        let new_bal =
            min_opt(new_holder_bal, new_cp_bal).expect("already checked that we have a new tx");

        // If this is the first commitment, we will have no current balance.
        // We will use our funding amount, or zero if we are not the funder.
        let cur_bal = cur_bal_opt.unwrap_or_else(|| self.initial_holder_value);

        log::debug!(
            "balance {} -> {} --- cur h {} c {} new h {} c {}",
            cur_bal,
            new_bal,
            self.current_holder_commit_info.is_some(),
            self.current_counterparty_commit_info.is_some(),
            new_holder_tx.is_some(),
            new_counterparty_tx.is_some()
        );

        BalanceDelta(cur_bal, new_bal)
    }

    /// Return channel balances
    pub fn balance<T: PreimageMap + core::fmt::Debug>(
        &self,
        preimage_map: &T,
        channel_setup: &ChannelSetup,
    ) -> ChannelBalance {
        debug!("{:#?}", preimage_map);

        // If either of commitments is missing, return 0.
        if self.current_holder_commit_info.is_none()
            || self.current_counterparty_commit_info.is_none()
        {
            return ChannelBalance::zero();
        }

        // Our balance in the holder commitment tx
        let cur_holder_bal = self.current_holder_commit_info.as_ref().unwrap().claimable_balance(
            preimage_map,
            channel_setup.is_outbound,
            channel_setup.channel_value_sat,
        );
        // Our balance in the counterparty commitment tx
        let cur_cp_bal = self.current_counterparty_commit_info.as_ref().unwrap().claimable_balance(
            preimage_map,
            channel_setup.is_outbound,
            channel_setup.channel_value_sat,
        );
        // Our overall balance is the lower of the two.  Use the htlc values from the same.
        // TODO - might be more correct to check the HTLC value for each payment hash, and do
        // Math.min on each one, then sum that.  If an htlc exists in one commitment but not the
        // other if we offered, then it would be -value, if we are receiving, it would be
        // 0. i.e. Math.min(0, value)
        let (cur_bal, received_htlc, offered_htlc, received_htlc_count, offered_htlc_count) =
            if cur_holder_bal < cur_cp_bal {
                let (received_htlc, offered_htlc, received_count, offered_count) =
                    self.current_holder_commit_info.as_ref().unwrap().htlc_balance();
                (cur_holder_bal, received_htlc, offered_htlc, received_count, offered_count)
            } else {
                let (received_htlc, offered_htlc, received_count, offered_count) =
                    self.current_counterparty_commit_info.as_ref().unwrap().htlc_balance();
                (cur_cp_bal, received_htlc, offered_htlc, received_count, offered_count)
            };

        let (claimable, sweeping) = if self.channel_closed { (0, cur_bal) } else { (cur_bal, 0) };

        let balance = ChannelBalance {
            claimable,
            received_htlc,
            offered_htlc,
            sweeping,
            channel_count: 1,
            received_htlc_count,
            offered_htlc_count,
        };
        balance
    }
}

/// Claimable balance before and after a new commitment tx, in satoshi
pub struct BalanceDelta(pub u64, pub u64);

impl Default for BalanceDelta {
    fn default() -> Self {
        BalanceDelta(0, 0)
    }
}

// The minimum of two optional values.  If both are None, the result is None.
fn min_opt(a_opt: Option<u64>, b_opt: Option<u64>) -> Option<u64> {
    if let Some(a) = a_opt {
        if let Some(b) = b_opt {
            Some(a.min(b))
        } else {
            a_opt
        }
    } else {
        b_opt
    }
}