vls-core 1.0.0-rc.1

A library for implementing a Lightning signer, which externalizes and secures cryptographic operations.
Documentation
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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
#[cfg(test)]
mod tests {
    use core::str::FromStr;

    use bitcoin::hash_types::Txid;
    use bitcoin::hashes::Hash;
    use bitcoin::secp256k1::ecdsa::Signature;
    use bitcoin::transaction::Version;
    use bitcoin::{self, Amount, Transaction};
    use lightning::ln::chan_utils::TxCreationKeys;
    use lightning::ln::channel_keys::DelayedPaymentKey;
    use lightning::types::payment::PaymentHash;

    use log::*;
    use test_log::test;

    use crate::channel::{Channel, ChannelBase, CommitmentType};
    use crate::node::SpendType;
    use crate::policy::error::policy_error;
    use crate::policy::validator::ChainState;
    use crate::tx::tx::HTLCInfo2;
    use crate::util::status::{Code, Status};
    use crate::util::test_utils::key::*;
    use crate::util::test_utils::*;

    use paste::paste;

    #[test]
    fn validate_holder_commitment_with_htlcs() {
        let node_ctx = test_node_ctx(1);

        let channel_amount = 3_000_000;
        let chan_ctx = fund_test_channel(&node_ctx, channel_amount);

        let offered_htlcs = vec![
            HTLCInfo2 {
                value_sat: 10_000,
                payment_hash: PaymentHash([1; 32]),
                cltv_expiry: 1 << 16,
            },
            HTLCInfo2 {
                value_sat: 10_000,
                payment_hash: PaymentHash([2; 32]),
                cltv_expiry: 2 << 16,
            },
        ];
        let received_htlcs = vec![
            HTLCInfo2 {
                value_sat: 10_000,
                payment_hash: PaymentHash([3; 32]),
                cltv_expiry: 3 << 16,
            },
            HTLCInfo2 {
                value_sat: 10_000,
                payment_hash: PaymentHash([4; 32]),
                cltv_expiry: 4 << 16,
            },
            HTLCInfo2 {
                value_sat: 10_000,
                payment_hash: PaymentHash([5; 32]),
                cltv_expiry: 5 << 16,
            },
        ];
        let sum_htlc = 50_000;

        let commit_num = 1;
        let feerate_per_kw = 1100;
        let fees = 20_000;
        let to_broadcaster = 1_000_000;
        let to_countersignatory = channel_amount - to_broadcaster - sum_htlc - fees;

        let mut commit_tx_ctx = channel_commitment(
            &node_ctx,
            &chan_ctx,
            commit_num,
            feerate_per_kw,
            to_broadcaster,
            to_countersignatory,
            offered_htlcs,
            received_htlcs,
        );
        let (csig, hsigs) =
            counterparty_sign_holder_commitment(&node_ctx, &chan_ctx, &mut commit_tx_ctx);
        validate_holder_commitment(&node_ctx, &chan_ctx, &commit_tx_ctx, &csig, &hsigs)
            .expect("valid holder commitment");
    }

    #[test]
    fn activate_initial_commitment_test() {
        let channel_amount = 3_000_000;
        let stype = SpendType::P2wpkh;
        let incoming = channel_amount + 2_000_000;
        let fee = 1000;
        let change = incoming - channel_amount - fee;

        let node_ctx = test_node_ctx(1);
        let mut chan_ctx = test_chan_ctx(&node_ctx, 1, channel_amount);
        let mut tx_ctx = TestFundingTxContext::new();

        tx_ctx.add_wallet_input(&node_ctx, stype, 1, incoming);
        tx_ctx.add_wallet_output(&node_ctx, stype, 1, change);
        let outpoint_ndx = tx_ctx.add_channel_outpoint(&node_ctx, &chan_ctx, channel_amount);
        let tx = tx_ctx.to_tx();

        funding_tx_setup_channel(&node_ctx, &mut chan_ctx, &tx, outpoint_ndx);

        let mut commit_tx_ctx = channel_initial_holder_commitment(&node_ctx, &chan_ctx);
        let (commit_sig, htlc_sigs) =
            counterparty_sign_holder_commitment(&node_ctx, &chan_ctx, &mut commit_tx_ctx);

        let htlcs = Channel::htlcs_info2_to_oic(
            &commit_tx_ctx.offered_htlcs,
            &commit_tx_ctx.received_htlcs,
        );

        let _ = node_ctx.node.with_channel(&chan_ctx.channel_id, |chan| {
            let channel_parameters = chan.make_channel_parameters();
            let parameters = channel_parameters.as_holder_broadcastable();

            let per_commitment_point = chan.get_per_commitment_point(commit_tx_ctx.commit_num)?;
            let keys = chan.make_holder_tx_keys(&per_commitment_point);

            let redeem_scripts = build_tx_scripts(
                &keys,
                commit_tx_ctx.to_broadcaster,
                commit_tx_ctx.to_countersignatory,
                &htlcs,
                &parameters,
                &chan.keys.pubkeys(&chan.secp_ctx).funding_pubkey,
                &chan.setup.counterparty_points.funding_pubkey,
            )
            .expect("scripts");
            let output_witscripts: Vec<_> =
                redeem_scripts.iter().map(|s| s.as_bytes().to_vec()).collect();

            // Call before validate fails
            assert_invalid_argument_err!(
                chan.activate_initial_commitment(),
                "activate_initial_commitment called before validation of the initial commitment"
            );

            chan.validate_holder_commitment_tx(
                &commit_tx_ctx.tx.as_ref().unwrap().trust().built_transaction().transaction,
                &output_witscripts,
                commit_tx_ctx.commit_num,
                commit_tx_ctx.feerate_per_kw,
                commit_tx_ctx.offered_htlcs.clone(),
                commit_tx_ctx.received_htlcs.clone(),
                &commit_sig,
                &htlc_sigs,
            )?;

            // Call right after validate succeeds
            assert_status_ok!(chan.activate_initial_commitment());

            // Call later fails
            assert_invalid_argument_err!(
                chan.activate_initial_commitment(),
                "activate_initial_commitment called with next_holder_commit_num 1"
            );

            Ok(())
        });
    }

