Check if msg.script.is_witness_program() before checking version
[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) {
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                 debug_assert!((msg.prevtx_out as usize) < tx.output.len());
310                 let prev_output = &tx.output[msg.prevtx_out as usize];
311                 self.prevtx_outpoints.insert(input.previous_output);
312                 self.inputs.insert(
313                         msg.serial_id,
314                         TxInputWithPrevOutput { input, prev_output: prev_output.clone() },
315                 );
316         }
317
318         fn sent_tx_add_output(&mut self, msg: &msgs::TxAddOutput) {
319                 self.outputs
320                         .insert(msg.serial_id, TxOut { value: msg.sats, script_pubkey: msg.script.clone() });
321         }
322
323         fn sent_tx_remove_input(&mut self, msg: &msgs::TxRemoveInput) {
324                 self.inputs.remove(&msg.serial_id);
325         }
326
327         fn sent_tx_remove_output(&mut self, msg: &msgs::TxRemoveOutput) {
328                 self.outputs.remove(&msg.serial_id);
329         }
330
331         fn build_transaction(self) -> Result<Transaction, AbortReason> {
332                 // The receiving node:
333                 // MUST fail the negotiation if:
334
335                 // - the peer's total input satoshis is less than their outputs
336                 let mut counterparty_inputs_value: u64 = 0;
337                 let mut counterparty_outputs_value: u64 = 0;
338                 for input in self.counterparty_inputs_contributed() {
339                         counterparty_inputs_value =
340                                 counterparty_inputs_value.saturating_add(input.prev_output.value);
341                 }
342                 for output in self.counterparty_outputs_contributed() {
343                         counterparty_outputs_value = counterparty_outputs_value.saturating_add(output.value);
344                 }
345                 if counterparty_inputs_value < counterparty_outputs_value {
346                         return Err(AbortReason::OutputsValueExceedsInputsValue);
347                 }
348
349                 // - there are more than 252 inputs
350                 // - there are more than 252 outputs
351                 if self.inputs.len() > MAX_INPUTS_OUTPUTS_COUNT
352                         || self.outputs.len() > MAX_INPUTS_OUTPUTS_COUNT
353                 {
354                         return Err(AbortReason::ExceededNumberOfInputsOrOutputs);
355                 }
356
357                 // TODO: How do we enforce their fees cover the witness without knowing its expected length?
358                 const INPUT_WEIGHT: u64 = BASE_INPUT_WEIGHT + EMPTY_SCRIPT_SIG_WEIGHT;
359
360                 // - the peer's paid feerate does not meet or exceed the agreed feerate (based on the minimum fee).
361                 let counterparty_output_weight_contributed: u64 = self
362                         .counterparty_outputs_contributed()
363                         .map(|output| {
364                                 (8 /* value */ + output.script_pubkey.consensus_encode(&mut sink()).unwrap() as u64)
365                                         * WITNESS_SCALE_FACTOR as u64
366                         })
367                         .sum();
368                 let counterparty_weight_contributed = counterparty_output_weight_contributed
369                         + self.counterparty_inputs_contributed().count() as u64 * INPUT_WEIGHT;
370                 let counterparty_fees_contributed =
371                         counterparty_inputs_value.saturating_sub(counterparty_outputs_value);
372                 let mut required_counterparty_contribution_fee =
373                         fee_for_weight(self.feerate_sat_per_kw, counterparty_weight_contributed);
374                 if !self.holder_is_initiator {
375                         // if is the non-initiator:
376                         //      - the initiator's fees do not cover the common fields (version, segwit marker + flag,
377                         //              input count, output count, locktime)
378                         let tx_common_fields_weight =
379                         (4 /* version */ + 4 /* locktime */ + 1 /* input count */ + 1 /* output count */) *
380                             WITNESS_SCALE_FACTOR as u64 + 2 /* segwit marker + flag */;
381                         let tx_common_fields_fee =
382                                 fee_for_weight(self.feerate_sat_per_kw, tx_common_fields_weight);
383                         required_counterparty_contribution_fee += tx_common_fields_fee;
384                 }
385                 if counterparty_fees_contributed < required_counterparty_contribution_fee {
386                         return Err(AbortReason::InsufficientFees);
387                 }
388
389                 // Inputs and outputs must be sorted by serial_id
390                 let mut inputs = self.inputs.into_iter().collect::<Vec<_>>();
391                 let mut outputs = self.outputs.into_iter().collect::<Vec<_>>();
392                 inputs.sort_unstable_by_key(|(serial_id, _)| *serial_id);
393                 outputs.sort_unstable_by_key(|(serial_id, _)| *serial_id);
394
395                 let tx_to_validate = Transaction {
396                         version: 2,
397                         lock_time: self.tx_locktime,
398                         input: inputs.into_iter().map(|(_, input)| input.input).collect(),
399                         output: outputs.into_iter().map(|(_, output)| output).collect(),
400                 };
401                 if tx_to_validate.weight().to_wu() > MAX_STANDARD_TX_WEIGHT as u64 {
402                         return Err(AbortReason::TransactionTooLarge);
403                 }
404
405                 Ok(tx_to_validate)
406         }
407 }
408
409 // The interactive transaction construction protocol allows two peers to collaboratively build a
410 // transaction for broadcast.
411 //
412 // The protocol is turn-based, so we define different states here that we store depending on whose
413 // turn it is to send the next message. The states are defined so that their types ensure we only
414 // perform actions (only send messages) via defined state transitions that do not violate the
415 // protocol.
416 //
417 // An example of a full negotiation and associated states follows:
418 //
419 //     +------------+                         +------------------+---- Holder state after message sent/received ----+
420 //     |            |--(1)- tx_add_input ---->|                  |                  SentChangeMsg                   +
421 //     |            |<-(2)- tx_complete ------|                  |                ReceivedTxComplete                +
422 //     |            |--(3)- tx_add_output --->|                  |                  SentChangeMsg                   +
423 //     |            |<-(4)- tx_complete ------|                  |                ReceivedTxComplete                +
424 //     |            |--(5)- tx_add_input ---->|                  |                  SentChangeMsg                   +
425 //     |   Holder   |<-(6)- tx_add_input -----|   Counterparty   |                ReceivedChangeMsg                 +
426 //     |            |--(7)- tx_remove_output >|                  |                  SentChangeMsg                   +
427 //     |            |<-(8)- tx_add_output ----|                  |                ReceivedChangeMsg                 +
428 //     |            |--(9)- tx_complete ----->|                  |                  SentTxComplete                  +
429 //     |            |<-(10) tx_complete ------|                  |                NegotiationComplete               +
430 //     +------------+                         +------------------+--------------------------------------------------+
431
432 /// Negotiation states that can send & receive `tx_(add|remove)_(input|output)` and `tx_complete`
433 trait State {}
434
435 /// Category of states where we have sent some message to the counterparty, and we are waiting for
436 /// a response.
437 trait SentMsgState: State {
438         fn into_negotiation_context(self) -> NegotiationContext;
439 }
440
441 /// Category of states that our counterparty has put us in after we receive a message from them.
442 trait ReceivedMsgState: State {
443         fn into_negotiation_context(self) -> NegotiationContext;
444 }
445
446 // This macro is a helper for implementing the above state traits for various states subsequently
447 // defined below the macro.
448 macro_rules! define_state {
449         (SENT_MSG_STATE, $state: ident, $doc: expr) => {
450                 define_state!($state, NegotiationContext, $doc);
451                 impl SentMsgState for $state {
452                         fn into_negotiation_context(self) -> NegotiationContext {
453                                 self.0
454                         }
455                 }
456         };
457         (RECEIVED_MSG_STATE, $state: ident, $doc: expr) => {
458                 define_state!($state, NegotiationContext, $doc);
459                 impl ReceivedMsgState for $state {
460                         fn into_negotiation_context(self) -> NegotiationContext {
461                                 self.0
462                         }
463                 }
464         };
465         ($state: ident, $inner: ident, $doc: expr) => {
466                 #[doc = $doc]
467                 #[derive(Debug)]
468                 struct $state($inner);
469                 impl State for $state {}
470         };
471 }
472
473 define_state!(
474         SENT_MSG_STATE,
475         SentChangeMsg,
476         "We have sent a message to the counterparty that has affected our negotiation state."
477 );
478 define_state!(
479         SENT_MSG_STATE,
480         SentTxComplete,
481         "We have sent a `tx_complete` message and are awaiting the counterparty's."
482 );
483 define_state!(
484         RECEIVED_MSG_STATE,
485         ReceivedChangeMsg,
486         "We have received a message from the counterparty that has affected our negotiation state."
487 );
488 define_state!(
489         RECEIVED_MSG_STATE,
490         ReceivedTxComplete,
491         "We have received a `tx_complete` message and the counterparty is awaiting ours."
492 );
493 define_state!(NegotiationComplete, Transaction, "We have exchanged consecutive `tx_complete` messages with the counterparty and the transaction negotiation is complete.");
494 define_state!(
495         NegotiationAborted,
496         AbortReason,
497         "The negotiation has failed and cannot be continued."
498 );
499
500 type StateTransitionResult<S> = Result<S, AbortReason>;
501
502 trait StateTransition<NewState: State, TransitionData> {
503         fn transition(self, data: TransitionData) -> StateTransitionResult<NewState>;
504 }
505
506 // This macro helps define the legal transitions between the states above by implementing
507 // the `StateTransition` trait for each of the states that follow this declaration.
508 macro_rules! define_state_transitions {
509         (SENT_MSG_STATE, [$(DATA $data: ty, TRANSITION $transition: ident),+]) => {
510                 $(
511                         impl<S: SentMsgState> StateTransition<ReceivedChangeMsg, $data> for S {
512                                 fn transition(self, data: $data) -> StateTransitionResult<ReceivedChangeMsg> {
513                                         let mut context = self.into_negotiation_context();
514                                         context.$transition(data)?;
515                                         Ok(ReceivedChangeMsg(context))
516                                 }
517                         }
518                  )*
519         };
520         (RECEIVED_MSG_STATE, [$(DATA $data: ty, TRANSITION $transition: ident),+]) => {
521                 $(
522                         impl<S: ReceivedMsgState> StateTransition<SentChangeMsg, $data> for S {
523                                 fn transition(self, data: $data) -> StateTransitionResult<SentChangeMsg> {
524                                         let mut context = self.into_negotiation_context();
525                                         context.$transition(data);
526                                         Ok(SentChangeMsg(context))
527                                 }
528                         }
529                  )*
530         };
531         (TX_COMPLETE, $from_state: ident, $tx_complete_state: ident) => {
532                 impl StateTransition<NegotiationComplete, &msgs::TxComplete> for $tx_complete_state {
533                         fn transition(self, _data: &msgs::TxComplete) -> StateTransitionResult<NegotiationComplete> {
534                                 let context = self.into_negotiation_context();
535                                 let tx = context.build_transaction()?;
536                                 Ok(NegotiationComplete(tx))
537                         }
538                 }
539
540                 impl StateTransition<$tx_complete_state, &msgs::TxComplete> for $from_state {
541                         fn transition(self, _data: &msgs::TxComplete) -> StateTransitionResult<$tx_complete_state> {
542                                 Ok($tx_complete_state(self.into_negotiation_context()))
543                         }
544                 }
545         };
546 }
547
548 // State transitions when we have sent our counterparty some messages and are waiting for them
549 // to respond.
550 define_state_transitions!(SENT_MSG_STATE, [
551         DATA &msgs::TxAddInput, TRANSITION received_tx_add_input,
552         DATA &msgs::TxRemoveInput, TRANSITION received_tx_remove_input,
553         DATA &msgs::TxAddOutput, TRANSITION received_tx_add_output,
554         DATA &msgs::TxRemoveOutput, TRANSITION received_tx_remove_output
555 ]);
556 // State transitions when we have received some messages from our counterparty and we should
557 // respond.
558 define_state_transitions!(RECEIVED_MSG_STATE, [
559         DATA &msgs::TxAddInput, TRANSITION sent_tx_add_input,
560         DATA &msgs::TxRemoveInput, TRANSITION sent_tx_remove_input,
561         DATA &msgs::TxAddOutput, TRANSITION sent_tx_add_output,
562         DATA &msgs::TxRemoveOutput, TRANSITION sent_tx_remove_output
563 ]);
564 define_state_transitions!(TX_COMPLETE, SentChangeMsg, ReceivedTxComplete);
565 define_state_transitions!(TX_COMPLETE, ReceivedChangeMsg, SentTxComplete);
566
567 #[derive(Debug)]
568 enum StateMachine {
569         Indeterminate,
570         SentChangeMsg(SentChangeMsg),
571         ReceivedChangeMsg(ReceivedChangeMsg),
572         SentTxComplete(SentTxComplete),
573         ReceivedTxComplete(ReceivedTxComplete),
574         NegotiationComplete(NegotiationComplete),
575         NegotiationAborted(NegotiationAborted),
576 }
577
578 impl Default for StateMachine {
579         fn default() -> Self {
580                 Self::Indeterminate
581         }
582 }
583
584 // The `StateMachine` internally executes the actual transition between two states and keeps
585 // track of the current state. This macro defines _how_ those state transitions happen to
586 // update the internal state.
587 macro_rules! define_state_machine_transitions {
588         ($transition: ident, $msg: ty, [$(FROM $from_state: ident, TO $to_state: ident),+]) => {
589                 fn $transition(self, msg: $msg) -> StateMachine {
590                         match self {
591                                 $(
592                                         Self::$from_state(s) => match s.transition(msg) {
593                                                 Ok(new_state) => StateMachine::$to_state(new_state),
594                                                 Err(abort_reason) => StateMachine::NegotiationAborted(NegotiationAborted(abort_reason)),
595                                         }
596                                  )*
597                                 _ => StateMachine::NegotiationAborted(NegotiationAborted(AbortReason::UnexpectedCounterpartyMessage)),
598                         }
599                 }
600         };
601 }
602
603 impl StateMachine {
604         fn new(feerate_sat_per_kw: u32, is_initiator: bool, tx_locktime: AbsoluteLockTime) -> Self {
605                 let context = NegotiationContext {
606                         tx_locktime,
607                         holder_is_initiator: is_initiator,
608                         received_tx_add_input_count: 0,
609                         received_tx_add_output_count: 0,
610                         inputs: new_hash_map(),
611                         prevtx_outpoints: new_hash_set(),
612                         outputs: new_hash_map(),
613                         feerate_sat_per_kw,
614                 };
615                 if is_initiator {
616                         Self::ReceivedChangeMsg(ReceivedChangeMsg(context))
617                 } else {
618                         Self::SentChangeMsg(SentChangeMsg(context))
619                 }
620         }
621
622         // TxAddInput
623         define_state_machine_transitions!(sent_tx_add_input, &msgs::TxAddInput, [
624                 FROM ReceivedChangeMsg, TO SentChangeMsg,
625                 FROM ReceivedTxComplete, TO SentChangeMsg
626         ]);
627         define_state_machine_transitions!(received_tx_add_input, &msgs::TxAddInput, [
628                 FROM SentChangeMsg, TO ReceivedChangeMsg,
629                 FROM SentTxComplete, TO ReceivedChangeMsg
630         ]);
631
632         // TxAddOutput
633         define_state_machine_transitions!(sent_tx_add_output, &msgs::TxAddOutput, [
634                 FROM ReceivedChangeMsg, TO SentChangeMsg,
635                 FROM ReceivedTxComplete, TO SentChangeMsg
636         ]);
637         define_state_machine_transitions!(received_tx_add_output, &msgs::TxAddOutput, [
638                 FROM SentChangeMsg, TO ReceivedChangeMsg,
639                 FROM SentTxComplete, TO ReceivedChangeMsg
640         ]);
641
642         // TxRemoveInput
643         define_state_machine_transitions!(sent_tx_remove_input, &msgs::TxRemoveInput, [
644                 FROM ReceivedChangeMsg, TO SentChangeMsg,
645                 FROM ReceivedTxComplete, TO SentChangeMsg
646         ]);
647         define_state_machine_transitions!(received_tx_remove_input, &msgs::TxRemoveInput, [
648                 FROM SentChangeMsg, TO ReceivedChangeMsg,
649                 FROM SentTxComplete, TO ReceivedChangeMsg
650         ]);
651
652         // TxRemoveOutput
653         define_state_machine_transitions!(sent_tx_remove_output, &msgs::TxRemoveOutput, [
654                 FROM ReceivedChangeMsg, TO SentChangeMsg,
655                 FROM ReceivedTxComplete, TO SentChangeMsg
656         ]);
657         define_state_machine_transitions!(received_tx_remove_output, &msgs::TxRemoveOutput, [
658                 FROM SentChangeMsg, TO ReceivedChangeMsg,
659                 FROM SentTxComplete, TO ReceivedChangeMsg
660         ]);
661
662         // TxComplete
663         define_state_machine_transitions!(sent_tx_complete, &msgs::TxComplete, [
664                 FROM ReceivedChangeMsg, TO SentTxComplete,
665                 FROM ReceivedTxComplete, TO NegotiationComplete
666         ]);
667         define_state_machine_transitions!(received_tx_complete, &msgs::TxComplete, [
668                 FROM SentChangeMsg, TO ReceivedTxComplete,
669                 FROM SentTxComplete, TO NegotiationComplete
670         ]);
671 }
672
673 pub struct InteractiveTxConstructor {
674         state_machine: StateMachine,
675         channel_id: ChannelId,
676         inputs_to_contribute: Vec<(SerialId, TxIn, TransactionU16LenLimited)>,
677         outputs_to_contribute: Vec<(SerialId, TxOut)>,
678 }
679
680 pub enum InteractiveTxMessageSend {
681         TxAddInput(msgs::TxAddInput),
682         TxAddOutput(msgs::TxAddOutput),
683         TxComplete(msgs::TxComplete),
684 }
685
686 // This macro executes a state machine transition based on a provided action.
687 macro_rules! do_state_transition {
688         ($self: ident, $transition: ident, $msg: expr) => {{
689                 let state_machine = core::mem::take(&mut $self.state_machine);
690                 $self.state_machine = state_machine.$transition($msg);
691                 match &$self.state_machine {
692                         StateMachine::NegotiationAborted(state) => Err(state.0.clone()),
693                         _ => Ok(()),
694                 }
695         }};
696 }
697
698 fn generate_holder_serial_id<ES: Deref>(entropy_source: &ES, is_initiator: bool) -> SerialId
699 where
700         ES::Target: EntropySource,
701 {
702         let rand_bytes = entropy_source.get_secure_random_bytes();
703         let mut serial_id_bytes = [0u8; 8];
704         serial_id_bytes.copy_from_slice(&rand_bytes[..8]);
705         let mut serial_id = u64::from_be_bytes(serial_id_bytes);
706         if serial_id.is_for_initiator() != is_initiator {
707                 serial_id ^= 1;
708         }
709         serial_id
710 }
711
712 pub enum HandleTxCompleteValue {
713         SendTxMessage(InteractiveTxMessageSend),
714         SendTxComplete(InteractiveTxMessageSend, Transaction),
715         NegotiationComplete(Transaction),
716 }
717
718 impl InteractiveTxConstructor {
719         /// Instantiates a new `InteractiveTxConstructor`.
720         ///
721         /// A tuple is returned containing the newly instantiate `InteractiveTxConstructor` and optionally
722         /// an initial wrapped `Tx_` message which the holder needs to send to the counterparty.
723         pub fn new<ES: Deref>(
724                 entropy_source: &ES, channel_id: ChannelId, feerate_sat_per_kw: u32, is_initiator: bool,
725                 funding_tx_locktime: AbsoluteLockTime,
726                 inputs_to_contribute: Vec<(TxIn, TransactionU16LenLimited)>,
727                 outputs_to_contribute: Vec<TxOut>,
728         ) -> (Self, Option<InteractiveTxMessageSend>)
729         where
730                 ES::Target: EntropySource,
731         {
732                 let state_machine =
733                         StateMachine::new(feerate_sat_per_kw, is_initiator, funding_tx_locktime);
734                 let mut inputs_to_contribute: Vec<(SerialId, TxIn, TransactionU16LenLimited)> =
735                         inputs_to_contribute
736                                 .into_iter()
737                                 .map(|(input, tx)| {
738                                         let serial_id = generate_holder_serial_id(entropy_source, is_initiator);
739                                         (serial_id, input, tx)
740                                 })
741                                 .collect();
742                 // We'll sort by the randomly generated serial IDs, effectively shuffling the order of the inputs
743                 // as the user passed them to us to avoid leaking any potential categorization of transactions
744                 // before we pass any of the inputs to the counterparty.
745                 inputs_to_contribute.sort_unstable_by_key(|(serial_id, _, _)| *serial_id);
746                 let mut outputs_to_contribute: Vec<(SerialId, TxOut)> = outputs_to_contribute
747                         .into_iter()
748                         .map(|output| {
749                                 let serial_id = generate_holder_serial_id(entropy_source, is_initiator);
750                                 (serial_id, output)
751                         })
752                         .collect();
753                 // In the same manner and for the same rationale as the inputs above, we'll shuffle the outputs.
754                 outputs_to_contribute.sort_unstable_by_key(|(serial_id, _)| *serial_id);
755                 let mut constructor =
756                         Self { state_machine, channel_id, inputs_to_contribute, outputs_to_contribute };
757                 let message_send = if is_initiator {
758                         match constructor.maybe_send_message() {
759                                 Ok(msg_send) => Some(msg_send),
760                                 Err(_) => {
761                                         debug_assert!(
762                                                 false,
763                                                 "We should always be able to start our state machine successfully"
764                                         );
765                                         None
766                                 },
767                         }
768                 } else {
769                         None
770                 };
771                 (constructor, message_send)
772         }
773
774         fn maybe_send_message(&mut self) -> Result<InteractiveTxMessageSend, AbortReason> {
775                 // We first attempt to send inputs we want to add, then outputs. Once we are done sending
776                 // them both, then we always send tx_complete.
777                 if let Some((serial_id, input, prevtx)) = self.inputs_to_contribute.pop() {
778                         let msg = msgs::TxAddInput {
779                                 channel_id: self.channel_id,
780                                 serial_id,
781                                 prevtx,
782                                 prevtx_out: input.previous_output.vout,
783                                 sequence: input.sequence.to_consensus_u32(),
784                         };
785                         do_state_transition!(self, sent_tx_add_input, &msg)?;
786                         Ok(InteractiveTxMessageSend::TxAddInput(msg))
787                 } else if let Some((serial_id, output)) = self.outputs_to_contribute.pop() {
788                         let msg = msgs::TxAddOutput {
789                                 channel_id: self.channel_id,
790                                 serial_id,
791                                 sats: output.value,
792                                 script: output.script_pubkey,
793                         };
794                         do_state_transition!(self, sent_tx_add_output, &msg)?;
795                         Ok(InteractiveTxMessageSend::TxAddOutput(msg))
796                 } else {
797                         let msg = msgs::TxComplete { channel_id: self.channel_id };
798                         do_state_transition!(self, sent_tx_complete, &msg)?;
799                         Ok(InteractiveTxMessageSend::TxComplete(msg))
800                 }
801         }
802
803         pub fn handle_tx_add_input(
804                 &mut self, msg: &msgs::TxAddInput,
805         ) -> Result<InteractiveTxMessageSend, AbortReason> {
806                 do_state_transition!(self, received_tx_add_input, msg)?;
807                 self.maybe_send_message()
808         }
809
810         pub fn handle_tx_remove_input(
811                 &mut self, msg: &msgs::TxRemoveInput,
812         ) -> Result<InteractiveTxMessageSend, AbortReason> {
813                 do_state_transition!(self, received_tx_remove_input, msg)?;
814                 self.maybe_send_message()
815         }
816
817         pub fn handle_tx_add_output(
818                 &mut self, msg: &msgs::TxAddOutput,
819         ) -> Result<InteractiveTxMessageSend, AbortReason> {
820                 do_state_transition!(self, received_tx_add_output, msg)?;
821                 self.maybe_send_message()
822         }
823
824         pub fn handle_tx_remove_output(
825                 &mut self, msg: &msgs::TxRemoveOutput,
826         ) -> Result<InteractiveTxMessageSend, AbortReason> {
827                 do_state_transition!(self, received_tx_remove_output, msg)?;
828                 self.maybe_send_message()
829         }
830
831         pub fn handle_tx_complete(
832                 &mut self, msg: &msgs::TxComplete,
833         ) -> Result<HandleTxCompleteValue, AbortReason> {
834                 do_state_transition!(self, received_tx_complete, msg)?;
835                 match &self.state_machine {
836                         StateMachine::ReceivedTxComplete(_) => {
837                                 let msg_send = self.maybe_send_message()?;
838                                 match &self.state_machine {
839                                         StateMachine::NegotiationComplete(s) => {
840                                                 Ok(HandleTxCompleteValue::SendTxComplete(msg_send, s.0.clone()))
841                                         },
842                                         StateMachine::SentChangeMsg(_) => {
843                                                 Ok(HandleTxCompleteValue::SendTxMessage(msg_send))
844                                         }, // We either had an input or output to contribute.
845                                         _ => {
846                                                 debug_assert!(false, "We cannot transition to any other states after receiving `tx_complete` and responding");
847                                                 Err(AbortReason::InvalidStateTransition)
848                                         },
849                                 }
850                         },
851                         StateMachine::NegotiationComplete(s) => {
852                                 Ok(HandleTxCompleteValue::NegotiationComplete(s.0.clone()))
853                         },
854                         _ => {
855                                 debug_assert!(
856                                         false,
857                                         "We cannot transition to any other states after receiving `tx_complete`"
858                                 );
859                                 Err(AbortReason::InvalidStateTransition)
860                         },
861                 }
862         }
863 }
864
865 #[cfg(test)]
866 mod tests {
867         use crate::chain::chaininterface::FEERATE_FLOOR_SATS_PER_KW;
868         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
869         use crate::ln::interactivetxs::{
870                 generate_holder_serial_id, AbortReason, HandleTxCompleteValue, InteractiveTxConstructor,
871                 InteractiveTxMessageSend, MAX_INPUTS_OUTPUTS_COUNT, MAX_RECEIVED_TX_ADD_INPUT_COUNT,
872                 MAX_RECEIVED_TX_ADD_OUTPUT_COUNT,
873         };
874         use crate::ln::ChannelId;
875         use crate::sign::EntropySource;
876         use crate::util::atomic_counter::AtomicCounter;
877         use crate::util::ser::TransactionU16LenLimited;
878         use bitcoin::blockdata::opcodes;
879         use bitcoin::blockdata::script::Builder;
880         use bitcoin::{
881                 absolute::LockTime as AbsoluteLockTime, OutPoint, Sequence, Transaction, TxIn, TxOut,
882         };
883         use core::ops::Deref;
884
885         // A simple entropy source that works based on an atomic counter.
886         struct TestEntropySource(AtomicCounter);
887         impl EntropySource for TestEntropySource {
888                 fn get_secure_random_bytes(&self) -> [u8; 32] {
889                         let mut res = [0u8; 32];
890                         let increment = self.0.get_increment();
891                         for i in 0..32 {
892                                 // Rotate the increment value by 'i' bits to the right, to avoid clashes
893                                 // when `generate_local_serial_id` does a parity flip on consecutive calls for the
894                                 // same party.
895                                 let rotated_increment = increment.rotate_right(i as u32);
896                                 res[i] = (rotated_increment & 0xff) as u8;
897                         }
898                         res
899                 }
900         }
901
902         // An entropy source that deliberately returns you the same seed every time. We use this
903         // to test if the constructor would catch inputs/outputs that are attempting to be added
904         // with duplicate serial ids.
905         struct DuplicateEntropySource;
906         impl EntropySource for DuplicateEntropySource {
907                 fn get_secure_random_bytes(&self) -> [u8; 32] {
908                         let mut res = [0u8; 32];
909                         let count = 1u64;
910                         res[0..8].copy_from_slice(&count.to_be_bytes());
911                         res
912                 }
913         }
914
915         #[derive(Debug, PartialEq, Eq)]
916         enum ErrorCulprit {
917                 NodeA,
918                 NodeB,
919                 // Some error values are only checked at the end of the negotiation and are not easy to attribute
920                 // to a particular party. Both parties would indicate an `AbortReason` in this case.
921                 // e.g. Exceeded max inputs and outputs after negotiation.
922                 Indeterminate,
923         }
924
925         struct TestSession {
926                 inputs_a: Vec<(TxIn, TransactionU16LenLimited)>,
927                 outputs_a: Vec<TxOut>,
928                 inputs_b: Vec<(TxIn, TransactionU16LenLimited)>,
929                 outputs_b: Vec<TxOut>,
930                 expect_error: Option<(AbortReason, ErrorCulprit)>,
931         }
932
933         fn do_test_interactive_tx_constructor(session: TestSession) {
934                 let entropy_source = TestEntropySource(AtomicCounter::new());
935                 do_test_interactive_tx_constructor_internal(session, &&entropy_source);
936         }
937
938         fn do_test_interactive_tx_constructor_with_entropy_source<ES: Deref>(
939                 session: TestSession, entropy_source: ES,
940         ) where
941                 ES::Target: EntropySource,
942         {
943                 do_test_interactive_tx_constructor_internal(session, &entropy_source);
944         }
945
946         fn do_test_interactive_tx_constructor_internal<ES: Deref>(
947                 session: TestSession, entropy_source: &ES,
948         ) where
949                 ES::Target: EntropySource,
950         {
951                 let channel_id = ChannelId(entropy_source.get_secure_random_bytes());
952                 let tx_locktime = AbsoluteLockTime::from_height(1337).unwrap();
953
954                 let (mut constructor_a, first_message_a) = InteractiveTxConstructor::new(
955                         entropy_source,
956                         channel_id,
957                         FEERATE_FLOOR_SATS_PER_KW * 10,
958                         true,
959                         tx_locktime,
960                         session.inputs_a,
961                         session.outputs_a,
962                 );
963                 let (mut constructor_b, first_message_b) = InteractiveTxConstructor::new(
964                         entropy_source,
965                         channel_id,
966                         FEERATE_FLOOR_SATS_PER_KW * 10,
967                         false,
968                         tx_locktime,
969                         session.inputs_b,
970                         session.outputs_b,
971                 );
972
973                 let handle_message_send =
974                         |msg: InteractiveTxMessageSend, for_constructor: &mut InteractiveTxConstructor| {
975                                 match msg {
976                                         InteractiveTxMessageSend::TxAddInput(msg) => for_constructor
977                                                 .handle_tx_add_input(&msg)
978                                                 .map(|msg_send| (Some(msg_send), None)),
979                                         InteractiveTxMessageSend::TxAddOutput(msg) => for_constructor
980                                                 .handle_tx_add_output(&msg)
981                                                 .map(|msg_send| (Some(msg_send), None)),
982                                         InteractiveTxMessageSend::TxComplete(msg) => {
983                                                 for_constructor.handle_tx_complete(&msg).map(|value| match value {
984                                                         HandleTxCompleteValue::SendTxMessage(msg_send) => {
985                                                                 (Some(msg_send), None)
986                                                         },
987                                                         HandleTxCompleteValue::SendTxComplete(msg_send, tx) => {
988                                                                 (Some(msg_send), Some(tx))
989                                                         },
990                                                         HandleTxCompleteValue::NegotiationComplete(tx) => (None, Some(tx)),
991                                                 })
992                                         },
993                                 }
994                         };
995
996                 assert!(first_message_b.is_none());
997                 let mut message_send_a = first_message_a;
998                 let mut message_send_b = None;
999                 let mut final_tx_a = None;
1000                 let mut final_tx_b = None;
1001                 while final_tx_a.is_none() || final_tx_b.is_none() {
1002                         if let Some(message_send_a) = message_send_a.take() {
1003                                 match handle_message_send(message_send_a, &mut constructor_b) {
1004                                         Ok((msg_send, final_tx)) => {
1005                                                 message_send_b = msg_send;
1006                                                 final_tx_b = final_tx;
1007                                         },
1008                                         Err(abort_reason) => {
1009                                                 let error_culprit = match abort_reason {
1010                                                         AbortReason::ExceededNumberOfInputsOrOutputs => {
1011                                                                 ErrorCulprit::Indeterminate
1012                                                         },
1013                                                         _ => ErrorCulprit::NodeA,
1014                                                 };
1015                                                 assert_eq!(Some((abort_reason, error_culprit)), session.expect_error);
1016                                                 assert!(message_send_b.is_none());
1017                                                 return;
1018                                         },
1019                                 }
1020                         }
1021                         if let Some(message_send_b) = message_send_b.take() {
1022                                 match handle_message_send(message_send_b, &mut constructor_a) {
1023                                         Ok((msg_send, final_tx)) => {
1024                                                 message_send_a = msg_send;
1025                                                 final_tx_a = final_tx;
1026                                         },
1027                                         Err(abort_reason) => {
1028                                                 let error_culprit = match abort_reason {
1029                                                         AbortReason::ExceededNumberOfInputsOrOutputs => {
1030                                                                 ErrorCulprit::Indeterminate
1031                                                         },
1032                                                         _ => ErrorCulprit::NodeB,
1033                                                 };
1034                                                 assert_eq!(Some((abort_reason, error_culprit)), session.expect_error);
1035                                                 assert!(message_send_a.is_none());
1036                                                 return;
1037                                         },
1038                                 }
1039                         }
1040                 }
1041                 assert!(message_send_a.is_none());
1042                 assert!(message_send_b.is_none());
1043                 assert_eq!(final_tx_a, final_tx_b);
1044                 assert!(session.expect_error.is_none());
1045         }
1046
1047         fn generate_tx(values: &[u64]) -> Transaction {
1048                 generate_tx_with_locktime(values, 1337)
1049         }
1050
1051         fn generate_tx_with_locktime(values: &[u64], locktime: u32) -> Transaction {
1052                 Transaction {
1053                         version: 2,
1054                         lock_time: AbsoluteLockTime::from_height(locktime).unwrap(),
1055                         input: vec![TxIn { ..Default::default() }],
1056                         output: values
1057                                 .iter()
1058                                 .map(|value| TxOut {
1059                                         value: *value,
1060                                         script_pubkey: Builder::new()
1061                                                 .push_opcode(opcodes::OP_TRUE)
1062                                                 .into_script()
1063                                                 .to_v0_p2wsh(),
1064                                 })
1065                                 .collect(),
1066                 }
1067         }
1068
1069         fn generate_inputs(values: &[u64]) -> Vec<(TxIn, TransactionU16LenLimited)> {
1070                 let tx = generate_tx(values);
1071                 let txid = tx.txid();
1072                 tx.output
1073                         .iter()
1074                         .enumerate()
1075                         .map(|(idx, _)| {
1076                                 let input = TxIn {
1077                                         previous_output: OutPoint { txid, vout: idx as u32 },
1078                                         script_sig: Default::default(),
1079                                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
1080                                         witness: Default::default(),
1081                                 };
1082                                 (input, TransactionU16LenLimited::new(tx.clone()).unwrap())
1083                         })
1084                         .collect()
1085         }
1086
1087         fn generate_outputs(values: &[u64]) -> Vec<TxOut> {
1088                 values
1089                         .iter()
1090                         .map(|value| TxOut {
1091                                 value: *value,
1092                                 script_pubkey: Builder::new()
1093                                         .push_opcode(opcodes::OP_TRUE)
1094                                         .into_script()
1095                                         .to_v0_p2wsh(),
1096                         })
1097                         .collect()
1098         }
1099
1100         fn generate_fixed_number_of_inputs(count: u16) -> Vec<(TxIn, TransactionU16LenLimited)> {
1101                 // Generate transactions with a total `count` number of outputs such that no transaction has a
1102                 // serialized length greater than u16::MAX.
1103                 let max_outputs_per_prevtx = 1_500;
1104                 let mut remaining = count;
1105                 let mut inputs: Vec<(TxIn, TransactionU16LenLimited)> = Vec::with_capacity(count as usize);
1106
1107                 while remaining > 0 {
1108                         let tx_output_count = remaining.min(max_outputs_per_prevtx);
1109                         remaining -= tx_output_count;
1110
1111                         // Use unique locktime for each tx so outpoints are different across transactions
1112                         let tx = generate_tx_with_locktime(
1113                                 &vec![1_000_000; tx_output_count as usize],
1114                                 (1337 + remaining).into(),
1115                         );
1116                         let txid = tx.txid();
1117
1118                         let mut temp: Vec<(TxIn, TransactionU16LenLimited)> = tx
1119                                 .output
1120                                 .iter()
1121                                 .enumerate()
1122                                 .map(|(idx, _)| {
1123                                         let input = TxIn {
1124                                                 previous_output: OutPoint { txid, vout: idx as u32 },
1125                                                 script_sig: Default::default(),
1126                                                 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
1127                                                 witness: Default::default(),
1128                                         };
1129                                         (input, TransactionU16LenLimited::new(tx.clone()).unwrap())
1130                                 })
1131                                 .collect();
1132
1133                         inputs.append(&mut temp);
1134                 }
1135
1136                 inputs
1137         }
1138
1139         fn generate_fixed_number_of_outputs(count: u16) -> Vec<TxOut> {
1140                 // Set a constant value for each TxOut
1141                 generate_outputs(&vec![1_000_000; count as usize])
1142         }
1143
1144         fn generate_non_witness_output(value: u64) -> TxOut {
1145                 TxOut {
1146                         value,
1147                         script_pubkey: Builder::new().push_opcode(opcodes::OP_TRUE).into_script().to_p2sh(),
1148                 }
1149         }
1150
1151         #[test]
1152         fn test_interactive_tx_constructor() {
1153                 // No contributions.
1154                 do_test_interactive_tx_constructor(TestSession {
1155                         inputs_a: vec![],
1156                         outputs_a: vec![],
1157                         inputs_b: vec![],
1158                         outputs_b: vec![],
1159                         expect_error: Some((AbortReason::InsufficientFees, ErrorCulprit::NodeA)),
1160                 });
1161                 // Single contribution, no initiator inputs.
1162                 do_test_interactive_tx_constructor(TestSession {
1163                         inputs_a: vec![],
1164                         outputs_a: generate_outputs(&[1_000_000]),
1165                         inputs_b: vec![],
1166                         outputs_b: vec![],
1167                         expect_error: Some((AbortReason::OutputsValueExceedsInputsValue, ErrorCulprit::NodeA)),
1168                 });
1169                 // Single contribution, no initiator outputs.
1170                 do_test_interactive_tx_constructor(TestSession {
1171                         inputs_a: generate_inputs(&[1_000_000]),
1172                         outputs_a: vec![],
1173                         inputs_b: vec![],
1174                         outputs_b: vec![],
1175                         expect_error: None,
1176                 });
1177                 // Single contribution, insufficient fees.
1178                 do_test_interactive_tx_constructor(TestSession {
1179                         inputs_a: generate_inputs(&[1_000_000]),
1180                         outputs_a: generate_outputs(&[1_000_000]),
1181                         inputs_b: vec![],
1182                         outputs_b: vec![],
1183                         expect_error: Some((AbortReason::InsufficientFees, ErrorCulprit::NodeA)),
1184                 });
1185                 // Initiator contributes sufficient fees, but non-initiator does not.
1186                 do_test_interactive_tx_constructor(TestSession {
1187                         inputs_a: generate_inputs(&[1_000_000]),
1188                         outputs_a: vec![],
1189                         inputs_b: generate_inputs(&[100_000]),
1190                         outputs_b: generate_outputs(&[100_000]),
1191                         expect_error: Some((AbortReason::InsufficientFees, ErrorCulprit::NodeB)),
1192                 });
1193                 // Multi-input-output contributions from both sides.
1194                 do_test_interactive_tx_constructor(TestSession {
1195                         inputs_a: generate_inputs(&[1_000_000, 1_000_000]),
1196                         outputs_a: generate_outputs(&[1_000_000, 200_000]),
1197                         inputs_b: generate_inputs(&[1_000_000, 500_000]),
1198                         outputs_b: generate_outputs(&[1_000_000, 400_000]),
1199                         expect_error: None,
1200                 });
1201
1202                 // Prevout from initiator is not a witness program
1203                 let non_segwit_output_tx = {
1204                         let mut tx = generate_tx(&[1_000_000]);
1205                         tx.output.push(TxOut {
1206                                 script_pubkey: Builder::new()
1207                                         .push_opcode(opcodes::all::OP_RETURN)
1208                                         .into_script()
1209                                         .to_p2sh(),
1210                                 ..Default::default()
1211                         });
1212
1213                         TransactionU16LenLimited::new(tx).unwrap()
1214                 };
1215                 let non_segwit_input = TxIn {
1216                         previous_output: OutPoint {
1217                                 txid: non_segwit_output_tx.as_transaction().txid(),
1218                                 vout: 1,
1219                         },
1220                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
1221                         ..Default::default()
1222                 };
1223                 do_test_interactive_tx_constructor(TestSession {
1224                         inputs_a: vec![(non_segwit_input, non_segwit_output_tx)],
1225                         outputs_a: vec![],
1226                         inputs_b: vec![],
1227                         outputs_b: vec![],
1228                         expect_error: Some((AbortReason::PrevTxOutInvalid, ErrorCulprit::NodeA)),
1229                 });
1230
1231                 // Invalid input sequence from initiator.
1232                 let tx = TransactionU16LenLimited::new(generate_tx(&[1_000_000])).unwrap();
1233                 let invalid_sequence_input = TxIn {
1234                         previous_output: OutPoint { txid: tx.as_transaction().txid(), vout: 0 },
1235                         ..Default::default()
1236                 };
1237                 do_test_interactive_tx_constructor(TestSession {
1238                         inputs_a: vec![(invalid_sequence_input, tx.clone())],
1239                         outputs_a: generate_outputs(&[1_000_000]),
1240                         inputs_b: vec![],
1241                         outputs_b: vec![],
1242                         expect_error: Some((AbortReason::IncorrectInputSequenceValue, ErrorCulprit::NodeA)),
1243                 });
1244                 // Duplicate prevout from initiator.
1245                 let duplicate_input = TxIn {
1246                         previous_output: OutPoint { txid: tx.as_transaction().txid(), vout: 0 },
1247                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
1248                         ..Default::default()
1249                 };
1250                 do_test_interactive_tx_constructor(TestSession {
1251                         inputs_a: vec![(duplicate_input.clone(), tx.clone()), (duplicate_input, tx.clone())],
1252                         outputs_a: generate_outputs(&[1_000_000]),
1253                         inputs_b: vec![],
1254                         outputs_b: vec![],
1255                         expect_error: Some((AbortReason::PrevTxOutInvalid, ErrorCulprit::NodeA)),
1256                 });
1257                 // Non-initiator uses same prevout as initiator.
1258                 let duplicate_input = TxIn {
1259                         previous_output: OutPoint { txid: tx.as_transaction().txid(), vout: 0 },
1260                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
1261                         ..Default::default()
1262                 };
1263                 do_test_interactive_tx_constructor(TestSession {
1264                         inputs_a: vec![(duplicate_input.clone(), tx.clone())],
1265                         outputs_a: generate_outputs(&[1_000_000]),
1266                         inputs_b: vec![(duplicate_input.clone(), tx.clone())],
1267                         outputs_b: vec![],
1268                         expect_error: Some((AbortReason::PrevTxOutInvalid, ErrorCulprit::NodeB)),
1269                 });
1270                 // Initiator sends too many TxAddInputs
1271                 do_test_interactive_tx_constructor(TestSession {
1272                         inputs_a: generate_fixed_number_of_inputs(MAX_RECEIVED_TX_ADD_INPUT_COUNT + 1),
1273                         outputs_a: vec![],
1274                         inputs_b: vec![],
1275                         outputs_b: vec![],
1276                         expect_error: Some((AbortReason::ReceivedTooManyTxAddInputs, ErrorCulprit::NodeA)),
1277                 });
1278                 // Attempt to queue up two inputs with duplicate serial ids. We use a deliberately bad
1279                 // entropy source, `DuplicateEntropySource` to simulate this.
1280                 do_test_interactive_tx_constructor_with_entropy_source(
1281                         TestSession {
1282                                 inputs_a: generate_fixed_number_of_inputs(2),
1283                                 outputs_a: vec![],
1284                                 inputs_b: vec![],
1285                                 outputs_b: vec![],
1286                                 expect_error: Some((AbortReason::DuplicateSerialId, ErrorCulprit::NodeA)),
1287                         },
1288                         &DuplicateEntropySource,
1289                 );
1290                 // Initiator sends too many TxAddOutputs.
1291                 do_test_interactive_tx_constructor(TestSession {
1292                         inputs_a: vec![],
1293                         outputs_a: generate_fixed_number_of_outputs(MAX_RECEIVED_TX_ADD_OUTPUT_COUNT + 1),
1294                         inputs_b: vec![],
1295                         outputs_b: vec![],
1296                         expect_error: Some((AbortReason::ReceivedTooManyTxAddOutputs, ErrorCulprit::NodeA)),
1297                 });
1298                 // Initiator sends an output below dust value.
1299                 do_test_interactive_tx_constructor(TestSession {
1300                         inputs_a: vec![],
1301                         outputs_a: generate_outputs(&[1]),
1302                         inputs_b: vec![],
1303                         outputs_b: vec![],
1304                         expect_error: Some((AbortReason::BelowDustLimit, ErrorCulprit::NodeA)),
1305                 });
1306                 // Initiator sends an output above maximum sats allowed.
1307                 do_test_interactive_tx_constructor(TestSession {
1308                         inputs_a: vec![],
1309                         outputs_a: generate_outputs(&[TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1]),
1310                         inputs_b: vec![],
1311                         outputs_b: vec![],
1312                         expect_error: Some((AbortReason::ExceededMaximumSatsAllowed, ErrorCulprit::NodeA)),
1313                 });
1314                 // Initiator sends an output without a witness program.
1315                 do_test_interactive_tx_constructor(TestSession {
1316                         inputs_a: vec![],
1317                         outputs_a: vec![generate_non_witness_output(1_000_000)],
1318                         inputs_b: vec![],
1319                         outputs_b: vec![],
1320                         expect_error: Some((AbortReason::InvalidOutputScript, ErrorCulprit::NodeA)),
1321                 });
1322                 // Attempt to queue up two outputs with duplicate serial ids. We use a deliberately bad
1323                 // entropy source, `DuplicateEntropySource` to simulate this.
1324                 do_test_interactive_tx_constructor_with_entropy_source(
1325                         TestSession {
1326                                 inputs_a: vec![],
1327                                 outputs_a: generate_fixed_number_of_outputs(2),
1328                                 inputs_b: vec![],
1329                                 outputs_b: vec![],
1330                                 expect_error: Some((AbortReason::DuplicateSerialId, ErrorCulprit::NodeA)),
1331                         },
1332                         &DuplicateEntropySource,
1333                 );
1334
1335                 // Peer contributed more output value than inputs
1336                 do_test_interactive_tx_constructor(TestSession {
1337                         inputs_a: generate_inputs(&[100_000]),
1338                         outputs_a: generate_outputs(&[1_000_000]),
1339                         inputs_b: vec![],
1340                         outputs_b: vec![],
1341                         expect_error: Some((AbortReason::OutputsValueExceedsInputsValue, ErrorCulprit::NodeA)),
1342                 });
1343
1344                 // Peer contributed more than allowed number of inputs.
1345                 do_test_interactive_tx_constructor(TestSession {
1346                         inputs_a: generate_fixed_number_of_inputs(MAX_INPUTS_OUTPUTS_COUNT as u16 + 1),
1347                         outputs_a: vec![],
1348                         inputs_b: vec![],
1349                         outputs_b: vec![],
1350                         expect_error: Some((
1351                                 AbortReason::ExceededNumberOfInputsOrOutputs,
1352                                 ErrorCulprit::Indeterminate,
1353                         )),
1354                 });
1355                 // Peer contributed more than allowed number of outputs.
1356                 do_test_interactive_tx_constructor(TestSession {
1357                         inputs_a: generate_inputs(&[TOTAL_BITCOIN_SUPPLY_SATOSHIS]),
1358                         outputs_a: generate_fixed_number_of_outputs(MAX_INPUTS_OUTPUTS_COUNT as u16 + 1),
1359                         inputs_b: vec![],
1360                         outputs_b: vec![],
1361                         expect_error: Some((
1362                                 AbortReason::ExceededNumberOfInputsOrOutputs,
1363                                 ErrorCulprit::Indeterminate,
1364                         )),
1365                 });
1366         }
1367
1368         #[test]
1369         fn test_generate_local_serial_id() {
1370                 let entropy_source = TestEntropySource(AtomicCounter::new());
1371
1372                 // Initiators should have even serial id, non-initiators should have odd serial id.
1373                 assert_eq!(generate_holder_serial_id(&&entropy_source, true) % 2, 0);
1374                 assert_eq!(generate_holder_serial_id(&&entropy_source, false) % 2, 1)
1375         }
1376 }