]> git.bitcoin.ninja Git - rust-lightning/blob - src/ln/chan_utils.rs
Narrow check_spend_remote_htlc input/output count check.
[rust-lightning] / src / ln / chan_utils.rs
1 use bitcoin::blockdata::script::{Script,Builder};
2 use bitcoin::blockdata::opcodes;
3 use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction};
4 use bitcoin::util::hash::{Hash160,Sha256dHash};
5
6 use secp256k1::key::{PublicKey,SecretKey};
7 use secp256k1::Secp256k1;
8 use secp256k1;
9
10 use crypto::digest::Digest;
11 use crypto::ripemd160::Ripemd160;
12
13 use util::sha2::Sha256;
14
15 pub const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
16 pub const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
17
18 // Various functions for key derivation and transaction creation for use within channels. Primarily
19 // used in Channel and ChannelMonitor.
20
21 pub fn build_commitment_secret(commitment_seed: [u8; 32], idx: u64) -> [u8; 32] {
22         let mut res: [u8; 32] = commitment_seed;
23         for i in 0..48 {
24                 let bitpos = 47 - i;
25                 if idx & (1 << bitpos) == (1 << bitpos) {
26                         res[bitpos / 8] ^= 1 << (bitpos & 7);
27                         let mut sha = Sha256::new();
28                         sha.input(&res);
29                         sha.result(&mut res);
30                 }
31         }
32         res
33 }
34
35 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> Result<SecretKey, secp256k1::Error> {
36         let mut sha = Sha256::new();
37         sha.input(&per_commitment_point.serialize());
38         sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
39         let mut res = [0; 32];
40         sha.result(&mut res);
41
42         let mut key = base_secret.clone();
43         key.add_assign(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &res)?)?;
44         Ok(key)
45 }
46
47 pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> Result<PublicKey, secp256k1::Error> {
48         let mut sha = Sha256::new();
49         sha.input(&per_commitment_point.serialize());
50         sha.input(&base_point.serialize());
51         let mut res = [0; 32];
52         sha.result(&mut res);
53
54         let hashkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &res)?);
55         base_point.combine(&secp_ctx, &hashkey)
56 }
57
58 /// Derives a revocation key from its constituent parts
59 pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_secret: &SecretKey, revocation_base_secret: &SecretKey) -> Result<SecretKey, secp256k1::Error> {
60         let revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &revocation_base_secret);
61         let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
62
63         let rev_append_commit_hash_key = {
64                 let mut sha = Sha256::new();
65                 sha.input(&revocation_base_point.serialize());
66                 sha.input(&per_commitment_point.serialize());
67                 let mut res = [0; 32];
68                 sha.result(&mut res);
69
70                 SecretKey::from_slice(&secp_ctx, &res)?
71         };
72         let commit_append_rev_hash_key = {
73                 let mut sha = Sha256::new();
74                 sha.input(&per_commitment_point.serialize());
75                 sha.input(&revocation_base_point.serialize());
76                 let mut res = [0; 32];
77                 sha.result(&mut res);
78
79                 SecretKey::from_slice(&secp_ctx, &res)?
80         };
81
82         let mut part_a = revocation_base_secret.clone();
83         part_a.mul_assign(&secp_ctx, &rev_append_commit_hash_key)?;
84         let mut part_b = per_commitment_secret.clone();
85         part_b.mul_assign(&secp_ctx, &commit_append_rev_hash_key)?;
86         part_a.add_assign(&secp_ctx, &part_b)?;
87         Ok(part_a)
88 }
89
90 pub fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, revocation_base_point: &PublicKey) -> Result<PublicKey, secp256k1::Error> {
91         let rev_append_commit_hash_key = {
92                 let mut sha = Sha256::new();
93                 sha.input(&revocation_base_point.serialize());
94                 sha.input(&per_commitment_point.serialize());
95                 let mut res = [0; 32];
96                 sha.result(&mut res);
97
98                 SecretKey::from_slice(&secp_ctx, &res)?
99         };
100         let commit_append_rev_hash_key = {
101                 let mut sha = Sha256::new();
102                 sha.input(&per_commitment_point.serialize());
103                 sha.input(&revocation_base_point.serialize());
104                 let mut res = [0; 32];
105                 sha.result(&mut res);
106
107                 SecretKey::from_slice(&secp_ctx, &res)?
108         };
109
110         let mut part_a = revocation_base_point.clone();
111         part_a.mul_assign(&secp_ctx, &rev_append_commit_hash_key)?;
112         let mut part_b = per_commitment_point.clone();
113         part_b.mul_assign(&secp_ctx, &commit_append_rev_hash_key)?;
114         part_a.combine(&secp_ctx, &part_b)
115 }
116
117 pub struct TxCreationKeys {
118         pub per_commitment_point: PublicKey,
119         pub revocation_key: PublicKey,
120         pub a_htlc_key: PublicKey,
121         pub b_htlc_key: PublicKey,
122         pub a_delayed_payment_key: PublicKey,
123         pub b_payment_key: PublicKey,
124 }
125
126 impl TxCreationKeys {
127         pub fn new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, a_delayed_payment_base: &PublicKey, a_htlc_base: &PublicKey, b_revocation_base: &PublicKey, b_payment_base: &PublicKey, b_htlc_base: &PublicKey) -> Result<TxCreationKeys, secp256k1::Error> {
128                 Ok(TxCreationKeys {
129                         per_commitment_point: per_commitment_point.clone(),
130                         revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &b_revocation_base)?,
131                         a_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_htlc_base)?,
132                         b_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_htlc_base)?,
133                         a_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_delayed_payment_base)?,
134                         b_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_payment_base)?,
135                 })
136         }
137 }
138
139 /// Gets the "to_local" output redeemscript, ie the script which is time-locked or spendable by
140 /// the revocation key
141 pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, to_self_delay: u16, delayed_payment_key: &PublicKey) -> Script {
142         Builder::new().push_opcode(opcodes::All::OP_IF)
143                       .push_slice(&revocation_key.serialize())
144                       .push_opcode(opcodes::All::OP_ELSE)
145                       .push_int(to_self_delay as i64)
146                       .push_opcode(opcodes::OP_CSV)
147                       .push_opcode(opcodes::All::OP_DROP)
148                       .push_slice(&delayed_payment_key.serialize())
149                       .push_opcode(opcodes::All::OP_ENDIF)
150                       .push_opcode(opcodes::All::OP_CHECKSIG)
151                       .into_script()
152 }
153
154 #[derive(Clone, PartialEq)]
155 pub struct HTLCOutputInCommitment {
156         pub offered: bool,
157         pub amount_msat: u64,
158         pub cltv_expiry: u32,
159         pub payment_hash: [u8; 32],
160         pub transaction_output_index: u32,
161 }
162
163 #[inline]
164 pub fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, a_htlc_key: &PublicKey, b_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
165         let payment_hash160 = {
166                 let mut ripemd = Ripemd160::new();
167                 ripemd.input(&htlc.payment_hash);
168                 let mut res = [0; 20];
169                 ripemd.result(&mut res);
170                 res
171         };
172         if htlc.offered {
173                 Builder::new().push_opcode(opcodes::All::OP_DUP)
174                               .push_opcode(opcodes::All::OP_HASH160)
175                               .push_slice(&Hash160::from_data(&revocation_key.serialize())[..])
176                               .push_opcode(opcodes::All::OP_EQUAL)
177                               .push_opcode(opcodes::All::OP_IF)
178                               .push_opcode(opcodes::All::OP_CHECKSIG)
179                               .push_opcode(opcodes::All::OP_ELSE)
180                               .push_slice(&b_htlc_key.serialize()[..])
181                               .push_opcode(opcodes::All::OP_SWAP)
182                               .push_opcode(opcodes::All::OP_SIZE)
183                               .push_int(32)
184                               .push_opcode(opcodes::All::OP_EQUAL)
185                               .push_opcode(opcodes::All::OP_NOTIF)
186                               .push_opcode(opcodes::All::OP_DROP)
187                               .push_int(2)
188                               .push_opcode(opcodes::All::OP_SWAP)
189                               .push_slice(&a_htlc_key.serialize()[..])
190                               .push_int(2)
191                               .push_opcode(opcodes::All::OP_CHECKMULTISIG)
192                               .push_opcode(opcodes::All::OP_ELSE)
193                               .push_opcode(opcodes::All::OP_HASH160)
194                               .push_slice(&payment_hash160)
195                               .push_opcode(opcodes::All::OP_EQUALVERIFY)
196                               .push_opcode(opcodes::All::OP_CHECKSIG)
197                               .push_opcode(opcodes::All::OP_ENDIF)
198                               .push_opcode(opcodes::All::OP_ENDIF)
199                               .into_script()
200         } else {
201                 Builder::new().push_opcode(opcodes::All::OP_DUP)
202                               .push_opcode(opcodes::All::OP_HASH160)
203                               .push_slice(&Hash160::from_data(&revocation_key.serialize())[..])
204                               .push_opcode(opcodes::All::OP_EQUAL)
205                               .push_opcode(opcodes::All::OP_IF)
206                               .push_opcode(opcodes::All::OP_CHECKSIG)
207                               .push_opcode(opcodes::All::OP_ELSE)
208                               .push_slice(&b_htlc_key.serialize()[..])
209                               .push_opcode(opcodes::All::OP_SWAP)
210                               .push_opcode(opcodes::All::OP_SIZE)
211                               .push_int(32)
212                               .push_opcode(opcodes::All::OP_EQUAL)
213                               .push_opcode(opcodes::All::OP_IF)
214                               .push_opcode(opcodes::All::OP_HASH160)
215                               .push_slice(&payment_hash160)
216                               .push_opcode(opcodes::All::OP_EQUALVERIFY)
217                               .push_int(2)
218                               .push_opcode(opcodes::All::OP_SWAP)
219                               .push_slice(&a_htlc_key.serialize()[..])
220                               .push_int(2)
221                               .push_opcode(opcodes::All::OP_CHECKMULTISIG)
222                               .push_opcode(opcodes::All::OP_ELSE)
223                               .push_opcode(opcodes::All::OP_DROP)
224                               .push_int(htlc.cltv_expiry as i64)
225                               .push_opcode(opcodes::OP_CLTV)
226                               .push_opcode(opcodes::All::OP_DROP)
227                               .push_opcode(opcodes::All::OP_CHECKSIG)
228                               .push_opcode(opcodes::All::OP_ENDIF)
229                               .push_opcode(opcodes::All::OP_ENDIF)
230                               .into_script()
231         }
232 }
233
234 /// note here that 'a_revocation_key' is generated using b_revocation_basepoint and a's
235 /// commitment secret. 'htlc' does *not* need to have its previous_output_index filled.
236 #[inline]
237 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, keys: &TxCreationKeys) -> Script {
238         get_htlc_redeemscript_with_explicit_keys(htlc, &keys.a_htlc_key, &keys.b_htlc_key, &keys.revocation_key)
239 }
240
241 pub fn build_htlc_transaction(prev_hash: &Sha256dHash, feerate_per_kw: u64, to_self_delay: u16, htlc: &HTLCOutputInCommitment, a_delayed_payment_key: &PublicKey, revocation_key: &PublicKey) -> Transaction {
242         let mut txins: Vec<TxIn> = Vec::new();
243         txins.push(TxIn {
244                 previous_output: OutPoint {
245                         txid: prev_hash.clone(),
246                         vout: htlc.transaction_output_index,
247                 },
248                 script_sig: Script::new(),
249                 sequence: 0,
250                 witness: Vec::new(),
251         });
252
253         let total_fee = if htlc.offered {
254                         feerate_per_kw * HTLC_TIMEOUT_TX_WEIGHT / 1000
255                 } else {
256                         feerate_per_kw * HTLC_SUCCESS_TX_WEIGHT / 1000
257                 };
258
259         let mut txouts: Vec<TxOut> = Vec::new();
260         txouts.push(TxOut {
261                 script_pubkey: get_revokeable_redeemscript(revocation_key, to_self_delay, a_delayed_payment_key).to_v0_p2wsh(),
262                 value: htlc.amount_msat / 1000 - total_fee //TODO: BOLT 3 does not specify if we should add amount_msat before dividing or if we should divide by 1000 before subtracting (as we do here)
263         });
264
265         Transaction {
266                 version: 2,
267                 lock_time: if htlc.offered { htlc.cltv_expiry } else { 0 },
268                 input: txins,
269                 output: txouts,
270         }
271 }