    // policy-revoke-new-commitment-signed
    #[test]
    fn validate_holder_commitment_with_bad_commit_num() {
        let node_ctx = test_node_ctx(1);

        let channel_amount = 3_000_000;
        let chan_ctx = fund_test_channel(&node_ctx, channel_amount);
        let offered_htlcs = vec![];
        let received_htlcs = vec![];

        let commit_num = 2;
        let feerate_per_kw = 1100;
        let fees = 10_000;
        let to_broadcaster = 1_000_000;
        let to_countersignatory = channel_amount - to_broadcaster - fees;

        // Force the channel to commit_num 2 to build the bogus commitment ...
        set_next_holder_commit_num_for_testing(&node_ctx, &chan_ctx, commit_num);

        let mut commit_tx_ctx = channel_commitment(
            &node_ctx,
            &chan_ctx,
            commit_num,
            feerate_per_kw,
            to_broadcaster,
            to_countersignatory,
            offered_htlcs,
            received_htlcs,
        );
        let (csig, hsigs) =
            counterparty_sign_holder_commitment(&node_ctx, &chan_ctx, &mut commit_tx_ctx);

        set_next_holder_commit_num_for_testing(&node_ctx, &chan_ctx, 1);

        assert_failed_precondition_err!(
            validate_holder_commitment(&node_ctx, &chan_ctx, &commit_tx_ctx, &csig, &hsigs,),
            "policy failure: get_per_commitment_point: commitment_number 3 invalid when next_holder_commit_num is 1"
        );
    }

    // policy-commitment-holder-not-revoked
    #[test]
    fn validate_holder_commitment_with_revoked_commit_num() {
        let node_ctx = test_node_ctx(1);

        let channel_amount = 3_000_000;
        let chan_ctx = fund_test_channel(&node_ctx, channel_amount);
        let offered_htlcs = vec![];
        let received_htlcs = vec![];

        let feerate_per_kw = 1100;
        let fees = 10_000;
        let to_broadcaster = 1_000_000;
        let to_countersignatory = channel_amount - to_broadcaster - fees;

        // Start by validating holder commitment #10 (which revokes #9)
        let commit_num = 10;
        set_next_holder_commit_num_for_testing(&node_ctx, &chan_ctx, commit_num);

        let mut commit_tx_ctx = channel_commitment(
            &node_ctx,
            &chan_ctx,
            commit_num,
            feerate_per_kw,
            to_broadcaster,
            to_countersignatory,
            offered_htlcs.clone(),
            received_htlcs.clone(),
        );
        let (csig, hsigs) =
            counterparty_sign_holder_commitment(&node_ctx, &chan_ctx, &mut commit_tx_ctx);

        validate_holder_commitment(&node_ctx, &chan_ctx, &commit_tx_ctx, &csig, &hsigs)
            .expect("valid holder commitment");

        let revoked_commit_num = commit_num - 1;

        // Now attempt to holder sign holder commitment #9
        let commit_tx_ctx = channel_commitment(
            &node_ctx,
            &chan_ctx,
            revoked_commit_num,
            feerate_per_kw,
            to_broadcaster,
            to_countersignatory,
            offered_htlcs,
            received_htlcs,
        );

        assert_failed_precondition_err!(
            sign_holder_commitment(&node_ctx, &chan_ctx, &commit_tx_ctx),
            "policy failure: get_current_holder_commitment_info: \
             invalid next holder commitment number: 10 != 11"
        );
    }

    #[test]
    fn validate_holder_commitment_with_same_commit_num() {
        let node_ctx = test_node_ctx(1);

        let channel_amount = 3_000_000;
        let chan_ctx = fund_test_channel(&node_ctx, channel_amount);
        let offered_htlcs = vec![];
        let received_htlcs = vec![];

        let commit_num = 1;
        let feerate_per_kw = 1100;
        let fees = 10_000;
        let to_broadcaster = 1_000_000;
        let to_countersignatory = channel_amount - to_broadcaster - fees;

        let mut commit_tx_ctx = channel_commitment(
            &node_ctx,
            &chan_ctx,
            commit_num,
            feerate_per_kw,
            to_broadcaster,
            to_countersignatory,
            offered_htlcs,
            received_htlcs,
        );
        let (csig, hsigs) =
            counterparty_sign_holder_commitment(&node_ctx, &chan_ctx, &mut commit_tx_ctx);
        validate_holder_commitment(&node_ctx, &chan_ctx, &commit_tx_ctx, &csig, &hsigs)
            .expect("valid holder commitment");

        // You can do it again w/ same commit num.
        validate_holder_commitment(&node_ctx, &chan_ctx, &commit_tx_ctx, &csig, &hsigs)
            .expect("valid holder commitment");
    }

    const HOLD_COMMIT_NUM: u64 = 43;

