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
#[cfg(test)]
mod tests {
    use bitcoin::absolute::{Height, LockTime};
    use bitcoin::hashes::Hash;
    use bitcoin::sighash::EcdsaSighashType;
    use bitcoin::transaction::Version;
    use bitcoin::{self, Amount, Sequence, Transaction};
    use lightning::ln::chan_utils::{
        build_htlc_transaction, get_htlc_redeemscript, get_revokeable_redeemscript,
        ChannelTransactionParameters, HTLCOutputInCommitment, TxCreationKeys,
    };
    use lightning::ln::channel_keys::{DelayedPaymentKey, RevocationKey};
    use lightning::types::payment::PaymentHash;
    use test_log::test;

    use crate::channel::{ChannelBase, ChannelSetup, CommitmentType};
    use crate::policy::validator::ChainState;
    use crate::util::status::{Code, Status};
    use crate::util::test_utils::key::*;
    use crate::util::test_utils::*;

    use paste::paste;

    #[test]
    fn sign_local_htlc_tx_static_test() {
        let setup = make_test_channel_setup();
        sign_local_htlc_tx_test(&setup);
    }

    fn sign_local_htlc_tx_test(setup: &ChannelSetup) {
        let (node, channel_id) =
            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], setup.clone());

        let htlc_amount_sat = 10 * 1000;

        let commitment_txid = bitcoin::Txid::from_slice(&[2u8; 32]).unwrap();
        let feerate_per_kw = 1000;
        let htlc = HTLCOutputInCommitment {
            offered: true,
            amount_msat: htlc_amount_sat * 1000,
            cltv_expiry: 2 << 16,
            payment_hash: PaymentHash([1; 32]),
            transaction_output_index: Some(0),
        };

        let n: u64 = 1;

        let (per_commitment_point, txkeys, to_self_delay) = node
            .with_channel(&channel_id, |chan| {
                chan.enforcement_state.set_next_holder_commit_num_for_testing(n);
                let per_commitment_point = chan.get_per_commitment_point(n).expect("point");
                let txkeys = chan.make_holder_tx_keys(&per_commitment_point);
                let to_self_delay =
                    chan.make_channel_parameters().as_holder_broadcastable().contest_delay();
                Ok((per_commitment_point, txkeys, to_self_delay))
            })
            .expect("point");

        let build_feerate = if setup.is_zero_fee_htlc() { 0 } else { feerate_per_kw };

        let htlc_tx = build_htlc_transaction(
            &commitment_txid,
            build_feerate,
            to_self_delay,
            &htlc,
            &setup.features(),
            &txkeys.broadcaster_delayed_payment_key,
            &txkeys.revocation_key,
        );

        let htlc_redeemscript = get_htlc_redeemscript(&htlc, &setup.features(), &txkeys);

        let output_witscript = get_revokeable_redeemscript(
            &txkeys.revocation_key,
            to_self_delay,
            &txkeys.broadcaster_delayed_payment_key,
        );

        let htlc_pubkey = get_channel_htlc_pubkey(&node, &channel_id, &per_commitment_point);

        let sig = node
            .with_channel(&channel_id, |chan| {
                chan.sign_holder_htlc_tx(
                    &htlc_tx,
                    n,
                    None,
                    &htlc_redeemscript,
                    htlc_amount_sat,
                    &output_witscript,
                )
            })
            .unwrap();

        check_signature(&htlc_tx, 0, sig, &htlc_pubkey, htlc_amount_sat, &htlc_redeemscript);

        let sig1 = node
            .with_channel(&channel_id, |chan| {
                chan.sign_holder_htlc_tx(
                    &htlc_tx,
                    999,
                    Some(per_commitment_point),
                    &htlc_redeemscript,
                    htlc_amount_sat,
                    &output_witscript,
                )
            })
            .unwrap();

        check_signature(&htlc_tx, 0, sig1, &htlc_pubkey, htlc_amount_sat, &htlc_redeemscript);
    }

    #[allow(dead_code)]
    struct ChanParamMutationState<'a> {
        is_counterparty: bool,
        param: &'a mut ChannelTransactionParameters,
    }

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

    #[allow(dead_code)]
    struct TxMutationState<'a> {
        is_offered: bool,
        cstate: &'a mut ChainState,
        tx: &'a mut Transaction,
    }

    fn sign_counterparty_htlc_tx_with_mutators<ChanParamMutator, KeysMutator, TxMutator>(
        is_offered: bool,
        commitment_type: CommitmentType,
        chanparammut: ChanParamMutator,
        keysmut: KeysMutator,
        txmut: TxMutator,
    ) -> Result<(), Status>
    where
        ChanParamMutator: Fn(&mut ChanParamMutationState),
        KeysMutator: Fn(&mut KeysMutationState),
        TxMutator: Fn(&mut TxMutationState),
    {
        let mut setup = make_test_channel_setup();
        setup.commitment_type = commitment_type;
        let (node, channel_id) =
            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], setup.clone());

        let remote_per_commitment_point = make_test_pubkey(10);
        let htlc_amount_sat = 1_000_000;

        let (typedsig, htlc_tx, htlc_redeemscript) = node.with_channel(&channel_id, |chan| {
            let mut channel_parameters = chan.make_channel_parameters();

            // Mutate the channel parameters
            chanparammut(&mut ChanParamMutationState {
                is_counterparty: true,
                param: &mut channel_parameters,
            });

            let mut keys = chan.make_counterparty_tx_keys(&remote_per_commitment_point);

            // Mutate the tx creation keys.
            keysmut(&mut KeysMutationState { keys: &mut keys });

            let commitment_txid = bitcoin::Txid::from_slice(&[2u8; 32]).unwrap();
            let feerate_per_kw = 1000;
            let to_self_delay = channel_parameters.as_counterparty_broadcastable().contest_delay();

            let htlc = HTLCOutputInCommitment {
                offered: is_offered,
                amount_msat: htlc_amount_sat * 1000,
                cltv_expiry: if is_offered { 2 << 16 } else { 0 },
                payment_hash: PaymentHash([1; 32]),
                transaction_output_index: Some(0),
            };

            let build_feerate = if setup.is_zero_fee_htlc() { 0 } else { feerate_per_kw };

            let mut htlc_tx = build_htlc_transaction(
                &commitment_txid,
                build_feerate,
                to_self_delay,
                &htlc,
                &setup.features(),
                &keys.broadcaster_delayed_payment_key,
                &keys.revocation_key,
            );

            let mut cstate = make_test_chain_state();

            // Mutate the transaction.
            txmut(&mut TxMutationState {
                is_offered: is_offered,
                cstate: &mut cstate,
                tx: &mut htlc_tx,
            });

            let htlc_redeemscript = get_htlc_redeemscript(&htlc, &setup.features(), &keys);

            let output_witscript = get_revokeable_redeemscript(
                &keys.revocation_key,
                to_self_delay,
                &keys.broadcaster_delayed_payment_key,
            );

            let typedsig = chan.sign_counterparty_htlc_tx(
                &htlc_tx,
                &remote_per_commitment_point,
                &htlc_redeemscript,
                htlc_amount_sat,
                &output_witscript,
            )?;
            Ok((typedsig, htlc_tx, htlc_redeemscript))
        })?;

        let expected_txid = if commitment_type == CommitmentType::StaticRemoteKey {
            if is_offered {
                "b93508d29f4866913340ce050c1f2fc366ac84824f1f4db388350cfa25a4f5cb"
            } else {
                "09bf12e4a113411134d9d8ee25e0d8e8ec3733867fe60bb4b8bebf29e393a08c"
            }
        } else if commitment_type == CommitmentType::AnchorsZeroFeeHtlc {
            if is_offered {
                "e3e293a3e9c447eab17baa88811cc10717bdbb805984eab08d12b8d6a271fd00"
            } else {
                "989947d5690c4823f28f66729be0cb09024a6b8279880dbede452db8772b8488"
            }
        } else {
            panic!("unknown commitment_type");
        };
        assert_eq!(htlc_tx.compute_txid().to_string(), expected_txid);

        let htlc_pubkey = get_channel_htlc_pubkey(&node, &channel_id, &remote_per_commitment_point);

        check_counterparty_htlc_signature(
            &htlc_tx,
            0,
            typedsig,
            &htlc_pubkey,
            htlc_amount_sat,
            &htlc_redeemscript,
            setup.is_anchors(),
        );

        Ok(())
    }

    fn sign_holder_htlc_tx_with_mutators<ChanParamMutator, KeysMutator, TxMutator>(
        is_offered: bool,
        commitment_type: CommitmentType,
        chanparammut: ChanParamMutator,
        keysmut: KeysMutator,
        txmut: TxMutator,
    ) -> Result<(), Status>
    where
        ChanParamMutator: Fn(&mut ChanParamMutationState),
        KeysMutator: Fn(&mut KeysMutationState),
        TxMutator: Fn(&mut TxMutationState),
    {
        let mut setup = make_test_channel_setup();
        setup.commitment_type = commitment_type;
        let (node, channel_id) =
            init_node_and_channel(TEST_NODE_CONFIG, TEST_SEED[1], setup.clone());

        let commit_num = 23;
        let htlc_amount_sat = 1_000_000;

        let (typedsig, per_commitment_point, htlc_tx, htlc_redeemscript) =
            node.with_channel(&channel_id, |chan| {
                chan.enforcement_state.set_next_holder_commit_num_for_testing(commit_num);
                let mut channel_parameters = chan.make_channel_parameters();

                // Mutate the channel parameters
                chanparammut(&mut ChanParamMutationState {
                    is_counterparty: false,
                    param: &mut channel_parameters,
                });

                let per_commitment_point =
                    chan.get_per_commitment_point(commit_num).expect("point");
                let mut keys = chan.make_holder_tx_keys(&per_commitment_point);

                // Mutate the tx creation keys.
                keysmut(&mut KeysMutationState { keys: &mut keys });

                let commitment_txid = bitcoin::Txid::from_slice(&[2u8; 32]).unwrap();
                let feerate_per_kw = 1000;
                let to_self_delay = channel_parameters.as_holder_broadcastable().contest_delay();

                let htlc = HTLCOutputInCommitment {
                    offered: is_offered,
                    amount_msat: htlc_amount_sat * 1000,
                    cltv_expiry: if is_offered { 2 << 16 } else { 0 },
                    payment_hash: PaymentHash([1; 32]),
                    transaction_output_index: Some(0),
                };

                let build_feerate = if setup.is_zero_fee_htlc() { 0 } else { feerate_per_kw };

                let mut htlc_tx = build_htlc_transaction(
                    &commitment_txid,
                    build_feerate,
                    to_self_delay,
                    &htlc,
                    &setup.features(),
                    &keys.broadcaster_delayed_payment_key,
                    &keys.revocation_key,
                );

                let mut cstate = make_test_chain_state();

                // Mutate the transaction.
                txmut(&mut TxMutationState { is_offered, cstate: &mut cstate, tx: &mut htlc_tx });

                let htlc_redeemscript = get_htlc_redeemscript(&htlc, &setup.features(), &keys);

                let output_witscript = get_revokeable_redeemscript(
                    &keys.revocation_key,
                    to_self_delay,
                    &keys.broadcaster_delayed_payment_key,
                );

                let typedsig = chan.sign_holder_htlc_tx(
                    &htlc_tx,
                    commit_num,
                    Some(per_commitment_point),
                    &htlc_redeemscript,
                    htlc_amount_sat,
                    &output_witscript,
                )?;
                Ok((typedsig, per_commitment_point, htlc_tx, htlc_redeemscript))
            })?;

        let expected_txid = if commitment_type == CommitmentType::StaticRemoteKey {
            if is_offered {
                "7358f246581726b4b5f51e361fb53e7ac23b46d05291ec9ed145835124291fe3"
            } else {
                "fd07a2d0bb62a2d6d64442e4ebb2208c0a64cee4a9727f02f457f26975960892"
            }
        } else if commitment_type == CommitmentType::AnchorsZeroFeeHtlc {
            if is_offered {
                "773b5faac142596f0aa385eba80e8abf44989528969763e8d8af2b4320644fa8"
            } else {
                "9e1c3501edc7490d1a04c848dbe1a2a988d977a54d287e294e03e4ac5947b1b2"
            }
        } else {
            panic!("unknown commitment_type");
        };
        assert_eq!(htlc_tx.compute_txid().to_string(), expected_txid);

        let htlc_pubkey = get_channel_htlc_pubkey(&node, &channel_id, &per_commitment_point);

        let sighash_type = if commitment_type == CommitmentType::StaticRemoteKey {
            EcdsaSighashType::All
        } else {
            EcdsaSighashType::SinglePlusAnyoneCanPay
        };
        check_signature_with_sighash_type(
            &htlc_tx,
            0,
            typedsig,
            &htlc_pubkey,
            htlc_amount_sat,
            &htlc_redeemscript,
            sighash_type,
        );

        Ok(())
    }

    macro_rules! generate_status_ok_variations {
        ($name: ident, $pm: expr, $km: expr, $tm: expr) => {
            paste! {
                #[test]
                fn [<$name _holder_received_static>]() {
                    assert_status_ok!(
                        sign_holder_htlc_tx_with_mutators(
                            false, CommitmentType::StaticRemoteKey, $pm, $km, $tm)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _holder_offered_static>]() {
                    assert_status_ok!(
                        sign_holder_htlc_tx_with_mutators(
                            true, CommitmentType::StaticRemoteKey, $pm, $km, $tm)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _counterparty_received_static>]() {
                    assert_status_ok!(
                        sign_counterparty_htlc_tx_with_mutators(
                            false, CommitmentType::StaticRemoteKey, $pm, $km, $tm)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _counterparty_offered_static>]() {
                    assert_status_ok!(
                        sign_counterparty_htlc_tx_with_mutators(
                            true, CommitmentType::StaticRemoteKey, $pm, $km, $tm)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _holder_received_zerofee>]() {
                    assert_status_ok!(
                        sign_holder_htlc_tx_with_mutators(
                            false, CommitmentType::AnchorsZeroFeeHtlc, $pm, $km, $tm)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _holder_offered_zerofee>]() {
                    assert_status_ok!(
                        sign_holder_htlc_tx_with_mutators(
                            true, CommitmentType::AnchorsZeroFeeHtlc, $pm, $km, $tm)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _counterparty_received_zerofee>]() {
                    assert_status_ok!(
                        sign_counterparty_htlc_tx_with_mutators(
                            false, CommitmentType::AnchorsZeroFeeHtlc, $pm, $km, $tm)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _counterparty_offered_zerofee>]() {
                    assert_status_ok!(
                        sign_counterparty_htlc_tx_with_mutators(
                            true, CommitmentType::AnchorsZeroFeeHtlc, $pm, $km, $tm)
                    );
                }
            }
        };
    }

    generate_status_ok_variations!(success, |_| {}, |_| {}, |_| {});

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

    const ERR_MSG_CONTEXT_HOLDER_RECEIVED_STATIC: ErrMsgContext = ErrMsgContext {
        is_counterparty: false,
        is_offered: false,
        opt_anchors: false,
        opt_zerofee: false,
    };
    const ERR_MSG_CONTEXT_HOLDER_OFFERED_STATIC: ErrMsgContext = ErrMsgContext {
        is_counterparty: false,
        is_offered: true,
        opt_anchors: false,
        opt_zerofee: false,
    };
    const ERR_MSG_CONTEXT_CPARTY_RECEIVED_STATIC: ErrMsgContext = ErrMsgContext {
        is_counterparty: true,
        is_offered: false,
        opt_anchors: false,
        opt_zerofee: false,
    };
    const ERR_MSG_CONTEXT_CPARTY_OFFERED_STATIC: ErrMsgContext = ErrMsgContext {
        is_counterparty: true,
        is_offered: true,
        opt_anchors: false,
        opt_zerofee: false,
    };
    const ERR_MSG_CONTEXT_HOLDER_RECEIVED_ZEROFEE: ErrMsgContext = ErrMsgContext {
        is_counterparty: false,
        is_offered: false,
        opt_anchors: true,
        opt_zerofee: true,
    };
    const ERR_MSG_CONTEXT_HOLDER_OFFERED_ZEROFEE: ErrMsgContext = ErrMsgContext {
        is_counterparty: false,
        is_offered: true,
        opt_anchors: true,
        opt_zerofee: true,
    };
    const ERR_MSG_CONTEXT_CPARTY_RECEIVED_ZEROFEE: ErrMsgContext = ErrMsgContext {
        is_counterparty: true,
        is_offered: false,
        opt_anchors: true,
        opt_zerofee: true,
    };
    const ERR_MSG_CONTEXT_CPARTY_OFFERED_ZEROFEE: ErrMsgContext = ErrMsgContext {
        is_counterparty: true,
        is_offered: true,
        opt_anchors: true,
        opt_zerofee: true,
    };

    macro_rules! generate_failed_precondition_error_variations {
        ($name: ident, $pm: expr, $km: expr, $tm: expr, $errcls: expr) => {
            paste! {
                #[test]
                fn [<$name _holder_received_static>]() {
                    assert_failed_precondition_err!(
                        sign_holder_htlc_tx_with_mutators(
                            false, CommitmentType::StaticRemoteKey, $pm, $km, $tm),
                        ($errcls)(ERR_MSG_CONTEXT_HOLDER_RECEIVED_STATIC)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _holder_offered_static>]() {
                    assert_failed_precondition_err!(
                        sign_holder_htlc_tx_with_mutators(
                            true, CommitmentType::StaticRemoteKey, $pm, $km, $tm),
                        ($errcls)(ERR_MSG_CONTEXT_HOLDER_OFFERED_STATIC)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _counterparty_received_static>]() {
                    assert_failed_precondition_err!(
                        sign_counterparty_htlc_tx_with_mutators(
                            false, CommitmentType::StaticRemoteKey, $pm, $km, $tm),
                        ($errcls)(ERR_MSG_CONTEXT_CPARTY_RECEIVED_STATIC)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _counterparty_offered_static>]() {
                    assert_failed_precondition_err!(
                        sign_counterparty_htlc_tx_with_mutators(
                            true, CommitmentType::StaticRemoteKey, $pm, $km, $tm),
                        ($errcls)(ERR_MSG_CONTEXT_CPARTY_OFFERED_STATIC)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _holder_received_zerofee>]() {
                    assert_failed_precondition_err!(
                        sign_holder_htlc_tx_with_mutators(
                            false, CommitmentType::AnchorsZeroFeeHtlc, $pm, $km, $tm),
                        ($errcls)(ERR_MSG_CONTEXT_HOLDER_RECEIVED_ZEROFEE)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _holder_offered_zerofee>]() {
                    assert_failed_precondition_err!(
                        sign_holder_htlc_tx_with_mutators(
                            true, CommitmentType::AnchorsZeroFeeHtlc, $pm, $km, $tm),
                        ($errcls)(ERR_MSG_CONTEXT_HOLDER_OFFERED_ZEROFEE)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _counterparty_received_zerofee>]() {
                    assert_failed_precondition_err!(
                        sign_counterparty_htlc_tx_with_mutators(
                            false, CommitmentType::AnchorsZeroFeeHtlc, $pm, $km, $tm),
                        ($errcls)(ERR_MSG_CONTEXT_CPARTY_RECEIVED_ZEROFEE)
                    );
                }
            }
            paste! {
                #[test]
                fn [<$name _counterparty_offered_zerofee>]() {
                    assert_failed_precondition_err!(
                        sign_counterparty_htlc_tx_with_mutators(
                            true, CommitmentType::AnchorsZeroFeeHtlc, $pm, $km, $tm),
                        ($errcls)(ERR_MSG_CONTEXT_CPARTY_OFFERED_ZEROFEE)
                    );
                }
            }
        };
    }

    macro_rules! generate_failed_precondition_error_with_mutated_param {
        ($name: ident, $pm: expr, $errmsg: expr) => {
            generate_failed_precondition_error_variations!($name, $pm, |_| {}, |_| {}, $errmsg);
        };
    }

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

    macro_rules! generate_failed_precondition_error_with_mutated_tx {
        ($name: ident, $tm: expr, $errmsg: expr) => {
            generate_failed_precondition_error_variations!($name, |_| {}, |_| {}, $tm, $errmsg);
        };
    }

    // policy-htlc-version
    generate_failed_precondition_error_with_mutated_tx!(
        bad_version,
        |tms| tms.tx.version = Version::non_standard(3), // only version 2 allowed
        |_| "policy failure: sighash mismatch"
    );

    // policy-htlc-locktime
    generate_failed_precondition_error_with_mutated_tx!(
        bad_locktime,
        |tms| {
            // offered must have non-zero, received must have zero
            tms.tx.lock_time = LockTime::Blocks(
                Height::from_consensus(if tms.is_offered { 0 } else { 42 }).unwrap(),
            );
        },
        |ectx: ErrMsgContext| {
            if ectx.is_offered {
                "policy failure: validate_htlc_tx: offered lock_time must be non-zero"
            } else {
                "policy failure: sighash mismatch"
            }
        }
    );

    // policy-htlc-sequence
    generate_failed_precondition_error_with_mutated_tx!(
        bad_sequence,
        |tms| tms.tx.input[0].sequence = Sequence(42), // sequence must be per BOLT#3
        |_| "policy failure: sighash mismatch"
    );

    // policy-htlc-to-self-delay
    generate_failed_precondition_error_with_mutated_param!(
        bad_to_self_delay,
        |pms| {
            if pms.is_counterparty {
                pms.param.holder_selected_contest_delay = 42;
            } else {
                let mut cptp = pms.param.counterparty_parameters.as_ref().unwrap().clone();
                cptp.selected_contest_delay = 42;
                pms.param.counterparty_parameters = Some(cptp);
            }
        },
        |_| "policy failure: sighash mismatch"
    );

    // policy-htlc-revocation-pubkey
    generate_failed_precondition_error_with_mutated_keys!(
        bad_revpubkey,
        |kms| kms.keys.revocation_key = RevocationKey(make_test_pubkey(42)),
        |_| "policy failure: sighash mismatch"
    );

    // policy-htlc-delayed-pubkey
    generate_failed_precondition_error_with_mutated_keys!(
        bad_delayedpubkey,
        |kms| kms.keys.broadcaster_delayed_payment_key = DelayedPaymentKey(make_test_pubkey(42)),
        |_| "policy failure: sighash mismatch"
    );

    // policy-htlc-fee-range
    generate_failed_precondition_error_with_mutated_tx!(
        low_feerate,
        |tms| tms.tx.output[0].value = Amount::from_sat(999_885), // htlc_amount_sat is 1_000_000
        |ectx: ErrMsgContext| {
            if ectx.opt_zerofee {
                // zero-fee fails sooner, because we don't estimate_feerate_per_kw so the recomposed
                // tx does not match.
                "policy failure: sighash mismatch".to_string()
            } else {
                if ectx.is_offered {
                    format!(
                        "policy failure: validate_htlc_tx: \
                     feerate_per_kw of {} is smaller than the minimum of 253",
                        if ectx.opt_anchors { 174 } else { 174 }
                    )
                } else {
                    format!(
                        "policy failure: validate_htlc_tx: \
                     feerate_per_kw of {} is smaller than the minimum of 253",
                        if ectx.opt_anchors { 164 } else { 165 }
                    )
                }
            }
        }
    );

    // policy-htlc-fee-range
    generate_failed_precondition_error_with_mutated_tx!(
        high_feerate,
        |tms| tms.tx.output[0].value = Amount::from_sat(660_000), // htlc_amount_sat is 1_000_000
        |ectx: ErrMsgContext| {
            if ectx.opt_zerofee {
                // zero-fee fails sooner, because we don't estimate_feerate_per_kw so the recomposed
                // tx does not match.
                "policy failure: sighash mismatch".to_string()
            } else {
                if ectx.is_offered {
                    format!(
                        "policy failure: validate_htlc_tx: \
                     feerate_per_kw of {} is larger than the maximum of 333333",
                        512822
                    )
                } else {
                    format!(
                        "policy failure: validate_htlc_tx: \
                     feerate_per_kw of {} is larger than the maximum of 333333",
                        483642
                    )
                }
            }
        }
    );
}