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