forked from lightningdevkit/rust-lightning
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathinteractivetxs.rs
More file actions
3743 lines (3407 loc) · 132 KB
/
interactivetxs.rs
File metadata and controls
3743 lines (3407 loc) · 132 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.
use crate::chain::transaction::OutPoint;
use crate::io_extras::sink;
use crate::prelude::*;
use bitcoin::absolute::LockTime as AbsoluteLockTime;
use bitcoin::amount::{Amount, SignedAmount};
use bitcoin::consensus::Encodable;
use bitcoin::constants::WITNESS_SCALE_FACTOR;
use bitcoin::ecdsa::Signature as BitcoinSignature;
use bitcoin::key::Secp256k1;
use bitcoin::policy::MAX_STANDARD_TX_WEIGHT;
use bitcoin::secp256k1::{Message, PublicKey};
use bitcoin::sighash::SighashCache;
use bitcoin::transaction::Version;
use bitcoin::{
sighash, EcdsaSighashType, OutPoint as BitcoinOutPoint, ScriptBuf, Sequence, TapSighashType,
Transaction, TxIn, TxOut, Txid, Weight, Witness, XOnlyPublicKey,
};
use crate::chain::chaininterface::fee_for_weight;
use crate::ln::chan_utils::{
BASE_INPUT_WEIGHT, EMPTY_SCRIPT_SIG_WEIGHT, FUNDING_TRANSACTION_WITNESS_WEIGHT,
};
use crate::ln::channel::{FundingNegotiationContext, TOTAL_BITCOIN_SUPPLY_SATOSHIS};
use crate::ln::funding::FundingTxInput;
use crate::ln::msgs;
use crate::ln::msgs::{MessageSendEvent, SerialId, TxSignatures};
use crate::ln::types::ChannelId;
use crate::sign::{EntropySource, P2TR_KEY_PATH_WITNESS_WEIGHT, P2WPKH_WITNESS_WEIGHT};
use core::fmt::Display;
use core::ops::Deref;
/// The number of received `tx_add_input` messages during a negotiation at which point the
/// negotiation MUST be failed.
const MAX_RECEIVED_TX_ADD_INPUT_COUNT: u16 = 4096;
/// The number of received `tx_add_output` messages during a negotiation at which point the
/// negotiation MUST be failed.
const MAX_RECEIVED_TX_ADD_OUTPUT_COUNT: u16 = 4096;
/// The number of inputs or outputs that the state machine can have, before it MUST fail the
/// negotiation.
const MAX_INPUTS_OUTPUTS_COUNT: usize = 252;
/// The total weight of the common fields whose fee is paid by the initiator of the interactive
/// transaction construction protocol.
pub(crate) const TX_COMMON_FIELDS_WEIGHT: u64 = (4 /* version */ + 4 /* locktime */ + 1 /* input count */ +
1 /* output count */) * WITNESS_SCALE_FACTOR as u64 + 2 /* segwit marker + flag */;
// BOLT 3 - Lower bounds for input weights
/// Lower bound for P2WPKH input weight
pub(crate) const P2WPKH_INPUT_WEIGHT_LOWER_BOUND: u64 =
BASE_INPUT_WEIGHT + EMPTY_SCRIPT_SIG_WEIGHT + P2WPKH_WITNESS_WEIGHT;
/// Lower bound for P2WSH input weight is chosen as same as P2WPKH input weight in BOLT 3
pub(crate) const P2WSH_INPUT_WEIGHT_LOWER_BOUND: u64 = P2WPKH_INPUT_WEIGHT_LOWER_BOUND;
/// Lower bound for P2TR input weight is chosen as the key spend path.
/// Not specified in BOLT 3, but a reasonable lower bound.
pub(crate) const P2TR_INPUT_WEIGHT_LOWER_BOUND: u64 =
BASE_INPUT_WEIGHT + EMPTY_SCRIPT_SIG_WEIGHT + P2TR_KEY_PATH_WITNESS_WEIGHT;
/// Lower bound for unknown segwit version input weight is chosen the same as P2WPKH in BOLT 3
pub(crate) const UNKNOWN_SEGWIT_VERSION_INPUT_WEIGHT_LOWER_BOUND: u64 =
P2WPKH_INPUT_WEIGHT_LOWER_BOUND;
trait SerialIdExt {
fn is_for_initiator(&self) -> bool;
fn is_for_non_initiator(&self) -> bool;
}
impl SerialIdExt for SerialId {
fn is_for_initiator(&self) -> bool {
self % 2 == 0
}
fn is_for_non_initiator(&self) -> bool {
!self.is_for_initiator()
}
}
#[derive(Clone, Debug)]
pub(crate) struct NegotiationError {
pub reason: AbortReason,
pub contributed_inputs: Vec<BitcoinOutPoint>,
pub contributed_outputs: Vec<TxOut>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum AbortReason {
InvalidStateTransition,
UnexpectedCounterpartyMessage,
ReceivedTooManyTxAddInputs,
ReceivedTooManyTxAddOutputs,
IncorrectInputSequenceValue,
IncorrectSerialIdParity,
SerialIdUnknown,
DuplicateSerialId,
/// Invalid provided inputs and previous transactions, several possible reasons:
/// - nonexisting `vout`, or
/// - mismatching `TxId`'s
/// - duplicate input,
/// - not a witness program,
/// etc.
PrevTxOutInvalid,
ExceededMaximumSatsAllowed,
ExceededNumberOfInputsOrOutputs,
TransactionTooLarge,
BelowDustLimit,
InvalidOutputScript,
InsufficientFees,
OutputsValueExceedsInputsValue,
InvalidTx,
/// No funding (shared) input found.
MissingFundingInput,
/// A funding (shared) input was seen, but we don't expect one
UnexpectedFundingInput,
/// In tx_add_input, the prev_tx field must be filled in case of non-shared input
MissingPrevTx,
/// In tx_add_input, the prev_tx field should not be filled in case of shared input
UnexpectedPrevTx,
/// No funding (shared) output found.
MissingFundingOutput,
/// More than one funding (shared) output found.
DuplicateFundingOutput,
/// More than one funding (shared) input found.
DuplicateFundingInput,
/// Internal error
InternalError(&'static str),
}
impl AbortReason {
pub fn into_tx_abort_msg(self, channel_id: ChannelId) -> msgs::TxAbort {
msgs::TxAbort { channel_id, data: self.to_string().into_bytes() }
}
}
impl Display for AbortReason {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
AbortReason::InvalidStateTransition => f.write_str("State transition was invalid"),
AbortReason::UnexpectedCounterpartyMessage => f.write_str("Unexpected message"),
AbortReason::ReceivedTooManyTxAddInputs => {
f.write_str("Too many `tx_add_input`s received")
},
AbortReason::ReceivedTooManyTxAddOutputs => {
f.write_str("Too many `tx_add_output`s received")
},
AbortReason::IncorrectInputSequenceValue => {
f.write_str("Input has a sequence value greater than 0xFFFFFFFD")
},
AbortReason::IncorrectSerialIdParity => {
f.write_str("Parity for `serial_id` was incorrect")
},
AbortReason::SerialIdUnknown => f.write_str("The `serial_id` is unknown"),
AbortReason::DuplicateSerialId => f.write_str("The `serial_id` already exists"),
AbortReason::PrevTxOutInvalid => f.write_str("Invalid previous transaction output"),
AbortReason::ExceededMaximumSatsAllowed => {
f.write_str("Output amount exceeded total bitcoin supply")
},
AbortReason::ExceededNumberOfInputsOrOutputs => {
f.write_str("Too many inputs or outputs")
},
AbortReason::TransactionTooLarge => f.write_str("Transaction weight is too large"),
AbortReason::BelowDustLimit => f.write_str("Output amount is below the dust limit"),
AbortReason::InvalidOutputScript => f.write_str("The output script is non-standard"),
AbortReason::InsufficientFees => f.write_str("Insufficient fees paid"),
AbortReason::OutputsValueExceedsInputsValue => {
f.write_str("Total value of outputs exceeds total value of inputs")
},
AbortReason::InvalidTx => f.write_str("The transaction is invalid"),
AbortReason::MissingFundingInput => f.write_str("No shared funding input found"),
AbortReason::UnexpectedFundingInput => {
f.write_str("A funding (shared) input was seen, but we don't expect one")
},
AbortReason::MissingPrevTx => f.write_str(
"In tx_add_input, the prev_tx field must be filled in case of non-shared input",
),
AbortReason::UnexpectedPrevTx => f.write_str(
"In tx_add_input, the prev_tx should not be filled in case of shared input",
),
AbortReason::MissingFundingOutput => f.write_str("No shared funding output found"),
AbortReason::DuplicateFundingOutput => {
f.write_str("More than one funding output found")
},
AbortReason::DuplicateFundingInput => f.write_str("More than one funding input found"),
AbortReason::InternalError(text) => {
f.write_fmt(format_args!("Internal error: {}", text))
},
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ConstructedTransaction {
holder_is_initiator: bool,
input_metadata: Vec<TxInMetadata>,
output_metadata: Vec<TxOutMetadata>,
tx: Transaction,
shared_input_index: Option<u16>,
shared_output_index: u16,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct TxInMetadata {
serial_id: SerialId,
prev_output: TxOut,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct TxOutMetadata {
serial_id: SerialId,
}
impl TxInMetadata {
pub(super) fn is_local(&self, holder_is_initiator: bool) -> bool {
!is_serial_id_valid_for_counterparty(holder_is_initiator, self.serial_id)
}
pub(super) fn prev_output(&self) -> &TxOut {
&self.prev_output
}
}
impl TxOutMetadata {
pub(super) fn is_local(&self, holder_is_initiator: bool) -> bool {
!is_serial_id_valid_for_counterparty(holder_is_initiator, self.serial_id)
}
}
impl_writeable_tlv_based!(TxInMetadata, {
(1, serial_id, required),
(3, prev_output, required),
});
impl_writeable_tlv_based!(TxOutMetadata, {
(1, serial_id, required),
});
impl_writeable_tlv_based!(ConstructedTransaction, {
(1, holder_is_initiator, required),
(3, input_metadata, required),
(5, output_metadata, required),
(7, tx, required),
(9, shared_input_index, option),
(11, shared_output_index, required),
});
impl ConstructedTransaction {
fn new(context: NegotiationContext) -> Result<Self, AbortReason> {
let remote_inputs_value = context.remote_inputs_value();
let remote_outputs_value = context.remote_outputs_value();
let remote_weight_contributed = context.remote_weight_contributed();
let satisfaction_weight =
Weight::from_wu(context.inputs.iter().fold(0u64, |value, (_, input)| {
value.saturating_add(input.satisfaction_weight().to_wu())
}));
let lock_time = context.tx_locktime;
let mut inputs: Vec<(TxIn, TxInMetadata)> =
context.inputs.into_values().map(|input| input.into_txin_and_metadata()).collect();
let mut outputs: Vec<(TxOut, TxOutMetadata)> =
context.outputs.into_values().map(|output| output.into_txout_and_metadata()).collect();
inputs.sort_unstable_by_key(|(_, input)| input.serial_id);
outputs.sort_unstable_by_key(|(_, output)| output.serial_id);
let (input, input_metadata): (Vec<TxIn>, Vec<TxInMetadata>) = inputs.into_iter().unzip();
let (output, output_metadata): (Vec<TxOut>, Vec<TxOutMetadata>) =
outputs.into_iter().unzip();
let shared_input_index =
context.shared_funding_input.as_ref().and_then(|shared_funding_input| {
input
.iter()
.position(|txin| {
txin.previous_output == shared_funding_input.input.previous_output
})
.map(|position| position as u16)
});
let shared_output_index = output
.iter()
.position(|txout| *txout == context.shared_funding_output.tx_out)
.map(|position| position as u16)
.unwrap_or(u16::MAX);
let tx = ConstructedTransaction {
holder_is_initiator: context.holder_is_initiator,
input_metadata,
output_metadata,
tx: Transaction { version: Version::TWO, lock_time, input, output },
shared_input_index,
shared_output_index,
};
// The receiving node:
// MUST fail the negotiation if:
// - the peer's total input satoshis is less than their outputs
if remote_inputs_value < remote_outputs_value {
return Err(AbortReason::OutputsValueExceedsInputsValue);
}
// - the peer's paid feerate does not meet or exceed the agreed feerate (based on the minimum fee).
let remote_fees_contributed = remote_inputs_value.saturating_sub(remote_outputs_value);
let required_remote_contribution_fee =
fee_for_weight(context.feerate_sat_per_kw, remote_weight_contributed);
if remote_fees_contributed < required_remote_contribution_fee {
return Err(AbortReason::InsufficientFees);
}
// - there are more than 252 inputs
// - there are more than 252 outputs
if tx.tx.input.len() > MAX_INPUTS_OUTPUTS_COUNT
|| tx.tx.output.len() > MAX_INPUTS_OUTPUTS_COUNT
{
return Err(AbortReason::ExceededNumberOfInputsOrOutputs);
}
if context.shared_funding_input.is_some() && tx.shared_input_index.is_none() {
return Err(AbortReason::MissingFundingInput);
}
if tx.shared_output_index == u16::MAX {
return Err(AbortReason::MissingFundingOutput);
}
let tx_weight = tx.tx.weight().checked_add(satisfaction_weight).unwrap_or(Weight::MAX);
if tx_weight > Weight::from_wu(MAX_STANDARD_TX_WEIGHT as u64) {
return Err(AbortReason::TransactionTooLarge);
}
Ok(tx)
}
fn into_negotiation_error(self, reason: AbortReason) -> NegotiationError {
let (contributed_inputs, contributed_outputs) = self.into_contributed_inputs_and_outputs();
NegotiationError { reason, contributed_inputs, contributed_outputs }
}
fn into_contributed_inputs_and_outputs(self) -> (Vec<BitcoinOutPoint>, Vec<TxOut>) {
let contributed_inputs = self
.tx
.input
.into_iter()
.zip(self.input_metadata.iter())
.enumerate()
.filter(|(_, (_, input))| input.is_local(self.holder_is_initiator))
.filter(|(index, _)| {
self.shared_input_index
.map(|shared_index| *index != shared_index as usize)
.unwrap_or(true)
})
.map(|(_, (txin, _))| txin.previous_output)
.collect();
let contributed_outputs = self
.tx
.output
.into_iter()
.zip(self.output_metadata.iter())
.enumerate()
.filter(|(_, (_, output))| output.is_local(self.holder_is_initiator))
.filter(|(index, _)| *index != self.shared_output_index as usize)
.map(|(_, (txout, _))| txout)
.collect();
(contributed_inputs, contributed_outputs)
}
pub fn tx(&self) -> &Transaction {
&self.tx
}
fn input_metadata(&self) -> impl Iterator<Item = &TxInMetadata> {
self.input_metadata.iter()
}
pub fn compute_txid(&self) -> Txid {
self.tx().compute_txid()
}
fn funding_outpoint(&self) -> OutPoint {
OutPoint { txid: self.compute_txid(), index: self.shared_output_index }
}
/// Returns the total input value from all local contributions, including the entire shared
/// input value if applicable.
fn local_contributed_input_value(&self) -> Amount {
self.input_metadata
.iter()
.filter(|input| input.is_local(self.holder_is_initiator))
.map(|input| input.prev_output.value)
.sum()
}
/// Returns the total input value from all remote contributions, including the entire shared
/// input value if applicable.
fn remote_contributed_input_value(&self) -> Amount {
self.input_metadata
.iter()
.filter(|input| !input.is_local(self.holder_is_initiator))
.map(|input| input.prev_output.value)
.sum()
}
fn finalize(
&self, holder_tx_signatures: &TxSignatures, counterparty_tx_signatures: &TxSignatures,
shared_input_sig: Option<&SharedInputSignature>,
) -> Option<Transaction> {
let mut tx = self.tx.clone();
self.add_local_witnesses(&mut tx, holder_tx_signatures.witnesses.clone());
self.add_remote_witnesses(&mut tx, counterparty_tx_signatures.witnesses.clone());
if let Some(shared_input_index) = self.shared_input_index {
let holder_shared_input_sig =
holder_tx_signatures.shared_input_signature.or_else(|| {
debug_assert!(false);
None
})?;
let counterparty_shared_input_sig =
counterparty_tx_signatures.shared_input_signature.or_else(|| {
debug_assert!(false);
None
})?;
let shared_input_sig = shared_input_sig.or_else(|| {
debug_assert!(false);
None
})?;
let mut witness = Witness::new();
witness.push(Vec::new());
let holder_sig = BitcoinSignature::sighash_all(holder_shared_input_sig);
let counterparty_sig = BitcoinSignature::sighash_all(counterparty_shared_input_sig);
if shared_input_sig.holder_signature_first {
witness.push_ecdsa_signature(&holder_sig);
witness.push_ecdsa_signature(&counterparty_sig);
} else {
witness.push_ecdsa_signature(&counterparty_sig);
witness.push_ecdsa_signature(&holder_sig);
}
witness.push(&shared_input_sig.witness_script);
tx.input[shared_input_index as usize].witness = witness;
}
Some(tx)
}
/// Adds provided holder witnesses to holder inputs of unsigned transaction.
///
/// Note that it is assumed that the witness count equals the holder input count.
fn add_local_witnesses(&self, transaction: &mut Transaction, witnesses: Vec<Witness>) {
transaction
.input
.iter_mut()
.zip(self.input_metadata.iter())
.enumerate()
.filter(|(_, (_, input))| input.is_local(self.holder_is_initiator))
.filter(|(index, _)| {
self.shared_input_index
.map(|shared_index| *index != shared_index as usize)
.unwrap_or(true)
})
.map(|(_, (txin, _))| txin)
.zip(witnesses)
.for_each(|(input, witness)| input.witness = witness);
}
/// Adds counterparty witnesses to counterparty inputs of unsigned transaction.
///
/// Note that it is assumed that the witness count equals the counterparty input count.
fn add_remote_witnesses(&self, transaction: &mut Transaction, witnesses: Vec<Witness>) {
transaction
.input
.iter_mut()
.zip(self.input_metadata.iter())
.enumerate()
.filter(|(_, (_, input))| !input.is_local(self.holder_is_initiator))
.filter(|(index, _)| {
self.shared_input_index
.map(|shared_index| *index != shared_index as usize)
.unwrap_or(true)
})
.map(|(_, (txin, _))| txin)
.zip(witnesses)
.for_each(|(input, witness)| input.witness = witness);
}
fn holder_is_initiator(&self) -> bool {
self.holder_is_initiator
}
pub fn shared_input_index(&self) -> Option<u16> {
self.shared_input_index
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct SharedInputSignature {
holder_signature_first: bool,
witness_script: ScriptBuf,
}
impl_writeable_tlv_based!(SharedInputSignature, {
(1, holder_signature_first, required),
(3, witness_script, required),
});
/// The InteractiveTxSigningSession coordinates the signing flow of interactively constructed
/// transactions from exhange of `commitment_signed` to ensuring proper ordering of `tx_signature`
/// message exchange.
///
/// See the specification for more details:
/// https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-commitment_signed-message
/// https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#sharing-funding-signatures-tx_signatures
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct InteractiveTxSigningSession {
unsigned_tx: ConstructedTransaction,
holder_sends_tx_signatures_first: bool,
has_received_commitment_signed: bool,
shared_input_signature: Option<SharedInputSignature>,
holder_tx_signatures: Option<TxSignatures>,
counterparty_tx_signatures: Option<TxSignatures>,
}
impl InteractiveTxSigningSession {
pub fn unsigned_tx(&self) -> &ConstructedTransaction {
&self.unsigned_tx
}
pub fn holder_sends_tx_signatures_first(&self) -> bool {
self.holder_sends_tx_signatures_first
}
pub fn has_received_commitment_signed(&self) -> bool {
self.has_received_commitment_signed
}
pub fn has_received_tx_signatures(&self) -> bool {
self.counterparty_tx_signatures.is_some()
}
pub fn holder_tx_signatures(&self) -> &Option<TxSignatures> {
&self.holder_tx_signatures
}
pub fn received_commitment_signed(&mut self) {
self.has_received_commitment_signed = true;
}
/// Handles a `tx_signatures` message received from the counterparty.
///
/// If the holder is required to send their `tx_signatures` message and these signatures have
/// already been provided to the signing session, then this return value will be `Some`, otherwise
/// None.
///
/// If the holder has already provided their `tx_signatures` to the signing session, a funding
/// transaction will be finalized and returned as Some, otherwise None.
///
/// Returns an error if the witness count does not equal the counterparty's input count in the
/// unsigned transaction or if the counterparty already provided their `tx_signatures`.
pub fn received_tx_signatures(
&mut self, tx_signatures: &TxSignatures,
) -> Result<(Option<TxSignatures>, Option<Transaction>), String> {
if self.has_received_tx_signatures() {
return Err("Already received a tx_signatures message".to_string());
}
if self.remote_inputs_count() != tx_signatures.witnesses.len() {
return Err("Witness count did not match contributed input count".to_string());
}
if self.shared_input().is_some() && tx_signatures.shared_input_signature.is_none() {
return Err("Missing shared input signature".to_string());
}
if self.shared_input().is_none() && tx_signatures.shared_input_signature.is_some() {
return Err("Unexpected shared input signature".to_string());
}
self.counterparty_tx_signatures = Some(tx_signatures.clone());
let holder_tx_signatures = if !self.holder_sends_tx_signatures_first {
self.holder_tx_signatures.clone()
} else {
None
};
let funding_tx_opt = self.maybe_finalize_funding_tx();
Ok((holder_tx_signatures, funding_tx_opt))
}
/// Provides the holder witnesses for the unsigned transaction.
///
/// Returns an error if the witness count does not equal the holder's input count in the
/// unsigned transaction.
pub fn provide_holder_witnesses<C: bitcoin::secp256k1::Verification>(
&mut self, tx_signatures: TxSignatures, secp_ctx: &Secp256k1<C>,
) -> Result<(Option<TxSignatures>, Option<Transaction>), String> {
if self.holder_tx_signatures.is_some() {
return Err("Holder witnesses were already provided".to_string());
}
let local_inputs_count = self.local_inputs_count();
if tx_signatures.witnesses.len() != local_inputs_count {
return Err(format!(
"Provided witness count of {} does not match required count for {} non-shared inputs",
tx_signatures.witnesses.len(),
local_inputs_count
));
}
self.verify_interactive_tx_signatures(secp_ctx, &tx_signatures.witnesses)?;
self.holder_tx_signatures = Some(tx_signatures);
let funding_tx_opt = self.maybe_finalize_funding_tx();
let holder_tx_signatures = (self.holder_sends_tx_signatures_first
|| self.has_received_tx_signatures())
.then(|| {
debug_assert!(self.has_received_commitment_signed);
self.holder_tx_signatures.clone().expect("Holder tx_signatures were just provided")
});
Ok((holder_tx_signatures, funding_tx_opt))
}
pub fn remote_inputs_count(&self) -> usize {
let shared_index = self.unsigned_tx.shared_input_index.as_ref();
self.unsigned_tx
.input_metadata
.iter()
.enumerate()
.filter(|(_, input)| !input.is_local(self.unsigned_tx.holder_is_initiator))
.filter(|(index, _)| {
shared_index.map(|shared_index| *index != *shared_index as usize).unwrap_or(true)
})
.count()
}
pub fn local_inputs_count(&self) -> usize {
self.unsigned_tx
.input_metadata
.iter()
.enumerate()
.filter(|(_, input)| input.is_local(self.unsigned_tx.holder_is_initiator))
.filter(|(index, _)| {
self.unsigned_tx
.shared_input_index
.map(|shared_index| *index != shared_index as usize)
.unwrap_or(true)
})
.count()
}
fn local_outputs_count(&self) -> usize {
self.unsigned_tx
.output_metadata
.iter()
.enumerate()
.filter(|(_, output)| output.is_local(self.unsigned_tx.holder_is_initiator))
.count()
}
pub fn has_local_contribution(&self) -> bool {
self.local_inputs_count() > 0 || self.local_outputs_count() > 0
}
pub fn shared_input(&self) -> Option<&TxInMetadata> {
self.unsigned_tx.shared_input_index.and_then(|shared_input_index| {
self.unsigned_tx.input_metadata.get(shared_input_index as usize)
})
}
fn maybe_finalize_funding_tx(&mut self) -> Option<Transaction> {
let holder_tx_signatures = self.holder_tx_signatures.as_ref()?;
let counterparty_tx_signatures = self.counterparty_tx_signatures.as_ref()?;
let shared_input_signature = self.shared_input_signature.as_ref();
self.unsigned_tx.finalize(
holder_tx_signatures,
counterparty_tx_signatures,
shared_input_signature,
)
}
fn verify_interactive_tx_signatures<C: bitcoin::secp256k1::Verification>(
&self, secp_ctx: &Secp256k1<C>, witnesses: &Vec<Witness>,
) -> Result<(), String> {
let unsigned_tx = self.unsigned_tx();
let built_tx = unsigned_tx.tx();
let prev_outputs: Vec<&TxOut> =
unsigned_tx.input_metadata().map(|input| input.prev_output()).collect::<Vec<_>>();
let all_prevouts = sighash::Prevouts::All(&prev_outputs[..]);
let mut cache = SighashCache::new(built_tx);
let script_pubkeys = unsigned_tx
.input_metadata()
.enumerate()
.filter(|(_, input)| input.is_local(unsigned_tx.holder_is_initiator()))
.filter(|(index, _)| {
unsigned_tx
.shared_input_index
.map(|shared_index| *index != shared_index as usize)
.unwrap_or(true)
});
for ((input_idx, input), witness) in script_pubkeys.zip(witnesses) {
if witness.is_empty() {
let err = format!("The witness for input at index {input_idx} is empty");
return Err(err);
}
let prev_output = input.prev_output();
let script_pubkey = &prev_output.script_pubkey;
// P2WPKH
if script_pubkey.is_p2wpkh() {
if witness.len() != 2 {
let err = format!("The witness for input at index {input_idx} does not have the correct number of elements for a P2WPKH spend. Expected 2 got {}", witness.len());
return Err(err);
}
let pubkey = PublicKey::from_slice(&witness[1]).map_err(|_| {
format!("The witness for input at index {input_idx} contains an invalid ECDSA public key")
})?;
let sig =
bitcoin::ecdsa::Signature::from_slice(&witness[0]).map_err(|_| {
format!("The witness for input at index {input_idx} contains an invalid signature")
})?;
if !matches!(sig.sighash_type, EcdsaSighashType::All) {
let err = format!("Signature does not use SIGHASH_ALL for input at index {input_idx} for P2WPKH spend");
return Err(err);
}
let sighash = cache
.p2wpkh_signature_hash(
input_idx,
script_pubkey,
prev_output.value,
EcdsaSighashType::All,
)
.map_err(|_| {
debug_assert!(false, "Funding transaction sighash should be calculable");
"The transaction sighash could not be calculated".to_string()
})?;
let msg = Message::from_digest_slice(&sighash[..])
.expect("Sighash is a SHA256 which is 32 bytes long");
secp_ctx.verify_ecdsa(&msg, &sig.signature, &pubkey).map_err(|_| {
format!("Failed signature verification for input at index {input_idx} for P2WPKH spend")
})?;
continue;
}
// P2TR key path spend witness includes signature and optional annex
if script_pubkey.is_p2tr() && witness.len() == 1 {
let pubkey = match script_pubkey.instructions().nth(1) {
Some(Ok(bitcoin::script::Instruction::PushBytes(push_bytes))) => {
XOnlyPublicKey::from_slice(push_bytes.as_bytes())
},
_ => {
let err = format!("The scriptPubKey of the previous output for input at index {input_idx} for a P2TR key path spend is invalid");
return Err(err)
},
}.map_err(|_| {
format!("The scriptPubKey of the previous output for input at index {input_idx} for a P2TR key path spend has an invalid public key")
})?;
let sig = bitcoin::taproot::Signature::from_slice(&witness[0]).map_err(|_| {
format!("The witness for input at index {input_idx} for a P2TR key path spend has an invalid signature")
})?;
if !matches!(sig.sighash_type, TapSighashType::Default | TapSighashType::All) {
let err = format!("Signature does not use SIGHASH_DEFAULT or SIGHASH_ALL for input at index {input_idx} for P2TR key path spend");
return Err(err);
}
let sighash = cache
.taproot_key_spend_signature_hash(input_idx, &all_prevouts, sig.sighash_type)
.map_err(|_| {
debug_assert!(false, "Funding transaction sighash should be calculable");
"The transaction sighash could not be calculated".to_string()
})?;
let msg = Message::from_digest_slice(&sighash[..])
.expect("Sighash is a SHA256 which is 32 bytes long");
secp_ctx.verify_schnorr(&sig.signature, &msg, &pubkey).map_err(|_| {
format!("Failed signature verification for input at index {input_idx} for P2TR key path spend")
})?;
continue;
}
// P2WSH - No validation just sighash checks
if script_pubkey.is_p2wsh() {
for element in witness {
match element.len() {
// Possibly a DER-encoded ECDSA signature with a sighash type byte assuming low-S
70..=73 => {
if !bitcoin::ecdsa::Signature::from_slice(element)
.map(|sig| matches!(sig.sighash_type, EcdsaSighashType::All))
.unwrap_or(true)
{
let err = format!("An ECDSA signature in the witness for input {input_idx} does not use SIGHASH_ALL");
return Err(err);
}
},
_ => (),
}
}
continue;
}
// P2TR script path - No validation, just sighash checks
if script_pubkey.is_p2tr() {
for element in witness {
match element.len() {
// Schnorr sig + sighash type byte.
// If this were just 64 bytes, it would implicitly be SIGHASH_DEFAULT (= SIGHASH_ALL)
65 => {
if !bitcoin::taproot::Signature::from_slice(element)
.map(|sig| matches!(sig.sighash_type, TapSighashType::All))
.unwrap_or(true)
{
let err = format!("A (likely) Schnorr signature in the witness for input {input_idx} does not use SIGHASH_DEFAULT or SIGHASH_ALL");
return Err(err);
}
},
_ => (),
}
}
continue;
}
debug_assert!(
false,
"We don't allow contributing inputs that are not spending P2WPKH, P2WSH, or P2TR"
);
let err = format!(
"Input at index {input_idx} does not spend from one of P2WPKH, P2WSH, or P2TR"
);
return Err(err);
}
Ok(())
}
pub(crate) fn into_negotiation_error(self, reason: AbortReason) -> NegotiationError {
self.unsigned_tx.into_negotiation_error(reason)
}
pub(super) fn into_contributed_inputs_and_outputs(self) -> (Vec<BitcoinOutPoint>, Vec<TxOut>) {
self.unsigned_tx.into_contributed_inputs_and_outputs()
}
}
impl_writeable_tlv_based!(InteractiveTxSigningSession, {
(1, unsigned_tx, required),
(3, has_received_commitment_signed, required),
(5, holder_tx_signatures, required),
(7, counterparty_tx_signatures, required),
(9, holder_sends_tx_signatures_first, required),
(11, shared_input_signature, required),
});
#[derive(Debug)]
struct NegotiationContext {
holder_node_id: PublicKey,
counterparty_node_id: PublicKey,
holder_is_initiator: bool,
received_tx_add_input_count: u16,
received_tx_add_output_count: u16,
inputs: HashMap<SerialId, InteractiveTxInput>,
/// Optional intended/expected funding input, used during splicing.
/// The funding input is shared, it is usually co-owned by both peers.
/// - For the initiator:
/// The intended previous funding input. This will be added alongside
/// the provided inputs.
/// - For the acceptor:
/// The expected previous funding input. It should be added by the initiator node.
shared_funding_input: Option<SharedOwnedInput>,
/// The intended/expected funding output, potentially co-owned by both peers (shared).
/// - For the initiator:
/// The output intended to be the new funding output. This will be added alongside
/// the provided outputs.
/// - For the acceptor:
/// The output expected as new funding output. It should be added by the initiator node.
shared_funding_output: SharedOwnedOutput,
prevtx_outpoints: HashSet<BitcoinOutPoint>,
/// The outputs added so far.
outputs: HashMap<SerialId, InteractiveTxOutput>,
/// The locktime of the funding transaction.
tx_locktime: AbsoluteLockTime,
/// The fee rate used for the transaction
feerate_sat_per_kw: u32,
}
fn estimate_input_satisfaction_weight(prev_output: &TxOut) -> Weight {
Weight::from_wu(
if prev_output.script_pubkey.is_p2wpkh() {
P2WPKH_INPUT_WEIGHT_LOWER_BOUND
} else if prev_output.script_pubkey.is_p2wsh() {
P2WSH_INPUT_WEIGHT_LOWER_BOUND
} else if prev_output.script_pubkey.is_p2tr() {
P2TR_INPUT_WEIGHT_LOWER_BOUND
} else {
UNKNOWN_SEGWIT_VERSION_INPUT_WEIGHT_LOWER_BOUND
} - BASE_INPUT_WEIGHT,
)
}
pub(crate) fn get_output_weight(script_pubkey: &ScriptBuf) -> Weight {
Weight::from_wu(
(8 /* value */ + script_pubkey.consensus_encode(&mut sink()).unwrap() as u64)
* WITNESS_SCALE_FACTOR as u64,
)
}
fn is_serial_id_valid_for_counterparty(holder_is_initiator: bool, serial_id: SerialId) -> bool {
// A received `SerialId`'s parity must match the role of the counterparty.
holder_is_initiator == serial_id.is_for_non_initiator()
}
impl NegotiationContext {
fn new(
holder_node_id: PublicKey, counterparty_node_id: PublicKey, holder_is_initiator: bool,
shared_funding_input: Option<SharedOwnedInput>, shared_funding_output: SharedOwnedOutput,
tx_locktime: AbsoluteLockTime, feerate_sat_per_kw: u32,
) -> Self {
NegotiationContext {
holder_node_id,
counterparty_node_id,
holder_is_initiator,
received_tx_add_input_count: 0,
received_tx_add_output_count: 0,
inputs: new_hash_map(),
shared_funding_input,
shared_funding_output,
prevtx_outpoints: new_hash_set(),
outputs: new_hash_map(),
tx_locktime,
feerate_sat_per_kw,
}
}
fn is_serial_id_valid_for_counterparty(&self, serial_id: &SerialId) -> bool {
is_serial_id_valid_for_counterparty(self.holder_is_initiator, *serial_id)
}
fn remote_inputs_value(&self) -> u64 {
self.inputs.iter().fold(0u64, |acc, (_, input)| acc.saturating_add(input.remote_value()))
}
fn remote_outputs_value(&self) -> u64 {
self.outputs.iter().fold(0u64, |acc, (_, output)| acc.saturating_add(output.remote_value()))
}
fn remote_inputs_weight(&self) -> Weight {
Weight::from_wu(
self.inputs
.iter()
.filter(|(serial_id, _)| self.is_serial_id_valid_for_counterparty(serial_id))
.fold(0u64, |weight, (_, input)| {
weight
.saturating_add(BASE_INPUT_WEIGHT)
.saturating_add(input.satisfaction_weight().to_wu())
}),
)
}
fn remote_weight_contributed(&self) -> u64 {
self.remote_inputs_weight()
.to_wu()
.saturating_add(self.remote_outputs_weight().to_wu())
// The receiving node:
// - MUST fail the negotiation if
// - if is the non-initiator:
// - the initiator's fees do not cover the common fields (version, segwit marker + flag,
// input count, output count, locktime)
.saturating_add(if !self.holder_is_initiator { TX_COMMON_FIELDS_WEIGHT } else { 0 })
}
fn remote_outputs_weight(&self) -> Weight {
Weight::from_wu(
self.outputs
.iter()
.filter(|(serial_id, _)| self.is_serial_id_valid_for_counterparty(serial_id))
.fold(0u64, |weight, (_, output)| {
weight.saturating_add(get_output_weight(output.script_pubkey()).to_wu())
}),