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};
22 use secp256k1::key::{SecretKey, PublicKey};
23 use secp256k1::{Secp256k1, Signature};
26 pub(super) const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
27 pub(super) const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
30 pub(crate) enum HTLCType {
36 /// Check if a given tx witnessScript len matchs one of a pre-signed HTLC
37 pub(crate) fn scriptlen_to_htlctype(witness_script_len: usize) -> Option<HTLCType> {
38 if witness_script_len == 133 {
39 Some(HTLCType::OfferedHTLC)
40 } else if witness_script_len >= 136 && witness_script_len <= 139 {
41 Some(HTLCType::AcceptedHTLC)
48 // Various functions for key derivation and transaction creation for use within channels. Primarily
49 // used in Channel and ChannelMonitor.
51 pub(super) fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
52 let mut res: [u8; 32] = commitment_seed.clone();
55 if idx & (1 << bitpos) == (1 << bitpos) {
56 res[bitpos / 8] ^= 1 << (bitpos & 7);
57 res = Sha256::hash(&res).into_inner();
63 /// Implements the per-commitment secret storage scheme from
64 /// [BOLT 3](https://github.com/lightningnetwork/lightning-rfc/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
66 /// Allows us to keep track of all of the revocation secrets of counterarties in just 50*32 bytes
69 pub(super) struct CounterpartyCommitmentSecrets {
70 old_secrets: [([u8; 32], u64); 49],
73 impl PartialEq for CounterpartyCommitmentSecrets {
74 fn eq(&self, other: &Self) -> bool {
75 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
76 if secret != o_secret || idx != o_idx {
84 impl CounterpartyCommitmentSecrets {
85 pub(super) fn new() -> Self {
86 Self { old_secrets: [([0; 32], 1 << 48); 49], }
90 fn place_secret(idx: u64) -> u8 {
92 if idx & (1 << i) == (1 << i) {
99 pub(super) fn get_min_seen_secret(&self) -> u64 {
100 //TODO This can be optimized?
101 let mut min = 1 << 48;
102 for &(_, idx) in self.old_secrets.iter() {
111 pub(super) fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
112 let mut res: [u8; 32] = secret;
114 let bitpos = bits - 1 - i;
115 if idx & (1 << bitpos) == (1 << bitpos) {
116 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
117 res = Sha256::hash(&res).into_inner();
123 pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
124 let pos = Self::place_secret(idx);
126 let (old_secret, old_idx) = self.old_secrets[i as usize];
127 if Self::derive_secret(secret, pos, old_idx) != old_secret {
131 if self.get_min_seen_secret() <= idx {
134 self.old_secrets[pos as usize] = (secret, idx);
138 /// Can only fail if idx is < get_min_seen_secret
139 pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
140 for i in 0..self.old_secrets.len() {
141 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
142 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
145 assert!(idx < self.get_min_seen_secret());
150 impl Writeable for CounterpartyCommitmentSecrets {
151 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
152 for &(ref secret, ref idx) in self.old_secrets.iter() {
153 writer.write_all(secret)?;
154 writer.write_all(&byte_utils::be64_to_array(*idx))?;
159 impl<R: ::std::io::Read> Readable<R> for CounterpartyCommitmentSecrets {
160 fn read(reader: &mut R) -> Result<Self, DecodeError> {
161 let mut old_secrets = [([0; 32], 1 << 48); 49];
162 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
163 *secret = Readable::read(reader)?;
164 *idx = Readable::read(reader)?;
167 Ok(Self { old_secrets })
171 /// Derives a per-commitment-transaction private key (eg an htlc key or payment key) from the base
172 /// private key for that type of key and the per_commitment_point (available in TxCreationKeys)
173 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> Result<SecretKey, secp256k1::Error> {
174 let mut sha = Sha256::engine();
175 sha.input(&per_commitment_point.serialize());
176 sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
177 let res = Sha256::from_engine(sha).into_inner();
179 let mut key = base_secret.clone();
180 key.add_assign(&res)?;
184 pub(super) fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> Result<PublicKey, secp256k1::Error> {
185 let mut sha = Sha256::engine();
186 sha.input(&per_commitment_point.serialize());
187 sha.input(&base_point.serialize());
188 let res = Sha256::from_engine(sha).into_inner();
190 let hashkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&res)?);
191 base_point.combine(&hashkey)
194 /// Derives a revocation key from its constituent parts.
195 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
196 /// generated (ie our own).
197 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> {
198 let revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &revocation_base_secret);
199 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
201 let rev_append_commit_hash_key = {
202 let mut sha = Sha256::engine();
203 sha.input(&revocation_base_point.serialize());
204 sha.input(&per_commitment_point.serialize());
206 Sha256::from_engine(sha).into_inner()
208 let commit_append_rev_hash_key = {
209 let mut sha = Sha256::engine();
210 sha.input(&per_commitment_point.serialize());
211 sha.input(&revocation_base_point.serialize());
213 Sha256::from_engine(sha).into_inner()
216 let mut part_a = revocation_base_secret.clone();
217 part_a.mul_assign(&rev_append_commit_hash_key)?;
218 let mut part_b = per_commitment_secret.clone();
219 part_b.mul_assign(&commit_append_rev_hash_key)?;
220 part_a.add_assign(&part_b[..])?;
224 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> {
225 let rev_append_commit_hash_key = {
226 let mut sha = Sha256::engine();
227 sha.input(&revocation_base_point.serialize());
228 sha.input(&per_commitment_point.serialize());
230 Sha256::from_engine(sha).into_inner()
232 let commit_append_rev_hash_key = {
233 let mut sha = Sha256::engine();
234 sha.input(&per_commitment_point.serialize());
235 sha.input(&revocation_base_point.serialize());
237 Sha256::from_engine(sha).into_inner()
240 let mut part_a = revocation_base_point.clone();
241 part_a.mul_assign(&secp_ctx, &rev_append_commit_hash_key)?;
242 let mut part_b = per_commitment_point.clone();
243 part_b.mul_assign(&secp_ctx, &commit_append_rev_hash_key)?;
244 part_a.combine(&part_b)
247 /// The set of public keys which are used in the creation of one commitment transaction.
248 /// These are derived from the channel base keys and per-commitment data.
250 pub struct TxCreationKeys {
251 /// The per-commitment public key which was used to derive the other keys.
252 pub per_commitment_point: PublicKey,
253 /// The revocation key which is used to allow the owner of the commitment transaction to
254 /// provide their counterparty the ability to punish them if they broadcast an old state.
255 pub(crate) revocation_key: PublicKey,
257 pub(crate) a_htlc_key: PublicKey,
259 pub(crate) b_htlc_key: PublicKey,
260 /// A's Payment Key (which isn't allowed to be spent from for some delay)
261 pub(crate) a_delayed_payment_key: PublicKey,
263 pub(crate) b_payment_key: PublicKey,
266 /// One counterparty's public keys which do not change over the life of a channel.
267 #[derive(Clone, PartialEq)]
268 pub struct ChannelPublicKeys {
269 /// The public key which is used to sign all commitment transactions, as it appears in the
270 /// on-chain channel lock-in 2-of-2 multisig output.
271 pub funding_pubkey: PublicKey,
272 /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
273 /// revocation keys. The per-commitment revocation private key is then revealed by the owner of
274 /// a commitment transaction so that their counterparty can claim all available funds if they
275 /// broadcast an old state.
276 pub revocation_basepoint: PublicKey,
277 /// The base point which is used (with derive_public_key) to derive a per-commitment payment
278 /// public key which receives immediately-spendable non-HTLC-encumbered funds.
279 pub payment_basepoint: PublicKey,
280 /// The base point which is used (with derive_public_key) to derive a per-commitment payment
281 /// public key which receives non-HTLC-encumbered funds which are only available for spending
282 /// after some delay (or can be claimed via the revocation path).
283 pub delayed_payment_basepoint: PublicKey,
284 /// The base point which is used (with derive_public_key) to derive a per-commitment public key
285 /// which is used to encumber HTLC-in-flight outputs.
286 pub htlc_basepoint: PublicKey,
289 impl_writeable!(ChannelPublicKeys, 33*5, {
291 revocation_basepoint,
293 delayed_payment_basepoint,
298 impl TxCreationKeys {
299 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> {
301 per_commitment_point: per_commitment_point.clone(),
302 revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &b_revocation_base)?,
303 a_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_htlc_base)?,
304 b_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_htlc_base)?,
305 a_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_delayed_payment_base)?,
306 b_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_payment_base)?,
311 /// Gets the "to_local" output redeemscript, ie the script which is time-locked or spendable by
312 /// the revocation key
313 pub(super) fn get_revokeable_redeemscript(revocation_key: &PublicKey, to_self_delay: u16, delayed_payment_key: &PublicKey) -> Script {
314 Builder::new().push_opcode(opcodes::all::OP_IF)
315 .push_slice(&revocation_key.serialize())
316 .push_opcode(opcodes::all::OP_ELSE)
317 .push_int(to_self_delay as i64)
318 .push_opcode(opcodes::all::OP_CSV)
319 .push_opcode(opcodes::all::OP_DROP)
320 .push_slice(&delayed_payment_key.serialize())
321 .push_opcode(opcodes::all::OP_ENDIF)
322 .push_opcode(opcodes::all::OP_CHECKSIG)
326 #[derive(Clone, PartialEq)]
327 /// Information about an HTLC as it appears in a commitment transaction
328 pub struct HTLCOutputInCommitment {
329 /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
330 /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
331 /// need to compare this value to whether the commitment transaction in question is that of
332 /// the remote party or our own.
334 /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
335 /// this divided by 1000.
336 pub amount_msat: u64,
337 /// The CLTV lock-time at which this HTLC expires.
338 pub cltv_expiry: u32,
339 /// The hash of the preimage which unlocks this HTLC.
340 pub payment_hash: PaymentHash,
341 /// The position within the commitment transactions' outputs. This may be None if the value is
342 /// below the dust limit (in which case no output appears in the commitment transaction and the
343 /// value is spent to additional transaction fees).
344 pub transaction_output_index: Option<u32>,
348 pub(super) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, a_htlc_key: &PublicKey, b_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
349 let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
351 Builder::new().push_opcode(opcodes::all::OP_DUP)
352 .push_opcode(opcodes::all::OP_HASH160)
353 .push_slice(&Hash160::hash(&revocation_key.serialize())[..])
354 .push_opcode(opcodes::all::OP_EQUAL)
355 .push_opcode(opcodes::all::OP_IF)
356 .push_opcode(opcodes::all::OP_CHECKSIG)
357 .push_opcode(opcodes::all::OP_ELSE)
358 .push_slice(&b_htlc_key.serialize()[..])
359 .push_opcode(opcodes::all::OP_SWAP)
360 .push_opcode(opcodes::all::OP_SIZE)
362 .push_opcode(opcodes::all::OP_EQUAL)
363 .push_opcode(opcodes::all::OP_NOTIF)
364 .push_opcode(opcodes::all::OP_DROP)
366 .push_opcode(opcodes::all::OP_SWAP)
367 .push_slice(&a_htlc_key.serialize()[..])
369 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
370 .push_opcode(opcodes::all::OP_ELSE)
371 .push_opcode(opcodes::all::OP_HASH160)
372 .push_slice(&payment_hash160)
373 .push_opcode(opcodes::all::OP_EQUALVERIFY)
374 .push_opcode(opcodes::all::OP_CHECKSIG)
375 .push_opcode(opcodes::all::OP_ENDIF)
376 .push_opcode(opcodes::all::OP_ENDIF)
379 Builder::new().push_opcode(opcodes::all::OP_DUP)
380 .push_opcode(opcodes::all::OP_HASH160)
381 .push_slice(&Hash160::hash(&revocation_key.serialize())[..])
382 .push_opcode(opcodes::all::OP_EQUAL)
383 .push_opcode(opcodes::all::OP_IF)
384 .push_opcode(opcodes::all::OP_CHECKSIG)
385 .push_opcode(opcodes::all::OP_ELSE)
386 .push_slice(&b_htlc_key.serialize()[..])
387 .push_opcode(opcodes::all::OP_SWAP)
388 .push_opcode(opcodes::all::OP_SIZE)
390 .push_opcode(opcodes::all::OP_EQUAL)
391 .push_opcode(opcodes::all::OP_IF)
392 .push_opcode(opcodes::all::OP_HASH160)
393 .push_slice(&payment_hash160)
394 .push_opcode(opcodes::all::OP_EQUALVERIFY)
396 .push_opcode(opcodes::all::OP_SWAP)
397 .push_slice(&a_htlc_key.serialize()[..])
399 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
400 .push_opcode(opcodes::all::OP_ELSE)
401 .push_opcode(opcodes::all::OP_DROP)
402 .push_int(htlc.cltv_expiry as i64)
403 .push_opcode(opcodes::all::OP_CLTV)
404 .push_opcode(opcodes::all::OP_DROP)
405 .push_opcode(opcodes::all::OP_CHECKSIG)
406 .push_opcode(opcodes::all::OP_ENDIF)
407 .push_opcode(opcodes::all::OP_ENDIF)
412 /// note here that 'a_revocation_key' is generated using b_revocation_basepoint and a's
413 /// commitment secret. 'htlc' does *not* need to have its previous_output_index filled.
415 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, keys: &TxCreationKeys) -> Script {
416 get_htlc_redeemscript_with_explicit_keys(htlc, &keys.a_htlc_key, &keys.b_htlc_key, &keys.revocation_key)
419 /// Gets the redeemscript for a funding output from the two funding public keys.
420 /// Note that the order of funding public keys does not matter.
421 pub fn make_funding_redeemscript(a: &PublicKey, b: &PublicKey) -> Script {
422 let our_funding_key = a.serialize();
423 let their_funding_key = b.serialize();
425 let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
426 if our_funding_key[..] < their_funding_key[..] {
427 builder.push_slice(&our_funding_key)
428 .push_slice(&their_funding_key)
430 builder.push_slice(&their_funding_key)
431 .push_slice(&our_funding_key)
432 }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
435 /// panics if htlc.transaction_output_index.is_none()!
436 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 {
437 let mut txins: Vec<TxIn> = Vec::new();
439 previous_output: OutPoint {
440 txid: prev_hash.clone(),
441 vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
443 script_sig: Script::new(),
448 let total_fee = if htlc.offered {
449 feerate_per_kw * HTLC_TIMEOUT_TX_WEIGHT / 1000
451 feerate_per_kw * HTLC_SUCCESS_TX_WEIGHT / 1000
454 let mut txouts: Vec<TxOut> = Vec::new();
456 script_pubkey: get_revokeable_redeemscript(revocation_key, to_self_delay, a_delayed_payment_key).to_v0_p2wsh(),
457 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)
462 lock_time: if htlc.offered { htlc.cltv_expiry } else { 0 },
468 /// Signs a transaction created by build_htlc_transaction. If the transaction is an
469 /// HTLC-Success transaction (ie htlc.offered is false), preimage must be set!
470 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), ()> {
471 if tx.input.len() != 1 { return Err(()); }
472 if tx.input[0].witness.len() != 0 { return Err(()); }
474 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&htlc, a_htlc_key, b_htlc_key, revocation_key);
476 let our_htlc_key = derive_private_key(secp_ctx, per_commitment_point, htlc_base_key).map_err(|_| ())?;
477 let sighash = hash_to_message!(&bip143::SighashComponents::new(&tx).sighash_all(&tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]);
478 let local_tx = PublicKey::from_secret_key(&secp_ctx, &our_htlc_key) == *a_htlc_key;
479 let our_sig = secp_ctx.sign(&sighash, &our_htlc_key);
481 tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
483 if local_tx { // b, then a
484 tx.input[0].witness.push(their_sig.serialize_der().to_vec());
485 tx.input[0].witness.push(our_sig.serialize_der().to_vec());
487 tx.input[0].witness.push(our_sig.serialize_der().to_vec());
488 tx.input[0].witness.push(their_sig.serialize_der().to_vec());
490 tx.input[0].witness[1].push(SigHashType::All as u8);
491 tx.input[0].witness[2].push(SigHashType::All as u8);
494 tx.input[0].witness.push(Vec::new());
495 assert!(preimage.is_none());
497 tx.input[0].witness.push(preimage.unwrap().0.to_vec());
500 tx.input[0].witness.push(htlc_redeemscript.as_bytes().to_vec());
502 Ok((our_sig, htlc_redeemscript))
506 /// We use this to track local commitment transactions and put off signing them until we are ready
507 /// to broadcast. Eventually this will require a signer which is possibly external, but for now we
508 /// just pass in the SecretKeys required.
509 pub(crate) struct LocalCommitmentTransaction {
512 impl LocalCommitmentTransaction {
514 pub fn dummy() -> Self {
515 Self { tx: Transaction {
523 pub fn new_missing_local_sig(mut tx: Transaction, their_sig: &Signature, our_funding_key: &PublicKey, their_funding_key: &PublicKey) -> LocalCommitmentTransaction {
524 if tx.input.len() != 1 { panic!("Tried to store a commitment transaction that had input count != 1!"); }
525 if tx.input[0].witness.len() != 0 { panic!("Tried to store a signed commitment transaction?"); }
527 tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
529 if our_funding_key.serialize()[..] < their_funding_key.serialize()[..] {
530 tx.input[0].witness.push(Vec::new());
531 tx.input[0].witness.push(their_sig.serialize_der().to_vec());
532 tx.input[0].witness[2].push(SigHashType::All as u8);
534 tx.input[0].witness.push(their_sig.serialize_der().to_vec());
535 tx.input[0].witness[1].push(SigHashType::All as u8);
536 tx.input[0].witness.push(Vec::new());
542 pub fn txid(&self) -> Sha256dHash {
546 pub fn has_local_sig(&self) -> bool {
547 if self.tx.input.len() != 1 { panic!("Commitment transactions must have input count == 1!"); }
548 if self.tx.input[0].witness.len() == 4 {
549 assert!(!self.tx.input[0].witness[1].is_empty());
550 assert!(!self.tx.input[0].witness[2].is_empty());
553 assert_eq!(self.tx.input[0].witness.len(), 3);
554 assert!(self.tx.input[0].witness[0].is_empty());
555 assert!(self.tx.input[0].witness[1].is_empty() || self.tx.input[0].witness[2].is_empty());
560 pub fn add_local_sig<T: secp256k1::Signing>(&mut self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) {
561 if self.has_local_sig() { return; }
562 let sighash = hash_to_message!(&bip143::SighashComponents::new(&self.tx)
563 .sighash_all(&self.tx.input[0], funding_redeemscript, channel_value_satoshis)[..]);
564 let our_sig = secp_ctx.sign(&sighash, funding_key);
566 if self.tx.input[0].witness[1].is_empty() {
567 self.tx.input[0].witness[1] = our_sig.serialize_der().to_vec();
568 self.tx.input[0].witness[1].push(SigHashType::All as u8);
570 self.tx.input[0].witness[2] = our_sig.serialize_der().to_vec();
571 self.tx.input[0].witness[2].push(SigHashType::All as u8);
574 self.tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
577 pub fn without_valid_witness(&self) -> &Transaction { &self.tx }
578 pub fn with_valid_witness(&self) -> &Transaction {
579 assert!(self.has_local_sig());
583 impl PartialEq for LocalCommitmentTransaction {
584 // We dont care whether we are signed in equality comparison
585 fn eq(&self, o: &Self) -> bool {
586 self.txid() == o.txid()
589 impl Writeable for LocalCommitmentTransaction {
590 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
591 if let Err(e) = self.tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
593 encode::Error::Io(e) => return Err(e),
594 _ => panic!("local tx must have been well-formed!"),
600 impl<R: ::std::io::Read> Readable<R> for LocalCommitmentTransaction {
601 fn read(reader: &mut R) -> Result<Self, DecodeError> {
602 let tx = match Transaction::consensus_decode(reader.by_ref()) {
605 encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
606 _ => return Err(DecodeError::InvalidValue),
610 if tx.input.len() != 1 {
611 // Ensure tx didn't hit the 0-input ambiguity case.
612 return Err(DecodeError::InvalidValue);
620 use super::CounterpartyCommitmentSecrets;
624 fn test_per_commitment_storage() {
625 // Test vectors from BOLT 3:
626 let mut secrets: Vec<[u8; 32]> = Vec::new();
629 macro_rules! test_secrets {
631 let mut idx = 281474976710655;
632 for secret in secrets.iter() {
633 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
636 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
637 assert!(monitor.get_secret(idx).is_none());
642 // insert_secret correct sequence
643 monitor = CounterpartyCommitmentSecrets::new();
646 secrets.push([0; 32]);
647 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
648 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
651 secrets.push([0; 32]);
652 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
653 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
656 secrets.push([0; 32]);
657 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
658 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
661 secrets.push([0; 32]);
662 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
663 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
666 secrets.push([0; 32]);
667 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
668 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
671 secrets.push([0; 32]);
672 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
673 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
676 secrets.push([0; 32]);
677 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
678 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
681 secrets.push([0; 32]);
682 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
683 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
688 // insert_secret #1 incorrect
689 monitor = CounterpartyCommitmentSecrets::new();
692 secrets.push([0; 32]);
693 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
694 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
697 secrets.push([0; 32]);
698 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
699 assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
703 // insert_secret #2 incorrect (#1 derived from incorrect)
704 monitor = CounterpartyCommitmentSecrets::new();
707 secrets.push([0; 32]);
708 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
709 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
712 secrets.push([0; 32]);
713 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
714 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
717 secrets.push([0; 32]);
718 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
719 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
722 secrets.push([0; 32]);
723 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
724 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
728 // insert_secret #3 incorrect
729 monitor = CounterpartyCommitmentSecrets::new();
732 secrets.push([0; 32]);
733 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
734 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
737 secrets.push([0; 32]);
738 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
739 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
742 secrets.push([0; 32]);
743 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
744 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
747 secrets.push([0; 32]);
748 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
749 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
753 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
754 monitor = CounterpartyCommitmentSecrets::new();
757 secrets.push([0; 32]);
758 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
759 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
762 secrets.push([0; 32]);
763 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
764 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
767 secrets.push([0; 32]);
768 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
769 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
772 secrets.push([0; 32]);
773 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
774 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
777 secrets.push([0; 32]);
778 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
779 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
782 secrets.push([0; 32]);
783 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
784 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
787 secrets.push([0; 32]);
788 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
789 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
792 secrets.push([0; 32]);
793 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
794 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
798 // insert_secret #5 incorrect
799 monitor = CounterpartyCommitmentSecrets::new();
802 secrets.push([0; 32]);
803 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
804 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
807 secrets.push([0; 32]);
808 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
809 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
812 secrets.push([0; 32]);
813 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
814 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
817 secrets.push([0; 32]);
818 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
819 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
822 secrets.push([0; 32]);
823 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
824 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
827 secrets.push([0; 32]);
828 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
829 assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
833 // insert_secret #6 incorrect (5 derived from incorrect)
834 monitor = CounterpartyCommitmentSecrets::new();
837 secrets.push([0; 32]);
838 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
839 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
842 secrets.push([0; 32]);
843 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
844 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
847 secrets.push([0; 32]);
848 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
849 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
852 secrets.push([0; 32]);
853 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
854 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
857 secrets.push([0; 32]);
858 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
859 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
862 secrets.push([0; 32]);
863 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
864 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
867 secrets.push([0; 32]);
868 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
869 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
872 secrets.push([0; 32]);
873 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
874 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
878 // insert_secret #7 incorrect
879 monitor = CounterpartyCommitmentSecrets::new();
882 secrets.push([0; 32]);
883 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
884 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
887 secrets.push([0; 32]);
888 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
889 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
892 secrets.push([0; 32]);
893 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
894 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
897 secrets.push([0; 32]);
898 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
899 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
902 secrets.push([0; 32]);
903 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
904 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
907 secrets.push([0; 32]);
908 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
909 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
912 secrets.push([0; 32]);
913 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
914 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
917 secrets.push([0; 32]);
918 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
919 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
923 // insert_secret #8 incorrect
924 monitor = CounterpartyCommitmentSecrets::new();
927 secrets.push([0; 32]);
928 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
929 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
932 secrets.push([0; 32]);
933 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
934 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
937 secrets.push([0; 32]);
938 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
939 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
942 secrets.push([0; 32]);
943 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
944 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
947 secrets.push([0; 32]);
948 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
949 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
952 secrets.push([0; 32]);
953 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
954 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
957 secrets.push([0; 32]);
958 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
959 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
962 secrets.push([0; 32]);
963 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
964 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());