Fix HTLC-output-in-commitment sorting for duplicate-HTLCs
[rust-lightning] / src / util / transaction_utils.rs
1 use bitcoin::blockdata::transaction::{TxIn, TxOut};
2 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
3
4 use std::cmp::Ordering;
5
6 pub fn sort_outputs<T, C : Fn(&T, &T) -> Ordering>(outputs: &mut Vec<(TxOut, T)>, tie_breaker: C) {
7         outputs.sort_unstable_by(|a, b| {
8                 a.0.value.cmp(&b.0.value).then_with(|| {
9                         a.0.script_pubkey[..].cmp(&b.0.script_pubkey[..]).then_with(|| {
10                                 tie_breaker(&a.1, &b.1)
11                         })
12                 })
13         });
14 }
15
16 fn cmp(a: &Sha256dHash, b: &Sha256dHash) -> Ordering {
17         use bitcoin_hashes::Hash;
18
19         let av = a.into_inner();
20         let bv = b.into_inner();
21         for i in (0..32).rev() {
22                 let cmp = av[i].cmp(&bv[i]);
23                 if cmp != Ordering::Equal {
24                         return cmp;
25                 }
26         }
27         Ordering::Equal
28 }
29
30 pub fn sort_inputs<T>(inputs: &mut Vec<(TxIn, T)>) {
31         inputs.sort_unstable_by(|a, b| {
32                 cmp( &a.0.previous_output.txid, &b.0.previous_output.txid).then(
33                 a.0.previous_output.vout.cmp(&b.0.previous_output.vout))
34         });
35 }
36
37 #[cfg(test)]
38 mod tests {
39         use super::*;
40
41         use bitcoin::blockdata::script::{Script, Builder};
42         use bitcoin::blockdata::transaction::{TxOut, OutPoint};
43         use bitcoin_hashes::sha256d::Hash as Sha256dHash;
44         use bitcoin_hashes::hex::FromHex;
45
46         use hex::decode;
47
48         #[test]
49         fn sort_output_by_value() {
50                 let txout1 = TxOut {
51                         value:  100,
52                         script_pubkey: Builder::new().push_int(0).into_script()
53                 };
54                 let txout1_ = txout1.clone();
55
56                 let txout2 = TxOut {
57                         value: 99,
58                         script_pubkey: Builder::new().push_int(0).into_script()
59                 };
60                 let txout2_ = txout2.clone();
61
62                 let mut outputs = vec![(txout1, "ignore"), (txout2, "ignore")];
63                 sort_outputs(&mut outputs, |_, _| { unreachable!(); });
64
65                 assert_eq!(
66                         &outputs,
67                         &vec![(txout2_, "ignore"), (txout1_, "ignore")]
68                         );
69         }
70
71         #[test]
72         fn sort_output_by_script_pubkey() {
73                 let txout1 = TxOut {
74                         value:  100,
75                         script_pubkey: Builder::new().push_int(3).into_script(),
76                 };
77                 let txout1_ = txout1.clone();
78
79                 let txout2 = TxOut {
80                         value: 100,
81                         script_pubkey: Builder::new().push_int(1).push_int(2).into_script()
82                 };
83                 let txout2_ = txout2.clone();
84
85                 let mut outputs = vec![(txout1, "ignore"), (txout2, "ignore")];
86                 sort_outputs(&mut outputs, |_, _| { unreachable!(); });
87
88                 assert_eq!(
89                         &outputs,
90                         &vec![(txout2_, "ignore"), (txout1_, "ignore")]
91                         );
92         }
93
94         #[test]
95         fn sort_output_by_bip_test() {
96                 let txout1 = TxOut {
97                         value: 100000000,
98                         script_pubkey: script_from_hex("41046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac")
99                 };
100                 let txout1_ = txout1.clone();
101
102                 // doesn't deserialize cleanly:
103                 let txout2 = TxOut {
104                         value: 2400000000,
105                         script_pubkey: script_from_hex("41044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac")
106                 };
107                 let txout2_ = txout2.clone();
108
109                 let mut outputs = vec![(txout1, "ignore"), (txout2, "ignore")];
110                 sort_outputs(&mut outputs, |_, _| { unreachable!(); });
111
112                 assert_eq!(&outputs, &vec![(txout1_, "ignore"), (txout2_, "ignore")]);
113         }
114
115         fn script_from_hex(hex_str: &str) -> Script {
116                 Script::from(decode(hex_str).unwrap())
117         }
118
119         macro_rules! bip_txout_tests {
120                 ($($name:ident: $value:expr,)*) => {
121                         $(
122                                 #[test]
123                                 fn $name() {
124                                         let expected_raw: Vec<(u64, &str)> = $value;
125                                         let expected: Vec<(TxOut, &str)> = expected_raw.iter()
126                                                 .map(|txout_raw| TxOut {
127                                                         value: txout_raw.0,
128                                                         script_pubkey: script_from_hex(txout_raw.1)
129                                                 }).map(|txout| (txout, "ignore"))
130                                         .collect();
131
132                                         let mut outputs = expected.clone();
133                                         outputs.reverse(); // prep it
134
135                                         // actually do the work!
136                                         sort_outputs(&mut outputs, |_, _| { unreachable!(); });
137
138                                         assert_eq!(outputs, expected);
139                                 }
140                         )*
141                 }
142         }
143
144         const TXOUT1: [(u64, &str); 2] = [
145                 (400057456, "76a9144a5fba237213a062f6f57978f796390bdcf8d01588ac"),
146                 (40000000000, "76a9145be32612930b8323add2212a4ec03c1562084f8488ac"),
147         ];
148         const TXOUT2: [(u64, &str); 2] = [
149                 (100000000, "41046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac"),
150                 (2400000000, "41044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac"),
151         ];
152         bip_txout_tests! {
153                 bip69_txout_test_1: TXOUT1.to_vec(),
154                 bip69_txout_test_2: TXOUT2.to_vec(),
155         }
156
157         macro_rules! bip_txin_tests {
158                 ($($name:ident: $value:expr,)*) => {
159                         $(
160                                 #[test]
161                                 fn $name() {
162                                         let expected_raw: Vec<(&str, u32)> = $value;
163                                         let expected: Vec<(TxIn, &str)> = expected_raw.iter().map(
164                                                 |txin_raw| TxIn {
165                                                         previous_output: OutPoint {
166                                                                 txid: Sha256dHash::from_hex(txin_raw.0).unwrap(),
167                                                                 vout: txin_raw.1,
168                                                         },
169                                                         script_sig: Script::new(),
170                                                         sequence: 0,
171                                                         witness: vec![]
172                                                 }
173                                                 ).map(|txin| (txin, "ignore")).collect();
174
175                                         let mut inputs = expected.clone();
176                                         inputs.reverse();
177
178                                         sort_inputs(&mut inputs);
179
180                                         assert_eq!(expected, inputs);
181                                 }
182                         )*
183                 }
184         }
185
186         const TXIN1_BIP69: [(&str, u32); 17] = [
187                 ("0e53ec5dfb2cb8a71fec32dc9a634a35b7e24799295ddd5278217822e0b31f57", 0),
188                 ("26aa6e6d8b9e49bb0630aac301db6757c02e3619feb4ee0eea81eb1672947024", 1),
189                 ("28e0fdd185542f2c6ea19030b0796051e7772b6026dd5ddccd7a2f93b73e6fc2", 0),
190                 ("381de9b9ae1a94d9c17f6a08ef9d341a5ce29e2e60c36a52d333ff6203e58d5d", 1),
191                 ("3b8b2f8efceb60ba78ca8bba206a137f14cb5ea4035e761ee204302d46b98de2", 0),
192                 ("402b2c02411720bf409eff60d05adad684f135838962823f3614cc657dd7bc0a", 1),
193                 ("54ffff182965ed0957dba1239c27164ace5a73c9b62a660c74b7b7f15ff61e7a", 1),
194                 ("643e5f4e66373a57251fb173151e838ccd27d279aca882997e005016bb53d5aa", 0),
195                 ("6c1d56f31b2de4bfc6aaea28396b333102b1f600da9c6d6149e96ca43f1102b1", 1),
196                 ("7a1de137cbafb5c70405455c49c5104ca3057a1f1243e6563bb9245c9c88c191", 0),
197                 ("7d037ceb2ee0dc03e82f17be7935d238b35d1deabf953a892a4507bfbeeb3ba4", 1),
198                 ("a5e899dddb28776ea9ddac0a502316d53a4a3fca607c72f66c470e0412e34086", 0),
199                 ("b4112b8f900a7ca0c8b0e7c4dfad35c6be5f6be46b3458974988e1cdb2fa61b8", 0),
200                 ("bafd65e3c7f3f9fdfdc1ddb026131b278c3be1af90a4a6ffa78c4658f9ec0c85", 0),
201                 ("de0411a1e97484a2804ff1dbde260ac19de841bebad1880c782941aca883b4e9", 1),
202                 ("f0a130a84912d03c1d284974f563c5949ac13f8342b8112edff52971599e6a45", 0),
203                 ("f320832a9d2e2452af63154bc687493484a0e7745ebd3aaf9ca19eb80834ad60", 0),
204         ];
205
206
207         const TXIN2_BIP69: [(&str, u32); 2] = [
208                 ("35288d269cee1941eaebb2ea85e32b42cdb2b04284a56d8b14dcc3f5c65d6055", 0),
209                 ("35288d269cee1941eaebb2ea85e32b42cdb2b04284a56d8b14dcc3f5c65d6055", 1),
210         ];
211         bip_txin_tests! {
212                 bip69_txin_test_1: TXIN1_BIP69.to_vec(),
213                 bip69_txin_test_2: TXIN2_BIP69.to_vec(),
214         }
215 }