33a8bfc2f7c2f7a54e36dd438fec020a884ef9d4
[rust-lightning] / lightning / src / ln / interactivetxs.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 use crate::io_extras::sink;
11 use crate::prelude::*;
12 use core::ops::Deref;
13
14 use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
15 use bitcoin::consensus::Encodable;
16 use bitcoin::policy::MAX_STANDARD_TX_WEIGHT;
17 use bitcoin::{
18         absolute::LockTime as AbsoluteLockTime, OutPoint, Sequence, Transaction, TxIn, TxOut,
19 };
20
21 use crate::chain::chaininterface::fee_for_weight;
22 use crate::events::bump_transaction::{BASE_INPUT_WEIGHT, EMPTY_SCRIPT_SIG_WEIGHT};
23 use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
24 use crate::ln::msgs::SerialId;
25 use crate::ln::{msgs, ChannelId};
26 use crate::sign::EntropySource;
27 use crate::util::ser::TransactionU16LenLimited;
28
29 /// The number of received `tx_add_input` messages during a negotiation at which point the
30 /// negotiation MUST be failed.
31 const MAX_RECEIVED_TX_ADD_INPUT_COUNT: u16 = 4096;
32
33 /// The number of received `tx_add_output` messages during a negotiation at which point the
34 /// negotiation MUST be failed.
35 const MAX_RECEIVED_TX_ADD_OUTPUT_COUNT: u16 = 4096;
36
37 /// The number of inputs or outputs that the state machine can have, before it MUST fail the
38 /// negotiation.
39 const MAX_INPUTS_OUTPUTS_COUNT: usize = 252;
40
41 trait SerialIdExt {
42         fn is_for_initiator(&self) -> bool;
43         fn is_for_non_initiator(&self) -> bool;
44 }
45
46 impl SerialIdExt for SerialId {
47         fn is_for_initiator(&self) -> bool {
48                 self % 2 == 0
49         }
50
51         fn is_for_non_initiator(&self) -> bool {
52                 !self.is_for_initiator()
53         }
54 }
55
56 #[derive(Debug, Clone, PartialEq)]
57 pub enum AbortReason {
58         InvalidStateTransition,
59         UnexpectedCounterpartyMessage,
60         ReceivedTooManyTxAddInputs,
61         ReceivedTooManyTxAddOutputs,
62         IncorrectInputSequenceValue,
63         IncorrectSerialIdParity,
64         SerialIdUnknown,
65         DuplicateSerialId,
66         PrevTxOutInvalid,
67         ExceededMaximumSatsAllowed,
68         ExceededNumberOfInputsOrOutputs,
69         TransactionTooLarge,
70         BelowDustLimit,
71         InvalidOutputScript,
72         InsufficientFees,
73         OutputsValueExceedsInputsValue,
74         InvalidTx,
75 }
76
77 #[derive(Debug)]
78 pub struct TxInputWithPrevOutput {
79         input: TxIn,
80         prev_output: TxOut,
81 }
82
83 #[derive(Debug)]
84 struct NegotiationContext {
85         holder_is_initiator: bool,
86         received_tx_add_input_count: u16,
87         received_tx_add_output_count: u16,
88         inputs: HashMap<SerialId, TxInputWithPrevOutput>,
89         prevtx_outpoints: HashSet<OutPoint>,
90         outputs: HashMap<SerialId, TxOut>,
91         tx_locktime: AbsoluteLockTime,
92         feerate_sat_per_kw: u32,
93 }
94
95 impl NegotiationContext {
96         fn is_serial_id_valid_for_counterparty(&self, serial_id: &SerialId) -> bool {
97                 // A received `SerialId`'s parity must match the role of the counterparty.
98                 self.holder_is_initiator == serial_id.is_for_non_initiator()
99         }
100
101         fn total_input_and_output_count(&self) -> usize {
102                 self.inputs.len().saturating_add(self.outputs.len())
103         }
104
105         fn counterparty_inputs_contributed(
106                 &self,
107         ) -> impl Iterator<Item = &TxInputWithPrevOutput> + Clone {
108                 self.inputs
109                         .iter()
110                         .filter(move |(serial_id, _)| self.is_serial_id_valid_for_counterparty(serial_id))
111                         .map(|(_, input_with_prevout)| input_with_prevout)
112         }
113
114         fn counterparty_outputs_contributed(&self) -> impl Iterator<Item = &TxOut> + Clone {
115                 self.outputs
116                         .iter()
117                         .filter(move |(serial_id, _)| self.is_serial_id_valid_for_counterparty(serial_id))
118                         .map(|(_, output)| output)
119         }
120
121         fn received_tx_add_input(&mut self, msg: &msgs::TxAddInput) -> Result<(), AbortReason> {
122                 // The interactive-txs spec calls for us to fail negotiation if the `prevtx` we receive is
123                 // invalid. However, we would not need to account for this explicit negotiation failure
124                 // mode here since `PeerManager` would already disconnect the peer if the `prevtx` is
125                 // invalid; implicitly ending the negotiation.
126
127                 if !self.is_serial_id_valid_for_counterparty(&msg.serial_id) {
128                         // The receiving node:
129                         //  - MUST fail the negotiation if:
130                         //     - the `serial_id` has the wrong parity
131                         return Err(AbortReason::IncorrectSerialIdParity);
132                 }
133
134                 self.received_tx_add_input_count += 1;
135                 if self.received_tx_add_input_count > MAX_RECEIVED_TX_ADD_INPUT_COUNT {
136                         // The receiving node:
137                         //  - MUST fail the negotiation if:
138                         //     - if has received 4096 `tx_add_input` messages during this negotiation
139                         return Err(AbortReason::ReceivedTooManyTxAddInputs);
140                 }
141
142                 if msg.sequence >= 0xFFFFFFFE {
143                         // The receiving node:
144                         //  - MUST fail the negotiation if:
145                         //    - `sequence` is set to `0xFFFFFFFE` or `0xFFFFFFFF`
146                         return Err(AbortReason::IncorrectInputSequenceValue);
147                 }
148
149                 let transaction = msg.prevtx.as_transaction();
150                 let txid = transaction.txid();
151
152                 if let Some(tx_out) = transaction.output.get(msg.prevtx_out as usize) {
153                         if !tx_out.script_pubkey.is_witness_program() {
154                                 // The receiving node:
155                                 //  - MUST fail the negotiation if:
156                                 //     - the `scriptPubKey` is not a witness program
157                                 return Err(AbortReason::PrevTxOutInvalid);
158                         }
159
160                         if !self.prevtx_outpoints.insert(OutPoint { txid, vout: msg.prevtx_out }) {
161                                 // The receiving node:
162                                 //  - MUST fail the negotiation if:
163                                 //     - the `prevtx` and `prevtx_vout` are identical to a previously added
164                                 //       (and not removed) input's
165                                 return Err(AbortReason::PrevTxOutInvalid);
166                         }
167                 } else {
168                         // The receiving node:
169                         //  - MUST fail the negotiation if:
170                         //     - `prevtx_vout` is greater or equal to the number of outputs on `prevtx`
171                         return Err(AbortReason::PrevTxOutInvalid);
172                 }
173
174                 let prev_out = if let Some(prev_out) = transaction.output.get(msg.prevtx_out as usize) {
175                         prev_out.clone()
176                 } else {
177                         return Err(AbortReason::PrevTxOutInvalid);
178                 };
179                 match self.inputs.entry(msg.serial_id) {
180                         hash_map::Entry::Occupied(_) => {
181                                 // The receiving node:
182                                 //  - MUST fail the negotiation if:
183                                 //    - the `serial_id` is already included in the transaction
184                                 Err(AbortReason::DuplicateSerialId)
185                         },
186                         hash_map::Entry::Vacant(entry) => {
187                                 let prev_outpoint = OutPoint { txid, vout: msg.prevtx_out };
188                                 entry.insert(TxInputWithPrevOutput {
189                                         input: TxIn {
190                                                 previous_output: prev_outpoint,
191                                                 sequence: Sequence(msg.sequence),
192                                                 ..Default::default()
193                                         },
194                                         prev_output: prev_out,
195                                 });
196                                 self.prevtx_outpoints.insert(prev_outpoint);
197                                 Ok(())
198                         },
199                 }
200         }
201
202         fn received_tx_remove_input(&mut self, msg: &msgs::TxRemoveInput) -> Result<(), AbortReason> {
203                 if !self.is_serial_id_valid_for_counterparty(&msg.serial_id) {
204                         return Err(AbortReason::IncorrectSerialIdParity);
205                 }
206
207                 self.inputs
208                         .remove(&msg.serial_id)
209                         // The receiving node:
210                         //  - MUST fail the negotiation if:
211                         //    - the input or output identified by the `serial_id` was not added by the sender
212                         //    - the `serial_id` does not correspond to a currently added input
213                         .ok_or(AbortReason::SerialIdUnknown)
214                         .map(|_| ())
215         }
216
217         fn received_tx_add_output(&mut self, msg: &msgs::TxAddOutput) -> Result<(), AbortReason> {
218                 // The receiving node:
219                 //  - MUST fail the negotiation if:
220                 //     - the serial_id has the wrong parity
221                 if !self.is_serial_id_valid_for_counterparty(&msg.serial_id) {
222                         return Err(AbortReason::IncorrectSerialIdParity);
223                 }
224
225                 self.received_tx_add_output_count += 1;
226                 if self.received_tx_add_output_count > MAX_RECEIVED_TX_ADD_OUTPUT_COUNT {
227                         // The receiving node:
228                         //  - MUST fail the negotiation if:
229                         //     - if has received 4096 `tx_add_output` messages during this negotiation
230                         return Err(AbortReason::ReceivedTooManyTxAddOutputs);
231                 }
232
233                 if msg.sats < msg.script.dust_value().to_sat() {
234                         // The receiving node:
235                         // - MUST fail the negotiation if:
236                         //              - the sats amount is less than the dust_limit
237                         return Err(AbortReason::BelowDustLimit);
238                 }
239
240                 // Check that adding this output would not cause the total output value to exceed the total
241                 // bitcoin supply.
242                 let mut outputs_value: u64 = 0;
243                 for output in self.outputs.iter() {
244                         outputs_value = outputs_value.saturating_add(output.1.value);
245                 }
246                 if outputs_value.saturating_add(msg.sats) > TOTAL_BITCOIN_SUPPLY_SATOSHIS {
247                         // The receiving node:
248                         // - MUST fail the negotiation if:
249                         //              - the sats amount is greater than 2,100,000,000,000,000 (TOTAL_BITCOIN_SUPPLY_SATOSHIS)
250                         return Err(AbortReason::ExceededMaximumSatsAllowed);
251                 }
252
253                 // The receiving node:
254                 //   - MUST accept P2WSH, P2WPKH, P2TR scripts
255                 //   - MAY fail the negotiation if script is non-standard
256                 //
257                 // We can actually be a bit looser than the above as only witness version 0 has special
258                 // length-based standardness constraints to match similar consensus rules. All witness scripts
259                 // with witness versions V1 and up are always considered standard. Yes, the scripts can be
260                 // anyone-can-spend-able, but if our counterparty wants to add an output like that then it's none
261                 // of our concern really Â¯\_(ツ)_/¯
262                 //
263                 // TODO: The last check would be simplified when https://github.com/rust-bitcoin/rust-bitcoin/commit/1656e1a09a1959230e20af90d20789a4a8f0a31b
264                 // hits the next release of rust-bitcoin.
265                 if !(msg.script.is_v0_p2wpkh()
266                         || msg.script.is_v0_p2wsh()
267                         || (msg.script.is_witness_program()
268                                 && msg.script.witness_version().map(|v| v.to_num() >= 1).unwrap_or(false)))
269                 {
270                         return Err(AbortReason::InvalidOutputScript);
271                 }
272
273                 match self.outputs.entry(msg.serial_id) {
274                         hash_map::Entry::Occupied(_) => {
275                                 // The receiving node:
276                                 //  - MUST fail the negotiation if:
277                                 //    - the `serial_id` is already included in the transaction
278                                 Err(AbortReason::DuplicateSerialId)
279                         },
280                         hash_map::Entry::Vacant(entry) => {
281                                 entry.insert(TxOut { value: msg.sats, script_pubkey: msg.script.clone() });
282                                 Ok(())
283                         },
284                 }
285         }
286
287         fn received_tx_remove_output(&mut self, msg: &msgs::TxRemoveOutput) -> Result<(), AbortReason> {
288                 if !self.is_serial_id_valid_for_counterparty(&msg.serial_id) {
289                         return Err(AbortReason::IncorrectSerialIdParity);
290                 }
291                 if self.outputs.remove(&msg.serial_id).is_some() {
292                         Ok(())
293                 } else {
294                         // The receiving node:
295                         //  - MUST fail the negotiation if:
296                         //    - the input or output identified by the `serial_id` was not added by the sender
297                         //    - the `serial_id` does not correspond to a currently added input
298                         Err(AbortReason::SerialIdUnknown)
299                 }
300         }
301
302         fn sent_tx_add_input(&mut self, msg: &msgs::TxAddInput) -> Result<(), AbortReason> {
303                 let tx = msg.prevtx.as_transaction();
304                 let input = TxIn {
305                         previous_output: OutPoint { txid: tx.txid(), vout: msg.prevtx_out },
306                         sequence: Sequence(msg.sequence),
307                         ..Default::default()
308                 };
309                 let prev_output =
310                         tx.output.get(msg.prevtx_out as usize).ok_or(AbortReason::PrevTxOutInvalid)?.clone();
311                 self.prevtx_outpoints.insert(input.previous_output);
312                 self.inputs.insert(msg.serial_id, TxInputWithPrevOutput { input, prev_output });
313                 Ok(())
314         }
315
316         fn sent_tx_add_output(&mut self, msg: &msgs::TxAddOutput) -> Result<(), AbortReason> {
317                 self.outputs
318                         .insert(msg.serial_id, TxOut { value: msg.sats, script_pubkey: msg.script.clone() });
319                 Ok(())
320         }
321
322         fn sent_tx_remove_input(&mut self, msg: &msgs::TxRemoveInput) -> Result<(), AbortReason> {
323                 self.inputs.remove(&msg.serial_id);
324                 Ok(())
325         }
326
327         fn sent_tx_remove_output(&mut self, msg: &msgs::TxRemoveOutput) -> Result<(), AbortReason> {
328                 self.outputs.remove(&msg.serial_id);
329                 Ok(())
330         }
331
332         fn build_transaction(self) -> Result<Transaction, AbortReason> {
333                 // The receiving node:
334                 // MUST fail the negotiation if:
335
336                 // - the peer's total input satoshis is less than their outputs
337                 let mut counterparty_inputs_value: u64 = 0;
338                 let mut counterparty_outputs_value: u64 = 0;
339                 for input in self.counterparty_inputs_contributed() {
340                         counterparty_inputs_value =
341                                 counterparty_inputs_value.saturating_add(input.prev_output.value);
342                 }
343                 for output in self.counterparty_outputs_contributed() {
344                         counterparty_outputs_value = counterparty_outputs_value.saturating_add(output.value);
345                 }
346                 if counterparty_inputs_value < counterparty_outputs_value {
347                         return Err(AbortReason::OutputsValueExceedsInputsValue);
348                 }
349
350                 // - there are more than 252 inputs
351                 // - there are more than 252 outputs
352                 if self.inputs.len() > MAX_INPUTS_OUTPUTS_COUNT
353                         || self.outputs.len() > MAX_INPUTS_OUTPUTS_COUNT
354                 {
355                         return Err(AbortReason::ExceededNumberOfInputsOrOutputs);
356                 }
357
358                 // TODO: How do we enforce their fees cover the witness without knowing its expected length?
359                 const INPUT_WEIGHT: u64 = BASE_INPUT_WEIGHT + EMPTY_SCRIPT_SIG_WEIGHT;
360
361                 // - the peer's paid feerate does not meet or exceed the agreed feerate (based on the minimum fee).
362                 let mut counterparty_weight_contributed: u64 = self
363                         .counterparty_outputs_contributed()
364                         .map(|output| {
365                                 (8 /* value */ + output.script_pubkey.consensus_encode(&mut sink()).unwrap() as u64)
366                                         * WITNESS_SCALE_FACTOR as u64
367                         })
368                         .sum();
369                 counterparty_weight_contributed +=
370                         self.counterparty_inputs_contributed().count() as u64 * INPUT_WEIGHT;
371                 let counterparty_fees_contributed =
372                         counterparty_inputs_value.saturating_sub(counterparty_outputs_value);
373                 let mut required_counterparty_contribution_fee =
374                         fee_for_weight(self.feerate_sat_per_kw, counterparty_weight_contributed);
375                 if !self.holder_is_initiator {
376                         // if is the non-initiator:
377                         //      - the initiator's fees do not cover the common fields (version, segwit marker + flag,
378                         //              input count, output count, locktime)
379                         let tx_common_fields_weight =
380                         (4 /* version */ + 4 /* locktime */ + 1 /* input count */ + 1 /* output count */) *
381                             WITNESS_SCALE_FACTOR as u64 + 2 /* segwit marker + flag */;
382                         let tx_common_fields_fee =
383                                 fee_for_weight(self.feerate_sat_per_kw, tx_common_fields_weight);
384                         required_counterparty_contribution_fee += tx_common_fields_fee;
385                 }
386                 if counterparty_fees_contributed < required_counterparty_contribution_fee {
387                         return Err(AbortReason::InsufficientFees);
388                 }
389
390                 // Inputs and outputs must be sorted by serial_id
391                 let mut inputs = self.inputs.into_iter().collect::<Vec<_>>();
392                 let mut outputs = self.outputs.into_iter().collect::<Vec<_>>();
393                 inputs.sort_unstable_by_key(|(serial_id, _)| *serial_id);
394                 outputs.sort_unstable_by_key(|(serial_id, _)| *serial_id);
395
396                 let tx_to_validate = Transaction {
397                         version: 2,
398                         lock_time: self.tx_locktime,
399                         input: inputs.into_iter().map(|(_, input)| input.input).collect(),
400                         output: outputs.into_iter().map(|(_, output)| output).collect(),
401                 };
402                 if tx_to_validate.weight().to_wu() > MAX_STANDARD_TX_WEIGHT as u64 {
403                         return Err(AbortReason::TransactionTooLarge);
404                 }
405
406                 Ok(tx_to_validate)
407         }
408 }
409
410 // The interactive transaction construction protocol allows two peers to collaboratively build a
411 // transaction for broadcast.
412 //
413 // The protocol is turn-based, so we define different states here that we store depending on whose
414 // turn it is to send the next message. The states are defined so that their types ensure we only
415 // perform actions (only send messages) via defined state transitions that do not violate the
416 // protocol.
417 //
418 // An example of a full negotiation and associated states follows:
419 //
420 //     +------------+                         +------------------+---- Holder state after message sent/received ----+
421 //     |            |--(1)- tx_add_input ---->|                  |                  SentChangeMsg                   +
422 //     |            |<-(2)- tx_complete ------|                  |                ReceivedTxComplete                +
423 //     |            |--(3)- tx_add_output --->|                  |                  SentChangeMsg                   +
424 //     |            |<-(4)- tx_complete ------|                  |                ReceivedTxComplete                +
425 //     |            |--(5)- tx_add_input ---->|                  |                  SentChangeMsg                   +
426 //     |   Holder   |<-(6)- tx_add_input -----|   Counterparty   |                ReceivedChangeMsg                 +
427 //     |            |--(7)- tx_remove_output >|                  |                  SentChangeMsg                   +
428 //     |            |<-(8)- tx_add_output ----|                  |                ReceivedChangeMsg                 +
429 //     |            |--(9)- tx_complete ----->|                  |                  SentTxComplete                  +
430 //     |            |<-(10) tx_complete ------|                  |                NegotiationComplete               +
431 //     +------------+                         +------------------+--------------------------------------------------+
432
433 /// Negotiation states that can send & receive `tx_(add|remove)_(input|output)` and `tx_complete`
434 trait State {}
435
436 /// Category of states where we have sent some message to the counterparty, and we are waiting for
437 /// a response.
438 trait SentMsgState: State {
439         fn into_negotiation_context(self) -> NegotiationContext;
440 }
441
442 /// Category of states that our counterparty has put us in after we receive a message from them.
443 trait ReceivedMsgState: State {
444         fn into_negotiation_context(self) -> NegotiationContext;
445 }
446
447 // This macro is a helper for implementing the above state traits for various states subsequently
448 // defined below the macro.
449 macro_rules! define_state {
450         (SENT_MSG_STATE, $state: ident, $doc: expr) => {
451                 define_state!($state, NegotiationContext, $doc);
452                 impl SentMsgState for $state {
453                         fn into_negotiation_context(self) -> NegotiationContext {
454                                 self.0
455                         }
456                 }
457         };
458         (RECEIVED_MSG_STATE, $state: ident, $doc: expr) => {
459                 define_state!($state, NegotiationContext, $doc);
460                 impl ReceivedMsgState for $state {
461                         fn into_negotiation_context(self) -> NegotiationContext {
462                                 self.0
463                         }
464                 }
465         };
466         ($state: ident, $inner: ident, $doc: expr) => {
467                 #[doc = $doc]
468                 #[derive(Debug)]
469                 struct $state($inner);
470                 impl State for $state {}
471         };
472 }
473
474 define_state!(
475         SENT_MSG_STATE,
476         SentChangeMsg,
477         "We have sent a message to the counterparty that has affected our negotiation state."
478 );
479 define_state!(
480         SENT_MSG_STATE,
481         SentTxComplete,
482         "We have sent a `tx_complete` message and are awaiting the counterparty's."
483 );
484 define_state!(
485         RECEIVED_MSG_STATE,
486         ReceivedChangeMsg,
487         "We have received a message from the counterparty that has affected our negotiation state."
488 );
489 define_state!(
490         RECEIVED_MSG_STATE,
491         ReceivedTxComplete,
492         "We have received a `tx_complete` message and the counterparty is awaiting ours."
493 );
494 define_state!(NegotiationComplete, Transaction, "We have exchanged consecutive `tx_complete` messages with the counterparty and the transaction negotiation is complete.");
495 define_state!(
496         NegotiationAborted,
497         AbortReason,
498         "The negotiation has failed and cannot be continued."
499 );
500
501 type StateTransitionResult<S> = Result<S, AbortReason>;
502
503 trait StateTransition<NewState: State, TransitionData> {
504         fn transition(self, data: TransitionData) -> StateTransitionResult<NewState>;
505 }
506
507 // This macro helps define the legal transitions between the states above by implementing
508 // the `StateTransition` trait for each of the states that follow this declaration.
509 macro_rules! define_state_transitions {
510         (SENT_MSG_STATE, [$(DATA $data: ty, TRANSITION $transition: ident),+]) => {
511                 $(
512                         impl<S: SentMsgState> StateTransition<ReceivedChangeMsg, $data> for S {
513                                 fn transition(self, data: $data) -> StateTransitionResult<ReceivedChangeMsg> {
514                                         let mut context = self.into_negotiation_context();
515                                         context.$transition(data)?;
516                                         Ok(ReceivedChangeMsg(context))
517                                 }
518                         }
519                  )*
520         };
521         (RECEIVED_MSG_STATE, [$(DATA $data: ty, TRANSITION $transition: ident),+]) => {
522                 $(
523                         impl<S: ReceivedMsgState> StateTransition<SentChangeMsg, $data> for S {
524                                 fn transition(self, data: $data) -> StateTransitionResult<SentChangeMsg> {
525                                         let mut context = self.into_negotiation_context();
526                                         context.$transition(data)?;
527                                         Ok(SentChangeMsg(context))
528                                 }
529                         }
530                  )*
531         };
532         (TX_COMPLETE, $from_state: ident, $tx_complete_state: ident) => {
533                 impl StateTransition<NegotiationComplete, &msgs::TxComplete> for $tx_complete_state {
534                         fn transition(self, _data: &msgs::TxComplete) -> StateTransitionResult<NegotiationComplete> {
535                                 let context = self.into_negotiation_context();
536                                 let tx = context.build_transaction()?;
537                                 Ok(NegotiationComplete(tx))
538                         }
539                 }
540
541                 impl StateTransition<$tx_complete_state, &msgs::TxComplete> for $from_state {
542                         fn transition(self, _data: &msgs::TxComplete) -> StateTransitionResult<$tx_complete_state> {
543                                 Ok($tx_complete_state(self.into_negotiation_context()))
544                         }
545                 }
546         };
547 }
548
549 // State transitions when we have sent our counterparty some messages and are waiting for them
550 // to respond.
551 define_state_transitions!(SENT_MSG_STATE, [
552         DATA &msgs::TxAddInput, TRANSITION received_tx_add_input,
553         DATA &msgs::TxRemoveInput, TRANSITION received_tx_remove_input,
554         DATA &msgs::TxAddOutput, TRANSITION received_tx_add_output,
555         DATA &msgs::TxRemoveOutput, TRANSITION received_tx_remove_output
556 ]);
557 // State transitions when we have received some messages from our counterparty and we should
558 // respond.
559 define_state_transitions!(RECEIVED_MSG_STATE, [
560         DATA &msgs::TxAddInput, TRANSITION sent_tx_add_input,
561         DATA &msgs::TxRemoveInput, TRANSITION sent_tx_remove_input,
562         DATA &msgs::TxAddOutput, TRANSITION sent_tx_add_output,
563         DATA &msgs::TxRemoveOutput, TRANSITION sent_tx_remove_output
564 ]);
565 define_state_transitions!(TX_COMPLETE, SentChangeMsg, ReceivedTxComplete);
566 define_state_transitions!(TX_COMPLETE, ReceivedChangeMsg, SentTxComplete);
567
568 #[derive(Debug)]
569 enum StateMachine {
570         Indeterminate,
571         SentChangeMsg(SentChangeMsg),
572         ReceivedChangeMsg(ReceivedChangeMsg),
573         SentTxComplete(SentTxComplete),
574         ReceivedTxComplete(ReceivedTxComplete),
575         NegotiationComplete(NegotiationComplete),
576         NegotiationAborted(NegotiationAborted),
577 }
578
579 impl Default for StateMachine {
580         fn default() -> Self {
581                 Self::Indeterminate
582         }
583 }
584
585 // The `StateMachine` internally executes the actual transition between two states and keeps
586 // track of the current state. This macro defines _how_ those state transitions happen to
587 // update the internal state.
588 macro_rules! define_state_machine_transitions {
589         ($transition: ident, $msg: ty, [$(FROM $from_state: ident, TO $to_state: ident),+]) => {
590                 fn $transition(self, msg: $msg) -> StateMachine {
591                         match self {
592                                 $(
593                                         Self::$from_state(s) => match s.transition(msg) {
594                                                 Ok(new_state) => StateMachine::$to_state(new_state),
595                                                 Err(abort_reason) => StateMachine::NegotiationAborted(NegotiationAborted(abort_reason)),
596                                         }
597                                  )*
598                                 _ => StateMachine::NegotiationAborted(NegotiationAborted(AbortReason::UnexpectedCounterpartyMessage)),
599                         }
600                 }
601         };
602 }
603
604 impl StateMachine {
605         fn new(feerate_sat_per_kw: u32, is_initiator: bool, tx_locktime: AbsoluteLockTime) -> Self {
606                 let context = NegotiationContext {
607                         tx_locktime,
608                         holder_is_initiator: is_initiator,
609                         received_tx_add_input_count: 0,
610                         received_tx_add_output_count: 0,
611                         inputs: new_hash_map(),
612                         prevtx_outpoints: new_hash_set(),
613                         outputs: new_hash_map(),
614                         feerate_sat_per_kw,
615                 };
616                 if is_initiator {
617                         Self::ReceivedChangeMsg(ReceivedChangeMsg(context))
618                 } else {
619                         Self::SentChangeMsg(SentChangeMsg(context))
620                 }
621         }
622
623         // TxAddInput
624         define_state_machine_transitions!(sent_tx_add_input, &msgs::TxAddInput, [
625                 FROM ReceivedChangeMsg, TO SentChangeMsg,
626                 FROM ReceivedTxComplete, TO SentChangeMsg
627         ]);
628         define_state_machine_transitions!(received_tx_add_input, &msgs::TxAddInput, [
629                 FROM SentChangeMsg, TO ReceivedChangeMsg,
630                 FROM SentTxComplete, TO ReceivedChangeMsg
631         ]);
632
633         // TxAddOutput
634         define_state_machine_transitions!(sent_tx_add_output, &msgs::TxAddOutput, [
635                 FROM ReceivedChangeMsg, TO SentChangeMsg,
636                 FROM ReceivedTxComplete, TO SentChangeMsg
637         ]);
638         define_state_machine_transitions!(received_tx_add_output, &msgs::TxAddOutput, [
639                 FROM SentChangeMsg, TO ReceivedChangeMsg,
640                 FROM SentTxComplete, TO ReceivedChangeMsg
641         ]);
642
643         // TxRemoveInput
644         define_state_machine_transitions!(sent_tx_remove_input, &msgs::TxRemoveInput, [
645                 FROM ReceivedChangeMsg, TO SentChangeMsg,
646                 FROM ReceivedTxComplete, TO SentChangeMsg
647         ]);
648         define_state_machine_transitions!(received_tx_remove_input, &msgs::TxRemoveInput, [
649                 FROM SentChangeMsg, TO ReceivedChangeMsg,
650                 FROM SentTxComplete, TO ReceivedChangeMsg
651         ]);
652
653         // TxRemoveOutput
654         define_state_machine_transitions!(sent_tx_remove_output, &msgs::TxRemoveOutput, [
655                 FROM ReceivedChangeMsg, TO SentChangeMsg,
656                 FROM ReceivedTxComplete, TO SentChangeMsg
657         ]);
658         define_state_machine_transitions!(received_tx_remove_output, &msgs::TxRemoveOutput, [
659                 FROM SentChangeMsg, TO ReceivedChangeMsg,
660                 FROM SentTxComplete, TO ReceivedChangeMsg
661         ]);
662
663         // TxComplete
664         define_state_machine_transitions!(sent_tx_complete, &msgs::TxComplete, [
665                 FROM ReceivedChangeMsg, TO SentTxComplete,
666                 FROM ReceivedTxComplete, TO NegotiationComplete
667         ]);
668         define_state_machine_transitions!(received_tx_complete, &msgs::TxComplete, [
669                 FROM SentChangeMsg, TO ReceivedTxComplete,
670                 FROM SentTxComplete, TO NegotiationComplete
671         ]);
672 }
673
674 pub struct InteractiveTxConstructor {
675         state_machine: StateMachine,
676         channel_id: ChannelId,
677         inputs_to_contribute: Vec<(SerialId, TxIn, TransactionU16LenLimited)>,
678         outputs_to_contribute: Vec<(SerialId, TxOut)>,
679 }
680
681 pub enum InteractiveTxMessageSend {
682         TxAddInput(msgs::TxAddInput),
683         TxAddOutput(msgs::TxAddOutput),
684         TxComplete(msgs::TxComplete),
685 }
686
687 // This macro executes a state machine transition based on a provided action.
688 macro_rules! do_state_transition {
689         ($self: ident, $transition: ident, $msg: expr) => {{
690                 let state_machine = core::mem::take(&mut $self.state_machine);
691                 $self.state_machine = state_machine.$transition($msg);
692                 match &$self.state_machine {
693                         StateMachine::NegotiationAborted(state) => Err(state.0.clone()),
694                         _ => Ok(()),
695                 }
696         }};
697 }
698
699 fn generate_holder_serial_id<ES: Deref>(entropy_source: &ES, is_initiator: bool) -> SerialId
700 where
701         ES::Target: EntropySource,
702 {
703         let rand_bytes = entropy_source.get_secure_random_bytes();
704         let mut serial_id_bytes = [0u8; 8];
705         serial_id_bytes.copy_from_slice(&rand_bytes[..8]);
706         let mut serial_id = u64::from_be_bytes(serial_id_bytes);
707         if serial_id.is_for_initiator() != is_initiator {
708                 serial_id ^= 1;
709         }
710         serial_id
711 }
712
713 pub enum HandleTxCompleteValue {
714         SendTxMessage(InteractiveTxMessageSend),
715         SendTxComplete(InteractiveTxMessageSend, Transaction),
716         NegotiationComplete(Transaction),
717 }
718
719 impl InteractiveTxConstructor {
720         /// Instantiates a new `InteractiveTxConstructor`.
721         ///
722         /// A tuple is returned containing the newly instantiate `InteractiveTxConstructor` and optionally
723         /// an initial wrapped `Tx_` message which the holder needs to send to the counterparty.
724         pub fn new<ES: Deref>(
725                 entropy_source: &ES, channel_id: ChannelId, feerate_sat_per_kw: u32, is_initiator: bool,
726                 funding_tx_locktime: AbsoluteLockTime,
727                 inputs_to_contribute: Vec<(TxIn, TransactionU16LenLimited)>,
728                 outputs_to_contribute: Vec<TxOut>,
729         ) -> (Self, Option<InteractiveTxMessageSend>)
730         where
731                 ES::Target: EntropySource,
732         {
733                 let state_machine =
734                         StateMachine::new(feerate_sat_per_kw, is_initiator, funding_tx_locktime);
735                 let mut inputs_to_contribute: Vec<(SerialId, TxIn, TransactionU16LenLimited)> =
736                         inputs_to_contribute
737                                 .into_iter()
738                                 .map(|(input, tx)| {
739                                         let serial_id = generate_holder_serial_id(entropy_source, is_initiator);
740                                         (serial_id, input, tx)
741                                 })
742                                 .collect();
743                 // We'll sort by the randomly generated serial IDs, effectively shuffling the order of the inputs
744                 // as the user passed them to us to avoid leaking any potential categorization of transactions
745                 // before we pass any of the inputs to the counterparty.
746                 inputs_to_contribute.sort_unstable_by_key(|(serial_id, _, _)| *serial_id);
747                 let mut outputs_to_contribute: Vec<(SerialId, TxOut)> = outputs_to_contribute
748                         .into_iter()
749                         .map(|output| {
750                                 let serial_id = generate_holder_serial_id(entropy_source, is_initiator);
751                                 (serial_id, output)
752                         })
753                         .collect();
754                 // In the same manner and for the same rationale as the inputs above, we'll shuffle the outputs.
755                 outputs_to_contribute.sort_unstable_by_key(|(serial_id, _)| *serial_id);
756                 let mut constructor =
757                         Self { state_machine, channel_id, inputs_to_contribute, outputs_to_contribute };
758                 let message_send = if is_initiator {
759                         match constructor.maybe_send_message() {
760                                 Ok(msg_send) => Some(msg_send),
761                                 Err(_) => {
762                                         debug_assert!(
763                                                 false,
764                                                 "We should always be able to start our state machine successfully"
765                                         );
766                                         None
767                                 },
768                         }
769                 } else {
770                         None
771                 };
772                 (constructor, message_send)
773         }
774
775         fn maybe_send_message(&mut self) -> Result<InteractiveTxMessageSend, AbortReason> {
776                 // We first attempt to send inputs we want to add, then outputs. Once we are done sending
777                 // them both, then we always send tx_complete.
778                 if let Some((serial_id, input, prevtx)) = self.inputs_to_contribute.pop() {
779                         let msg = msgs::TxAddInput {
780                                 channel_id: self.channel_id,
781                                 serial_id,
782                                 prevtx,
783                                 prevtx_out: input.previous_output.vout,
784                                 sequence: input.sequence.to_consensus_u32(),
785                         };
786                         do_state_transition!(self, sent_tx_add_input, &msg)?;
787                         Ok(InteractiveTxMessageSend::TxAddInput(msg))
788                 } else if let Some((serial_id, output)) = self.outputs_to_contribute.pop() {
789                         let msg = msgs::TxAddOutput {
790                                 channel_id: self.channel_id,
791                                 serial_id,
792                                 sats: output.value,
793                                 script: output.script_pubkey,
794                         };
795                         do_state_transition!(self, sent_tx_add_output, &msg)?;
796                         Ok(InteractiveTxMessageSend::TxAddOutput(msg))
797                 } else {
798                         let msg = msgs::TxComplete { channel_id: self.channel_id };
799                         do_state_transition!(self, sent_tx_complete, &msg)?;
800                         Ok(InteractiveTxMessageSend::TxComplete(msg))
801                 }
802         }
803
804         pub fn handle_tx_add_input(
805                 &mut self, msg: &msgs::TxAddInput,
806         ) -> Result<InteractiveTxMessageSend, AbortReason> {
807                 do_state_transition!(self, received_tx_add_input, msg)?;
808                 self.maybe_send_message()
809         }
810
811         pub fn handle_tx_remove_input(
812                 &mut self, msg: &msgs::TxRemoveInput,
813         ) -> Result<InteractiveTxMessageSend, AbortReason> {
814                 do_state_transition!(self, received_tx_remove_input, msg)?;
815                 self.maybe_send_message()
816         }
817
818         pub fn handle_tx_add_output(
819                 &mut self, msg: &msgs::TxAddOutput,
820         ) -> Result<InteractiveTxMessageSend, AbortReason> {
821                 do_state_transition!(self, received_tx_add_output, msg)?;
822                 self.maybe_send_message()
823         }
824
825         pub fn handle_tx_remove_output(
826                 &mut self, msg: &msgs::TxRemoveOutput,
827         ) -> Result<InteractiveTxMessageSend, AbortReason> {
828                 do_state_transition!(self, received_tx_remove_output, msg)?;
829                 self.maybe_send_message()
830         }
831
832         pub fn handle_tx_complete(
833                 &mut self, msg: &msgs::TxComplete,
834         ) -> Result<HandleTxCompleteValue, AbortReason> {
835                 do_state_transition!(self, received_tx_complete, msg)?;
836                 match &self.state_machine {
837                         StateMachine::ReceivedTxComplete(_) => {
838                                 let msg_send = self.maybe_send_message()?;
839                                 match &self.state_machine {
840                                         StateMachine::NegotiationComplete(s) => {
841                                                 Ok(HandleTxCompleteValue::SendTxComplete(msg_send, s.0.clone()))
842                                         },
843                                         StateMachine::SentChangeMsg(_) => {
844                                                 Ok(HandleTxCompleteValue::SendTxMessage(msg_send))
845                                         }, // We either had an input or output to contribute.
846                                         _ => {
847                                                 debug_assert!(false, "We cannot transition to any other states after receiving `tx_complete` and responding");
848                                                 Err(AbortReason::InvalidStateTransition)
849                                         },
850                                 }
851                         },
852                         StateMachine::NegotiationComplete(s) => {
853                                 Ok(HandleTxCompleteValue::NegotiationComplete(s.0.clone()))
854                         },
855                         _ => {
856                                 debug_assert!(
857                                         false,
858                                         "We cannot transition to any other states after receiving `tx_complete`"
859                                 );
860                                 Err(AbortReason::InvalidStateTransition)
861                         },
862                 }
863         }
864 }
865
866 #[cfg(test)]
867 mod tests {
868         use crate::chain::chaininterface::FEERATE_FLOOR_SATS_PER_KW;
869         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
870         use crate::ln::interactivetxs::{
871                 generate_holder_serial_id, AbortReason, HandleTxCompleteValue, InteractiveTxConstructor,
872                 InteractiveTxMessageSend, MAX_INPUTS_OUTPUTS_COUNT, MAX_RECEIVED_TX_ADD_INPUT_COUNT,
873                 MAX_RECEIVED_TX_ADD_OUTPUT_COUNT,
874         };
875         use crate::ln::ChannelId;
876         use crate::sign::EntropySource;
877         use crate::util::atomic_counter::AtomicCounter;
878         use crate::util::ser::TransactionU16LenLimited;
879         use bitcoin::blockdata::opcodes;
880         use bitcoin::blockdata::script::Builder;
881         use bitcoin::{
882                 absolute::LockTime as AbsoluteLockTime, OutPoint, Sequence, Transaction, TxIn, TxOut,
883         };
884         use core::ops::Deref;
885
886         // A simple entropy source that works based on an atomic counter.
887         struct TestEntropySource(AtomicCounter);
888         impl EntropySource for TestEntropySource {
889                 fn get_secure_random_bytes(&self) -> [u8; 32] {
890                         let mut res = [0u8; 32];
891                         let increment = self.0.get_increment();
892                         for i in 0..32 {
893                                 // Rotate the increment value by 'i' bits to the right, to avoid clashes
894                                 // when `generate_local_serial_id` does a parity flip on consecutive calls for the
895                                 // same party.
896                                 let rotated_increment = increment.rotate_right(i as u32);
897                                 res[i] = (rotated_increment & 0xff) as u8;
898                         }
899                         res
900                 }
901         }
902
903         // An entropy source that deliberately returns you the same seed every time. We use this
904         // to test if the constructor would catch inputs/outputs that are attempting to be added
905         // with duplicate serial ids.
906         struct DuplicateEntropySource;
907         impl EntropySource for DuplicateEntropySource {
908                 fn get_secure_random_bytes(&self) -> [u8; 32] {
909                         let mut res = [0u8; 32];
910                         let count = 1u64;
911                         res[0..8].copy_from_slice(&count.to_be_bytes());
912                         res
913                 }
914         }
915
916         #[derive(Debug, PartialEq, Eq)]
917         enum ErrorCulprit {
918                 NodeA,
919                 NodeB,
920                 // Some error values are only checked at the end of the negotiation and are not easy to attribute
921                 // to a particular party. Both parties would indicate an `AbortReason` in this case.
922                 // e.g. Exceeded max inputs and outputs after negotiation.
923                 Indeterminate,
924         }
925
926         struct TestSession {
927                 inputs_a: Vec<(TxIn, TransactionU16LenLimited)>,
928                 outputs_a: Vec<TxOut>,
929                 inputs_b: Vec<(TxIn, TransactionU16LenLimited)>,
930                 outputs_b: Vec<TxOut>,
931                 expect_error: Option<(AbortReason, ErrorCulprit)>,
932         }
933
934         fn do_test_interactive_tx_constructor(session: TestSession) {
935                 let entropy_source = TestEntropySource(AtomicCounter::new());
936                 do_test_interactive_tx_constructor_internal(session, &&entropy_source);
937         }
938
939         fn do_test_interactive_tx_constructor_with_entropy_source<ES: Deref>(
940                 session: TestSession, entropy_source: ES,
941         ) where
942                 ES::Target: EntropySource,
943         {
944                 do_test_interactive_tx_constructor_internal(session, &entropy_source);
945         }
946
947         fn do_test_interactive_tx_constructor_internal<ES: Deref>(
948                 session: TestSession, entropy_source: &ES,
949         ) where
950                 ES::Target: EntropySource,
951         {
952                 let channel_id = ChannelId(entropy_source.get_secure_random_bytes());
953                 let tx_locktime = AbsoluteLockTime::from_height(1337).unwrap();
954
955                 let (mut constructor_a, first_message_a) = InteractiveTxConstructor::new(
956                         entropy_source,
957                         channel_id,
958                         FEERATE_FLOOR_SATS_PER_KW * 10,
959                         true,
960                         tx_locktime,
961                         session.inputs_a,
962                         session.outputs_a,
963                 );
964                 let (mut constructor_b, first_message_b) = InteractiveTxConstructor::new(
965                         entropy_source,
966                         channel_id,
967                         FEERATE_FLOOR_SATS_PER_KW * 10,
968                         false,
969                         tx_locktime,
970                         session.inputs_b,
971                         session.outputs_b,
972                 );
973
974                 let handle_message_send =
975                         |msg: InteractiveTxMessageSend, for_constructor: &mut InteractiveTxConstructor| {
976                                 match msg {
977                                         InteractiveTxMessageSend::TxAddInput(msg) => for_constructor
978                                                 .handle_tx_add_input(&msg)
979                                                 .map(|msg_send| (Some(msg_send), None)),
980                                         InteractiveTxMessageSend::TxAddOutput(msg) => for_constructor
981                                                 .handle_tx_add_output(&msg)
982                                                 .map(|msg_send| (Some(msg_send), None)),
983                                         InteractiveTxMessageSend::TxComplete(msg) => {
984                                                 for_constructor.handle_tx_complete(&msg).map(|value| match value {
985                                                         HandleTxCompleteValue::SendTxMessage(msg_send) => {
986                                                                 (Some(msg_send), None)
987                                                         },
988                                                         HandleTxCompleteValue::SendTxComplete(msg_send, tx) => {
989                                                                 (Some(msg_send), Some(tx))
990                                                         },
991                                                         HandleTxCompleteValue::NegotiationComplete(tx) => (None, Some(tx)),
992                                                 })
993                                         },
994                                 }
995                         };
996
997                 assert!(first_message_b.is_none());
998                 let mut message_send_a = first_message_a;
999                 let mut message_send_b = None;
1000                 let mut final_tx_a = None;
1001                 let mut final_tx_b = None;
1002                 while final_tx_a.is_none() || final_tx_b.is_none() {
1003                         if let Some(message_send_a) = message_send_a.take() {
1004                                 match handle_message_send(message_send_a, &mut constructor_b) {
1005                                         Ok((msg_send, final_tx)) => {
1006                                                 message_send_b = msg_send;
1007                                                 final_tx_b = final_tx;
1008                                         },
1009                                         Err(abort_reason) => {
1010                                                 let error_culprit = match abort_reason {
1011                                                         AbortReason::ExceededNumberOfInputsOrOutputs => {
1012                                                                 ErrorCulprit::Indeterminate
1013                                                         },
1014                                                         _ => ErrorCulprit::NodeA,
1015                                                 };
1016                                                 assert_eq!(Some((abort_reason, error_culprit)), session.expect_error);
1017                                                 assert!(message_send_b.is_none());
1018                                                 return;
1019                                         },
1020                                 }
1021                         }
1022                         if let Some(message_send_b) = message_send_b.take() {
1023                                 match handle_message_send(message_send_b, &mut constructor_a) {
1024                                         Ok((msg_send, final_tx)) => {
1025                                                 message_send_a = msg_send;
1026                                                 final_tx_a = final_tx;
1027                                         },
1028                                         Err(abort_reason) => {
1029                                                 let error_culprit = match abort_reason {
1030                                                         AbortReason::ExceededNumberOfInputsOrOutputs => {
1031                                                                 ErrorCulprit::Indeterminate
1032                                                         },
1033                                                         _ => ErrorCulprit::NodeB,
1034                                                 };
1035                                                 assert_eq!(Some((abort_reason, error_culprit)), session.expect_error);
1036                                                 assert!(message_send_a.is_none());
1037                                                 return;
1038                                         },
1039                                 }
1040                         }
1041                 }
1042                 assert!(message_send_a.is_none());
1043                 assert!(message_send_b.is_none());
1044                 assert_eq!(final_tx_a, final_tx_b);
1045                 assert!(session.expect_error.is_none());
1046         }
1047
1048         fn generate_tx(values: &[u64]) -> Transaction {
1049                 generate_tx_with_locktime(values, 1337)
1050         }
1051
1052         fn generate_tx_with_locktime(values: &[u64], locktime: u32) -> Transaction {
1053                 Transaction {
1054                         version: 2,
1055                         lock_time: AbsoluteLockTime::from_height(locktime).unwrap(),
1056                         input: vec![TxIn { ..Default::default() }],
1057                         output: values
1058                                 .iter()
1059                                 .map(|value| TxOut {
1060                                         value: *value,
1061                                         script_pubkey: Builder::new()
1062                                                 .push_opcode(opcodes::OP_TRUE)
1063                                                 .into_script()
1064                                                 .to_v0_p2wsh(),
1065                                 })
1066                                 .collect(),
1067                 }
1068         }
1069
1070         fn generate_inputs(values: &[u64]) -> Vec<(TxIn, TransactionU16LenLimited)> {
1071                 let tx = generate_tx(values);
1072                 let txid = tx.txid();
1073                 tx.output
1074                         .iter()
1075                         .enumerate()
1076                         .map(|(idx, _)| {
1077                                 let input = TxIn {
1078                                         previous_output: OutPoint { txid, vout: idx as u32 },
1079                                         script_sig: Default::default(),
1080                                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
1081                                         witness: Default::default(),
1082                                 };
1083                                 (input, TransactionU16LenLimited::new(tx.clone()).unwrap())
1084                         })
1085                         .collect()
1086         }
1087
1088         fn generate_outputs(values: &[u64]) -> Vec<TxOut> {
1089                 values
1090                         .iter()
1091                         .map(|value| TxOut {
1092                                 value: *value,
1093                                 script_pubkey: Builder::new()
1094                                         .push_opcode(opcodes::OP_TRUE)
1095                                         .into_script()
1096                                         .to_v0_p2wsh(),
1097                         })
1098                         .collect()
1099         }
1100
1101         fn generate_fixed_number_of_inputs(count: u16) -> Vec<(TxIn, TransactionU16LenLimited)> {
1102                 // Generate transactions with a total `count` number of outputs such that no transaction has a
1103                 // serialized length greater than u16::MAX.
1104                 let max_outputs_per_prevtx = 1_500;
1105                 let mut remaining = count;
1106                 let mut inputs: Vec<(TxIn, TransactionU16LenLimited)> = Vec::with_capacity(count as usize);
1107
1108                 while remaining > 0 {
1109                         let tx_output_count = remaining.min(max_outputs_per_prevtx);
1110                         remaining -= tx_output_count;
1111
1112                         // Use unique locktime for each tx so outpoints are different across transactions
1113                         let tx = generate_tx_with_locktime(
1114                                 &vec![1_000_000; tx_output_count as usize],
1115                                 (1337 + remaining).into(),
1116                         );
1117                         let txid = tx.txid();
1118
1119                         let mut temp: Vec<(TxIn, TransactionU16LenLimited)> = tx
1120                                 .output
1121                                 .iter()
1122                                 .enumerate()
1123                                 .map(|(idx, _)| {
1124                                         let input = TxIn {
1125                                                 previous_output: OutPoint { txid, vout: idx as u32 },
1126                                                 script_sig: Default::default(),
1127                                                 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
1128                                                 witness: Default::default(),
1129                                         };
1130                                         (input, TransactionU16LenLimited::new(tx.clone()).unwrap())
1131                                 })
1132                                 .collect();
1133
1134                         inputs.append(&mut temp);
1135                 }
1136
1137                 inputs
1138         }
1139
1140         fn generate_fixed_number_of_outputs(count: u16) -> Vec<TxOut> {
1141                 // Set a constant value for each TxOut
1142                 generate_outputs(&vec![1_000_000; count as usize])
1143         }
1144
1145         fn generate_non_witness_output(value: u64) -> TxOut {
1146                 TxOut {
1147                         value,
1148                         script_pubkey: Builder::new().push_opcode(opcodes::OP_TRUE).into_script().to_p2sh(),
1149                 }
1150         }
1151
1152         #[test]
1153         fn test_interactive_tx_constructor() {
1154                 // No contributions.
1155                 do_test_interactive_tx_constructor(TestSession {
1156                         inputs_a: vec![],
1157                         outputs_a: vec![],
1158                         inputs_b: vec![],
1159                         outputs_b: vec![],
1160                         expect_error: Some((AbortReason::InsufficientFees, ErrorCulprit::NodeA)),
1161                 });
1162                 // Single contribution, no initiator inputs.
1163                 do_test_interactive_tx_constructor(TestSession {
1164                         inputs_a: vec![],
1165                         outputs_a: generate_outputs(&[1_000_000]),
1166                         inputs_b: vec![],
1167                         outputs_b: vec![],
1168                         expect_error: Some((AbortReason::OutputsValueExceedsInputsValue, ErrorCulprit::NodeA)),
1169                 });
1170                 // Single contribution, no initiator outputs.
1171                 do_test_interactive_tx_constructor(TestSession {
1172                         inputs_a: generate_inputs(&[1_000_000]),
1173                         outputs_a: vec![],
1174                         inputs_b: vec![],
1175                         outputs_b: vec![],
1176                         expect_error: None,
1177                 });
1178                 // Single contribution, insufficient fees.
1179                 do_test_interactive_tx_constructor(TestSession {
1180                         inputs_a: generate_inputs(&[1_000_000]),
1181                         outputs_a: generate_outputs(&[1_000_000]),
1182                         inputs_b: vec![],
1183                         outputs_b: vec![],
1184                         expect_error: Some((AbortReason::InsufficientFees, ErrorCulprit::NodeA)),
1185                 });
1186                 // Initiator contributes sufficient fees, but non-initiator does not.
1187                 do_test_interactive_tx_constructor(TestSession {
1188                         inputs_a: generate_inputs(&[1_000_000]),
1189                         outputs_a: vec![],
1190                         inputs_b: generate_inputs(&[100_000]),
1191                         outputs_b: generate_outputs(&[100_000]),
1192                         expect_error: Some((AbortReason::InsufficientFees, ErrorCulprit::NodeB)),
1193                 });
1194                 // Multi-input-output contributions from both sides.
1195                 do_test_interactive_tx_constructor(TestSession {
1196                         inputs_a: generate_inputs(&[1_000_000, 1_000_000]),
1197                         outputs_a: generate_outputs(&[1_000_000, 200_000]),
1198                         inputs_b: generate_inputs(&[1_000_000, 500_000]),
1199                         outputs_b: generate_outputs(&[1_000_000, 400_000]),
1200                         expect_error: None,
1201                 });
1202
1203                 // Prevout from initiator is not a witness program
1204                 let non_segwit_output_tx = {
1205                         let mut tx = generate_tx(&[1_000_000]);
1206                         tx.output.push(TxOut {
1207                                 script_pubkey: Builder::new()
1208                                         .push_opcode(opcodes::all::OP_RETURN)
1209                                         .into_script()
1210                                         .to_p2sh(),
1211                                 ..Default::default()
1212                         });
1213
1214                         TransactionU16LenLimited::new(tx).unwrap()
1215                 };
1216                 let non_segwit_input = TxIn {
1217                         previous_output: OutPoint {
1218                                 txid: non_segwit_output_tx.as_transaction().txid(),
1219                                 vout: 1,
1220                         },
1221                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
1222                         ..Default::default()
1223                 };
1224                 do_test_interactive_tx_constructor(TestSession {
1225                         inputs_a: vec![(non_segwit_input, non_segwit_output_tx)],
1226                         outputs_a: vec![],
1227                         inputs_b: vec![],
1228                         outputs_b: vec![],
1229                         expect_error: Some((AbortReason::PrevTxOutInvalid, ErrorCulprit::NodeA)),
1230                 });
1231
1232                 // Invalid input sequence from initiator.
1233                 let tx = TransactionU16LenLimited::new(generate_tx(&[1_000_000])).unwrap();
1234                 let invalid_sequence_input = TxIn {
1235                         previous_output: OutPoint { txid: tx.as_transaction().txid(), vout: 0 },
1236                         ..Default::default()
1237                 };
1238                 do_test_interactive_tx_constructor(TestSession {
1239                         inputs_a: vec![(invalid_sequence_input, tx.clone())],
1240                         outputs_a: generate_outputs(&[1_000_000]),
1241                         inputs_b: vec![],
1242                         outputs_b: vec![],
1243                         expect_error: Some((AbortReason::IncorrectInputSequenceValue, ErrorCulprit::NodeA)),
1244                 });
1245                 // Duplicate prevout from initiator.
1246                 let duplicate_input = TxIn {
1247                         previous_output: OutPoint { txid: tx.as_transaction().txid(), vout: 0 },
1248                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
1249                         ..Default::default()
1250                 };
1251                 do_test_interactive_tx_constructor(TestSession {
1252                         inputs_a: vec![(duplicate_input.clone(), tx.clone()), (duplicate_input, tx.clone())],
1253                         outputs_a: generate_outputs(&[1_000_000]),
1254                         inputs_b: vec![],
1255                         outputs_b: vec![],
1256                         expect_error: Some((AbortReason::PrevTxOutInvalid, ErrorCulprit::NodeA)),
1257                 });
1258                 // Non-initiator uses same prevout as initiator.
1259                 let duplicate_input = TxIn {
1260                         previous_output: OutPoint { txid: tx.as_transaction().txid(), vout: 0 },
1261                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
1262                         ..Default::default()
1263                 };
1264                 do_test_interactive_tx_constructor(TestSession {
1265                         inputs_a: vec![(duplicate_input.clone(), tx.clone())],
1266                         outputs_a: generate_outputs(&[1_000_000]),
1267                         inputs_b: vec![(duplicate_input.clone(), tx.clone())],
1268                         outputs_b: vec![],
1269                         expect_error: Some((AbortReason::PrevTxOutInvalid, ErrorCulprit::NodeB)),
1270                 });
1271                 // Initiator sends too many TxAddInputs
1272                 do_test_interactive_tx_constructor(TestSession {
1273                         inputs_a: generate_fixed_number_of_inputs(MAX_RECEIVED_TX_ADD_INPUT_COUNT + 1),
1274                         outputs_a: vec![],
1275                         inputs_b: vec![],
1276                         outputs_b: vec![],
1277                         expect_error: Some((AbortReason::ReceivedTooManyTxAddInputs, ErrorCulprit::NodeA)),
1278                 });
1279                 // Attempt to queue up two inputs with duplicate serial ids. We use a deliberately bad
1280                 // entropy source, `DuplicateEntropySource` to simulate this.
1281                 do_test_interactive_tx_constructor_with_entropy_source(
1282                         TestSession {
1283                                 inputs_a: generate_fixed_number_of_inputs(2),
1284                                 outputs_a: vec![],
1285                                 inputs_b: vec![],
1286                                 outputs_b: vec![],
1287                                 expect_error: Some((AbortReason::DuplicateSerialId, ErrorCulprit::NodeA)),
1288                         },
1289                         &DuplicateEntropySource,
1290                 );
1291                 // Initiator sends too many TxAddOutputs.
1292                 do_test_interactive_tx_constructor(TestSession {
1293                         inputs_a: vec![],
1294                         outputs_a: generate_fixed_number_of_outputs(MAX_RECEIVED_TX_ADD_OUTPUT_COUNT + 1),
1295                         inputs_b: vec![],
1296                         outputs_b: vec![],
1297                         expect_error: Some((AbortReason::ReceivedTooManyTxAddOutputs, ErrorCulprit::NodeA)),
1298                 });
1299                 // Initiator sends an output below dust value.
1300                 do_test_interactive_tx_constructor(TestSession {
1301                         inputs_a: vec![],
1302                         outputs_a: generate_outputs(&[1]),
1303                         inputs_b: vec![],
1304                         outputs_b: vec![],
1305                         expect_error: Some((AbortReason::BelowDustLimit, ErrorCulprit::NodeA)),
1306                 });
1307                 // Initiator sends an output above maximum sats allowed.
1308                 do_test_interactive_tx_constructor(TestSession {
1309                         inputs_a: vec![],
1310                         outputs_a: generate_outputs(&[TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1]),
1311                         inputs_b: vec![],
1312                         outputs_b: vec![],
1313                         expect_error: Some((AbortReason::ExceededMaximumSatsAllowed, ErrorCulprit::NodeA)),
1314                 });
1315                 // Initiator sends an output without a witness program.
1316                 do_test_interactive_tx_constructor(TestSession {
1317                         inputs_a: vec![],
1318                         outputs_a: vec![generate_non_witness_output(1_000_000)],
1319                         inputs_b: vec![],
1320                         outputs_b: vec![],
1321                         expect_error: Some((AbortReason::InvalidOutputScript, ErrorCulprit::NodeA)),
1322                 });
1323                 // Attempt to queue up two outputs with duplicate serial ids. We use a deliberately bad
1324                 // entropy source, `DuplicateEntropySource` to simulate this.
1325                 do_test_interactive_tx_constructor_with_entropy_source(
1326                         TestSession {
1327                                 inputs_a: vec![],
1328                                 outputs_a: generate_fixed_number_of_outputs(2),
1329                                 inputs_b: vec![],
1330                                 outputs_b: vec![],
1331                                 expect_error: Some((AbortReason::DuplicateSerialId, ErrorCulprit::NodeA)),
1332                         },
1333                         &DuplicateEntropySource,
1334                 );
1335
1336                 // Peer contributed more output value than inputs
1337                 do_test_interactive_tx_constructor(TestSession {
1338                         inputs_a: generate_inputs(&[100_000]),
1339                         outputs_a: generate_outputs(&[1_000_000]),
1340                         inputs_b: vec![],
1341                         outputs_b: vec![],
1342                         expect_error: Some((AbortReason::OutputsValueExceedsInputsValue, ErrorCulprit::NodeA)),
1343                 });
1344
1345                 // Peer contributed more than allowed number of inputs.
1346                 do_test_interactive_tx_constructor(TestSession {
1347                         inputs_a: generate_fixed_number_of_inputs(MAX_INPUTS_OUTPUTS_COUNT as u16 + 1),
1348                         outputs_a: vec![],
1349                         inputs_b: vec![],
1350                         outputs_b: vec![],
1351                         expect_error: Some((
1352                                 AbortReason::ExceededNumberOfInputsOrOutputs,
1353                                 ErrorCulprit::Indeterminate,
1354                         )),
1355                 });
1356                 // Peer contributed more than allowed number of outputs.
1357                 do_test_interactive_tx_constructor(TestSession {
1358                         inputs_a: generate_inputs(&[TOTAL_BITCOIN_SUPPLY_SATOSHIS]),
1359                         outputs_a: generate_fixed_number_of_outputs(MAX_INPUTS_OUTPUTS_COUNT as u16 + 1),
1360                         inputs_b: vec![],
1361                         outputs_b: vec![],
1362                         expect_error: Some((
1363                                 AbortReason::ExceededNumberOfInputsOrOutputs,
1364                                 ErrorCulprit::Indeterminate,
1365                         )),
1366                 });
1367         }
1368
1369         #[test]
1370         fn test_generate_local_serial_id() {
1371                 let entropy_source = TestEntropySource(AtomicCounter::new());
1372
1373                 // Initiators should have even serial id, non-initiators should have odd serial id.
1374                 assert_eq!(generate_holder_serial_id(&&entropy_source, true) % 2, 0);
1375                 assert_eq!(generate_holder_serial_id(&&entropy_source, false) % 2, 1)
1376         }
1377 }