X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=src%2Fln%2Fchannel.rs;h=2a8dd924506038bc1f1f0207aa3fd1714ee4e4f3;hb=98f264372eda2d3e0d5028d962c850e6ef074722;hp=ddfb809ccdeaf6f7b542c0c08e2850f7646a80cf;hpb=608cf1c89db01f9cf612516a88a3f77f1f48bc52;p=rust-lightning diff --git a/src/ln/channel.rs b/src/ln/channel.rs index ddfb809c..2a8dd924 100644 --- a/src/ln/channel.rs +++ b/src/ln/channel.rs @@ -11,11 +11,11 @@ use bitcoin_hashes::sha256::Hash as Sha256; use bitcoin_hashes::hash160::Hash as Hash160; use secp256k1::key::{PublicKey,SecretKey}; -use secp256k1::{Secp256k1,Message,Signature}; +use secp256k1::{Secp256k1,Signature}; use secp256k1; use ln::msgs; -use ln::msgs::DecodeError; +use ln::msgs::{DecodeError, OptionalField}; use ln::channelmonitor::ChannelMonitor; use ln::channelmanager::{PendingHTLCStatus, HTLCSource, HTLCFailReason, HTLCFailureMsg, PendingForwardHTLCInfo, RAACommitmentOrder, PaymentPreimage, PaymentHash}; use ln::chan_utils::{TxCreationKeys,HTLCOutputInCommitment,HTLC_SUCCESS_TX_WEIGHT,HTLC_TIMEOUT_TX_WEIGHT}; @@ -23,7 +23,7 @@ use ln::chan_utils; use chain::chaininterface::{FeeEstimator,ConfirmationTarget}; use chain::transaction::OutPoint; use chain::keysinterface::{ChannelKeys, KeysInterface}; -use util::{transaction_utils,rng}; +use util::transaction_utils; use util::ser::{Readable, ReadableArgs, Writeable, Writer, WriterWriteAdaptor}; use util::logger::Logger; use util::errors::APIError; @@ -132,18 +132,6 @@ struct OutboundHTLCOutput { fail_reason: Option, } -macro_rules! get_htlc_in_commitment { - ($htlc: expr, $offered: expr) => { - HTLCOutputInCommitment { - offered: $offered, - amount_msat: $htlc.amount_msat, - cltv_expiry: $htlc.cltv_expiry, - payment_hash: $htlc.payment_hash, - transaction_output_index: 0 - } - } -} - /// See AwaitingRemoteRevoke ChannelState for more info enum HTLCUpdateAwaitingACK { AddHTLC { @@ -319,6 +307,9 @@ pub(super) struct Channel { pub(super) our_dust_limit_satoshis: u64, #[cfg(not(test))] our_dust_limit_satoshis: u64, + #[cfg(test)] + pub(super) their_max_htlc_value_in_flight_msat: u64, + #[cfg(not(test))] their_max_htlc_value_in_flight_msat: u64, //get_our_max_htlc_value_in_flight_msat(): u64, /// minimum channel reserve for **self** to maintain - set by them. @@ -328,6 +319,9 @@ pub(super) struct Channel { our_htlc_minimum_msat: u64, their_to_self_delay: u16, //implied by BREAKDOWN_TIMEOUT: our_to_self_delay: u16, + #[cfg(test)] + pub their_max_accepted_htlcs: u16, + #[cfg(not(test))] their_max_accepted_htlcs: u16, //implied by OUR_MAX_HTLCS: our_max_accepted_htlcs: u16, minimum_depth: u32, @@ -349,14 +343,17 @@ pub(super) struct Channel { logger: Arc, } -const OUR_MAX_HTLCS: u16 = 50; //TODO +pub const OUR_MAX_HTLCS: u16 = 50; //TODO /// Confirmation count threshold at which we close a channel. Ideally we'd keep the channel around /// on ice until the funding transaction gets more confirmations, but the LN protocol doesn't /// really allow for this, so instead we're stuck closing it out at that point. const UNCONF_THRESHOLD: u32 = 6; /// The amount of time we require our counterparty wait to claim their money (ie time between when /// we, or our watchtower, must check for them having broadcast a theft transaction). +#[cfg(not(test))] const BREAKDOWN_TIMEOUT: u16 = 6 * 24 * 7; //TODO? +#[cfg(test)] +pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24 * 7; //TODO? /// The amount of time we're willing to wait to claim money back to us const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 6 * 24 * 14; /// Exposing these two constants for use in test in ChannelMonitor @@ -450,7 +447,7 @@ impl Channel { user_id: user_id, config: config.channel_options.clone(), - channel_id: rng::rand_u832(), + channel_id: keys_provider.get_channel_id(), channel_state: ChannelState::OurInitSent as u32, channel_outbound: true, secp_ctx: secp_ctx, @@ -720,7 +717,7 @@ impl Channel { fn build_local_commitment_secret(&self, idx: u64) -> SecretKey { let res = chan_utils::build_commitment_secret(self.local_keys.commitment_seed, idx); - SecretKey::from_slice(&self.secp_ctx, &res).unwrap() + SecretKey::from_slice(&res).unwrap() } // Utilities to build transactions: @@ -759,8 +756,12 @@ impl Channel { /// have not yet committed it. Such HTLCs will only be included in transactions which are being /// generated by the peer which proposed adding the HTLCs, and thus we need to understand both /// which peer generated this transaction and "to whom" this transaction flows. + /// Returns (the transaction built, the number of HTLC outputs which were present in the + /// transaction, the list of HTLCs which were not ignored when building the transaction). + /// Note that below-dust HTLCs are included in the third return value, but not the second, and + /// sources are provided only for outbound HTLCs in the third return value. #[inline] - fn build_commitment_transaction(&self, commitment_number: u64, keys: &TxCreationKeys, local: bool, generated_by_local: bool, feerate_per_kw: u64) -> (Transaction, Vec, Vec<(PaymentHash, &HTLCSource, Option)>) { + fn build_commitment_transaction(&self, commitment_number: u64, keys: &TxCreationKeys, local: bool, generated_by_local: bool, feerate_per_kw: u64) -> (Transaction, usize, Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>) { let obscured_commitment_transaction_number = self.get_commitment_transaction_number_obscure_factor() ^ (INITIAL_COMMITMENT_NUMBER - commitment_number); let txins = { @@ -775,38 +776,46 @@ impl Channel { }; let mut txouts: Vec<(TxOut, Option<(HTLCOutputInCommitment, Option<&HTLCSource>)>)> = Vec::with_capacity(self.pending_inbound_htlcs.len() + self.pending_outbound_htlcs.len() + 2); - let mut unincluded_htlc_sources: Vec<(PaymentHash, &HTLCSource, Option)> = Vec::new(); + let mut included_dust_htlcs: Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)> = Vec::new(); let dust_limit_satoshis = if local { self.our_dust_limit_satoshis } else { self.their_dust_limit_satoshis }; let mut remote_htlc_total_msat = 0; let mut local_htlc_total_msat = 0; let mut value_to_self_msat_offset = 0; + macro_rules! get_htlc_in_commitment { + ($htlc: expr, $offered: expr) => { + HTLCOutputInCommitment { + offered: $offered, + amount_msat: $htlc.amount_msat, + cltv_expiry: $htlc.cltv_expiry, + payment_hash: $htlc.payment_hash, + transaction_output_index: None + } + } + } + macro_rules! add_htlc_output { ($htlc: expr, $outbound: expr, $source: expr) => { if $outbound == local { // "offered HTLC output" + let htlc_in_tx = get_htlc_in_commitment!($htlc, true); if $htlc.amount_msat / 1000 >= dust_limit_satoshis + (feerate_per_kw * HTLC_TIMEOUT_TX_WEIGHT / 1000) { - let htlc_in_tx = get_htlc_in_commitment!($htlc, true); txouts.push((TxOut { script_pubkey: chan_utils::get_htlc_redeemscript(&htlc_in_tx, &keys).to_v0_p2wsh(), value: $htlc.amount_msat / 1000 }, Some((htlc_in_tx, $source)))); } else { - if let Some(source) = $source { - unincluded_htlc_sources.push(($htlc.payment_hash, source, None)); - } + included_dust_htlcs.push((htlc_in_tx, $source)); } } else { + let htlc_in_tx = get_htlc_in_commitment!($htlc, false); if $htlc.amount_msat / 1000 >= dust_limit_satoshis + (feerate_per_kw * HTLC_SUCCESS_TX_WEIGHT / 1000) { - let htlc_in_tx = get_htlc_in_commitment!($htlc, false); txouts.push((TxOut { // "received HTLC output" script_pubkey: chan_utils::get_htlc_redeemscript(&htlc_in_tx, &keys).to_v0_p2wsh(), value: $htlc.amount_msat / 1000 }, Some((htlc_in_tx, $source)))); } else { - if let Some(source) = $source { - unincluded_htlc_sources.push(($htlc.payment_hash, source, None)); - } + included_dust_htlcs.push((htlc_in_tx, $source)); } } } @@ -909,7 +918,7 @@ impl Channel { if value_to_b >= (dust_limit_satoshis as i64) { txouts.push((TxOut { - script_pubkey: Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0) + script_pubkey: Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0) .push_slice(&Hash160::hash(&keys.b_payment_key.serialize())[..]) .into_script(), value: value_to_b as u64 @@ -919,32 +928,29 @@ impl Channel { transaction_utils::sort_outputs(&mut txouts); let mut outputs: Vec = Vec::with_capacity(txouts.len()); - let mut htlcs_included: Vec = Vec::with_capacity(txouts.len()); - let mut htlc_sources: Vec<(PaymentHash, &HTLCSource, Option)> = Vec::with_capacity(txouts.len() + unincluded_htlc_sources.len()); - for (idx, out) in txouts.drain(..).enumerate() { + let mut htlcs_included: Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)> = Vec::with_capacity(txouts.len() + included_dust_htlcs.len()); + for (idx, mut out) in txouts.drain(..).enumerate() { outputs.push(out.0); - if let Some((mut htlc, source_option)) = out.1 { - htlc.transaction_output_index = idx as u32; - if let Some(source) = source_option { - htlc_sources.push((htlc.payment_hash, source, Some(idx as u32))); - } - htlcs_included.push(htlc); + if let Some((mut htlc, source_option)) = out.1.take() { + htlc.transaction_output_index = Some(idx as u32); + htlcs_included.push((htlc, source_option)); } } - htlc_sources.append(&mut unincluded_htlc_sources); + let non_dust_htlc_count = htlcs_included.len(); + htlcs_included.append(&mut included_dust_htlcs); (Transaction { version: 2, lock_time: ((0x20 as u32) << 8*3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32), input: txins, output: outputs, - }, htlcs_included, htlc_sources) + }, non_dust_htlc_count, htlcs_included) } #[inline] fn get_closing_scriptpubkey(&self) -> Script { let our_channel_close_key_hash = Hash160::hash(&self.shutdown_pubkey.serialize()); - Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script() + Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script() } #[inline] @@ -1042,7 +1048,7 @@ impl Channel { /// pays to get_funding_redeemscript().to_v0_p2wsh()). /// Panics if called before accept_channel/new_from_req pub fn get_funding_redeemscript(&self) -> Script { - let builder = Builder::new().push_opcode(opcodes::All::OP_PUSHNUM_2); + let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2); let our_funding_key = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.funding_key).serialize(); let their_funding_key = self.their_funding_pubkey.expect("get_funding_redeemscript only allowed after accept_channel").serialize(); if our_funding_key[..] < their_funding_key[..] { @@ -1051,7 +1057,7 @@ impl Channel { } else { builder.push_slice(&their_funding_key) .push_slice(&our_funding_key) - }.push_opcode(opcodes::All::OP_PUSHNUM_2).push_opcode(opcodes::All::OP_CHECKMULTISIG).into_script() + }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script() } fn sign_commitment_transaction(&self, tx: &mut Transaction, their_sig: &Signature) -> Signature { @@ -1064,7 +1070,7 @@ impl Channel { let funding_redeemscript = self.get_funding_redeemscript(); - let sighash = Message::from_slice(&bip143::SighashComponents::new(&tx).sighash_all(&tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]).unwrap(); + let sighash = hash_to_message!(&bip143::SighashComponents::new(&tx).sighash_all(&tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]); let our_sig = self.secp_ctx.sign(&sighash, &self.local_keys.funding_key); tx.input[0].witness.push(Vec::new()); // First is the multisig dummy @@ -1072,11 +1078,11 @@ impl Channel { let our_funding_key = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.funding_key).serialize(); let their_funding_key = self.their_funding_pubkey.unwrap().serialize(); if our_funding_key[..] < their_funding_key[..] { - tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec()); - tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec()); + tx.input[0].witness.push(our_sig.serialize_der().to_vec()); + tx.input[0].witness.push(their_sig.serialize_der().to_vec()); } else { - tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec()); - tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec()); + tx.input[0].witness.push(their_sig.serialize_der().to_vec()); + tx.input[0].witness.push(our_sig.serialize_der().to_vec()); } tx.input[0].witness[1].push(SigHashType::All as u8); tx.input[0].witness[2].push(SigHashType::All as u8); @@ -1101,7 +1107,7 @@ impl Channel { let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys); let our_htlc_key = secp_check!(chan_utils::derive_private_key(&self.secp_ctx, &keys.per_commitment_point, &self.local_keys.htlc_base_key), "Derived invalid key, peer is maliciously selecting parameters"); - let sighash = Message::from_slice(&bip143::SighashComponents::new(&tx).sighash_all(&tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]).unwrap(); + let sighash = hash_to_message!(&bip143::SighashComponents::new(&tx).sighash_all(&tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]); let is_local_tx = PublicKey::from_secret_key(&self.secp_ctx, &our_htlc_key) == keys.a_htlc_key; Ok((htlc_redeemscript, self.secp_ctx.sign(&sighash, &our_htlc_key), is_local_tx)) } @@ -1121,11 +1127,11 @@ impl Channel { tx.input[0].witness.push(Vec::new()); // First is the multisig dummy if local_tx { // b, then a - tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec()); - tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec()); + tx.input[0].witness.push(their_sig.serialize_der().to_vec()); + tx.input[0].witness.push(our_sig.serialize_der().to_vec()); } else { - tx.input[0].witness.push(our_sig.serialize_der(&self.secp_ctx).to_vec()); - tx.input[0].witness.push(their_sig.serialize_der(&self.secp_ctx).to_vec()); + tx.input[0].witness.push(our_sig.serialize_der().to_vec()); + tx.input[0].witness.push(their_sig.serialize_der().to_vec()); } tx.input[0].witness[1].push(SigHashType::All as u8); tx.input[0].witness[2].push(SigHashType::All as u8); @@ -1405,7 +1411,7 @@ impl Channel { let local_keys = self.build_local_transaction_keys(self.cur_local_commitment_transaction_number)?; let mut local_initial_commitment_tx = self.build_commitment_transaction(self.cur_local_commitment_transaction_number, &local_keys, true, false, self.feerate_per_kw).0; - let local_sighash = Message::from_slice(&bip143::SighashComponents::new(&local_initial_commitment_tx).sighash_all(&local_initial_commitment_tx.input[0], &funding_script, self.channel_value_satoshis)[..]).unwrap(); + let local_sighash = hash_to_message!(&bip143::SighashComponents::new(&local_initial_commitment_tx).sighash_all(&local_initial_commitment_tx.input[0], &funding_script, self.channel_value_satoshis)[..]); // They sign the "local" commitment transaction... secp_check!(self.secp_ctx.verify(&local_sighash, &sig, &self.their_funding_pubkey.unwrap()), "Invalid funding_created signature from peer"); @@ -1415,7 +1421,7 @@ impl Channel { let remote_keys = self.build_remote_transaction_keys()?; let remote_initial_commitment_tx = self.build_commitment_transaction(self.cur_remote_commitment_transaction_number, &remote_keys, false, false, self.feerate_per_kw).0; - let remote_sighash = Message::from_slice(&bip143::SighashComponents::new(&remote_initial_commitment_tx).sighash_all(&remote_initial_commitment_tx.input[0], &funding_script, self.channel_value_satoshis)[..]).unwrap(); + let remote_sighash = hash_to_message!(&bip143::SighashComponents::new(&remote_initial_commitment_tx).sighash_all(&remote_initial_commitment_tx.input[0], &funding_script, self.channel_value_satoshis)[..]); // We sign the "remote" commitment transaction, allowing them to broadcast the tx if they wish. Ok((remote_initial_commitment_tx, local_initial_commitment_tx, self.secp_ctx.sign(&remote_sighash, &self.local_keys.funding_key), local_keys)) @@ -1451,9 +1457,9 @@ impl Channel { // Now that we're past error-generating stuff, update our local state: - self.channel_monitor.provide_latest_remote_commitment_tx_info(&remote_initial_commitment_tx, Vec::new(), Vec::new(), self.cur_remote_commitment_transaction_number, self.their_cur_commitment_point.unwrap()); + self.channel_monitor.provide_latest_remote_commitment_tx_info(&remote_initial_commitment_tx, Vec::new(), self.cur_remote_commitment_transaction_number, self.their_cur_commitment_point.unwrap()); self.last_local_commitment_txn = vec![local_initial_commitment_tx.clone()]; - self.channel_monitor.provide_latest_local_commitment_tx_info(local_initial_commitment_tx, local_keys, self.feerate_per_kw, Vec::new(), Vec::new()); + self.channel_monitor.provide_latest_local_commitment_tx_info(local_initial_commitment_tx, local_keys, self.feerate_per_kw, Vec::new()); self.channel_state = ChannelState::FundingSent as u32; self.channel_id = funding_txo.to_channel_id(); self.cur_remote_commitment_transaction_number -= 1; @@ -1484,13 +1490,13 @@ impl Channel { let local_keys = self.build_local_transaction_keys(self.cur_local_commitment_transaction_number)?; let mut local_initial_commitment_tx = self.build_commitment_transaction(self.cur_local_commitment_transaction_number, &local_keys, true, false, self.feerate_per_kw).0; - let local_sighash = Message::from_slice(&bip143::SighashComponents::new(&local_initial_commitment_tx).sighash_all(&local_initial_commitment_tx.input[0], &funding_script, self.channel_value_satoshis)[..]).unwrap(); + let local_sighash = hash_to_message!(&bip143::SighashComponents::new(&local_initial_commitment_tx).sighash_all(&local_initial_commitment_tx.input[0], &funding_script, self.channel_value_satoshis)[..]); // They sign the "local" commitment transaction, allowing us to broadcast the tx if we wish. secp_check!(self.secp_ctx.verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid funding_signed signature from peer"); self.sign_commitment_transaction(&mut local_initial_commitment_tx, &msg.signature); - self.channel_monitor.provide_latest_local_commitment_tx_info(local_initial_commitment_tx.clone(), local_keys, self.feerate_per_kw, Vec::new(), Vec::new()); + self.channel_monitor.provide_latest_local_commitment_tx_info(local_initial_commitment_tx.clone(), local_keys, self.feerate_per_kw, Vec::new()); self.last_local_commitment_txn = vec![local_initial_commitment_tx]; self.channel_state = ChannelState::FundingSent as u32; self.cur_local_commitment_transaction_number -= 1; @@ -1600,7 +1606,6 @@ impl Channel { cltv_expiry: msg.cltv_expiry, state: InboundHTLCState::RemoteAnnounced(pending_forward_state), }); - Ok(()) } @@ -1693,16 +1698,16 @@ impl Channel { let mut local_commitment_tx = { let mut commitment_tx = self.build_commitment_transaction(self.cur_local_commitment_transaction_number, &local_keys, true, false, feerate_per_kw); - let htlcs_cloned: Vec<_> = commitment_tx.2.drain(..).map(|htlc_source| (htlc_source.0, htlc_source.1.clone(), htlc_source.2)).collect(); + let htlcs_cloned: Vec<_> = commitment_tx.2.drain(..).map(|htlc| (htlc.0, htlc.1.map(|h| h.clone()))).collect(); (commitment_tx.0, commitment_tx.1, htlcs_cloned) }; let local_commitment_txid = local_commitment_tx.0.txid(); - let local_sighash = Message::from_slice(&bip143::SighashComponents::new(&local_commitment_tx.0).sighash_all(&local_commitment_tx.0.input[0], &funding_script, self.channel_value_satoshis)[..]).unwrap(); + let local_sighash = hash_to_message!(&bip143::SighashComponents::new(&local_commitment_tx.0).sighash_all(&local_commitment_tx.0.input[0], &funding_script, self.channel_value_satoshis)[..]); secp_check!(self.secp_ctx.verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid commitment tx signature from peer"); //If channel fee was updated by funder confirm funder can afford the new fee rate when applied to the current local commitment transaction if update_fee { - let num_htlcs = local_commitment_tx.1.len(); + let num_htlcs = local_commitment_tx.1; let total_fee: u64 = feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000; if self.channel_value_satoshis - self.value_to_self_msat / 1000 < total_fee + self.their_channel_reserve_satoshis { @@ -1710,28 +1715,32 @@ impl Channel { } } - if msg.htlc_signatures.len() != local_commitment_tx.1.len() { + if msg.htlc_signatures.len() != local_commitment_tx.1 { return Err(ChannelError::Close("Got wrong number of HTLC signatures from remote")); } - let mut new_local_commitment_txn = Vec::with_capacity(local_commitment_tx.1.len() + 1); + let mut new_local_commitment_txn = Vec::with_capacity(local_commitment_tx.1 + 1); self.sign_commitment_transaction(&mut local_commitment_tx.0, &msg.signature); new_local_commitment_txn.push(local_commitment_tx.0.clone()); - let mut htlcs_and_sigs = Vec::with_capacity(local_commitment_tx.1.len()); - for (idx, htlc) in local_commitment_tx.1.drain(..).enumerate() { - let mut htlc_tx = self.build_htlc_transaction(&local_commitment_txid, &htlc, true, &local_keys, feerate_per_kw); - let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &local_keys); - let htlc_sighash = Message::from_slice(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]).unwrap(); - secp_check!(self.secp_ctx.verify(&htlc_sighash, &msg.htlc_signatures[idx], &local_keys.b_htlc_key), "Invalid HTLC tx signature from peer"); - let htlc_sig = if htlc.offered { - let htlc_sig = self.sign_htlc_transaction(&mut htlc_tx, &msg.htlc_signatures[idx], &None, &htlc, &local_keys)?; - new_local_commitment_txn.push(htlc_tx); - htlc_sig + let mut htlcs_and_sigs = Vec::with_capacity(local_commitment_tx.2.len()); + for (idx, (htlc, source)) in local_commitment_tx.2.drain(..).enumerate() { + if let Some(_) = htlc.transaction_output_index { + let mut htlc_tx = self.build_htlc_transaction(&local_commitment_txid, &htlc, true, &local_keys, feerate_per_kw); + let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &local_keys); + let htlc_sighash = hash_to_message!(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]); + secp_check!(self.secp_ctx.verify(&htlc_sighash, &msg.htlc_signatures[idx], &local_keys.b_htlc_key), "Invalid HTLC tx signature from peer"); + let htlc_sig = if htlc.offered { + let htlc_sig = self.sign_htlc_transaction(&mut htlc_tx, &msg.htlc_signatures[idx], &None, &htlc, &local_keys)?; + new_local_commitment_txn.push(htlc_tx); + htlc_sig + } else { + self.create_htlc_tx_signature(&htlc_tx, &htlc, &local_keys)?.1 + }; + htlcs_and_sigs.push((htlc, Some((msg.htlc_signatures[idx], htlc_sig)), source)); } else { - self.create_htlc_tx_signature(&htlc_tx, &htlc, &local_keys)?.1 - }; - htlcs_and_sigs.push((htlc, msg.htlc_signatures[idx], htlc_sig)); + htlcs_and_sigs.push((htlc, None, source)); + } } let next_per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &self.build_local_commitment_secret(self.cur_local_commitment_transaction_number - 1)); @@ -1758,7 +1767,7 @@ impl Channel { self.monitor_pending_order = None; } - self.channel_monitor.provide_latest_local_commitment_tx_info(local_commitment_tx.0, local_keys, self.feerate_per_kw, htlcs_and_sigs, local_commitment_tx.2); + self.channel_monitor.provide_latest_local_commitment_tx_info(local_commitment_tx.0, local_keys, self.feerate_per_kw, htlcs_and_sigs); for htlc in self.pending_inbound_htlcs.iter_mut() { let new_forward = if let &InboundHTLCState::RemoteAnnounced(ref forward_info) = &htlc.state { @@ -1913,7 +1922,7 @@ impl Channel { } if let Some(their_prev_commitment_point) = self.their_prev_commitment_point { - if PublicKey::from_secret_key(&self.secp_ctx, &secp_check!(SecretKey::from_slice(&self.secp_ctx, &msg.per_commitment_secret), "Peer provided an invalid per_commitment_secret")) != their_prev_commitment_point { + if PublicKey::from_secret_key(&self.secp_ctx, &secp_check!(SecretKey::from_slice(&msg.per_commitment_secret), "Peer provided an invalid per_commitment_secret")) != their_prev_commitment_point { return Err(ChannelError::Close("Got a revoke commitment secret which didn't correspond to their current pubkey")); } } @@ -2030,6 +2039,10 @@ impl Channel { // cells) while we can't update the monitor, so we just return what we have. if require_commitment { self.monitor_pending_commitment_signed = true; + // When the monitor updating is restored we'll call get_last_commitment_update(), + // which does not update state, but we're definitely now awaiting a remote revoke + // before we can step forward any more, so set it here. + self.channel_state |= ChannelState::AwaitingRemoteRevoke as u32; } self.monitor_pending_forwards.append(&mut to_forward_infos); self.monitor_pending_failures.append(&mut revoked_htlcs); @@ -2181,23 +2194,15 @@ impl Channel { /// commitment update or a revoke_and_ack generation). The messages which were generated from /// that original call must *not* have been sent to the remote end, and must instead have been /// dropped. They will be regenerated when monitor_updating_restored is called. - pub fn monitor_update_failed(&mut self, order: RAACommitmentOrder, mut pending_forwards: Vec<(PendingForwardHTLCInfo, u64)>, mut pending_fails: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>, raa_first_dropped_cs: bool) { + pub fn monitor_update_failed(&mut self, order: RAACommitmentOrder, resend_raa: bool, resend_commitment: bool, mut pending_forwards: Vec<(PendingForwardHTLCInfo, u64)>, mut pending_fails: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>) { assert_eq!(self.channel_state & ChannelState::MonitorUpdateFailed as u32, 0); - match order { - RAACommitmentOrder::CommitmentFirst => { - self.monitor_pending_revoke_and_ack = false; - self.monitor_pending_commitment_signed = true; - }, - RAACommitmentOrder::RevokeAndACKFirst => { - self.monitor_pending_revoke_and_ack = true; - self.monitor_pending_commitment_signed = raa_first_dropped_cs; - }, - } + self.monitor_pending_revoke_and_ack = resend_raa; + self.monitor_pending_commitment_signed = resend_commitment; + self.monitor_pending_order = Some(order); assert!(self.monitor_pending_forwards.is_empty()); mem::swap(&mut pending_forwards, &mut self.monitor_pending_forwards); assert!(self.monitor_pending_failures.is_empty()); mem::swap(&mut pending_fails, &mut self.monitor_pending_failures); - self.monitor_pending_order = Some(order); self.channel_state |= ChannelState::MonitorUpdateFailed as u32; } @@ -2420,9 +2425,6 @@ impl Channel { log_debug!(self, "Reconnected channel {} with only lost remote commitment tx", log_bytes!(self.channel_id())); } - // If monitor_pending_order is set, it must be CommitmentSigned if we have no RAA - debug_assert!(self.monitor_pending_order != Some(RAACommitmentOrder::RevokeAndACKFirst) || required_revoke.is_some()); - if self.channel_state & (ChannelState::MonitorUpdateFailed as u32) != 0 { self.monitor_pending_commitment_signed = true; return Ok((resend_funding_locked, None, None, None, order, shutdown_msg)); @@ -2450,7 +2452,7 @@ impl Channel { let (closing_tx, total_fee_satoshis) = self.build_closing_transaction(proposed_total_fee_satoshis, false); let funding_redeemscript = self.get_funding_redeemscript(); - let sighash = Message::from_slice(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]).unwrap(); + let sighash = hash_to_message!(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]); self.last_sent_closing_fee = Some((proposed_feerate, total_fee_satoshis)); Some(msgs::ClosingSigned { @@ -2552,7 +2554,7 @@ impl Channel { if used_total_fee != msg.fee_satoshis { return Err(ChannelError::Close("Remote sent us a closing_signed with a fee greater than the value they can claim")); } - let mut sighash = Message::from_slice(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]).unwrap(); + let mut sighash = hash_to_message!(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]); match self.secp_ctx.verify(&sighash, &msg.signature, &self.their_funding_pubkey.unwrap()) { Ok(_) => {}, @@ -2560,7 +2562,7 @@ impl Channel { // The remote end may have decided to revoke their output due to inconsistent dust // limits, so check for that case by re-checking the signature here. closing_tx = self.build_closing_transaction(msg.fee_satoshis, true).0; - sighash = Message::from_slice(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]).unwrap(); + sighash = hash_to_message!(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]); secp_check!(self.secp_ctx.verify(&sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid closing tx signature from peer"); }, }; @@ -2578,7 +2580,7 @@ impl Channel { ($new_feerate: expr) => { let closing_tx_max_weight = Self::get_closing_transaction_weight(&self.get_closing_scriptpubkey(), self.their_shutdown_scriptpubkey.as_ref().unwrap()); let (closing_tx, used_total_fee) = self.build_closing_transaction($new_feerate * closing_tx_max_weight / 1000, false); - sighash = Message::from_slice(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]).unwrap(); + sighash = hash_to_message!(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]); let our_sig = self.secp_ctx.sign(&sighash, &self.local_keys.funding_key); self.last_sent_closing_fee = Some(($new_feerate, used_total_fee)); return Ok((Some(msgs::ClosingSigned { @@ -2945,7 +2947,7 @@ impl Channel { htlc_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key), first_per_commitment_point: PublicKey::from_secret_key(&self.secp_ctx, &local_commitment_secret), channel_flags: if self.config.announced_channel {1} else {0}, - shutdown_scriptpubkey: None, + shutdown_scriptpubkey: OptionalField::Absent } } @@ -2977,7 +2979,7 @@ impl Channel { delayed_payment_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.delayed_payment_base_key), htlc_basepoint: PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key), first_per_commitment_point: PublicKey::from_secret_key(&self.secp_ctx, &local_commitment_secret), - shutdown_scriptpubkey: None, + shutdown_scriptpubkey: OptionalField::Absent } } @@ -2987,7 +2989,7 @@ impl Channel { let remote_keys = self.build_remote_transaction_keys()?; let remote_initial_commitment_tx = self.build_commitment_transaction(self.cur_remote_commitment_transaction_number, &remote_keys, false, false, self.feerate_per_kw).0; - let remote_sighash = Message::from_slice(&bip143::SighashComponents::new(&remote_initial_commitment_tx).sighash_all(&remote_initial_commitment_tx.input[0], &funding_script, self.channel_value_satoshis)[..]).unwrap(); + let remote_sighash = hash_to_message!(&bip143::SighashComponents::new(&remote_initial_commitment_tx).sighash_all(&remote_initial_commitment_tx.input[0], &funding_script, self.channel_value_satoshis)[..]); // We sign the "remote" commitment transaction, allowing them to broadcast the tx if they wish. Ok((self.secp_ctx.sign(&remote_sighash, &self.local_keys.funding_key), remote_initial_commitment_tx)) @@ -3028,7 +3030,7 @@ impl Channel { let temporary_channel_id = self.channel_id; // Now that we're past error-generating stuff, update our local state: - self.channel_monitor.provide_latest_remote_commitment_tx_info(&commitment_tx, Vec::new(), Vec::new(), self.cur_remote_commitment_transaction_number, self.their_cur_commitment_point.unwrap()); + self.channel_monitor.provide_latest_remote_commitment_tx_info(&commitment_tx, Vec::new(), self.cur_remote_commitment_transaction_number, self.their_cur_commitment_point.unwrap()); self.channel_state = ChannelState::FundingCreated as u32; self.channel_id = funding_txo.to_channel_id(); self.cur_remote_commitment_transaction_number -= 1; @@ -3074,7 +3076,7 @@ impl Channel { excess_data: Vec::new(), }; - let msghash = Message::from_slice(&Sha256dHash::from_data(&msg.encode()[..])[..]).unwrap(); + let msghash = hash_to_message!(&Sha256dHash::from_data(&msg.encode()[..])[..]); let sig = self.secp_ctx.sign(&msghash, &self.local_keys.funding_key); Ok((msg, sig)) @@ -3105,7 +3107,7 @@ impl Channel { // dropped this channel on disconnect as it hasn't yet reached FundingSent so we can't // overflow here. next_remote_commitment_number: INITIAL_COMMITMENT_NUMBER - self.cur_remote_commitment_transaction_number - 1, - data_loss_protect: None, + data_loss_protect: OptionalField::Absent, } } @@ -3260,23 +3262,23 @@ impl Channel { } } - let (res, remote_commitment_tx, htlcs, htlc_sources) = match self.send_commitment_no_state_update() { - Ok((res, (remote_commitment_tx, htlcs, mut htlc_sources))) => { + let (res, remote_commitment_tx, htlcs) = match self.send_commitment_no_state_update() { + Ok((res, (remote_commitment_tx, mut htlcs))) => { // Update state now that we've passed all the can-fail calls... - let htlc_sources_no_ref = htlc_sources.drain(..).map(|htlc_source| (htlc_source.0, htlc_source.1.clone(), htlc_source.2)).collect(); - (res, remote_commitment_tx, htlcs, htlc_sources_no_ref) + let htlcs_no_ref = htlcs.drain(..).map(|(htlc, htlc_source)| (htlc, htlc_source.map(|source_ref| Box::new(source_ref.clone())))).collect(); + (res, remote_commitment_tx, htlcs_no_ref) }, Err(e) => return Err(e), }; - self.channel_monitor.provide_latest_remote_commitment_tx_info(&remote_commitment_tx, htlcs, htlc_sources, self.cur_remote_commitment_transaction_number, self.their_cur_commitment_point.unwrap()); + self.channel_monitor.provide_latest_remote_commitment_tx_info(&remote_commitment_tx, htlcs, self.cur_remote_commitment_transaction_number, self.their_cur_commitment_point.unwrap()); self.channel_state |= ChannelState::AwaitingRemoteRevoke as u32; Ok((res, self.channel_monitor.clone())) } /// Only fails in case of bad keys. Used for channel_reestablish commitment_signed generation /// when we shouldn't change HTLC/channel state. - fn send_commitment_no_state_update(&self) -> Result<(msgs::CommitmentSigned, (Transaction, Vec, Vec<(PaymentHash, &HTLCSource, Option)>)), ChannelError> { + fn send_commitment_no_state_update(&self) -> Result<(msgs::CommitmentSigned, (Transaction, Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>)), ChannelError> { let funding_script = self.get_funding_redeemscript(); let mut feerate_per_kw = self.feerate_per_kw; @@ -3289,24 +3291,25 @@ impl Channel { let remote_keys = self.build_remote_transaction_keys()?; let remote_commitment_tx = self.build_commitment_transaction(self.cur_remote_commitment_transaction_number, &remote_keys, false, true, feerate_per_kw); let remote_commitment_txid = remote_commitment_tx.0.txid(); - let remote_sighash = Message::from_slice(&bip143::SighashComponents::new(&remote_commitment_tx.0).sighash_all(&remote_commitment_tx.0.input[0], &funding_script, self.channel_value_satoshis)[..]).unwrap(); + let remote_sighash = hash_to_message!(&bip143::SighashComponents::new(&remote_commitment_tx.0).sighash_all(&remote_commitment_tx.0.input[0], &funding_script, self.channel_value_satoshis)[..]); let our_sig = self.secp_ctx.sign(&remote_sighash, &self.local_keys.funding_key); - let mut htlc_sigs = Vec::new(); - - for ref htlc in remote_commitment_tx.1.iter() { - let htlc_tx = self.build_htlc_transaction(&remote_commitment_txid, htlc, false, &remote_keys, feerate_per_kw); - let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &remote_keys); - let htlc_sighash = Message::from_slice(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]).unwrap(); - let our_htlc_key = secp_check!(chan_utils::derive_private_key(&self.secp_ctx, &remote_keys.per_commitment_point, &self.local_keys.htlc_base_key), "Derived invalid key, peer is maliciously selecting parameters"); - htlc_sigs.push(self.secp_ctx.sign(&htlc_sighash, &our_htlc_key)); + let mut htlc_sigs = Vec::with_capacity(remote_commitment_tx.1); + for &(ref htlc, _) in remote_commitment_tx.2.iter() { + if let Some(_) = htlc.transaction_output_index { + let htlc_tx = self.build_htlc_transaction(&remote_commitment_txid, htlc, false, &remote_keys, feerate_per_kw); + let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &remote_keys); + let htlc_sighash = hash_to_message!(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]); + let our_htlc_key = secp_check!(chan_utils::derive_private_key(&self.secp_ctx, &remote_keys.per_commitment_point, &self.local_keys.htlc_base_key), "Derived invalid key, peer is maliciously selecting parameters"); + htlc_sigs.push(self.secp_ctx.sign(&htlc_sighash, &our_htlc_key)); + } } Ok((msgs::CommitmentSigned { channel_id: self.channel_id, signature: our_sig, htlc_signatures: htlc_sigs, - }, remote_commitment_tx)) + }, (remote_commitment_tx.0, remote_commitment_tx.2))) } /// Adds a pending outbound HTLC to this channel, and creates a signed commitment transaction @@ -3689,14 +3692,6 @@ impl ReadableArgs> for Channel { }); } - macro_rules! read_option { () => { - match >::read(reader)? { - 0 => None, - 1 => Some(Readable::read(reader)?), - _ => return Err(DecodeError::InvalidValue), - } - } } - let pending_outbound_htlc_count: u64 = Readable::read(reader)?; let mut pending_outbound_htlcs = Vec::with_capacity(cmp::min(pending_outbound_htlc_count as usize, OUR_MAX_HTLCS as usize)); for _ in 0..pending_outbound_htlc_count { @@ -3706,7 +3701,7 @@ impl ReadableArgs> for Channel { cltv_expiry: Readable::read(reader)?, payment_hash: Readable::read(reader)?, source: Readable::read(reader)?, - fail_reason: read_option!(), + fail_reason: Readable::read(reader)?, state: match >::read(reader)? { 0 => OutboundHTLCState::LocalAnnounced(Box::new(Readable::read(reader)?)), 1 => OutboundHTLCState::Committed, @@ -3764,8 +3759,8 @@ impl ReadableArgs> for Channel { monitor_pending_failures.push((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?)); } - let pending_update_fee = read_option!(); - let holding_cell_update_fee = read_option!(); + let pending_update_fee = Readable::read(reader)?; + let holding_cell_update_fee = Readable::read(reader)?; let next_local_htlc_id = Readable::read(reader)?; let next_remote_htlc_id = Readable::read(reader)?; @@ -3787,8 +3782,8 @@ impl ReadableArgs> for Channel { _ => return Err(DecodeError::InvalidValue), }; - let funding_tx_confirmed_in = read_option!(); - let short_channel_id = read_option!(); + let funding_tx_confirmed_in = Readable::read(reader)?; + let short_channel_id = Readable::read(reader)?; let last_block_connected = Readable::read(reader)?; let funding_tx_confirmations = Readable::read(reader)?; @@ -3803,17 +3798,17 @@ impl ReadableArgs> for Channel { let their_max_accepted_htlcs = Readable::read(reader)?; let minimum_depth = Readable::read(reader)?; - let their_funding_pubkey = read_option!(); - let their_revocation_basepoint = read_option!(); - let their_payment_basepoint = read_option!(); - let their_delayed_payment_basepoint = read_option!(); - let their_htlc_basepoint = read_option!(); - let their_cur_commitment_point = read_option!(); + let their_funding_pubkey = Readable::read(reader)?; + let their_revocation_basepoint = Readable::read(reader)?; + let their_payment_basepoint = Readable::read(reader)?; + let their_delayed_payment_basepoint = Readable::read(reader)?; + let their_htlc_basepoint = Readable::read(reader)?; + let their_cur_commitment_point = Readable::read(reader)?; - let their_prev_commitment_point = read_option!(); + let their_prev_commitment_point = Readable::read(reader)?; let their_node_id = Readable::read(reader)?; - let their_shutdown_scriptpubkey = read_option!(); + let their_shutdown_scriptpubkey = Readable::read(reader)?; let (monitor_last_block, channel_monitor) = ReadableArgs::read(reader, logger.clone())?; // We drop the ChannelMonitor's last block connected hash cause we don't actually bother // doing full block connection operations on the internal CHannelMonitor copies @@ -3946,19 +3941,20 @@ mod tests { fn get_node_secret(&self) -> SecretKey { panic!(); } fn get_destination_script(&self) -> Script { let secp_ctx = Secp256k1::signing_only(); - let channel_monitor_claim_key = SecretKey::from_slice(&secp_ctx, &hex::decode("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap(); + let channel_monitor_claim_key = SecretKey::from_slice(&hex::decode("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap(); let our_channel_monitor_claim_key_hash = Hash160::from_data(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize()); - Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script() + Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script() } fn get_shutdown_pubkey(&self) -> PublicKey { let secp_ctx = Secp256k1::signing_only(); - let channel_close_key = SecretKey::from_slice(&secp_ctx, &hex::decode("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap(); + let channel_close_key = SecretKey::from_slice(&hex::decode("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap(); PublicKey::from_secret_key(&secp_ctx, &channel_close_key) } fn get_channel_keys(&self, _inbound: bool) -> ChannelKeys { self.chan_keys.clone() } fn get_session_key(&self) -> SecretKey { panic!(); } + fn get_channel_id(&self) -> [u8; 32] { [0; 32] } } #[test] @@ -3969,20 +3965,20 @@ mod tests { let secp_ctx = Secp256k1::new(); let chan_keys = ChannelKeys { - funding_key: SecretKey::from_slice(&secp_ctx, &hex::decode("30ff4956bbdd3222d44cc5e8a1261dab1e07957bdac5ae88fe3261ef321f3749").unwrap()[..]).unwrap(), - payment_base_key: SecretKey::from_slice(&secp_ctx, &hex::decode("1111111111111111111111111111111111111111111111111111111111111111").unwrap()[..]).unwrap(), - delayed_payment_base_key: SecretKey::from_slice(&secp_ctx, &hex::decode("3333333333333333333333333333333333333333333333333333333333333333").unwrap()[..]).unwrap(), - htlc_base_key: SecretKey::from_slice(&secp_ctx, &hex::decode("1111111111111111111111111111111111111111111111111111111111111111").unwrap()[..]).unwrap(), + funding_key: SecretKey::from_slice(&hex::decode("30ff4956bbdd3222d44cc5e8a1261dab1e07957bdac5ae88fe3261ef321f3749").unwrap()[..]).unwrap(), + payment_base_key: SecretKey::from_slice(&hex::decode("1111111111111111111111111111111111111111111111111111111111111111").unwrap()[..]).unwrap(), + delayed_payment_base_key: SecretKey::from_slice(&hex::decode("3333333333333333333333333333333333333333333333333333333333333333").unwrap()[..]).unwrap(), + htlc_base_key: SecretKey::from_slice(&hex::decode("1111111111111111111111111111111111111111111111111111111111111111").unwrap()[..]).unwrap(), // These aren't set in the test vectors: - revocation_base_key: SecretKey::from_slice(&secp_ctx, &hex::decode("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap(), + revocation_base_key: SecretKey::from_slice(&hex::decode("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap(), commitment_seed: [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], }; assert_eq!(PublicKey::from_secret_key(&secp_ctx, &chan_keys.funding_key).serialize()[..], hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]); let keys_provider: Arc = Arc::new(Keys { chan_keys }); - let their_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap()); + let their_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()); let mut config = UserConfig::new(); config.channel_options.announced_channel = false; let mut chan = Channel::new_outbound(&feeest, &keys_provider, their_node_id, 10000000, 100000, 42, Arc::clone(&logger), &config).unwrap(); // Nothing uses their network key in this test @@ -3992,25 +3988,25 @@ mod tests { let funding_info = OutPoint::new(Sha256dHash::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(), 0); chan.channel_monitor.set_funding_info((funding_info, Script::new())); - chan.their_payment_basepoint = Some(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("4444444444444444444444444444444444444444444444444444444444444444").unwrap()[..]).unwrap())); + chan.their_payment_basepoint = Some(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("4444444444444444444444444444444444444444444444444444444444444444").unwrap()[..]).unwrap())); assert_eq!(chan.their_payment_basepoint.unwrap().serialize()[..], hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]); - chan.their_funding_pubkey = Some(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("1552dfba4f6cf29a62a0af13c8d6981d36d0ef8d61ba10fb0fe90da7634d7e13").unwrap()[..]).unwrap())); + chan.their_funding_pubkey = Some(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("1552dfba4f6cf29a62a0af13c8d6981d36d0ef8d61ba10fb0fe90da7634d7e13").unwrap()[..]).unwrap())); assert_eq!(chan.their_funding_pubkey.unwrap().serialize()[..], hex::decode("030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c1").unwrap()[..]); - chan.their_htlc_basepoint = Some(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("4444444444444444444444444444444444444444444444444444444444444444").unwrap()[..]).unwrap())); + chan.their_htlc_basepoint = Some(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("4444444444444444444444444444444444444444444444444444444444444444").unwrap()[..]).unwrap())); assert_eq!(chan.their_htlc_basepoint.unwrap().serialize()[..], hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]); - chan.their_revocation_basepoint = Some(PublicKey::from_slice(&secp_ctx, &hex::decode("02466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f27").unwrap()[..]).unwrap()); + chan.their_revocation_basepoint = Some(PublicKey::from_slice(&hex::decode("02466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f27").unwrap()[..]).unwrap()); // We can't just use build_local_transaction_keys here as the per_commitment_secret is not // derived from a commitment_seed, so instead we copy it here and call // build_commitment_transaction. let delayed_payment_base = PublicKey::from_secret_key(&secp_ctx, &chan.local_keys.delayed_payment_base_key); - let per_commitment_secret = SecretKey::from_slice(&secp_ctx, &hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap(); + let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap(); let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret); let htlc_basepoint = PublicKey::from_secret_key(&secp_ctx, &chan.local_keys.htlc_base_key); let keys = TxCreationKeys::new(&secp_ctx, &per_commitment_point, &delayed_payment_base, &htlc_basepoint, &chan.their_revocation_basepoint.unwrap(), &chan.their_payment_basepoint.unwrap(), &chan.their_htlc_basepoint.unwrap()).unwrap(); @@ -4020,10 +4016,13 @@ mod tests { macro_rules! test_commitment { ( $their_sig_hex: expr, $our_sig_hex: expr, $tx_hex: expr) => { unsigned_tx = { - let res = chan.build_commitment_transaction(0xffffffffffff - 42, &keys, true, false, chan.feerate_per_kw); - (res.0, res.1) + let mut res = chan.build_commitment_transaction(0xffffffffffff - 42, &keys, true, false, chan.feerate_per_kw); + let htlcs = res.2.drain(..) + .filter_map(|(htlc, _)| if htlc.transaction_output_index.is_some() { Some(htlc) } else { None }) + .collect(); + (res.0, htlcs) }; - let their_signature = Signature::from_der(&secp_ctx, &hex::decode($their_sig_hex).unwrap()[..]).unwrap(); + let their_signature = Signature::from_der(&hex::decode($their_sig_hex).unwrap()[..]).unwrap(); let sighash = Message::from_slice(&bip143::SighashComponents::new(&unsigned_tx.0).sighash_all(&unsigned_tx.0.input[0], &chan.get_funding_redeemscript(), chan.channel_value_satoshis)[..]).unwrap(); secp_ctx.verify(&sighash, &their_signature, &chan.their_funding_pubkey.unwrap()).unwrap(); @@ -4036,7 +4035,7 @@ mod tests { macro_rules! test_htlc_output { ( $htlc_idx: expr, $their_sig_hex: expr, $our_sig_hex: expr, $tx_hex: expr ) => { - let remote_signature = Signature::from_der(&secp_ctx, &hex::decode($their_sig_hex).unwrap()[..]).unwrap(); + let remote_signature = Signature::from_der(&hex::decode($their_sig_hex).unwrap()[..]).unwrap(); let ref htlc = unsigned_tx.1[$htlc_idx]; let mut htlc_tx = chan.build_htlc_transaction(&unsigned_tx.0.txid(), &htlc, true, &keys, chan.feerate_per_kw); @@ -4479,8 +4478,8 @@ mod tests { // Test vectors from BOLT 3 Appendix E: let secp_ctx = Secp256k1::new(); - let base_secret = SecretKey::from_slice(&secp_ctx, &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap()[..]).unwrap(); - let per_commitment_secret = SecretKey::from_slice(&secp_ctx, &hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap(); + let base_secret = SecretKey::from_slice(&hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap()[..]).unwrap(); + let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap(); let base_point = PublicKey::from_secret_key(&secp_ctx, &base_secret); assert_eq!(base_point.serialize()[..], hex::decode("036d6caac248af96f6afa7f904f550253a0f3ef3f5aa2fe6838a95b216691468e2").unwrap()[..]); @@ -4492,12 +4491,12 @@ mod tests { hex::decode("0235f2dbfaa89b57ec7b055afe29849ef7ddfeb1cefdb9ebdc43f5494984db29e5").unwrap()[..]); assert_eq!(chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &base_secret).unwrap(), - SecretKey::from_slice(&secp_ctx, &hex::decode("cbced912d3b21bf196a766651e436aff192362621ce317704ea2f75d87e7be0f").unwrap()[..]).unwrap()); + SecretKey::from_slice(&hex::decode("cbced912d3b21bf196a766651e436aff192362621ce317704ea2f75d87e7be0f").unwrap()[..]).unwrap()); assert_eq!(chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &base_point).unwrap().serialize()[..], hex::decode("02916e326636d19c33f13e8c0c3a03dd157f332f3e99c317c141dd865eb01f8ff0").unwrap()[..]); assert_eq!(chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_secret, &base_secret).unwrap(), - SecretKey::from_slice(&secp_ctx, &hex::decode("d09ffff62ddb2297ab000cc85bcb4283fdeb6aa052affbc9dddcf33b61078110").unwrap()[..]).unwrap()); + SecretKey::from_slice(&hex::decode("d09ffff62ddb2297ab000cc85bcb4283fdeb6aa052affbc9dddcf33b61078110").unwrap()[..]).unwrap()); } }