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