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