Merge pull request #2740 from wpaulino/rust-bitcoin-30-update
[rust-lightning] / lightning / src / util / transaction_utils.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 bitcoin::blockdata::transaction::{Transaction, TxOut};
11 use bitcoin::blockdata::script::ScriptBuf;
12 use bitcoin::consensus::Encodable;
13 use bitcoin::consensus::encode::VarInt;
14
15 use crate::ln::msgs::MAX_VALUE_MSAT;
16
17 use crate::prelude::*;
18 use crate::io_extras::sink;
19 use core::cmp::Ordering;
20
21 pub fn sort_outputs<T, C : Fn(&T, &T) -> Ordering>(outputs: &mut Vec<(TxOut, T)>, tie_breaker: C) {
22         outputs.sort_unstable_by(|a, b| {
23                 a.0.value.cmp(&b.0.value).then_with(|| {
24                         a.0.script_pubkey[..].cmp(&b.0.script_pubkey[..]).then_with(|| {
25                                 tie_breaker(&a.1, &b.1)
26                         })
27                 })
28         });
29 }
30
31 /// Possibly adds a change output to the given transaction, always doing so if there are excess
32 /// funds available beyond the requested feerate.
33 /// Assumes at least one input will have a witness (ie spends a segwit output).
34 /// Returns an Err(()) if the requested feerate cannot be met.
35 /// Returns the expected maximum weight of the fully signed transaction on success.
36 pub(crate) fn maybe_add_change_output(tx: &mut Transaction, input_value: u64, witness_max_weight: u64, feerate_sat_per_1000_weight: u32, change_destination_script: ScriptBuf) -> Result<u64, ()> {
37         if input_value > MAX_VALUE_MSAT / 1000 { return Err(()); }
38
39         const WITNESS_FLAG_BYTES: u64 = 2;
40
41         let mut output_value = 0;
42         for output in tx.output.iter() {
43                 output_value += output.value;
44                 if output_value >= input_value { return Err(()); }
45         }
46
47         let dust_value = change_destination_script.dust_value();
48         let mut change_output = TxOut {
49                 script_pubkey: change_destination_script,
50                 value: 0,
51         };
52         let change_len = change_output.consensus_encode(&mut sink()).unwrap();
53         let starting_weight = tx.weight().to_wu() + WITNESS_FLAG_BYTES + witness_max_weight as u64;
54         let mut weight_with_change: i64 = starting_weight as i64 + change_len as i64 * 4;
55         // Include any extra bytes required to push an extra output.
56         weight_with_change += (VarInt(tx.output.len() as u64 + 1).len() - VarInt(tx.output.len() as u64).len()) as i64 * 4;
57         // When calculating weight, add two for the flag bytes
58         let change_value: i64 = (input_value - output_value) as i64 - weight_with_change * feerate_sat_per_1000_weight as i64 / 1000;
59         if change_value >= dust_value.to_sat() as i64 {
60                 change_output.value = change_value as u64;
61                 tx.output.push(change_output);
62                 Ok(weight_with_change as u64)
63         } else if (input_value - output_value) as i64 - (starting_weight as i64) * feerate_sat_per_1000_weight as i64 / 1000 < 0 {
64                 Err(())
65         } else {
66                 Ok(starting_weight)
67         }
68 }
69
70 #[cfg(test)]
71 mod tests {
72         use super::*;
73
74         use bitcoin::blockdata::locktime::absolute::LockTime;
75         use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, OutPoint};
76         use bitcoin::blockdata::script::{ScriptBuf, Builder};
77         use bitcoin::hash_types::{PubkeyHash, Txid};
78         use bitcoin::hashes::Hash;
79         use bitcoin::hashes::hex::FromHex;
80         use bitcoin::{Sequence, Witness};
81
82         use alloc::vec;
83
84         #[test]
85         fn sort_output_by_value() {
86                 let txout1 = TxOut {
87                         value:  100,
88                         script_pubkey: Builder::new().push_int(0).into_script()
89                 };
90                 let txout1_ = txout1.clone();
91
92                 let txout2 = TxOut {
93                         value: 99,
94                         script_pubkey: Builder::new().push_int(0).into_script()
95                 };
96                 let txout2_ = txout2.clone();
97
98                 let mut outputs = vec![(txout1, "ignore"), (txout2, "ignore")];
99                 sort_outputs(&mut outputs, |_, _| { unreachable!(); });
100
101                 assert_eq!(
102                         &outputs,
103                         &vec![(txout2_, "ignore"), (txout1_, "ignore")]
104                         );
105         }
106
107         #[test]
108         fn sort_output_by_script_pubkey() {
109                 let txout1 = TxOut {
110                         value:  100,
111                         script_pubkey: Builder::new().push_int(3).into_script(),
112                 };
113                 let txout1_ = txout1.clone();
114
115                 let txout2 = TxOut {
116                         value: 100,
117                         script_pubkey: Builder::new().push_int(1).push_int(2).into_script()
118                 };
119                 let txout2_ = txout2.clone();
120
121                 let mut outputs = vec![(txout1, "ignore"), (txout2, "ignore")];
122                 sort_outputs(&mut outputs, |_, _| { unreachable!(); });
123
124                 assert_eq!(
125                         &outputs,
126                         &vec![(txout2_, "ignore"), (txout1_, "ignore")]
127                         );
128         }
129
130         #[test]
131         fn sort_output_by_bip_test() {
132                 let txout1 = TxOut {
133                         value: 100000000,
134                         script_pubkey: script_from_hex("41046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac")
135                 };
136                 let txout1_ = txout1.clone();
137
138                 // doesn't deserialize cleanly:
139                 let txout2 = TxOut {
140                         value: 2400000000,
141                         script_pubkey: script_from_hex("41044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac")
142                 };
143                 let txout2_ = txout2.clone();
144
145                 let mut outputs = vec![(txout1, "ignore"), (txout2, "ignore")];
146                 sort_outputs(&mut outputs, |_, _| { unreachable!(); });
147
148                 assert_eq!(&outputs, &vec![(txout1_, "ignore"), (txout2_, "ignore")]);
149         }
150
151         #[test]
152         fn sort_output_tie_breaker_test() {
153                 let txout1 = TxOut {
154                         value:  100,
155                         script_pubkey: Builder::new().push_int(1).push_int(2).into_script()
156                 };
157                 let txout1_ = txout1.clone();
158
159                 let txout2 = txout1.clone();
160                 let txout2_ = txout1.clone();
161
162                 let mut outputs = vec![(txout1, 420), (txout2, 69)];
163                 sort_outputs(&mut outputs, |a, b| { a.cmp(b) });
164
165                 assert_eq!(
166                         &outputs,
167                         &vec![(txout2_, 69), (txout1_, 420)]
168                 );
169         }
170
171         fn script_from_hex(hex_str: &str) -> ScriptBuf {
172                 ScriptBuf::from(<Vec<u8>>::from_hex(hex_str).unwrap())
173         }
174
175         macro_rules! bip_txout_tests {
176                 ($($name:ident: $value:expr,)*) => {
177                         $(
178                                 #[test]
179                                 fn $name() {
180                                         let expected_raw: Vec<(u64, &str)> = $value;
181                                         let expected: Vec<(TxOut, &str)> = expected_raw.iter()
182                                                 .map(|txout_raw| TxOut {
183                                                         value: txout_raw.0,
184                                                         script_pubkey: script_from_hex(txout_raw.1)
185                                                 }).map(|txout| (txout, "ignore"))
186                                         .collect();
187
188                                         let mut outputs = expected.clone();
189                                         outputs.reverse(); // prep it
190
191                                         // actually do the work!
192                                         sort_outputs(&mut outputs, |_, _| { unreachable!(); });
193
194                                         assert_eq!(outputs, expected);
195                                 }
196                         )*
197                 }
198         }
199
200         const TXOUT1: [(u64, &str); 2] = [
201                 (400057456, "76a9144a5fba237213a062f6f57978f796390bdcf8d01588ac"),
202                 (40000000000, "76a9145be32612930b8323add2212a4ec03c1562084f8488ac"),
203         ];
204         const TXOUT2: [(u64, &str); 2] = [
205                 (100000000, "41046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac"),
206                 (2400000000, "41044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac"),
207         ];
208         bip_txout_tests! {
209                 bip69_txout_test_1: TXOUT1.to_vec(),
210                 bip69_txout_test_2: TXOUT2.to_vec(),
211         }
212
213         #[test]
214         fn test_tx_value_overrun() {
215                 // If we have a bogus input amount or outputs valued more than inputs, we should fail
216                 let mut tx = Transaction { version: 2, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
217                         script_pubkey: ScriptBuf::new(), value: 1000
218                 }] };
219                 assert!(maybe_add_change_output(&mut tx, 21_000_000_0000_0001, 0, 253, ScriptBuf::new()).is_err());
220                 assert!(maybe_add_change_output(&mut tx, 400, 0, 253, ScriptBuf::new()).is_err());
221                 assert!(maybe_add_change_output(&mut tx, 4000, 0, 253, ScriptBuf::new()).is_ok());
222         }
223
224         #[test]
225         fn test_tx_change_edge() {
226                 // Check that we never add dust outputs
227                 let mut tx = Transaction { version: 2, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
228                 let orig_wtxid = tx.wtxid();
229                 let output_spk = ScriptBuf::new_p2pkh(&PubkeyHash::hash(&[0; 0]));
230                 assert_eq!(output_spk.dust_value().to_sat(), 546);
231                 // 9 sats isn't enough to pay fee on a dummy transaction...
232                 assert_eq!(tx.weight().to_wu(), 40); // ie 10 vbytes
233                 assert!(maybe_add_change_output(&mut tx, 9, 0, 250, output_spk.clone()).is_err());
234                 assert_eq!(tx.wtxid(), orig_wtxid); // Failure doesn't change the transaction
235                 // but 10-564 is, just not enough to add a change output...
236                 assert!(maybe_add_change_output(&mut tx, 10, 0, 250, output_spk.clone()).is_ok());
237                 assert_eq!(tx.output.len(), 0);
238                 assert_eq!(tx.wtxid(), orig_wtxid); // If we don't add an output, we don't change the transaction
239                 assert!(maybe_add_change_output(&mut tx, 549, 0, 250, output_spk.clone()).is_ok());
240                 assert_eq!(tx.output.len(), 0);
241                 assert_eq!(tx.wtxid(), orig_wtxid); // If we don't add an output, we don't change the transaction
242                 // 590 is also not enough, if we anticipate 2 more weight units pushing us up to the next vbyte
243                 // (considering the two bytes for segwit flags)
244                 assert!(maybe_add_change_output(&mut tx, 590, 2, 250, output_spk.clone()).is_ok());
245                 assert_eq!(tx.output.len(), 0);
246                 assert_eq!(tx.wtxid(), orig_wtxid); // If we don't add an output, we don't change the transaction
247                 // at 590 we can afford the change output at the dust limit (546)
248                 assert!(maybe_add_change_output(&mut tx, 590, 0, 250, output_spk.clone()).is_ok());
249                 assert_eq!(tx.output.len(), 1);
250                 assert_eq!(tx.output[0].value, 546);
251                 assert_eq!(tx.output[0].script_pubkey, output_spk);
252                 assert_eq!(tx.weight().to_wu() / 4, 590-546); // New weight is exactly the fee we wanted.
253
254                 tx.output.pop();
255                 assert_eq!(tx.wtxid(), orig_wtxid); // The only change is the addition of one output.
256         }
257
258         #[test]
259         fn test_tx_extra_outputs() {
260                 // Check that we correctly handle existing outputs
261                 let mut tx = Transaction { version: 2, lock_time: LockTime::ZERO, input: vec![TxIn {
262                         previous_output: OutPoint::new(Txid::all_zeros(), 0), script_sig: ScriptBuf::new(), witness: Witness::new(), sequence: Sequence::ZERO,
263                 }], output: vec![TxOut {
264                         script_pubkey: Builder::new().push_int(1).into_script(), value: 1000
265                 }] };
266                 let orig_wtxid = tx.wtxid();
267                 let orig_weight = tx.weight().to_wu();
268                 assert_eq!(orig_weight / 4, 61);
269
270                 assert_eq!(Builder::new().push_int(2).into_script().dust_value().to_sat(), 474);
271
272                 // Input value of the output value + fee - 1 should fail:
273                 assert!(maybe_add_change_output(&mut tx, 1000 + 61 + 100 - 1, 400, 250, Builder::new().push_int(2).into_script()).is_err());
274                 assert_eq!(tx.wtxid(), orig_wtxid); // Failure doesn't change the transaction
275                 // but one more input sat should succeed, without changing the transaction
276                 assert!(maybe_add_change_output(&mut tx, 1000 + 61 + 100, 400, 250, Builder::new().push_int(2).into_script()).is_ok());
277                 assert_eq!(tx.wtxid(), orig_wtxid); // If we don't add an output, we don't change the transaction
278                 // In order to get a change output, we need to add 474 plus the output's weight / 4 (10)...
279                 assert!(maybe_add_change_output(&mut tx, 1000 + 61 + 100 + 474 + 9, 400, 250, Builder::new().push_int(2).into_script()).is_ok());
280                 assert_eq!(tx.wtxid(), orig_wtxid); // If we don't add an output, we don't change the transaction
281
282                 assert!(maybe_add_change_output(&mut tx, 1000 + 61 + 100 + 474 + 10, 400, 250, Builder::new().push_int(2).into_script()).is_ok());
283                 assert_eq!(tx.output.len(), 2);
284                 assert_eq!(tx.output[1].value, 474);
285                 assert_eq!(tx.output[1].script_pubkey, Builder::new().push_int(2).into_script());
286                 assert_eq!(tx.weight().to_wu() - orig_weight, 40); // Weight difference matches what we had to add above
287                 tx.output.pop();
288                 assert_eq!(tx.wtxid(), orig_wtxid); // The only change is the addition of one output.
289         }
290 }