    #[allow(dead_code)]
    struct TxBuilderMutationState<'a> {
        commit_tx_ctx: &'a mut TestCommitmentTxContext,
    }

    #[allow(dead_code)]
    struct KeysMutationState<'a> {
        keys: &'a mut TxCreationKeys,
    }

    #[allow(dead_code)]
    struct ValidationMutationState<'a> {
        opt_anchors: bool,
        chan: &'a mut Channel,
        cstate: &'a mut ChainState,
        commit_tx_ctx: &'a mut TestCommitmentTxContext,
        tx: &'a mut Transaction,
        witscripts: &'a mut Vec<Vec<u8>>,
        commit_sig: &'a mut Signature,
        htlc_sigs: &'a mut Vec<Signature>,
    }

    #[allow(dead_code)]
    struct ValidationState<'a> {
        chan: &'a Channel,
    }

    fn validate_holder_commitment_with_mutators_common<
        TxBuilderMutator,
        KeysMutator,
        ValidationMutator,
        ChannelStateValidator,
    >(
        commitment_type: CommitmentType,
        node_ctx: &TestNodeContext,
        chan_ctx: &TestChannelContext,
        mutate_tx_builder: TxBuilderMutator,
        mutate_keys: KeysMutator,
        mutate_validation_input: ValidationMutator,
        validate_channel_state: ChannelStateValidator,
    ) -> Result<(), Status>
    where
        TxBuilderMutator: Fn(&mut TxBuilderMutationState),
        KeysMutator: Fn(&mut KeysMutationState),
        ValidationMutator: Fn(&mut ValidationMutationState),
        ChannelStateValidator: Fn(&ValidationState),
    {
        let to_broadcaster = 1_979_997;
        let to_countersignatory = 1_000_000;
        let feerate_per_kw = 1200;
        let htlc1 =
            HTLCInfo2 { value_sat: 4000, payment_hash: PaymentHash([1; 32]), cltv_expiry: 2 << 16 };

        let htlc2 =
            HTLCInfo2 { value_sat: 5000, payment_hash: PaymentHash([3; 32]), cltv_expiry: 3 << 16 };

        let htlc3 = HTLCInfo2 {
            value_sat: 10_003,
            payment_hash: PaymentHash([5; 32]),
            cltv_expiry: 4 << 16,
        };
        let offered_htlcs = vec![htlc1];
        let received_htlcs = vec![htlc2, htlc3];

        let mut commit_tx_ctx0 = TestCommitmentTxContext {
            commit_num: HOLD_COMMIT_NUM,
            feerate_per_kw,
            to_broadcaster,
            to_countersignatory,
            offered_htlcs: offered_htlcs.clone(),
            received_htlcs: received_htlcs.clone(),
            tx: None,
        };

        mutate_tx_builder(&mut TxBuilderMutationState { commit_tx_ctx: &mut commit_tx_ctx0 });

        commit_tx_ctx0 = channel_commitment(
            &node_ctx,
            &chan_ctx,
            commit_tx_ctx0.commit_num,
            commit_tx_ctx0.feerate_per_kw,
            commit_tx_ctx0.to_broadcaster,
            commit_tx_ctx0.to_countersignatory,
            commit_tx_ctx0.offered_htlcs.clone(),
            commit_tx_ctx0.received_htlcs.clone(),
        );

        let (commit_sig0, htlc_sigs0) =
            counterparty_sign_holder_commitment(&node_ctx, &chan_ctx, &mut commit_tx_ctx0);

        node_ctx.node.with_channel(&chan_ctx.channel_id, |chan| {
            let mut commit_tx_ctx = commit_tx_ctx0.clone();
            let mut commit_sig = commit_sig0.clone();
            let mut htlc_sigs = htlc_sigs0.clone();

            let channel_parameters = chan.make_channel_parameters();
            let parameters = channel_parameters.as_holder_broadcastable();
            let per_commitment_point = chan.get_per_commitment_point(commit_tx_ctx.commit_num)?;

            let mut keys = chan.make_holder_tx_keys(&per_commitment_point);

            mutate_keys(&mut KeysMutationState { keys: &mut keys });

            let htlcs = Channel::htlcs_info2_to_oic(
                &commit_tx_ctx.offered_htlcs,
                &commit_tx_ctx.received_htlcs,
            );
            let redeem_scripts = build_tx_scripts(
                &keys,
                commit_tx_ctx.to_broadcaster,
                commit_tx_ctx.to_countersignatory,
                &htlcs,
                &parameters,
                &chan.keys.pubkeys(&chan.secp_ctx).funding_pubkey,
                &chan.setup.counterparty_points.funding_pubkey,
            )
            .expect("scripts");
            let mut output_witscripts =
                redeem_scripts.iter().map(|s| s.as_bytes().to_vec()).collect();

            let mut tx =
                commit_tx_ctx.tx.as_ref().unwrap().trust().built_transaction().transaction.clone();

            let mut cstate = make_test_chain_state();

            mutate_validation_input(&mut ValidationMutationState {
                opt_anchors: commitment_type == CommitmentType::AnchorsZeroFeeHtlc,
                chan: chan,
                cstate: &mut cstate,
                commit_tx_ctx: &mut commit_tx_ctx,
                tx: &mut tx,
                witscripts: &mut output_witscripts,
                commit_sig: &mut commit_sig,
                htlc_sigs: &mut htlc_sigs,
            });

            for offered_htlc in commit_tx_ctx.offered_htlcs.clone() {
                node_ctx.node.add_keysend(
                    make_test_pubkey(1),
                    offered_htlc.payment_hash,
                    offered_htlc.value_sat * 1000,
                )?;
            }

            // Validate the holder_commitment, but defer error returns till after we've had
            // a chance to validate the channel state for side-effects
            let mut deferred_rv = chan.validate_holder_commitment_tx(
                &tx,
                &output_witscripts,
                commit_tx_ctx.commit_num,
                commit_tx_ctx.feerate_per_kw,
                commit_tx_ctx.offered_htlcs.clone(),
                commit_tx_ctx.received_htlcs.clone(),
                &commit_sig,
                &htlc_sigs,
            );
            if deferred_rv.is_ok() {
                if commit_tx_ctx.commit_num == 0 {
                    deferred_rv = chan.activate_initial_commitment().map(|_| ());
                }
            }

            if deferred_rv.is_ok() {
                // It's ok to re-revoke prior commitment's ([#502])
                debug!("re-revoking a previously revoked commitment");
                chan.revoke_previous_holder_commitment(commit_tx_ctx.commit_num - 1)?;

                debug!("revoking the previous holder commitment");
                chan.revoke_previous_holder_commitment(commit_tx_ctx.commit_num)?;

                debug!("revoking it again to check idempotency");
                chan.revoke_previous_holder_commitment(commit_tx_ctx.commit_num)?;
            }
            validate_channel_state(&ValidationState { chan });
            deferred_rv?;
            Ok(())
        })
    }

    fn validate_holder_commitment_with_mutators<
        TxBuilderMutator,
        KeysMutator,
        ValidationMutator,
        ChannelStateValidator,
    >(
        commitment_type: CommitmentType,
        mutate_tx_builder: TxBuilderMutator,
        mutate_keys: KeysMutator,
        mutate_validation_input: ValidationMutator,
        validate_channel_state: ChannelStateValidator,
    ) -> Result<(), Status>
    where
        TxBuilderMutator: Fn(&mut TxBuilderMutationState),
        KeysMutator: Fn(&mut KeysMutationState),
        ValidationMutator: Fn(&mut ValidationMutationState),
        ChannelStateValidator: Fn(&ValidationState),
    {
        let next_holder_commit_num = HOLD_COMMIT_NUM;
        let next_counterparty_commit_num = HOLD_COMMIT_NUM + 1;
        let next_counterparty_revoke_num = next_counterparty_commit_num - 1;
        let mut setup = make_test_channel_setup();
        setup.commitment_type = commitment_type;
        let (node_ctx, chan_ctx) = setup_funded_channel_with_setup(
            setup,
            next_holder_commit_num,
            next_counterparty_commit_num,
            next_counterparty_revoke_num,
        );

        validate_holder_commitment_with_mutators_common(
            commitment_type,
            &node_ctx,
            &chan_ctx,
            mutate_tx_builder,
            mutate_keys,
            mutate_validation_input,
            validate_channel_state,
        )
    }

    fn validate_holder_commitment_retry_with_mutators<
        TxBuilderMutator,
        KeysMutator,
        ValidationMutator,
        ChannelStateValidator,
    >(
        commitment_type: CommitmentType,
        mutate_tx_builder: TxBuilderMutator,
        mutate_keys: KeysMutator,
        mutate_validation_input: ValidationMutator,
        validate_channel_state: ChannelStateValidator,
    ) -> Result<(), Status>
    where
        TxBuilderMutator: Fn(&mut TxBuilderMutationState),
        KeysMutator: Fn(&mut KeysMutationState),
        ValidationMutator: Fn(&mut ValidationMutationState),
        ChannelStateValidator: Fn(&ValidationState),
    {
        let next_holder_commit_num = HOLD_COMMIT_NUM;
        let next_counterparty_commit_num = HOLD_COMMIT_NUM + 1;
        let next_counterparty_revoke_num = next_counterparty_commit_num - 1;
        let mut setup = make_test_channel_setup();
        setup.commitment_type = commitment_type;
        let (node_ctx, chan_ctx) = setup_funded_channel_with_setup(
            setup,
            next_holder_commit_num,
            next_counterparty_commit_num,
            next_counterparty_revoke_num,
        );

        // Start with successful validation w/o mutations
        validate_holder_commitment_with_mutators_common(
            commitment_type,
            &node_ctx,
            &chan_ctx,
            |_tms| {},
            |_kms| {},
            |_vms| {},
            |vs| {
                // Channel state should advance.
                assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM + 1);
            },
        )?;

        // Retry with mutations
        validate_holder_commitment_with_mutators_common(
            commitment_type,
            &node_ctx,
            &chan_ctx,
            mutate_tx_builder,
            mutate_keys,
            mutate_validation_input,
            validate_channel_state,
        )
    }

    macro_rules! generate_status_ok_variations {
        ($name: ident, $tms: expr, $kms: expr, $vms: expr, $vs: expr) => {
            paste! {
                #[test]
                fn [<$name _static>]() {
                    assert_status_ok!(
                        validate_holder_commitment_with_mutators(
                            CommitmentType::StaticRemoteKey, $tms, $kms, $vms, $vs)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _anchors>]() {
                    assert_status_ok!(
                        validate_holder_commitment_with_mutators(
                            CommitmentType::AnchorsZeroFeeHtlc, $tms, $kms, $vms, $vs)
                    );
                }
            }
        };
    }

    macro_rules! generate_status_ok_retry_variations {
        ($name: ident, $tms: expr, $kms: expr, $vms: expr, $vs: expr) => {
            paste! {
                #[test]
                fn [<$name _static>]() {
                    assert_status_ok!(
                        validate_holder_commitment_retry_with_mutators(
                            CommitmentType::StaticRemoteKey, $tms, $kms, $vms, $vs)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _anchors>]() {
                    assert_status_ok!(
                        validate_holder_commitment_retry_with_mutators(
                            CommitmentType::AnchorsZeroFeeHtlc, $tms, $kms, $vms, $vs)
                    );
                }
            }
        };
    }

    #[allow(dead_code)]
    struct ErrMsgContext {
        opt_anchors: bool,
    }

    const ERR_MSG_CONTEXT_STATIC: ErrMsgContext = ErrMsgContext { opt_anchors: false };
    const ERR_MSG_CONTEXT_ANCHORS: ErrMsgContext = ErrMsgContext { opt_anchors: true };

    macro_rules! generate_failed_precondition_error_variations {
        ($name: ident, $tms: expr, $kms: expr, $vms: expr, $vs: expr, $errcls: expr) => {
            paste! {
                #[test]
                fn [<$name _static>]() {
                    assert_failed_precondition_err!(
                        validate_holder_commitment_with_mutators(
                            CommitmentType::StaticRemoteKey, $tms, $kms, $vms, $vs),
                        ($errcls)(ERR_MSG_CONTEXT_STATIC)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _anchors>]() {
                    assert_failed_precondition_err!(
                        validate_holder_commitment_with_mutators(
                            CommitmentType::AnchorsZeroFeeHtlc, $tms, $kms, $vms, $vs),
                        ($errcls)(ERR_MSG_CONTEXT_ANCHORS)
                    );
                }
            }
        };
    }

    macro_rules! generate_failed_precondition_error_retry_variations {
        ($name: ident, $tms: expr, $kms: expr, $vms: expr, $vs: expr, $errcls: expr) => {
            paste! {
                #[test]
                fn [<$name _static>]() {
                    assert_failed_precondition_err!(
                        validate_holder_commitment_retry_with_mutators(
                            CommitmentType::StaticRemoteKey, $tms, $kms, $vms, $vs),
                        ($errcls)(ERR_MSG_CONTEXT_STATIC)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _anchors>]() {
                    assert_failed_precondition_err!(
                        validate_holder_commitment_retry_with_mutators(
                            CommitmentType::AnchorsZeroFeeHtlc, $tms, $kms, $vms, $vs),
                        ($errcls)(ERR_MSG_CONTEXT_ANCHORS)
                    );
                }
            }
        };
    }

    macro_rules! generate_failed_precondition_error_retry_with_mutated_tx {
        ($name: ident, $tms: expr, $vs: expr, $errmsg: expr) => {
            generate_failed_precondition_error_retry_variations!(
                $name,
                $tms,
                |_| {},
                |_| {},
                $vs,
                $errmsg
            );
        };
    }

    macro_rules! generate_failed_precondition_error_with_mutated_keys {
        ($name: ident, $kms: expr, $vs: expr, $errmsg: expr) => {
            generate_failed_precondition_error_variations!(
                $name,
                |_| {},
                $kms,
                |_| {},
                $vs,
                $errmsg
            );
        };
    }

    macro_rules! generate_failed_precondition_error_with_mutated_validation_input {
        ($name: ident, $vms: expr, $vs: expr, $errmsg: expr) => {
            generate_failed_precondition_error_variations!(
                $name,
                |_| {},
                |_| {},
                $vms,
                $vs,
                $errmsg
            );
        };
    }

    generate_status_ok_variations!(success, |_tms| {}, |_kms| {}, |_vms| {}, |vs| {
        // Channel state should advance.
        assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM + 1);
    });

    // policy-commitment-retry-same
    generate_status_ok_retry_variations!(can_retry, |_tms| {}, |_kms| {}, |_vms| {}, |vs| {
        // Channel state should advance.
        assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM + 1);
    });

    // policy-revoke-not-closed
    // It's ok to retry a validate_holder_commitment after it has been signed.
    generate_status_ok_retry_variations!(
        can_retry_after_signed,
        |_tms| {},
        |_kms| {},
        |vms| {
            vms.chan.enforcement_state.channel_closed = true;
        },
        |vs| {
            // Channel state should stay advanced
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM + 1);
        }
    );

    // policy-revoke-not-closed
    // It's not ok to advance after a prior has been signed
    generate_failed_precondition_error_with_mutated_validation_input!(
        not_after_signed,
        |vms| {
            vms.chan.enforcement_state.channel_closed = true;
        },
        |vs| {
            // Channel state should not advance.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM);
        },
        |_| "policy failure: validate_holder_commitment_tx: channel is closing"
    );

    // policy-commitment-retry-same
    generate_failed_precondition_error_retry_with_mutated_tx!(
        bad_to_holder,
        |tms| {
            tms.commit_tx_ctx.to_broadcaster -= 1;
        },
        |vs| {
            // Channel state should stay where we advanced it initially.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM + 1);
        },
        |_| "policy failure: validate_holder_commitment_tx: \
             retry holder commitment 43 with changed info"
    );

    // policy-commitment-retry-same
    generate_failed_precondition_error_retry_with_mutated_tx!(
        bad_to_counterparty,
        |tms| {
            tms.commit_tx_ctx.to_countersignatory -= 1;
        },
        |vs| {
            // Channel state should stay where we advanced it initially.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM + 1);
        },
        |_| "policy failure: validate_holder_commitment_tx: \
             retry holder commitment 43 with changed info"
    );

    // policy-commitment-retry-same
    generate_failed_precondition_error_retry_with_mutated_tx!(
        bad_offered_htlc,
        |tms| {
            tms.commit_tx_ctx.offered_htlcs[0].value_sat -= 1;
        },
        |vs| {
            // Channel state should stay where we advanced it initially.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM + 1);
        },
        |_| "policy failure: validate_holder_commitment_tx: \
             retry holder commitment 43 with changed info"
    );

    // policy-commitment-retry-same
    generate_failed_precondition_error_retry_with_mutated_tx!(
        bad_received_htlc,
        |tms| {
            tms.commit_tx_ctx.received_htlcs[0].value_sat -= 1;
        },
        |vs| {
            // Channel state should stay where we advanced it initially.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM + 1);
        },
        |_| "policy failure: validate_holder_commitment_tx: \
             retry holder commitment 43 with changed info"
    );

    generate_failed_precondition_error_with_mutated_validation_input!(
        bad_commit_sig,
        |vms| {
            *vms.commit_sig = Signature::from_str("30450221009338316aef0f17f75127a24d60ae8a980fee5e2b4605dc96fba2d5407e77fcee022029e311ff22df5b515e4a2fbe412d32ed49e93cabbb31b067ad3318ac22441cd2").expect("sig");
        },
        |vs| {
            // Channel state should not advance.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM);
        },
        |_| "policy failure: commit sig verify failed: signature failed verification"
    );

    generate_failed_precondition_error_with_mutated_validation_input!(
        bad_htlc_sig,
        |vms| {
            vms.htlc_sigs[0] = Signature::from_str("30450221009338316aef0f17f75127a24d60ae8a980fee5e2b4605dc96fba2d5407e77fcee022029e311ff22df5b515e4a2fbe412d32ed49e93cabbb31b067ad3318ac22441cd2").expect("sig");
        },
        |vs| {
            // Channel state should not advance.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM);
        },
        |_| "policy failure: \
             commit sig verify failed for htlc 0: signature failed verification"
    );

    generate_failed_precondition_error_with_mutated_validation_input!(
        not_ahead,
        |vms| {
            // Set the channel's next_holder_commit_num ahead two, past the retry ...
            vms.chan.enforcement_state.set_next_holder_commit_num_for_testing(HOLD_COMMIT_NUM + 2);
        },
        |vs| {
            // Channel state should stay where we advanced it.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM + 2);
        },
        |_| "policy failure: validate_holder_commitment_tx: \
             can't validate revoked commitment_number 43, next_holder_commit_num is 45"
    );

    generate_failed_precondition_error_with_mutated_validation_input!(
        not_behind,
        |vms| {
            // Set the channel's next_holder_commit_num ahead two behind 1, in the past ...
            vms.chan.enforcement_state.set_next_holder_commit_num_for_testing(HOLD_COMMIT_NUM - 1);
        },
        |vs| {
            // Channel state should stay where we set it.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM - 1);
        },
        |_| {
            "policy failure: revoke_previous_holder_commitment: \
             new_current_commitment == next_holder_commit_num 42 \
             but next_holder_commit_info.is_none"
        }
    );

    // policy-revoke-not-closed
    generate_failed_precondition_error_with_mutated_validation_input!(
        not_closed,
        |vms| {
            vms.chan.enforcement_state.channel_closed = true;
        },
        |vs| {
            // Channel state should not advance.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM);
        },
        |_| "policy failure: validate_holder_commitment_tx: channel is closing"
    );

    // policy-revoke-not-closed
    generate_status_ok_retry_variations!(
        // It's ok to validate existing when closed (ie: retry after mutual close)
        closed_ok_on_previous,
        |_tms| {},
        |_kms| {},
        |vms| {
            vms.chan.enforcement_state.channel_closed = true;
        },
        |vs| {
            // Channel state should advance.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM + 1);
        }
    );

    // policy-revoke-new-commitment-valid
    // policy-commitment-version
    generate_failed_precondition_error_with_mutated_validation_input!(
        bad_version,
        |vms| {
            vms.tx.version = Version::non_standard(3);
        },
        |vs| {
            // Channel state should not advance.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM);
        },
        |_| "policy failure: decode_commitment_tx: bad commitment version: 3"
    );

    // policy-revoke-new-commitment-valid
    // policy-commitment-broadcaster-pubkey
    generate_failed_precondition_error_with_mutated_keys!(
        bad_delayed_pubkey,
        |kms| {
            kms.keys.broadcaster_delayed_payment_key = DelayedPaymentKey(make_test_pubkey(42));
        },
        |vs| {
            // Channel state should not advance.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM);
        },
        |ectx: ErrMsgContext| {
            format!(
            "transaction format: decode_commitment_tx: \
             tx output[{}]: script pubkey doesn't match inner script: OP_0 OP_PUSHBYTES_32 a838650404f18b3bdac3ff705fd16d9c221b4ffe46ea675f5ede586b63ae2b63 != OP_0 OP_PUSHBYTES_32 e8c680c7abd47830f5657a0f0ccd46bf3392bb472ba50e98be0ec46a88f982d3",
            if ectx.opt_anchors { 6 } else { 4 }
        )
        }
    );

    // policy-revoke-new-commitment-valid
    // policy-commitment-singular-to-holder
    generate_failed_precondition_error_with_mutated_validation_input!(
        multiple_to_holder,
        |vms| {
            let basendx = if vms.opt_anchors { 2 } else { 0 };
            let ndx = basendx + 4;
            vms.tx.output.push(vms.tx.output[ndx].clone());
            vms.witscripts.push(vms.witscripts[ndx].clone());
        },
        |vs| {
            // Channel state should not advance.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM);
        },
        |ectx: ErrMsgContext| format!(
            "transaction format: decode_commitment_tx: \
             tx output[{}]: more than one to_broadcaster output",
            if ectx.opt_anchors { 7 } else { 5 }
        )
    );

    // policy-revoke-new-commitment-valid
    // policy-commitment-singular-to-counterparty
    generate_failed_precondition_error_with_mutated_validation_input!(
        multiple_to_counterparty,
        |vms| {
            let basendx = if vms.opt_anchors { 2 } else { 0 };
            let ndx = basendx + 3;
            vms.tx.output.push(vms.tx.output[ndx].clone());
            vms.witscripts.push(vms.witscripts[ndx].clone());
        },
        |vs| {
            // Channel state should not advance.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM);
        },
        |ectx: ErrMsgContext| format!(
            "transaction format: decode_commitment_tx: \
             tx output[{}]: more than one to_countersigner output",
            if ectx.opt_anchors { 7 } else { 5 }
        )
    );

    // policy-commitment-outputs-trimmed
    generate_failed_precondition_error_with_mutated_validation_input!(
        dust_to_holder,
        |vms| {
            let basendx = if vms.opt_anchors { 2 } else { 0 };
            let delta = Amount::from_sat(1_979_900);
            vms.tx.output[basendx + 3].value += delta;
            vms.tx.output[basendx + 4].value -= delta;
        },
        |vs| {
            // Channel state should not advance.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM);
        },
        |_| "policy failure: validate_holder_commitment_tx: validate_commitment_tx: \
             to_broadcaster_value_sat 97 less than dust limit 354"
    );

    // policy-commitment-outputs-trimmed
    generate_failed_precondition_error_with_mutated_validation_input!(
        dust_to_counterparty,
        |vms| {
            let basendx = if vms.opt_anchors { 2 } else { 0 };
            let delta = Amount::from_sat(999_900);
            vms.tx.output[basendx + 3].value -= delta;
            vms.tx.output[basendx + 4].value += delta;
        },
        |vs| {
            // Channel state should not advance.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM);
        },
        |_| "policy failure: validate_holder_commitment_tx: validate_commitment_tx: \
             to_countersigner_value_sat 100 less than dust limit 354"
    );

    // policy-commitment-outputs-trimmed
    generate_failed_precondition_error_with_mutated_validation_input!(
        dust_offered_htlc,
        |vms| {
            let basendx = if vms.opt_anchors { 2 } else { 0 };
            vms.commit_tx_ctx.offered_htlcs[0].value_sat = 300;
            vms.tx.output[basendx].value = Amount::from_sat(300);
        },
        |vs| {
            // Channel state should not advance.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM);
        },
        |ectx: ErrMsgContext| format!(
            "policy failure: validate_holder_commitment_tx: validate_commitment_tx: \
             offered htlc.value_sat 300 less than dust limit {}",
            if ectx.opt_anchors { 354 } else { 1125 }
        )
    );

    // policy-commitment-outputs-trimmed
    generate_failed_precondition_error_with_mutated_validation_input!(
        dust_received_htlc,
        |vms| {
            let basendx = if vms.opt_anchors { 2 } else { 0 };
            vms.commit_tx_ctx.received_htlcs[0].value_sat = 300;
            vms.tx.output[basendx + 1].value = Amount::from_sat(300);
        },
        |vs| {
            // Channel state should not advance.
            assert_eq!(vs.chan.enforcement_state.next_holder_commit_num, HOLD_COMMIT_NUM);
        },
        |ectx: ErrMsgContext| format!(
            "policy failure: validate_holder_commitment_tx: validate_commitment_tx: \
             received htlc.value_sat 300 less than dust limit {}",
            if ectx.opt_anchors { 354 } else { 1173 }
        )
    );

    #[test]
    fn channel_state_counterparty_commit_and_revoke_test() {
        let node_ctx = test_node_ctx(1);
        let mut chan_ctx = test_chan_ctx(&node_ctx, 1, 3_000_000);
        synthesize_setup_channel(
            &node_ctx,
            &mut chan_ctx,
            bitcoin::OutPoint { txid: Txid::from_slice(&[2u8; 32]).unwrap(), vout: 0 },
            HOLD_COMMIT_NUM,
        );
        node_ctx
            .node
            .with_channel(&chan_ctx.channel_id, |chan| {
                let validator = chan.validator();
                let state = &mut chan.enforcement_state;

                // We'll need a placeholder; actual values not checked here ...
                let commit_info = make_test_commitment_info();

                // confirm initial state
                assert_eq!(state.next_counterparty_revoke_num, 0);
                assert_eq!(state.next_counterparty_commit_num, 0);
                // commit 0: unitialized <- next_revoke, <- next_commit

                // can't set next_commit to 0 (what would current point be?)
                assert_policy_err!(
                    validator.set_next_counterparty_commit_num(
                        state,
                        0,
                        make_test_pubkey(0x08),
                        commit_info.clone()
                    ),
                    "policy-other",
                    "set_next_counterparty_commit_num: can\'t set next to 0"
                );
                assert_eq!(state.next_counterparty_commit_num, 0);

                // can't set next_revoke to 0 either
                assert_policy_err!(
                    validator.set_next_counterparty_revoke_num(state, 0),
                    "policy-other",
                    "set_next_counterparty_revoke_num: can\'t set next to 0"
                );
                assert_eq!(state.next_counterparty_revoke_num, 0);

                // ADVANCE next_commit to 1
                assert_validation_ok!(validator.set_next_counterparty_commit_num(
                    state,
                    1,
                    make_test_pubkey(0x10),
                    commit_info.clone()
                ));
                assert_eq!(state.next_counterparty_revoke_num, 0);
                assert_eq!(state.next_counterparty_commit_num, 1);
                // commit 0: current <- next_revoke
                // commit 1: next    <- next_commit

                // retries are ok
                assert_validation_ok!(validator.set_next_counterparty_commit_num(
                    state,
                    1,
                    make_test_pubkey(0x10),
                    commit_info.clone()
                ));
                assert_eq!(state.next_counterparty_revoke_num, 0);
                assert_eq!(state.next_counterparty_commit_num, 1);

                // can't skip next_commit forward
                assert_policy_err!(
                    validator.set_next_counterparty_commit_num(
                        state,
                        3,
                        make_test_pubkey(0x14),
                        commit_info.clone()
                    ),
                    "policy-commitment-previous-revoked",
                    "set_next_counterparty_commit_num: invalid progression: 1 to 3"
                );
                assert_eq!(state.next_counterparty_commit_num, 1);

                // can't skip next_revoke forward
                assert_policy_err!(
                    validator.set_next_counterparty_revoke_num(state, 1),
                    "policy-commitment-previous-revoked",
                    "set_next_counterparty_revoke_num: \
                     1 too large relative to next_counterparty_commit_num 1"
                );
                assert_eq!(state.next_counterparty_revoke_num, 0);

                // ADVANCE next_commit to 2
                assert_validation_ok!(validator.set_next_counterparty_commit_num(
                    state,
                    2,
                    make_test_pubkey(0x12),
                    commit_info.clone()
                ));
                assert_eq!(state.next_counterparty_revoke_num, 0);
                assert_eq!(state.next_counterparty_commit_num, 2);
                // commit 0: unrevoked <- next_revoke
                // commit 1: current
                // commit 2: next    <- next_commit

                // retries are ok
                assert_validation_ok!(validator.set_next_counterparty_commit_num(
                    state,
                    2,
                    make_test_pubkey(0x12),
                    commit_info.clone()
                ));
                assert_eq!(state.next_counterparty_revoke_num, 0);
                assert_eq!(state.next_counterparty_commit_num, 2);

                // can't commit old thing
                assert_policy_err!(
                    validator.set_next_counterparty_commit_num(
                        state,
                        1,
                        make_test_pubkey(0x10),
                        commit_info.clone()
                    ),
                    "policy-commitment-previous-revoked",
                    "set_next_counterparty_commit_num: invalid progression: 2 to 1"
                );
                assert_eq!(state.next_counterparty_commit_num, 2);

                // can't (ever) set next_revoke to 0
                assert_policy_err!(
                    validator.set_next_counterparty_revoke_num(state, 0),
                    "policy-other",
                    "set_next_counterparty_revoke_num: can\'t set next to 0"
                );
                assert_eq!(state.next_counterparty_revoke_num, 0);

                // can't skip revoke ahead
                assert_policy_err!(
                    validator.set_next_counterparty_revoke_num(state, 2),
                    "policy-commitment-previous-revoked",
                    "set_next_counterparty_revoke_num: 2 too large relative to \
                     next_counterparty_commit_num 2"
                );
                assert_eq!(state.next_counterparty_revoke_num, 0);

                // REVOKE commit 0
                assert_validation_ok!(validator.set_next_counterparty_revoke_num(state, 1));
                assert_eq!(state.next_counterparty_revoke_num, 1);
                assert_eq!(state.next_counterparty_commit_num, 2);
                // commit 0: revoked
                // commit 1: current   <- next_revoke
                // commit 2: next      <- next_commit

                // retries are ok
                assert_validation_ok!(validator.set_next_counterparty_revoke_num(state, 1));
                assert_eq!(state.next_counterparty_revoke_num, 1);
                assert_eq!(state.next_counterparty_commit_num, 2);

                // can't retry the previous commit anymore
                assert_policy_err!(
                    validator.set_next_counterparty_commit_num(
                        state,
                        2,
                        make_test_pubkey(0x12),
                        commit_info.clone()
                    ),
                    "policy-commitment-previous-revoked",
                    "set_next_counterparty_commit_num: 2 too small relative to \
                     next_counterparty_revoke_num 1"
                );
                assert_eq!(state.next_counterparty_commit_num, 2);

                // can't skip commit ahead
                assert_policy_err!(
                    validator.set_next_counterparty_commit_num(
                        state,
                        4,
                        make_test_pubkey(0x16),
                        commit_info.clone()
                    ),
                    "policy-commitment-previous-revoked",
                    "set_next_counterparty_commit_num: invalid progression: 2 to 4"
                );
                assert_eq!(state.next_counterparty_commit_num, 2);

                // can't revoke backwards
                assert_policy_err!(
                    validator.set_next_counterparty_revoke_num(state, 0),
                    "policy-other",
                    "set_next_counterparty_revoke_num: can\'t set next to 0"
                );
                assert_eq!(state.next_counterparty_revoke_num, 1);

                // can't skip revoke ahead
                assert_policy_err!(
                    validator.set_next_counterparty_revoke_num(state, 2),
                    "policy-commitment-previous-revoked",
                    "set_next_counterparty_revoke_num: 2 too large \
                     relative to next_counterparty_commit_num 2"
                );
                assert_eq!(state.next_counterparty_revoke_num, 1);

                // ADVANCE next_commit to 3
                assert_validation_ok!(validator.set_next_counterparty_commit_num(
                    state,
                    3,
                    make_test_pubkey(0x14),
                    commit_info.clone()
                ));
                // commit 0: revoked
                // commit 1: unrevoked <- next_revoke
                // commit 2: current
                // commit 3: next      <- next_commit
                assert_eq!(state.next_counterparty_revoke_num, 1);
                assert_eq!(state.next_counterparty_commit_num, 3);

                // retries ok
                assert_validation_ok!(validator.set_next_counterparty_commit_num(
                    state,
                    3,
                    make_test_pubkey(0x14),
                    commit_info.clone()
                ));
                assert_eq!(state.next_counterparty_commit_num, 3);

                // Can still retry the old revoke (they may not have seen our commit).
                assert_validation_ok!(validator.set_next_counterparty_revoke_num(state, 1));
                assert_eq!(state.next_counterparty_revoke_num, 1);
                assert_eq!(state.next_counterparty_commit_num, 3);

                // Can't skip revoke ahead
                assert_policy_err!(
                    validator.set_next_counterparty_revoke_num(state, 3),
                    "policy-commitment-previous-revoked",
                    "set_next_counterparty_revoke_num: 3 too large relative to \
                     next_counterparty_commit_num 3"
                );
                assert_eq!(state.next_counterparty_revoke_num, 1);

                // can't commit behind
                assert_policy_err!(
                    validator.set_next_counterparty_commit_num(
                        state,
                        2,
                        make_test_pubkey(0x12),
                        commit_info.clone()
                    ),
                    "policy-commitment-previous-revoked",
                    "set_next_counterparty_commit_num: 2 too small relative to \
                     next_counterparty_revoke_num 1"
                );
                assert_eq!(state.next_counterparty_commit_num, 3);

                // REVOKE commit 1
                assert_validation_ok!(validator.set_next_counterparty_revoke_num(state, 2));
                // commit 1: revoked
                // commit 2: current   <- next_revoke
                // commit 3: next      <- next_commit
                assert_eq!(state.next_counterparty_revoke_num, 2);
                assert_eq!(state.next_counterparty_commit_num, 3);

                // revoke retries ok
                assert_validation_ok!(validator.set_next_counterparty_revoke_num(state, 2));
                assert_eq!(state.next_counterparty_revoke_num, 2);
                assert_eq!(state.next_counterparty_commit_num, 3);

                // can't revoke backwards
                assert_policy_err!(
                    validator.set_next_counterparty_revoke_num(state, 1),
                    "policy-commitment-previous-revoked",
                    "set_next_counterparty_revoke_num: invalid progression: 2 to 1"
                );
                assert_eq!(state.next_counterparty_revoke_num, 2);

                // can't revoke ahead until next commit
                assert_policy_err!(
                    validator.set_next_counterparty_revoke_num(state, 3),
                    "policy-commitment-previous-revoked",
                    "set_next_counterparty_revoke_num: 3 too large relative to \
                     next_counterparty_commit_num 3"
                );
                assert_eq!(state.next_counterparty_revoke_num, 2);

                // commit retry not ok anymore
                assert_policy_err!(
                    validator.set_next_counterparty_commit_num(
                        state,
                        3,
                        make_test_pubkey(0x14),
                        commit_info.clone()
                    ),
                    "policy-commitment-previous-revoked",
                    "set_next_counterparty_commit_num: 3 too small relative to \
                     next_counterparty_revoke_num 2"
                );
                assert_eq!(state.next_counterparty_commit_num, 3);

                // can't skip commit ahead
                assert_policy_err!(
                    validator.set_next_counterparty_commit_num(
                        state,
                        5,
                        make_test_pubkey(0x18),
                        commit_info.clone()
                    ),
                    "policy-commitment-previous-revoked",
                    "set_next_counterparty_commit_num: invalid progression: 3 to 5"
                );
                assert_eq!(state.next_counterparty_commit_num, 3);

                // ADVANCE next_commit to 4
                assert_validation_ok!(validator.set_next_counterparty_commit_num(
                    state,
                    4,
                    make_test_pubkey(0x16),
                    commit_info.clone()
                ));
                // commit 2: unrevoked <- next_revoke
                // commit 3: current
                // commit 4: next      <- next_commit
                assert_eq!(state.next_counterparty_revoke_num, 2);
                assert_eq!(state.next_counterparty_commit_num, 4);

                Ok(())
            })
            .expect("success");
    }
}