1 //! Various utilities for building scripts and deriving keys related to channels. These are
2 //! largely of interest for those implementing chain::keysinterface::ChannelKeys message signing
5 use bitcoin::blockdata::script::{Script,Builder};
6 use bitcoin::blockdata::opcodes;
7 use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction, SigHashType};
8 use bitcoin::consensus::encode::{self, Decodable, Encodable};
9 use bitcoin::util::bip143;
11 use bitcoin_hashes::{Hash, HashEngine};
12 use bitcoin_hashes::sha256::Hash as Sha256;
13 use bitcoin_hashes::ripemd160::Hash as Ripemd160;
14 use bitcoin_hashes::hash160::Hash as Hash160;
15 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
17 use ln::channelmanager::{PaymentHash, PaymentPreimage};
18 use ln::msgs::DecodeError;
19 use util::ser::{Readable, Writeable, Writer, WriterWriteAdaptor};
21 use secp256k1::key::{SecretKey, PublicKey};
22 use secp256k1::{Secp256k1, Signature};
25 pub(super) const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
26 pub(super) const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
29 pub(crate) enum HTLCType {
35 /// Check if a given tx witnessScript len matchs one of a pre-signed HTLC
36 pub(crate) fn scriptlen_to_htlctype(witness_script_len: usize) -> Option<HTLCType> {
37 if witness_script_len == 133 {
38 Some(HTLCType::OfferedHTLC)
39 } else if witness_script_len >= 136 && witness_script_len <= 139 {
40 Some(HTLCType::AcceptedHTLC)
47 // Various functions for key derivation and transaction creation for use within channels. Primarily
48 // used in Channel and ChannelMonitor.
50 pub(super) fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
51 let mut res: [u8; 32] = commitment_seed.clone();
54 if idx & (1 << bitpos) == (1 << bitpos) {
55 res[bitpos / 8] ^= 1 << (bitpos & 7);
56 res = Sha256::hash(&res).into_inner();
62 /// Derives a per-commitment-transaction private key (eg an htlc key or payment key) from the base
63 /// private key for that type of key and the per_commitment_point (available in TxCreationKeys)
64 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> Result<SecretKey, secp256k1::Error> {
65 let mut sha = Sha256::engine();
66 sha.input(&per_commitment_point.serialize());
67 sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
68 let res = Sha256::from_engine(sha).into_inner();
70 let mut key = base_secret.clone();
71 key.add_assign(&res)?;
75 pub(super) fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> Result<PublicKey, secp256k1::Error> {
76 let mut sha = Sha256::engine();
77 sha.input(&per_commitment_point.serialize());
78 sha.input(&base_point.serialize());
79 let res = Sha256::from_engine(sha).into_inner();
81 let hashkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&res)?);
82 base_point.combine(&hashkey)
85 /// Derives a revocation key from its constituent parts.
86 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
87 /// generated (ie our own).
88 pub(super) fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_secret: &SecretKey, revocation_base_secret: &SecretKey) -> Result<SecretKey, secp256k1::Error> {
89 let revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &revocation_base_secret);
90 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
92 let rev_append_commit_hash_key = {
93 let mut sha = Sha256::engine();
94 sha.input(&revocation_base_point.serialize());
95 sha.input(&per_commitment_point.serialize());
97 Sha256::from_engine(sha).into_inner()
99 let commit_append_rev_hash_key = {
100 let mut sha = Sha256::engine();
101 sha.input(&per_commitment_point.serialize());
102 sha.input(&revocation_base_point.serialize());
104 Sha256::from_engine(sha).into_inner()
107 let mut part_a = revocation_base_secret.clone();
108 part_a.mul_assign(&rev_append_commit_hash_key)?;
109 let mut part_b = per_commitment_secret.clone();
110 part_b.mul_assign(&commit_append_rev_hash_key)?;
111 part_a.add_assign(&part_b[..])?;
115 pub(super) fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, revocation_base_point: &PublicKey) -> Result<PublicKey, secp256k1::Error> {
116 let rev_append_commit_hash_key = {
117 let mut sha = Sha256::engine();
118 sha.input(&revocation_base_point.serialize());
119 sha.input(&per_commitment_point.serialize());
121 Sha256::from_engine(sha).into_inner()
123 let commit_append_rev_hash_key = {
124 let mut sha = Sha256::engine();
125 sha.input(&per_commitment_point.serialize());
126 sha.input(&revocation_base_point.serialize());
128 Sha256::from_engine(sha).into_inner()
131 let mut part_a = revocation_base_point.clone();
132 part_a.mul_assign(&secp_ctx, &rev_append_commit_hash_key)?;
133 let mut part_b = per_commitment_point.clone();
134 part_b.mul_assign(&secp_ctx, &commit_append_rev_hash_key)?;
135 part_a.combine(&part_b)
138 /// The set of public keys which are used in the creation of one commitment transaction.
139 /// These are derived from the channel base keys and per-commitment data.
141 pub struct TxCreationKeys {
142 /// The per-commitment public key which was used to derive the other keys.
143 pub per_commitment_point: PublicKey,
144 /// The revocation key which is used to allow the owner of the commitment transaction to
145 /// provide their counterparty the ability to punish them if they broadcast an old state.
146 pub(crate) revocation_key: PublicKey,
148 pub(crate) a_htlc_key: PublicKey,
150 pub(crate) b_htlc_key: PublicKey,
151 /// A's Payment Key (which isn't allowed to be spent from for some delay)
152 pub(crate) a_delayed_payment_key: PublicKey,
154 pub(crate) b_payment_key: PublicKey,
157 /// One counterparty's public keys which do not change over the life of a channel.
159 pub struct ChannelPublicKeys {
160 /// The public key which is used to sign all commitment transactions, as it appears in the
161 /// on-chain channel lock-in 2-of-2 multisig output.
162 pub funding_pubkey: PublicKey,
163 /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
164 /// revocation keys. The per-commitment revocation private key is then revealed by the owner of
165 /// a commitment transaction so that their counterparty can claim all available funds if they
166 /// broadcast an old state.
167 pub revocation_basepoint: PublicKey,
168 /// The base point which is used (with derive_public_key) to derive a per-commitment payment
169 /// public key which receives immediately-spendable non-HTLC-encumbered funds.
170 pub payment_basepoint: PublicKey,
171 /// The base point which is used (with derive_public_key) to derive a per-commitment payment
172 /// public key which receives non-HTLC-encumbered funds which are only available for spending
173 /// after some delay (or can be claimed via the revocation path).
174 pub delayed_payment_basepoint: PublicKey,
175 /// The base point which is used (with derive_public_key) to derive a per-commitment public key
176 /// which is used to encumber HTLC-in-flight outputs.
177 pub htlc_basepoint: PublicKey,
180 impl_writeable!(ChannelPublicKeys, 33*5, {
182 revocation_basepoint,
184 delayed_payment_basepoint,
189 impl TxCreationKeys {
190 pub(crate) 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> {
192 per_commitment_point: per_commitment_point.clone(),
193 revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &b_revocation_base)?,
194 a_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_htlc_base)?,
195 b_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_htlc_base)?,
196 a_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_delayed_payment_base)?,
197 b_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_payment_base)?,
202 /// Gets the "to_local" output redeemscript, ie the script which is time-locked or spendable by
203 /// the revocation key
204 pub(super) fn get_revokeable_redeemscript(revocation_key: &PublicKey, to_self_delay: u16, delayed_payment_key: &PublicKey) -> Script {
205 Builder::new().push_opcode(opcodes::all::OP_IF)
206 .push_slice(&revocation_key.serialize())
207 .push_opcode(opcodes::all::OP_ELSE)
208 .push_int(to_self_delay as i64)
209 .push_opcode(opcodes::all::OP_CSV)
210 .push_opcode(opcodes::all::OP_DROP)
211 .push_slice(&delayed_payment_key.serialize())
212 .push_opcode(opcodes::all::OP_ENDIF)
213 .push_opcode(opcodes::all::OP_CHECKSIG)
217 #[derive(Clone, PartialEq)]
218 /// Information about an HTLC as it appears in a commitment transaction
219 pub struct HTLCOutputInCommitment {
220 /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
221 /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
222 /// need to compare this value to whether the commitment transaction in question is that of
223 /// the remote party or our own.
225 /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
226 /// this divided by 1000.
227 pub amount_msat: u64,
228 /// The CLTV lock-time at which this HTLC expires.
229 pub cltv_expiry: u32,
230 /// The hash of the preimage which unlocks this HTLC.
231 pub payment_hash: PaymentHash,
232 /// The position within the commitment transactions' outputs. This may be None if the value is
233 /// below the dust limit (in which case no output appears in the commitment transaction and the
234 /// value is spent to additional transaction fees).
235 pub transaction_output_index: Option<u32>,
239 pub(super) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, a_htlc_key: &PublicKey, b_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
240 let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
242 Builder::new().push_opcode(opcodes::all::OP_DUP)
243 .push_opcode(opcodes::all::OP_HASH160)
244 .push_slice(&Hash160::hash(&revocation_key.serialize())[..])
245 .push_opcode(opcodes::all::OP_EQUAL)
246 .push_opcode(opcodes::all::OP_IF)
247 .push_opcode(opcodes::all::OP_CHECKSIG)
248 .push_opcode(opcodes::all::OP_ELSE)
249 .push_slice(&b_htlc_key.serialize()[..])
250 .push_opcode(opcodes::all::OP_SWAP)
251 .push_opcode(opcodes::all::OP_SIZE)
253 .push_opcode(opcodes::all::OP_EQUAL)
254 .push_opcode(opcodes::all::OP_NOTIF)
255 .push_opcode(opcodes::all::OP_DROP)
257 .push_opcode(opcodes::all::OP_SWAP)
258 .push_slice(&a_htlc_key.serialize()[..])
260 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
261 .push_opcode(opcodes::all::OP_ELSE)
262 .push_opcode(opcodes::all::OP_HASH160)
263 .push_slice(&payment_hash160)
264 .push_opcode(opcodes::all::OP_EQUALVERIFY)
265 .push_opcode(opcodes::all::OP_CHECKSIG)
266 .push_opcode(opcodes::all::OP_ENDIF)
267 .push_opcode(opcodes::all::OP_ENDIF)
270 Builder::new().push_opcode(opcodes::all::OP_DUP)
271 .push_opcode(opcodes::all::OP_HASH160)
272 .push_slice(&Hash160::hash(&revocation_key.serialize())[..])
273 .push_opcode(opcodes::all::OP_EQUAL)
274 .push_opcode(opcodes::all::OP_IF)
275 .push_opcode(opcodes::all::OP_CHECKSIG)
276 .push_opcode(opcodes::all::OP_ELSE)
277 .push_slice(&b_htlc_key.serialize()[..])
278 .push_opcode(opcodes::all::OP_SWAP)
279 .push_opcode(opcodes::all::OP_SIZE)
281 .push_opcode(opcodes::all::OP_EQUAL)
282 .push_opcode(opcodes::all::OP_IF)
283 .push_opcode(opcodes::all::OP_HASH160)
284 .push_slice(&payment_hash160)
285 .push_opcode(opcodes::all::OP_EQUALVERIFY)
287 .push_opcode(opcodes::all::OP_SWAP)
288 .push_slice(&a_htlc_key.serialize()[..])
290 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
291 .push_opcode(opcodes::all::OP_ELSE)
292 .push_opcode(opcodes::all::OP_DROP)
293 .push_int(htlc.cltv_expiry as i64)
294 .push_opcode(opcodes::all::OP_CLTV)
295 .push_opcode(opcodes::all::OP_DROP)
296 .push_opcode(opcodes::all::OP_CHECKSIG)
297 .push_opcode(opcodes::all::OP_ENDIF)
298 .push_opcode(opcodes::all::OP_ENDIF)
303 /// note here that 'a_revocation_key' is generated using b_revocation_basepoint and a's
304 /// commitment secret. 'htlc' does *not* need to have its previous_output_index filled.
306 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, keys: &TxCreationKeys) -> Script {
307 get_htlc_redeemscript_with_explicit_keys(htlc, &keys.a_htlc_key, &keys.b_htlc_key, &keys.revocation_key)
310 /// Gets the redeemscript for a funding output from the two funding public keys.
311 /// Note that the order of funding public keys does not matter.
312 pub fn make_funding_redeemscript(a: &PublicKey, b: &PublicKey) -> Script {
313 let our_funding_key = a.serialize();
314 let their_funding_key = b.serialize();
316 let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
317 if our_funding_key[..] < their_funding_key[..] {
318 builder.push_slice(&our_funding_key)
319 .push_slice(&their_funding_key)
321 builder.push_slice(&their_funding_key)
322 .push_slice(&our_funding_key)
323 }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
326 /// panics if htlc.transaction_output_index.is_none()!
327 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 {
328 let mut txins: Vec<TxIn> = Vec::new();
330 previous_output: OutPoint {
331 txid: prev_hash.clone(),
332 vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
334 script_sig: Script::new(),
339 let total_fee = if htlc.offered {
340 feerate_per_kw * HTLC_TIMEOUT_TX_WEIGHT / 1000
342 feerate_per_kw * HTLC_SUCCESS_TX_WEIGHT / 1000
345 let mut txouts: Vec<TxOut> = Vec::new();
347 script_pubkey: get_revokeable_redeemscript(revocation_key, to_self_delay, a_delayed_payment_key).to_v0_p2wsh(),
348 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)
353 lock_time: if htlc.offered { htlc.cltv_expiry } else { 0 },
359 /// Signs a transaction created by build_htlc_transaction. If the transaction is an
360 /// HTLC-Success transaction (ie htlc.offered is false), preimage must be set!
361 pub(crate) fn sign_htlc_transaction<T: secp256k1::Signing>(tx: &mut Transaction, their_sig: &Signature, preimage: &Option<PaymentPreimage>, htlc: &HTLCOutputInCommitment, a_htlc_key: &PublicKey, b_htlc_key: &PublicKey, revocation_key: &PublicKey, per_commitment_point: &PublicKey, htlc_base_key: &SecretKey, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Script), ()> {
362 if tx.input.len() != 1 { return Err(()); }
363 if tx.input[0].witness.len() != 0 { return Err(()); }
365 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&htlc, a_htlc_key, b_htlc_key, revocation_key);
367 let our_htlc_key = derive_private_key(secp_ctx, per_commitment_point, htlc_base_key).map_err(|_| ())?;
368 let sighash = hash_to_message!(&bip143::SighashComponents::new(&tx).sighash_all(&tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]);
369 let local_tx = PublicKey::from_secret_key(&secp_ctx, &our_htlc_key) == *a_htlc_key;
370 let our_sig = secp_ctx.sign(&sighash, &our_htlc_key);
372 tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
374 if local_tx { // b, then a
375 tx.input[0].witness.push(their_sig.serialize_der().to_vec());
376 tx.input[0].witness.push(our_sig.serialize_der().to_vec());
378 tx.input[0].witness.push(our_sig.serialize_der().to_vec());
379 tx.input[0].witness.push(their_sig.serialize_der().to_vec());
381 tx.input[0].witness[1].push(SigHashType::All as u8);
382 tx.input[0].witness[2].push(SigHashType::All as u8);
385 tx.input[0].witness.push(Vec::new());
386 assert!(preimage.is_none());
388 tx.input[0].witness.push(preimage.unwrap().0.to_vec());
391 tx.input[0].witness.push(htlc_redeemscript.as_bytes().to_vec());
393 Ok((our_sig, htlc_redeemscript))
397 /// We use this to track local commitment transactions and put off signing them until we are ready
398 /// to broadcast. Eventually this will require a signer which is possibly external, but for now we
399 /// just pass in the SecretKeys required.
400 pub(crate) struct LocalCommitmentTransaction {
403 impl LocalCommitmentTransaction {
405 pub fn dummy() -> Self {
406 Self { tx: Transaction {
414 pub fn new_missing_local_sig(mut tx: Transaction, their_sig: &Signature, our_funding_key: &PublicKey, their_funding_key: &PublicKey) -> LocalCommitmentTransaction {
415 if tx.input.len() != 1 { panic!("Tried to store a commitment transaction that had input count != 1!"); }
416 if tx.input[0].witness.len() != 0 { panic!("Tried to store a signed commitment transaction?"); }
418 tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
420 if our_funding_key.serialize()[..] < their_funding_key.serialize()[..] {
421 tx.input[0].witness.push(Vec::new());
422 tx.input[0].witness.push(their_sig.serialize_der().to_vec());
423 tx.input[0].witness[2].push(SigHashType::All as u8);
425 tx.input[0].witness.push(their_sig.serialize_der().to_vec());
426 tx.input[0].witness[1].push(SigHashType::All as u8);
427 tx.input[0].witness.push(Vec::new());
433 pub fn txid(&self) -> Sha256dHash {
437 pub fn has_local_sig(&self) -> bool {
438 if self.tx.input.len() != 1 { panic!("Commitment transactions must have input count == 1!"); }
439 if self.tx.input[0].witness.len() == 4 {
440 assert!(!self.tx.input[0].witness[1].is_empty());
441 assert!(!self.tx.input[0].witness[2].is_empty());
444 assert_eq!(self.tx.input[0].witness.len(), 3);
445 assert!(self.tx.input[0].witness[0].is_empty());
446 assert!(self.tx.input[0].witness[1].is_empty() || self.tx.input[0].witness[2].is_empty());
451 pub fn add_local_sig<T: secp256k1::Signing>(&mut self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) {
452 if self.has_local_sig() { return; }
453 let sighash = hash_to_message!(&bip143::SighashComponents::new(&self.tx)
454 .sighash_all(&self.tx.input[0], funding_redeemscript, channel_value_satoshis)[..]);
455 let our_sig = secp_ctx.sign(&sighash, funding_key);
457 if self.tx.input[0].witness[1].is_empty() {
458 self.tx.input[0].witness[1] = our_sig.serialize_der().to_vec();
459 self.tx.input[0].witness[1].push(SigHashType::All as u8);
461 self.tx.input[0].witness[2] = our_sig.serialize_der().to_vec();
462 self.tx.input[0].witness[2].push(SigHashType::All as u8);
465 self.tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
468 pub fn without_valid_witness(&self) -> &Transaction { &self.tx }
469 pub fn with_valid_witness(&self) -> &Transaction {
470 assert!(self.has_local_sig());
474 impl PartialEq for LocalCommitmentTransaction {
475 // We dont care whether we are signed in equality comparison
476 fn eq(&self, o: &Self) -> bool {
477 self.txid() == o.txid()
480 impl Writeable for LocalCommitmentTransaction {
481 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
482 if let Err(e) = self.tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
484 encode::Error::Io(e) => return Err(e),
485 _ => panic!("local tx must have been well-formed!"),
491 impl<R: ::std::io::Read> Readable<R> for LocalCommitmentTransaction {
492 fn read(reader: &mut R) -> Result<Self, DecodeError> {
493 let tx = match Transaction::consensus_decode(reader.by_ref()) {
496 encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
497 _ => return Err(DecodeError::InvalidValue),
501 if tx.input.len() != 1 {
502 // Ensure tx didn't hit the 0-input ambiguity case.
503 return Err(DecodeError::InvalidValue);