forked from lightningdevkit/rust-lightning
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmod.rs
More file actions
2733 lines (2519 loc) · 105 KB
/
mod.rs
File metadata and controls
2733 lines (2519 loc) · 105 KB
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
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! Provides keys to LDK and defines some useful objects describing spendable on-chain outputs.
//!
//! The provided output descriptors follow a custom LDK data format and are currently not fully
//! compatible with Bitcoin Core output descriptors.
use bitcoin::amount::Amount;
use bitcoin::bip32::{ChildNumber, Xpriv, Xpub};
use bitcoin::ecdsa::Signature as EcdsaSignature;
use bitcoin::locktime::absolute::LockTime;
use bitcoin::network::Network;
use bitcoin::opcodes;
use bitcoin::script::{Builder, Script, ScriptBuf};
use bitcoin::sighash;
use bitcoin::sighash::EcdsaSighashType;
use bitcoin::transaction::Version;
use bitcoin::transaction::{Transaction, TxIn, TxOut};
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::hashes::sha256d::Hash as Sha256dHash;
use bitcoin::hashes::{Hash, HashEngine};
use bitcoin::secp256k1::ecdh::SharedSecret;
use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
use bitcoin::secp256k1::schnorr;
use bitcoin::secp256k1::All;
use bitcoin::secp256k1::{Keypair, PublicKey, Scalar, Secp256k1, SecretKey, Signing};
use bitcoin::{secp256k1, Psbt, Sequence, Txid, WPubkeyHash, Witness};
use lightning_invoice::RawBolt11Invoice;
use crate::chain::transaction::OutPoint;
use crate::crypto::utils::{hkdf_extract_expand_twice, sign, sign_with_aux_rand};
use crate::ln::chan_utils;
use crate::ln::chan_utils::{
get_countersigner_payment_script, get_revokeable_redeemscript, make_funding_redeemscript,
ChannelPublicKeys, ChannelTransactionParameters, ClosingTransaction, CommitmentTransaction,
HTLCOutputInCommitment, HolderCommitmentTransaction,
};
use crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI;
use crate::ln::channel_keys::{
add_public_key_tweak, DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, HtlcKey,
RevocationBasepoint, RevocationKey,
};
use crate::ln::inbound_payment::ExpandedKey;
#[cfg(taproot)]
use crate::ln::msgs::PartialSignatureWithNonce;
use crate::ln::msgs::{UnsignedChannelAnnouncement, UnsignedGossipMessage};
use crate::ln::script::ShutdownScript;
use crate::offers::invoice::UnsignedBolt12Invoice;
use crate::types::features::ChannelTypeFeatures;
use crate::types::payment::PaymentPreimage;
use crate::util::async_poll::AsyncResult;
use crate::util::ser::{ReadableArgs, Writeable};
use crate::util::transaction_utils;
use crate::crypto::chacha20::ChaCha20;
use crate::prelude::*;
use crate::sign::ecdsa::EcdsaChannelSigner;
#[cfg(taproot)]
use crate::sign::taproot::TaprootChannelSigner;
use crate::util::atomic_counter::AtomicCounter;
use core::convert::TryInto;
use core::ops::Deref;
use core::sync::atomic::{AtomicUsize, Ordering};
#[cfg(taproot)]
use musig2::types::{PartialSignature, PublicNonce};
pub(crate) mod type_resolver;
pub mod ecdsa;
#[cfg(taproot)]
pub mod taproot;
pub mod tx_builder;
/// Information about a spendable output to a P2WSH script.
///
/// See [`SpendableOutputDescriptor::DelayedPaymentOutput`] for more details on how to spend this.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct DelayedPaymentOutputDescriptor {
/// The outpoint which is spendable.
pub outpoint: OutPoint,
/// Per commitment point to derive the delayed payment key by key holder.
pub per_commitment_point: PublicKey,
/// The `nSequence` value which must be set in the spending input to satisfy the `OP_CSV` in
/// the witness_script.
pub to_self_delay: u16,
/// The output which is referenced by the given outpoint.
pub output: TxOut,
/// The revocation point specific to the commitment transaction which was broadcast. Used to
/// derive the witnessScript for this output.
pub revocation_pubkey: RevocationKey,
/// Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`].
/// This may be useful in re-deriving keys used in the channel to spend the output.
pub channel_keys_id: [u8; 32],
/// The value of the channel which this output originated from, possibly indirectly.
pub channel_value_satoshis: u64,
/// The channel public keys and other parameters needed to generate a spending transaction or
/// to provide to a signer.
///
/// Added as optional, but always `Some` if the descriptor was produced in v0.0.123 or later.
pub channel_transaction_parameters: Option<ChannelTransactionParameters>,
}
impl DelayedPaymentOutputDescriptor {
/// The maximum length a well-formed witness spending one of these should have.
/// Note: If you have the grind_signatures feature enabled, this will be at least 1 byte
/// shorter.
// Calculated as 1 byte length + 73 byte signature, 1 byte empty vec push, 1 byte length plus
// redeemscript push length.
pub const MAX_WITNESS_LENGTH: u64 =
1 + 73 + 1 + chan_utils::REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH as u64 + 1;
}
impl_writeable_tlv_based!(DelayedPaymentOutputDescriptor, {
(0, outpoint, required),
(2, per_commitment_point, required),
(4, to_self_delay, required),
(6, output, required),
(8, revocation_pubkey, required),
(10, channel_keys_id, required),
(12, channel_value_satoshis, required),
(13, channel_transaction_parameters, (option: ReadableArgs, Some(channel_value_satoshis.0.unwrap()))),
});
pub(crate) const P2WPKH_WITNESS_WEIGHT: u64 = 1 /* num stack items */ +
1 /* sig length */ +
73 /* sig including sighash flag */ +
1 /* pubkey length */ +
33 /* pubkey */;
/// Witness weight for satisying a P2TR key-path spend.
pub(crate) const P2TR_KEY_PATH_WITNESS_WEIGHT: u64 = 1 /* witness items */
+ 1 /* schnorr sig len */ + 64 /* schnorr sig */;
/// If a [`KeysManager`] is built with [`KeysManager::new`] with `v2_remote_key_derivation` set
/// (and for all channels after they've been spliced), the script which we receive funds to on-chain
/// when our counterparty force-closes a channel is one of this many possible derivation paths.
///
/// Keeping this limited allows for scanning the chain to find lost funds if our state is destroyed,
/// while this being more than a handful provides some privacy by not constantly reusing the same
/// scripts on-chain across channels.
// Note that this MUST remain below the maximum BIP 32 derivation paths (2^31)
pub const STATIC_PAYMENT_KEY_COUNT: u16 = 1000;
/// Information about a spendable output to our "payment key".
///
/// See [`SpendableOutputDescriptor::StaticPaymentOutput`] for more details on how to spend this.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct StaticPaymentOutputDescriptor {
/// The outpoint which is spendable.
pub outpoint: OutPoint,
/// The output which is referenced by the given outpoint.
pub output: TxOut,
/// Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`].
/// This may be useful in re-deriving keys used in the channel to spend the output.
pub channel_keys_id: [u8; 32],
/// The value of the channel which this transactions spends.
pub channel_value_satoshis: u64,
/// The necessary channel parameters that need to be provided to the signer.
///
/// Added as optional, but always `Some` if the descriptor was produced in v0.0.117 or later.
pub channel_transaction_parameters: Option<ChannelTransactionParameters>,
}
impl StaticPaymentOutputDescriptor {
/// Returns the `witness_script` of the spendable output.
///
/// Note that this will only return `Some` for [`StaticPaymentOutputDescriptor`]s that
/// originated from an anchor outputs channel, as they take the form of a P2WSH script.
pub fn witness_script(&self) -> Option<ScriptBuf> {
self.channel_transaction_parameters.as_ref().and_then(|channel_params| {
if channel_params.channel_type_features.supports_anchors_zero_fee_htlc_tx() {
let payment_point = channel_params.holder_pubkeys.payment_point;
Some(chan_utils::get_to_countersigner_keyed_anchor_redeemscript(&payment_point))
} else {
None
}
})
}
/// The maximum length a well-formed witness spending one of these should have.
/// Note: If you have the grind_signatures feature enabled, this will be at least 1 byte
/// shorter.
pub fn max_witness_length(&self) -> u64 {
if self.needs_csv_1_for_spend() {
let witness_script_weight = 1 /* pubkey push */ + 33 /* pubkey */ +
1 /* OP_CHECKSIGVERIFY */ + 1 /* OP_1 */ + 1 /* OP_CHECKSEQUENCEVERIFY */;
1 /* num witness items */ + 1 /* sig push */ + 73 /* sig including sighash flag */ +
1 /* witness script push */ + witness_script_weight
} else {
P2WPKH_WITNESS_WEIGHT
}
}
/// Returns true if spending this output requires a transaction with a CheckSequenceVerify
/// value of at least 1.
pub fn needs_csv_1_for_spend(&self) -> bool {
let chan_params = self.channel_transaction_parameters.as_ref();
chan_params.is_some_and(|p| p.channel_type_features.supports_anchors_zero_fee_htlc_tx())
}
}
impl_writeable_tlv_based!(StaticPaymentOutputDescriptor, {
(0, outpoint, required),
(2, output, required),
(4, channel_keys_id, required),
(6, channel_value_satoshis, required),
(7, channel_transaction_parameters, (option: ReadableArgs, Some(channel_value_satoshis.0.unwrap()))),
});
/// Describes the necessary information to spend a spendable output.
///
/// When on-chain outputs are created by LDK (which our counterparty is not able to claim at any
/// point in the future) a [`SpendableOutputs`] event is generated which you must track and be able
/// to spend on-chain. The information needed to do this is provided in this enum, including the
/// outpoint describing which `txid` and output `index` is available, the full output which exists
/// at that `txid`/`index`, and any keys or other information required to sign.
///
/// [`SpendableOutputs`]: crate::events::Event::SpendableOutputs
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub enum SpendableOutputDescriptor {
/// An output to a script which was provided via [`SignerProvider`] directly, either from
/// [`get_destination_script`] or [`get_shutdown_scriptpubkey`], thus you should already
/// know how to spend it. No secret keys are provided as LDK was never given any key.
/// These may include outputs from a transaction punishing our counterparty or claiming an HTLC
/// on-chain using the payment preimage or after it has timed out.
///
/// [`get_shutdown_scriptpubkey`]: SignerProvider::get_shutdown_scriptpubkey
/// [`get_destination_script`]: SignerProvider::get_shutdown_scriptpubkey
StaticOutput {
/// The outpoint which is spendable.
outpoint: OutPoint,
/// The output which is referenced by the given outpoint.
output: TxOut,
/// The `channel_keys_id` for the channel which this output came from.
///
/// For channels which were generated on LDK 0.0.119 or later, this is the value which was
/// passed to the [`SignerProvider::get_destination_script`] call which provided this
/// output script.
///
/// For channels which were generated prior to LDK 0.0.119, no such argument existed,
/// however this field may still be filled in if such data is available.
channel_keys_id: Option<[u8; 32]>,
},
/// An output to a P2WSH script which can be spent with a single signature after an `OP_CSV`
/// delay.
///
/// The witness in the spending input should be:
/// ```bitcoin
/// <BIP 143 signature> <empty vector> (MINIMALIF standard rule) <provided witnessScript>
/// ```
///
/// Note that the `nSequence` field in the spending input must be set to
/// [`DelayedPaymentOutputDescriptor::to_self_delay`] (which means the transaction is not
/// broadcastable until at least [`DelayedPaymentOutputDescriptor::to_self_delay`] blocks after
/// the outpoint confirms, see [BIP
/// 68](https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki)). Also note that LDK
/// won't generate a [`SpendableOutputDescriptor`] until the corresponding block height
/// is reached.
///
/// These are generally the result of a "revocable" output to us, spendable only by us unless
/// it is an output from an old state which we broadcast (which should never happen).
///
/// To derive the delayed payment key which is used to sign this input, you must pass the
/// holder [`InMemorySigner::delayed_payment_base_key`] (i.e., the private key which
/// corresponds to the [`ChannelPublicKeys::delayed_payment_basepoint`] in
/// [`ChannelSigner::pubkeys`]) and the provided
/// [`DelayedPaymentOutputDescriptor::per_commitment_point`] to
/// [`chan_utils::derive_private_key`]. The DelayedPaymentKey can be generated without the
/// secret key using [`DelayedPaymentKey::from_basepoint`] and only the
/// [`ChannelPublicKeys::delayed_payment_basepoint`] which appears in
/// [`ChannelSigner::pubkeys`].
///
/// To derive the [`DelayedPaymentOutputDescriptor::revocation_pubkey`] provided here (which is
/// used in the witness script generation), you must pass the counterparty
/// [`ChannelPublicKeys::revocation_basepoint`] and the provided
/// [`DelayedPaymentOutputDescriptor::per_commitment_point`] to
/// [`RevocationKey`].
///
/// The witness script which is hashed and included in the output `script_pubkey` may be
/// regenerated by passing the [`DelayedPaymentOutputDescriptor::revocation_pubkey`] (derived
/// as explained above), our delayed payment pubkey (derived as explained above), and the
/// [`DelayedPaymentOutputDescriptor::to_self_delay`] contained here to
/// [`chan_utils::get_revokeable_redeemscript`].
DelayedPaymentOutput(DelayedPaymentOutputDescriptor),
/// An output spendable exclusively by our payment key (i.e., the private key that corresponds
/// to the `payment_point` in [`ChannelSigner::pubkeys`]). The output type depends on the
/// channel type negotiated.
///
/// On an anchor outputs channel, the witness in the spending input is:
/// ```bitcoin
/// <BIP 143 signature> <witness script>
/// ```
///
/// Otherwise, it is:
/// ```bitcoin
/// <BIP 143 signature> <payment key>
/// ```
///
/// These are generally the result of our counterparty having broadcast the current state,
/// allowing us to claim the non-HTLC-encumbered outputs immediately, or after one confirmation
/// in the case of anchor outputs channels.
StaticPaymentOutput(StaticPaymentOutputDescriptor),
}
impl_writeable_tlv_based_enum_legacy!(SpendableOutputDescriptor,
(0, StaticOutput) => {
(0, outpoint, required),
(1, channel_keys_id, option),
(2, output, required),
},
;
(1, DelayedPaymentOutput),
(2, StaticPaymentOutput),
);
impl SpendableOutputDescriptor {
/// Turns this into a [`bitcoin::psbt::Input`] which can be used to create a
/// [`Psbt`] which spends the given descriptor.
///
/// Note that this does not include any signatures, just the information required to
/// construct the transaction and sign it.
///
/// This is not exported to bindings users as there is no standard serialization for an input.
/// See [`Self::create_spendable_outputs_psbt`] instead.
///
/// The proprietary field is used to store add tweak for the signing key of this transaction.
/// See the [`DelayedPaymentBasepoint::derive_add_tweak`] docs for more info on add tweak and how to use it.
///
/// To get the proprietary field use:
/// ```
/// use bitcoin::psbt::{Psbt};
/// use bitcoin::hex::FromHex;
///
/// # let s = "70736274ff0100520200000001dee978529ab3e61a2987bea5183713d0e6d5ceb5ac81100fdb54a1a2\
/// # 69cef505000000000090000000011f26000000000000160014abb3ab63280d4ccc5c11d6b50fd427a8\
/// # e19d6470000000000001012b10270000000000002200200afe4736760d814a2651bae63b572d935d9a\
/// # b74a1a16c01774e341a32afa763601054d63210394a27a700617f5b7aee72bd4f8076b5770a582b7fb\
/// # d1d4ee2ea3802cd3cfbe2067029000b27521034629b1c8fdebfaeb58a74cd181f485e2c462e594cb30\
/// # 34dee655875f69f6c7c968ac20fc144c444b5f7370656e6461626c655f6f7574707574006164645f74\
/// # 7765616b20a86534f38ad61dc580ef41c3886204adf0911b81619c1ad7a2f5b5de39a2ba600000";
/// # let psbt = Psbt::deserialize(<Vec<u8> as FromHex>::from_hex(s).unwrap().as_slice()).unwrap();
/// let key = bitcoin::psbt::raw::ProprietaryKey {
/// prefix: "LDK_spendable_output".as_bytes().to_vec(),
/// subtype: 0,
/// key: "add_tweak".as_bytes().to_vec(),
/// };
/// let value = psbt
/// .inputs
/// .first()
/// .expect("Unable to get add tweak as there are no inputs")
/// .proprietary
/// .get(&key)
/// .map(|x| x.to_owned());
/// ```
pub fn to_psbt_input<T: secp256k1::Signing>(
&self, secp_ctx: &Secp256k1<T>,
) -> bitcoin::psbt::Input {
match self {
SpendableOutputDescriptor::StaticOutput { output, .. } => {
// Is a standard P2WPKH, no need for witness script
bitcoin::psbt::Input { witness_utxo: Some(output.clone()), ..Default::default() }
},
SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
channel_transaction_parameters,
per_commitment_point,
revocation_pubkey,
to_self_delay,
output,
..
}) => {
let delayed_payment_basepoint = channel_transaction_parameters
.as_ref()
.map(|params| params.holder_pubkeys.delayed_payment_basepoint);
let (witness_script, add_tweak) =
if let Some(basepoint) = delayed_payment_basepoint.as_ref() {
// Required to derive signing key: privkey = basepoint_secret + SHA256(per_commitment_point || basepoint)
let add_tweak = basepoint.derive_add_tweak(&per_commitment_point);
let delayed_payment_key = DelayedPaymentKey(add_public_key_tweak(
secp_ctx,
&basepoint.to_public_key(),
&add_tweak,
));
(
Some(get_revokeable_redeemscript(
&revocation_pubkey,
*to_self_delay,
&delayed_payment_key,
)),
Some(add_tweak),
)
} else {
(None, None)
};
bitcoin::psbt::Input {
witness_utxo: Some(output.clone()),
witness_script,
proprietary: add_tweak
.map(|add_tweak| {
[(
bitcoin::psbt::raw::ProprietaryKey {
// A non standard namespace for spendable outputs, used to store the tweak needed
// to derive the private key
prefix: "LDK_spendable_output".as_bytes().to_vec(),
subtype: 0,
key: "add_tweak".as_bytes().to_vec(),
},
add_tweak.as_byte_array().to_vec(),
)]
.into_iter()
.collect()
})
.unwrap_or_default(),
..Default::default()
}
},
SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => bitcoin::psbt::Input {
witness_utxo: Some(descriptor.output.clone()),
witness_script: descriptor.witness_script(),
..Default::default()
},
}
}
/// Creates an unsigned [`Psbt`] which spends the given descriptors to
/// the given outputs, plus an output to the given change destination (if sufficient
/// change value remains). The PSBT will have a feerate, at least, of the given value.
///
/// The `locktime` argument is used to set the transaction's locktime. If `None`, the
/// transaction will have a locktime of 0. It it recommended to set this to the current block
/// height to avoid fee sniping, unless you have some specific reason to use a different
/// locktime.
///
/// Returns the PSBT and expected max transaction weight.
///
/// Returns `Err(())` if the output value is greater than the input value minus required fee,
/// if a descriptor was duplicated, or if an output descriptor `script_pubkey`
/// does not match the one we can spend.
///
/// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
pub fn create_spendable_outputs_psbt<T: secp256k1::Signing>(
secp_ctx: &Secp256k1<T>, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
locktime: Option<LockTime>,
) -> Result<(Psbt, u64), ()> {
let mut input = Vec::with_capacity(descriptors.len());
let mut input_value = Amount::ZERO;
let mut witness_weight = 0;
let mut output_set = hash_set_with_capacity(descriptors.len());
for outp in descriptors {
match outp {
SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
if !output_set.insert(descriptor.outpoint) {
return Err(());
}
let sequence = if descriptor.needs_csv_1_for_spend() {
Sequence::from_consensus(1)
} else {
Sequence::ZERO
};
input.push(TxIn {
previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
script_sig: ScriptBuf::new(),
sequence,
witness: Witness::new(),
});
witness_weight += descriptor.max_witness_length();
#[cfg(feature = "grind_signatures")]
{
// Guarantees a low R signature
witness_weight -= 1;
}
input_value += descriptor.output.value;
},
SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
if !output_set.insert(descriptor.outpoint) {
return Err(());
}
input.push(TxIn {
previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
script_sig: ScriptBuf::new(),
sequence: Sequence(descriptor.to_self_delay as u32),
witness: Witness::new(),
});
witness_weight += DelayedPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
#[cfg(feature = "grind_signatures")]
{
// Guarantees a low R signature
witness_weight -= 1;
}
input_value += descriptor.output.value;
},
SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => {
if !output_set.insert(*outpoint) {
return Err(());
}
input.push(TxIn {
previous_output: outpoint.into_bitcoin_outpoint(),
script_sig: ScriptBuf::new(),
sequence: Sequence::ZERO,
witness: Witness::new(),
});
witness_weight += 1 + 73 + 34;
#[cfg(feature = "grind_signatures")]
{
// Guarantees a low R signature
witness_weight -= 1;
}
input_value += output.value;
},
}
if input_value > Amount::MAX_MONEY {
return Err(());
}
}
let mut tx = Transaction {
version: Version::TWO,
lock_time: locktime.unwrap_or(LockTime::ZERO),
input,
output: outputs,
};
let expected_max_weight = transaction_utils::maybe_add_change_output(
&mut tx,
input_value,
witness_weight,
feerate_sat_per_1000_weight,
change_destination_script,
)?;
let psbt_inputs =
descriptors.iter().map(|d| d.to_psbt_input(&secp_ctx)).collect::<Vec<_>>();
let psbt = Psbt {
inputs: psbt_inputs,
outputs: vec![Default::default(); tx.output.len()],
unsigned_tx: tx,
xpub: Default::default(),
version: 0,
proprietary: Default::default(),
unknown: Default::default(),
};
Ok((psbt, expected_max_weight))
}
/// Returns the outpoint of the spendable output.
pub fn spendable_outpoint(&self) -> OutPoint {
match self {
Self::StaticOutput { outpoint, .. } => *outpoint,
Self::StaticPaymentOutput(descriptor) => descriptor.outpoint,
Self::DelayedPaymentOutput(descriptor) => descriptor.outpoint,
}
}
}
/// The parameters required to derive a channel signer via [`SignerProvider`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ChannelDerivationParameters {
/// The value in satoshis of the channel we're attempting to spend the anchor output of.
pub value_satoshis: u64,
/// The unique identifier to re-derive the signer for the associated channel.
pub keys_id: [u8; 32],
/// The necessary channel parameters that need to be provided to the signer.
pub transaction_parameters: ChannelTransactionParameters,
}
impl_writeable_tlv_based!(ChannelDerivationParameters, {
(0, value_satoshis, required),
(2, keys_id, required),
(4, transaction_parameters, (required: ReadableArgs, Some(value_satoshis.0.unwrap()))),
});
/// A descriptor used to sign for a commitment transaction's HTLC output.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HTLCDescriptor {
/// The parameters required to derive the signer for the HTLC input.
pub channel_derivation_parameters: ChannelDerivationParameters,
/// The txid of the commitment transaction in which the HTLC output lives.
pub commitment_txid: Txid,
/// The number of the commitment transaction in which the HTLC output lives.
pub per_commitment_number: u64,
/// The key tweak corresponding to the number of the commitment transaction in which the HTLC
/// output lives. This tweak is applied to all the basepoints for both parties in the channel to
/// arrive at unique keys per commitment.
///
/// See <https://github.com/lightning/bolts/blob/master/03-transactions.md#keys> for more info.
pub per_commitment_point: PublicKey,
/// The feerate to use on the HTLC claiming transaction. This is always `0` for HTLCs
/// originating from a channel supporting anchor outputs, otherwise it is the channel's
/// negotiated feerate at the time the commitment transaction was built.
pub feerate_per_kw: u32,
/// The details of the HTLC as it appears in the commitment transaction.
pub htlc: HTLCOutputInCommitment,
/// The preimage, if `Some`, to claim the HTLC output with. If `None`, the timeout path must be
/// taken.
pub preimage: Option<PaymentPreimage>,
/// The counterparty's signature required to spend the HTLC output.
pub counterparty_sig: Signature,
}
impl_writeable_tlv_based!(HTLCDescriptor, {
(0, channel_derivation_parameters, required),
(1, feerate_per_kw, (default_value, 0)),
(2, commitment_txid, required),
(4, per_commitment_number, required),
(6, per_commitment_point, required),
(8, htlc, required),
(10, preimage, option),
(12, counterparty_sig, required),
});
impl HTLCDescriptor {
/// Returns the outpoint of the HTLC output in the commitment transaction. This is the outpoint
/// being spent by the HTLC input in the HTLC transaction.
pub fn outpoint(&self) -> bitcoin::OutPoint {
bitcoin::OutPoint {
txid: self.commitment_txid,
vout: self.htlc.transaction_output_index.unwrap(),
}
}
/// Returns the UTXO to be spent by the HTLC input, which can be obtained via
/// [`Self::unsigned_tx_input`].
pub fn previous_utxo<C: secp256k1::Signing + secp256k1::Verification>(
&self, secp: &Secp256k1<C>,
) -> TxOut {
TxOut {
script_pubkey: self.witness_script(secp).to_p2wsh(),
value: self.htlc.to_bitcoin_amount(),
}
}
/// Returns the unsigned transaction input spending the HTLC output in the commitment
/// transaction.
pub fn unsigned_tx_input(&self) -> TxIn {
chan_utils::build_htlc_input(
&self.commitment_txid,
&self.htlc,
&self.channel_derivation_parameters.transaction_parameters.channel_type_features,
)
}
/// Returns the delayed output created as a result of spending the HTLC output in the commitment
/// transaction.
pub fn tx_output<C: secp256k1::Signing + secp256k1::Verification>(
&self, secp: &Secp256k1<C>,
) -> TxOut {
let channel_params =
self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
let broadcaster_keys = channel_params.broadcaster_pubkeys();
let counterparty_keys = channel_params.countersignatory_pubkeys();
let broadcaster_delayed_key = DelayedPaymentKey::from_basepoint(
secp,
&broadcaster_keys.delayed_payment_basepoint,
&self.per_commitment_point,
);
let counterparty_revocation_key = &RevocationKey::from_basepoint(
&secp,
&counterparty_keys.revocation_basepoint,
&self.per_commitment_point,
);
chan_utils::build_htlc_output(
self.feerate_per_kw,
channel_params.contest_delay(),
&self.htlc,
channel_params.channel_type_features(),
&broadcaster_delayed_key,
&counterparty_revocation_key,
)
}
/// Returns the witness script of the HTLC output in the commitment transaction.
pub fn witness_script<C: secp256k1::Signing + secp256k1::Verification>(
&self, secp: &Secp256k1<C>,
) -> ScriptBuf {
let channel_params =
self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
let broadcaster_keys = channel_params.broadcaster_pubkeys();
let counterparty_keys = channel_params.countersignatory_pubkeys();
let broadcaster_htlc_key = HtlcKey::from_basepoint(
secp,
&broadcaster_keys.htlc_basepoint,
&self.per_commitment_point,
);
let counterparty_htlc_key = HtlcKey::from_basepoint(
secp,
&counterparty_keys.htlc_basepoint,
&self.per_commitment_point,
);
let counterparty_revocation_key = &RevocationKey::from_basepoint(
&secp,
&counterparty_keys.revocation_basepoint,
&self.per_commitment_point,
);
chan_utils::get_htlc_redeemscript_with_explicit_keys(
&self.htlc,
channel_params.channel_type_features(),
&broadcaster_htlc_key,
&counterparty_htlc_key,
&counterparty_revocation_key,
)
}
/// Returns the fully signed witness required to spend the HTLC output in the commitment
/// transaction.
pub fn tx_input_witness(&self, signature: &Signature, witness_script: &Script) -> Witness {
chan_utils::build_htlc_input_witness(
signature,
&self.counterparty_sig,
&self.preimage,
witness_script,
&self.channel_derivation_parameters.transaction_parameters.channel_type_features,
)
}
}
/// A trait to handle Lightning channel key material without concretizing the channel type or
/// the signature mechanism.
///
/// Several methods allow errors to be returned to support async signing. In such cases, the
/// signing operation can be replayed by calling [`ChannelManager::signer_unblocked`] once the
/// result is ready, at which point the channel operation will resume. Methods which allow for
/// async results are explicitly documented as such
///
/// [`ChannelManager::signer_unblocked`]: crate::ln::channelmanager::ChannelManager::signer_unblocked
pub trait ChannelSigner {
/// Gets the per-commitment point for a specific commitment number
///
/// Note that the commitment number starts at `(1 << 48) - 1` and counts backwards.
///
/// This method is *not* asynchronous. This method is expected to always return `Ok`
/// immediately after we reconnect to peers, and returning an `Err` may lead to an immediate
/// `panic`. This method will be made asynchronous in a future release.
fn get_per_commitment_point(
&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>,
) -> Result<PublicKey, ()>;
/// Gets the commitment secret for a specific commitment number as part of the revocation process
///
/// An external signer implementation should error here if the commitment was already signed
/// and should refuse to sign it in the future.
///
/// May be called more than once for the same index.
///
/// Note that the commitment number starts at `(1 << 48) - 1` and counts backwards.
///
/// An `Err` can be returned to signal that the signer is unavailable/cannot produce a valid
/// signature and should be retried later. Once the signer is ready to provide a signature after
/// previously returning an `Err`, [`ChannelManager::signer_unblocked`] must be called.
///
/// [`ChannelManager::signer_unblocked`]: crate::ln::channelmanager::ChannelManager::signer_unblocked
fn release_commitment_secret(&self, idx: u64) -> Result<[u8; 32], ()>;
/// Validate the counterparty's signatures on the holder commitment transaction and HTLCs.
///
/// This is required in order for the signer to make sure that releasing a commitment
/// secret won't leave us without a broadcastable holder transaction.
/// Policy checks should be implemented in this function, including checking the amount
/// sent to us and checking the HTLCs.
///
/// The preimages of outbound HTLCs that were fulfilled since the last commitment are provided.
/// A validating signer should ensure that an HTLC output is removed only when the matching
/// preimage is provided, or when the value to holder is restored.
///
/// Note that all the relevant preimages will be provided, but there may also be additional
/// irrelevant or duplicate preimages.
///
/// This method is *not* asynchronous. If an `Err` is returned, the channel will be immediately
/// closed. If you wish to make this operation asynchronous, you should instead return `Ok(())`
/// and pause future signing operations until this validation completes.
fn validate_holder_commitment(
&self, holder_tx: &HolderCommitmentTransaction,
outbound_htlc_preimages: Vec<PaymentPreimage>,
) -> Result<(), ()>;
/// Validate the counterparty's revocation.
///
/// This is required in order for the signer to make sure that the state has moved
/// forward and it is safe to sign the next counterparty commitment.
///
/// This method is *not* asynchronous. If an `Err` is returned, the channel will be immediately
/// closed. If you wish to make this operation asynchronous, you should instead return `Ok(())`
/// and pause future signing operations until this validation completes.
fn validate_counterparty_revocation(&self, idx: u64, secret: &SecretKey) -> Result<(), ()>;
/// Returns the holder channel public keys and basepoints. This should only be called once
/// during channel creation and as such implementations are allowed undefined behavior if
/// called more than once.
///
/// This method is *not* asynchronous. Instead, the value must be computed locally or in
/// advance and cached.
fn pubkeys(&self, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelPublicKeys;
/// Returns a new funding pubkey (i.e. our public which is used in a 2-of-2 with the
/// counterparty's key to to lock the funds on-chain) for a spliced channel.
///
/// `splice_parent_funding_txid` can be used to compute a tweak with which to rotate the base
/// key (which will then be available later in signing operations via
/// [`ChannelTransactionParameters::splice_parent_funding_txid`]).
///
/// This method is *not* asynchronous. Instead, the value must be cached locally.
fn new_funding_pubkey(
&self, splice_parent_funding_txid: Txid, secp_ctx: &Secp256k1<secp256k1::All>,
) -> PublicKey;
/// Returns an arbitrary identifier describing the set of keys which are provided back to you in
/// some [`SpendableOutputDescriptor`] types. This should be sufficient to identify this
/// [`EcdsaChannelSigner`] object uniquely and lookup or re-derive its keys.
///
/// This method is *not* asynchronous. Instead, the value must be cached locally.
fn channel_keys_id(&self) -> [u8; 32];
}
/// Represents the secret key material used for encrypting Peer Storage.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct PeerStorageKey {
/// Represents the key used to encrypt and decrypt Peer Storage.
pub inner: [u8; 32],
}
/// A secret key used to authenticate message contexts in received [`BlindedMessagePath`]s.
///
/// This key ensures that a node only accepts incoming messages delivered through
/// blinded paths that it constructed itself.
///
/// [`BlindedMessagePath`]: crate::blinded_path::message::BlindedMessagePath
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct ReceiveAuthKey(pub [u8; 32]);
/// Specifies the recipient of an invoice.
///
/// This indicates to [`NodeSigner::sign_invoice`] what node secret key should be used to sign
/// the invoice.
#[derive(Clone, Copy)]
pub enum Recipient {
/// The invoice should be signed with the local node secret key.
Node,
/// The invoice should be signed with the phantom node secret key. This secret key must be the
/// same for all nodes participating in the [phantom node payment].
///
/// [phantom node payment]: PhantomKeysManager
PhantomNode,
}
/// A trait that describes a source of entropy.
pub trait EntropySource {
/// Gets a unique, cryptographically-secure, random 32-byte value. This method must return a
/// different value each time it is called.
fn get_secure_random_bytes(&self) -> [u8; 32];
}
/// A trait that can handle cryptographic operations at the scope level of a node.
pub trait NodeSigner {
/// Get the [`ExpandedKey`] which provides cryptographic material for various Lightning Network operations.
///
/// This key set is used for:
/// - Encrypting and decrypting inbound payment metadata
/// - Authenticating payment hashes (both LDK-provided and user-provided)
/// - Supporting BOLT 12 Offers functionality (key derivation and authentication)
/// - Authenticating spontaneous payments' metadata
///
/// This method must return the same value each time it is called.
///
/// If the implementor of this trait supports [phantom node payments], then every node that is
/// intended to be included in the phantom invoice route hints must return the same value from
/// this method. This is because LDK avoids storing inbound payment data. Instead, this key
/// is used to construct a payment secret which is received in the payment onion and used to
/// reconstruct the payment preimage. Therefore, for a payment to be receivable by multiple
/// nodes, they must share the same key.
///
/// [phantom node payments]: PhantomKeysManager
fn get_expanded_key(&self) -> ExpandedKey;
/// Defines a method to derive a 32-byte encryption key for peer storage.
///
/// Implementations of this method must derive a secure encryption key.
/// The key is used to encrypt or decrypt backups of our state stored with our peers.
///
/// Thus, if you wish to rely on recovery using this method, you should use a key which
/// can be re-derived from data which would be available after state loss (eg the wallet seed).
fn get_peer_storage_key(&self) -> PeerStorageKey;
/// Returns the [`ReceiveAuthKey`] used to authenticate incoming [`BlindedMessagePath`] contexts.
///
/// This key is used as additional associated data (AAD) during MAC verification of the
/// [`MessageContext`] at the final hop of a blinded path. It ensures that only paths
/// constructed by this node will be accepted, preventing unauthorized parties from forging
/// valid-looking messages.
///
/// Implementers must ensure that this key remains secret and consistent across invocations.
///
/// [`BlindedMessagePath`]: crate::blinded_path::message::BlindedMessagePath
/// [`MessageContext`]: crate::blinded_path::message::MessageContext
fn get_receive_auth_key(&self) -> ReceiveAuthKey;
/// Get node id based on the provided [`Recipient`].
///
/// This method must return the same value each time it is called with a given [`Recipient`]
/// parameter.
///
/// Errors if the [`Recipient`] variant is not supported by the implementation.
fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()>;
/// Gets the ECDH shared secret of our node secret and `other_key`, multiplying by `tweak` if
/// one is provided. Note that this tweak can be applied to `other_key` instead of our node
/// secret, though this is less efficient.
///
/// Note that if this fails while attempting to forward an HTLC, LDK will panic. The error
/// should be resolved to allow LDK to resume forwarding HTLCs.
///
/// Errors if the [`Recipient`] variant is not supported by the implementation.
fn ecdh(
&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
) -> Result<SharedSecret, ()>;
/// Sign an invoice.
///
/// By parameterizing by the raw invoice bytes instead of the hash, we allow implementors of
/// this trait to parse the invoice and make sure they're signing what they expect, rather than
/// blindly signing the hash.
///
/// The `hrp_bytes` are ASCII bytes, while the `invoice_data` is base32.
///
/// The secret key used to sign the invoice is dependent on the [`Recipient`].
///
/// Errors if the [`Recipient`] variant is not supported by the implementation.
fn sign_invoice(
&self, invoice: &RawBolt11Invoice, recipient: Recipient,
) -> Result<RecoverableSignature, ()>;
/// Signs the [`TaggedHash`] of a BOLT 12 invoice.
///
/// May be called by a function passed to [`UnsignedBolt12Invoice::sign`] where `invoice` is the
/// callee.
///
/// Implementors may check that the `invoice` is expected rather than blindly signing the tagged
/// hash. An `Ok` result should sign `invoice.tagged_hash().as_digest()` with the node's signing
/// key or an ephemeral key to preserve privacy, whichever is associated with
/// [`UnsignedBolt12Invoice::signing_pubkey`].
///
/// [`TaggedHash`]: crate::offers::merkle::TaggedHash
fn sign_bolt12_invoice(
&self, invoice: &UnsignedBolt12Invoice,
) -> Result<schnorr::Signature, ()>;
/// Sign a gossip message.
///
/// Note that if this fails, LDK may panic and the message will not be broadcast to the network
/// or a possible channel counterparty. If LDK panics, the error should be resolved to allow the
/// message to be broadcast, as otherwise it may prevent one from receiving funds over the
/// corresponding channel.
fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()>;
/// Sign an arbitrary message with the node's secret key.
///
/// Creates a digital signature of a message given the node's secret. The message is prefixed
/// with "Lightning Signed Message:" before signing. See [this description of the format](https://web.archive.org/web/20191010011846/https://twitter.com/rusty_twit/status/1182102005914800128)
/// for more details.
///
/// A receiver knowing the node's id and the message can be sure that the signature was generated by the caller.
/// An `Err` can be returned to signal that the signer is unavailable / cannot produce a valid
/// signature.
fn sign_message(&self, msg: &[u8]) -> Result<String, ()>;
}
/// A trait that describes a wallet capable of creating a spending [`Transaction`] from a set of
/// [`SpendableOutputDescriptor`]s.
pub trait OutputSpender {
/// Creates a [`Transaction`] which spends the given descriptors to the given outputs, plus an
/// output to the given change destination (if sufficient change value remains). The
/// transaction will have a feerate, at least, of the given value.
///
/// The `locktime` argument is used to set the transaction's locktime. If `None`, the
/// transaction will have a locktime of 0. It it recommended to set this to the current block
/// height to avoid fee sniping, unless you have some specific reason to use a different
/// locktime.
///
/// Returns `Err(())` if the output value is greater than the input value minus required fee,
/// if a descriptor was duplicated, or if an output descriptor `script_pubkey`
/// does not match the one we can spend.
fn spend_spendable_outputs(
&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
locktime: Option<LockTime>, secp_ctx: &Secp256k1<All>,
) -> Result<Transaction, ()>;
}
// Primarily needed in doctests because of https://github.com/rust-lang/rust/issues/67295
/// A dynamic [`SignerProvider`] temporarily needed for doc tests.
///
/// This is not exported to bindings users as it is not intended for public consumption.