Several fuzz-found bugfixes.
/// The output which is referenced by the given outpoint
output: TxOut,
},
- /// Outpoint commits to a P2WSH, should be spend by the following witness :
+ /// Outpoint commits to a P2WSH
+ /// P2WSH should be spend by the following witness :
/// <local_delayedsig> 0 <witnessScript>
/// With input nSequence set to_self_delay.
- /// Outputs from a HTLC-Success/Timeout tx
- DynamicOutput {
+ /// Outputs from a HTLC-Success/Timeout tx/commitment tx
+ DynamicOutputP2WSH {
/// Outpoint spendable by user wallet
outpoint: OutPoint,
- /// local_delayedkey = delayed_payment_basepoint_secret + SHA256(per_commitment_point || delayed_payment_basepoint)
- local_delayedkey: SecretKey,
- /// witness redeemScript encumbering output
+ /// local_delayedkey = delayed_payment_basepoint_secret + SHA256(per_commitment_point || delayed_payment_basepoint) OR
+ key: SecretKey,
+ /// witness redeemScript encumbering output.
witness_script: Script,
/// nSequence input must commit to self_delay to satisfy script's OP_CSV
to_self_delay: u16,
+ /// The output which is referenced by the given outpoint
+ output: TxOut,
+ },
+ /// Outpoint commits to a P2WPKH
+ /// P2WPKH should be spend by the following witness :
+ /// <local_sig> <local_pubkey>
+ /// Outputs to_remote from a commitment tx
+ DynamicOutputP2WPKH {
+ /// Outpoint spendable by user wallet
+ outpoint: OutPoint,
+ /// localkey = payment_basepoint_secret + SHA256(per_commitment_point || payment_basepoint
+ key: SecretKey,
+ /// The output which is reference by the given outpoint
+ output: TxOut,
}
}
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;
-const COMMITMENT_TX_BASE_WEIGHT: u64 = 724;
-const COMMITMENT_TX_WEIGHT_PER_HTLC: u64 = 172;
+/// Exposing these two constants for use in test in ChannelMonitor
+pub const COMMITMENT_TX_BASE_WEIGHT: u64 = 724;
+pub const COMMITMENT_TX_WEIGHT_PER_HTLC: u64 = 172;
const SPENDING_INPUT_FOR_A_OUTPUT_WEIGHT: u64 = 79; // prevout: 36, nSequence: 4, script len: 1, witness lengths: (3+1)/4, sig: 73/4, if-selector: 1, redeemScript: (6 ops + 2*33 pubkeys + 1*2 delay)/4
const B_OUTPUT_PLUS_SPENDING_INPUT_WEIGHT: u64 = 104; // prevout: 40, nSequence: 4, script len: 1, witness lengths: 3/4, sig: 73/4, pubkey: 33/4, output: 31 (TODO: Wrong? Useless?)
/// Maximmum `funding_satoshis` value, according to the BOLT #2 specification
/// Used to return a simple Error back to ChannelManager. Will get converted to a
/// msgs::ErrorAction::SendErrorMessage or msgs::ErrorAction::IgnoreError as appropriate with our
/// channel_id in ChannelManager.
+#[derive(Debug)]
pub(super) enum ChannelError {
Ignore(&'static str),
Close(&'static str),
};
}
-macro_rules! secp_derived_key {
- ( $res: expr, $chan_id: expr ) => {
- secp_call!($res, "Derived invalid key, peer is maliciously selecting parameters", $chan_id)
- }
+macro_rules! secp_check {
+ ($res: expr, $err: expr) => {
+ match $res {
+ Ok(thing) => thing,
+ Err(_) => return Err(ChannelError::Close($err)),
+ }
+ };
}
+
impl Channel {
// Convert constants + channel value to limits:
fn get_our_max_htlc_value_in_flight_msat(channel_value_satoshis: u64) -> u64 {
let secp_ctx = Secp256k1::new();
let channel_monitor = ChannelMonitor::new(&chan_keys.revocation_base_key, &chan_keys.delayed_payment_base_key,
- &chan_keys.htlc_base_key, BREAKDOWN_TIMEOUT,
+ &chan_keys.htlc_base_key, &chan_keys.payment_base_key, &keys_provider.get_shutdown_pubkey(), BREAKDOWN_TIMEOUT,
keys_provider.get_destination_script(), logger.clone());
Ok(Channel {
let secp_ctx = Secp256k1::new();
let mut channel_monitor = ChannelMonitor::new(&chan_keys.revocation_base_key, &chan_keys.delayed_payment_base_key,
- &chan_keys.htlc_base_key, BREAKDOWN_TIMEOUT,
+ &chan_keys.htlc_base_key, &chan_keys.payment_base_key, &keys_provider.get_shutdown_pubkey(), BREAKDOWN_TIMEOUT,
keys_provider.get_destination_script(), logger.clone());
channel_monitor.set_their_base_keys(&msg.htlc_basepoint, &msg.delayed_payment_basepoint);
channel_monitor.set_their_to_self_delay(msg.to_self_delay);
/// our counterparty!)
/// The result is a transaction which we can revoke ownership of (ie a "local" transaction)
/// TODO Some magic rust shit to compile-time check this?
- fn build_local_transaction_keys(&self, commitment_number: u64) -> Result<TxCreationKeys, HandleError> {
+ fn build_local_transaction_keys(&self, commitment_number: u64) -> Result<TxCreationKeys, ChannelError> {
let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &self.build_local_commitment_secret(commitment_number));
let delayed_payment_base = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.delayed_payment_base_key);
let htlc_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key);
- Ok(secp_derived_key!(TxCreationKeys::new(&self.secp_ctx, &per_commitment_point, &delayed_payment_base, &htlc_basepoint, &self.their_revocation_basepoint.unwrap(), &self.their_payment_basepoint.unwrap(), &self.their_htlc_basepoint.unwrap()), self.channel_id()))
+ Ok(secp_check!(TxCreationKeys::new(&self.secp_ctx, &per_commitment_point, &delayed_payment_base, &htlc_basepoint, &self.their_revocation_basepoint.unwrap(), &self.their_payment_basepoint.unwrap(), &self.their_htlc_basepoint.unwrap()), "Local tx keys generation got bogus keys"))
}
#[inline]
/// Creates a set of keys for build_commitment_transaction to generate a transaction which we
/// will sign and send to our counterparty.
- fn build_remote_transaction_keys(&self) -> Result<TxCreationKeys, HandleError> {
+ fn build_remote_transaction_keys(&self) -> Result<TxCreationKeys, ChannelError> {
//TODO: Ensure that the payment_key derived here ends up in the library users' wallet as we
//may see payments to it!
let payment_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.payment_base_key);
let revocation_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.revocation_base_key);
let htlc_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.htlc_base_key);
- Ok(secp_derived_key!(TxCreationKeys::new(&self.secp_ctx, &self.their_cur_commitment_point.unwrap(), &self.their_delayed_payment_basepoint.unwrap(), &self.their_htlc_basepoint.unwrap(), &revocation_basepoint, &payment_basepoint, &htlc_basepoint), self.channel_id()))
+ Ok(secp_check!(TxCreationKeys::new(&self.secp_ctx, &self.their_cur_commitment_point.unwrap(), &self.their_delayed_payment_basepoint.unwrap(), &self.their_htlc_basepoint.unwrap(), &revocation_basepoint, &payment_basepoint, &htlc_basepoint), "Remote tx keys generation got bogus keys"))
}
/// Gets the redeemscript for the funding transaction output (ie the funding transaction output
chan_utils::build_htlc_transaction(prev_hash, feerate_per_kw, if local { self.their_to_self_delay } else { BREAKDOWN_TIMEOUT }, htlc, &keys.a_delayed_payment_key, &keys.revocation_key)
}
- fn create_htlc_tx_signature(&self, tx: &Transaction, htlc: &HTLCOutputInCommitment, keys: &TxCreationKeys) -> Result<(Script, Signature, bool), HandleError> {
+ fn create_htlc_tx_signature(&self, tx: &Transaction, htlc: &HTLCOutputInCommitment, keys: &TxCreationKeys) -> Result<(Script, Signature, bool), ChannelError> {
if tx.input.len() != 1 {
panic!("Tried to sign HTLC transaction that had input count != 1!");
}
let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, &keys);
- let our_htlc_key = secp_derived_key!(chan_utils::derive_private_key(&self.secp_ctx, &keys.per_commitment_point, &self.local_keys.htlc_base_key), self.channel_id());
+ 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 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))
/// Signs a transaction created by build_htlc_transaction. If the transaction is an
/// HTLC-Success transaction (ie htlc.offered is false), preimate must be set!
- fn sign_htlc_transaction(&self, tx: &mut Transaction, their_sig: &Signature, preimage: &Option<[u8; 32]>, htlc: &HTLCOutputInCommitment, keys: &TxCreationKeys) -> Result<Signature, HandleError> {
+ fn sign_htlc_transaction(&self, tx: &mut Transaction, their_sig: &Signature, preimage: &Option<[u8; 32]>, htlc: &HTLCOutputInCommitment, keys: &TxCreationKeys) -> Result<Signature, ChannelError> {
if tx.input.len() != 1 {
panic!("Tried to sign HTLC transaction that had input count != 1!");
}
/// Per HTLC, only one get_update_fail_htlc or get_update_fulfill_htlc call may be made.
/// In such cases we debug_assert!(false) and return an IgnoreError. Thus, will always return
/// Ok(_) if debug assertions are turned on and preconditions are met.
- fn get_update_fulfill_htlc(&mut self, htlc_id_arg: u64, payment_preimage_arg: [u8; 32]) -> Result<(Option<msgs::UpdateFulfillHTLC>, Option<ChannelMonitor>), HandleError> {
+ fn get_update_fulfill_htlc(&mut self, htlc_id_arg: u64, payment_preimage_arg: [u8; 32]) -> Result<(Option<msgs::UpdateFulfillHTLC>, Option<ChannelMonitor>), ChannelError> {
// Either ChannelFunded got set (which means it wont bet unset) or there is no way any
// caller thought we could have something claimed (cause we wouldn't have accepted in an
// incoming HTLC anyway). If we got to ShutdownComplete, callers aren't allowed to call us,
}
if pending_idx == std::usize::MAX {
debug_assert!(false, "Unable to find a pending HTLC which matched the given HTLC ID");
- return Err(HandleError{err: "Unable to find a pending HTLC which matched the given HTLC ID", action: Some(msgs::ErrorAction::IgnoreError)});
+ return Err(ChannelError::Ignore("Unable to find a pending HTLC which matched the given HTLC ID"));
}
// Now update local state:
}), Some(self.channel_monitor.clone())))
}
- pub fn get_update_fulfill_htlc_and_commit(&mut self, htlc_id: u64, payment_preimage: [u8; 32]) -> Result<(Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)>, Option<ChannelMonitor>), HandleError> {
+ pub fn get_update_fulfill_htlc_and_commit(&mut self, htlc_id: u64, payment_preimage: [u8; 32]) -> Result<(Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)>, Option<ChannelMonitor>), ChannelError> {
match self.get_update_fulfill_htlc(htlc_id, payment_preimage)? {
(Some(update_fulfill_htlc), _) => {
let (commitment, monitor_update) = self.send_commitment_no_status_check()?;
/// Per HTLC, only one get_update_fail_htlc or get_update_fulfill_htlc call may be made.
/// In such cases we debug_assert!(false) and return an IgnoreError. Thus, will always return
/// Ok(_) if debug assertions are turned on and preconditions are met.
- pub fn get_update_fail_htlc(&mut self, htlc_id_arg: u64, err_packet: msgs::OnionErrorPacket) -> Result<Option<msgs::UpdateFailHTLC>, HandleError> {
+ pub fn get_update_fail_htlc(&mut self, htlc_id_arg: u64, err_packet: msgs::OnionErrorPacket) -> Result<Option<msgs::UpdateFailHTLC>, ChannelError> {
if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) {
panic!("Was asked to fail an HTLC when channel was not in an operational state");
}
if let InboundHTLCState::Committed = htlc.state {
} else {
debug_assert!(false, "Have an inbound HTLC we tried to fail before it was fully committed to");
- return Err(HandleError{err: "Unable to find a pending HTLC which matched the given HTLC ID", action: Some(msgs::ErrorAction::IgnoreError)});
+ return Err(ChannelError::Ignore("Unable to find a pending HTLC which matched the given HTLC ID"));
}
pending_idx = idx;
}
}
if pending_idx == std::usize::MAX {
debug_assert!(false, "Unable to find a pending HTLC which matched the given HTLC ID");
- return Err(HandleError{err: "Unable to find a pending HTLC which matched the given HTLC ID", action: Some(msgs::ErrorAction::IgnoreError)});
+ return Err(ChannelError::Ignore("Unable to find a pending HTLC which matched the given HTLC ID"));
}
// Now update local state:
&HTLCUpdateAwaitingACK::ClaimHTLC { htlc_id, .. } => {
if htlc_id_arg == htlc_id {
debug_assert!(false, "Unable to find a pending HTLC which matched the given HTLC ID");
- return Err(HandleError{err: "Unable to find a pending HTLC which matched the given HTLC ID", action: Some(msgs::ErrorAction::IgnoreError)});
+ return Err(ChannelError::Ignore("Unable to find a pending HTLC which matched the given HTLC ID"));
}
},
&HTLCUpdateAwaitingACK::FailHTLC { htlc_id, .. } => {
}))
}
- pub fn get_update_fail_htlc_and_commit(&mut self, htlc_id: u64, err_packet: msgs::OnionErrorPacket) -> Result<Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned, ChannelMonitor)>, HandleError> {
+ pub fn get_update_fail_htlc_and_commit(&mut self, htlc_id: u64, err_packet: msgs::OnionErrorPacket) -> Result<Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned, ChannelMonitor)>, ChannelError> {
match self.get_update_fail_htlc(htlc_id, err_packet)? {
Some(update_fail_htlc) => {
let (commitment, monitor_update) = self.send_commitment_no_status_check()?;
Ok(())
}
- fn funding_created_signature(&mut self, sig: &Signature) -> Result<(Transaction, Signature), HandleError> {
+ fn funding_created_signature(&mut self, sig: &Signature) -> Result<(Transaction, Transaction, Signature, TxCreationKeys), ChannelError> {
let funding_script = self.get_funding_redeemscript();
let local_keys = self.build_local_transaction_keys(self.cur_local_commitment_transaction_number)?;
- let local_initial_commitment_tx = self.build_commitment_transaction(self.cur_local_commitment_transaction_number, &local_keys, true, false, self.feerate_per_kw).0;
+ 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();
- // They sign the "local" commitment transaction, allowing us to broadcast the tx if we wish.
- secp_call!(self.secp_ctx.verify(&local_sighash, &sig, &self.their_funding_pubkey.unwrap()), "Invalid funding_created signature from peer", self.channel_id());
+ // 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");
+
+ // ...and we sign it, allowing us to broadcast the tx if we wish
+ self.sign_commitment_transaction(&mut local_initial_commitment_tx, sig);
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();
// We sign the "remote" commitment transaction, allowing them to broadcast the tx if they wish.
- Ok((remote_initial_commitment_tx, self.secp_ctx.sign(&remote_sighash, &self.local_keys.funding_key)))
+ Ok((remote_initial_commitment_tx, local_initial_commitment_tx, self.secp_ctx.sign(&remote_sighash, &self.local_keys.funding_key), local_keys))
}
- pub fn funding_created(&mut self, msg: &msgs::FundingCreated) -> Result<(msgs::FundingSigned, ChannelMonitor), HandleError> {
+ pub fn funding_created(&mut self, msg: &msgs::FundingCreated) -> Result<(msgs::FundingSigned, ChannelMonitor), ChannelError> {
if self.channel_outbound {
- return Err(HandleError{err: "Received funding_created for an outbound channel?", action: Some(msgs::ErrorAction::SendErrorMessage {msg: msgs::ErrorMessage {channel_id: self.channel_id, data: "Received funding_created for an outbound channel?".to_string()}})});
+ return Err(ChannelError::Close("Received funding_created for an outbound channel?"));
}
if self.channel_state != (ChannelState::OurInitSent as u32 | ChannelState::TheirInitSent as u32) {
// BOLT 2 says that if we disconnect before we send funding_signed we SHOULD NOT
// remember the channel, so its safe to just send an error_message here and drop the
// channel.
- return Err(HandleError{err: "Received funding_created after we got the channel!", action: Some(msgs::ErrorAction::SendErrorMessage {msg: msgs::ErrorMessage {channel_id: self.channel_id, data: "Received funding_created after we got the channel!".to_string()}})});
+ return Err(ChannelError::Close("Received funding_created after we got the channel!"));
}
if self.channel_monitor.get_min_seen_secret() != (1 << 48) ||
self.cur_remote_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER ||
let funding_txo_script = self.get_funding_redeemscript().to_v0_p2wsh();
self.channel_monitor.set_funding_info((funding_txo, funding_txo_script));
- let (remote_initial_commitment_tx, our_signature) = match self.funding_created_signature(&msg.signature) {
+ let (remote_initial_commitment_tx, local_initial_commitment_tx, our_signature, local_keys) = match self.funding_created_signature(&msg.signature) {
Ok(res) => res,
Err(e) => {
self.channel_monitor.unset_funding_info();
// 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(), self.cur_remote_commitment_transaction_number);
+ 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());
self.channel_state = ChannelState::FundingSent as u32;
self.channel_id = funding_txo.to_channel_id();
self.cur_remote_commitment_transaction_number -= 1;
/// Handles a funding_signed message from the remote end.
/// If this call is successful, broadcast the funding transaction (and not before!)
- pub fn funding_signed(&mut self, msg: &msgs::FundingSigned) -> Result<ChannelMonitor, HandleError> {
+ pub fn funding_signed(&mut self, msg: &msgs::FundingSigned) -> Result<ChannelMonitor, ChannelError> {
if !self.channel_outbound {
- return Err(HandleError{err: "Received funding_signed for an inbound channel?", action: None});
+ return Err(ChannelError::Close("Received funding_signed for an inbound channel?"));
}
if self.channel_state != ChannelState::FundingCreated as u32 {
- return Err(HandleError{err: "Received funding_signed in strange state!", action: None});
+ return Err(ChannelError::Close("Received funding_signed in strange state!"));
}
if self.channel_monitor.get_min_seen_secret() != (1 << 48) ||
self.cur_remote_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER - 1 ||
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();
// They sign the "local" commitment transaction, allowing us to broadcast the tx if we wish.
- secp_call!(self.secp_ctx.verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid funding_signed signature from peer", self.channel_id());
+ 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());
self.mark_outbound_htlc_removed(msg.htlc_id, None, Some(fail_reason))
}
- pub fn commitment_signed(&mut self, msg: &msgs::CommitmentSigned, fee_estimator: &FeeEstimator) -> Result<(msgs::RevokeAndACK, Option<msgs::CommitmentSigned>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
+ pub fn commitment_signed(&mut self, msg: &msgs::CommitmentSigned, fee_estimator: &FeeEstimator) -> Result<(msgs::RevokeAndACK, Option<msgs::CommitmentSigned>, Option<msgs::ClosingSigned>, ChannelMonitor), ChannelError> {
if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) {
- return Err(HandleError{err: "Got commitment signed message when channel was not in an operational state", action: None});
+ return Err(ChannelError::Close("Got commitment signed message when channel was not in an operational state"));
}
if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 {
- return Err(HandleError{err: "Peer sent commitment_signed when we needed a channel_reestablish", action: Some(msgs::ErrorAction::SendErrorMessage{msg: msgs::ErrorMessage{data: "Peer sent commitment_signed when we needed a channel_reestablish".to_string(), channel_id: msg.channel_id}})});
+ return Err(ChannelError::Close("Peer sent commitment_signed when we needed a channel_reestablish"));
}
if self.channel_state & BOTH_SIDES_SHUTDOWN_MASK == BOTH_SIDES_SHUTDOWN_MASK && self.last_sent_closing_fee.is_some() {
- return Err(HandleError{err: "Peer sent commitment_signed after we'd started exchanging closing_signeds", action: Some(msgs::ErrorAction::SendErrorMessage{msg: msgs::ErrorMessage{data: "Peer sent commitment_signed after we'd started exchanging closing_signeds".to_string(), channel_id: msg.channel_id}})});
+ return Err(ChannelError::Close("Peer sent commitment_signed after we'd started exchanging closing_signeds"));
}
let funding_script = self.get_funding_redeemscript();
let local_keys = self.build_local_transaction_keys(self.cur_local_commitment_transaction_number)?;
+ let mut update_fee = false;
let feerate_per_kw = if !self.channel_outbound && self.pending_update_fee.is_some() {
+ update_fee = true;
self.pending_update_fee.unwrap()
} else {
self.feerate_per_kw
let mut local_commitment_tx = self.build_commitment_transaction(self.cur_local_commitment_transaction_number, &local_keys, true, false, feerate_per_kw);
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();
- secp_call!(self.secp_ctx.verify(&local_sighash, &msg.signature, &self.their_funding_pubkey.unwrap()), "Invalid commitment tx signature from peer", self.channel_id());
+ 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 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 {
+ return Err(ChannelError::Close("Funding remote cannot afford proposed new fee"));
+ }
+ }
if msg.htlc_signatures.len() != local_commitment_tx.1.len() {
- return Err(HandleError{err: "Got wrong number of HTLC signatures from remote", action: None});
+ 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 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_call!(self.secp_ctx.verify(&htlc_sighash, &msg.htlc_signatures[idx], &local_keys.b_htlc_key), "Invalid HTLC tx siganture from peer", self.channel_id());
+ 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);
}
}
}
+
if self.channel_state & (ChannelState::MonitorUpdateFailed as u32) == 0 {
// This is a response to our post-monitor-failed unfreeze messages, so we can clear the
// monitor_pending_order requirement as we won't re-send the monitor_pending messages.
if (self.channel_state & ChannelState::MonitorUpdateFailed as u32) != 0 {
self.monitor_pending_revoke_and_ack = true;
self.monitor_pending_commitment_signed |= need_our_commitment;
- return Err(HandleError{err: "Previous monitor update failure prevented generation of RAA", action: Some(ErrorAction::IgnoreError)});
+ return Err(ChannelError::Ignore("Previous monitor update failure prevented generation of RAA"));
}
let (our_commitment_signed, monitor_update, closing_signed) = if need_our_commitment && (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) == 0 {
/// Used to fulfill holding_cell_htlcs when we get a remote ack (or implicitly get it by them
/// fulfilling or failing the last pending HTLC)
- fn free_holding_cell_htlcs(&mut self) -> Result<Option<(msgs::CommitmentUpdate, ChannelMonitor)>, HandleError> {
+ fn free_holding_cell_htlcs(&mut self) -> Result<Option<(msgs::CommitmentUpdate, ChannelMonitor)>, ChannelError> {
assert_eq!(self.channel_state & ChannelState::MonitorUpdateFailed as u32, 0);
if self.holding_cell_htlc_updates.len() != 0 || self.holding_cell_update_fee.is_some() {
let mut htlc_updates = Vec::new();
match self.get_update_fulfill_htlc(htlc_id, payment_preimage) {
Ok(update_fulfill_msg_option) => update_fulfill_htlcs.push(update_fulfill_msg_option.0.unwrap()),
Err(e) => {
- if let Some(msgs::ErrorAction::IgnoreError) = e.action {}
+ if let ChannelError::Ignore(_) = e {}
else {
panic!("Got a non-IgnoreError action trying to fulfill holding cell HTLC");
}
match self.get_update_fail_htlc(htlc_id, err_packet.clone()) {
Ok(update_fail_msg_option) => update_fail_htlcs.push(update_fail_msg_option.unwrap()),
Err(e) => {
- if let Some(msgs::ErrorAction::IgnoreError) = e.action {}
+ if let ChannelError::Ignore(_) = e {}
else {
panic!("Got a non-IgnoreError action trying to fail holding cell HTLC");
}
/// waiting on this revoke_and_ack. The generation of this new commitment_signed may also fail,
/// generating an appropriate error *after* the channel state has been updated based on the
/// revoke_and_ack message.
- pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), HandleError> {
+ pub fn revoke_and_ack(&mut self, msg: &msgs::RevokeAndACK, fee_estimator: &FeeEstimator) -> Result<(Option<msgs::CommitmentUpdate>, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>, Option<msgs::ClosingSigned>, ChannelMonitor), ChannelError> {
if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) {
- return Err(HandleError{err: "Got revoke/ACK message when channel was not in an operational state", action: None});
+ return Err(ChannelError::Close("Got revoke/ACK message when channel was not in an operational state"));
}
if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 {
- return Err(HandleError{err: "Peer sent revoke_and_ack when we needed a channel_reestablish", action: Some(msgs::ErrorAction::SendErrorMessage{msg: msgs::ErrorMessage{data: "Peer sent revoke_and_ack when we needed a channel_reestablish".to_string(), channel_id: msg.channel_id}})});
+ return Err(ChannelError::Close("Peer sent revoke_and_ack when we needed a channel_reestablish"));
}
if self.channel_state & BOTH_SIDES_SHUTDOWN_MASK == BOTH_SIDES_SHUTDOWN_MASK && self.last_sent_closing_fee.is_some() {
- return Err(HandleError{err: "Peer sent revoke_and_ack after we'd started exchanging closing_signeds", action: Some(msgs::ErrorAction::SendErrorMessage{msg: msgs::ErrorMessage{data: "Peer sent revoke_and_ack after we'd started exchanging closing_signeds".to_string(), channel_id: msg.channel_id}})});
+ return Err(ChannelError::Close("Peer sent revoke_and_ack after we'd started exchanging closing_signeds"));
}
if let Some(their_prev_commitment_point) = self.their_prev_commitment_point {
- if PublicKey::from_secret_key(&self.secp_ctx, &secp_call!(SecretKey::from_slice(&self.secp_ctx, &msg.per_commitment_secret), "Peer provided an invalid per_commitment_secret", self.channel_id())) != their_prev_commitment_point {
- return Err(HandleError{err: "Got a revoke commitment secret which didn't correspond to their current pubkey", action: None});
+ 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 {
+ return Err(ChannelError::Close("Got a revoke commitment secret which didn't correspond to their current pubkey"));
}
}
- self.channel_monitor.provide_secret(self.cur_remote_commitment_transaction_number + 1, msg.per_commitment_secret, Some((self.cur_remote_commitment_transaction_number - 1, msg.next_per_commitment_point)))?;
+ self.channel_monitor.provide_secret(self.cur_remote_commitment_transaction_number + 1, msg.per_commitment_secret)
+ .map_err(|e| ChannelError::Close(e.0))?;
// Update state now that we've passed all the can-fail calls...
// (note that we may still fail to generate the new commitment_signed message, but that's
})
}
- pub fn send_update_fee_and_commit(&mut self, feerate_per_kw: u64) -> Result<Option<(msgs::UpdateFee, msgs::CommitmentSigned, ChannelMonitor)>, HandleError> {
+ pub fn send_update_fee_and_commit(&mut self, feerate_per_kw: u64) -> Result<Option<(msgs::UpdateFee, msgs::CommitmentSigned, ChannelMonitor)>, ChannelError> {
match self.send_update_fee(feerate_per_kw) {
Some(update_fee) => {
let (commitment_signed, monitor_update) = self.send_commitment_no_status_check()?;
return Err(ChannelError::Close("Peer sent update_fee when we needed a channel_reestablish"));
}
Channel::check_remote_fee(fee_estimator, msg.feerate_per_kw)?;
-
self.pending_update_fee = Some(msg.feerate_per_kw as u64);
self.channel_update_count += 1;
Ok(())
// have received some updates while we were disconnected. Free the holding cell
// now!
match self.free_holding_cell_htlcs() {
- Err(e) => {
- if let &Some(msgs::ErrorAction::DisconnectPeer{msg: Some(_)}) = &e.action {
- return Err(ChannelError::Close(e.err));
- } else if let &Some(msgs::ErrorAction::SendErrorMessage{msg: _}) = &e.action {
- return Err(ChannelError::Close(e.err));
- } else {
- panic!("Got non-channel-failing result from free_holding_cell_htlcs");
- }
- },
+ Err(ChannelError::Close(msg)) => return Err(ChannelError::Close(msg)),
+ Err(ChannelError::Ignore(_)) => panic!("Got non-channel-failing result from free_holding_cell_htlcs"),
Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor), order, shutdown_msg)),
Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None, order, shutdown_msg)),
}
}
}
- fn get_outbound_funding_created_signature(&mut self) -> Result<(Signature, Transaction), HandleError> {
+ fn get_outbound_funding_created_signature(&mut self) -> Result<(Signature, Transaction), ChannelError> {
let funding_script = self.get_funding_redeemscript();
let remote_keys = self.build_remote_transaction_keys()?;
/// or if called on an inbound channel.
/// Note that channel_id changes during this call!
/// Do NOT broadcast the funding transaction until after a successful funding_signed call!
- pub fn get_outbound_funding_created(&mut self, funding_txo: OutPoint) -> Result<(msgs::FundingCreated, ChannelMonitor), HandleError> {
+ pub fn get_outbound_funding_created(&mut self, funding_txo: OutPoint) -> Result<(msgs::FundingCreated, ChannelMonitor), ChannelError> {
if !self.channel_outbound {
panic!("Tried to create outbound funding_created message on an inbound channel!");
}
let (our_signature, commitment_tx) = match self.get_outbound_funding_created_signature() {
Ok(res) => res,
Err(e) => {
- log_error!(self, "Got bad signatures: {}!", e.err);
+ log_error!(self, "Got bad signatures: {:?}!", e);
self.channel_monitor.unset_funding_info();
return Err(e);
}
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(), self.cur_remote_commitment_transaction_number);
+ 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;
/// waiting on the remote peer to send us a revoke_and_ack during which time we cannot add new
/// HTLCs on the wire or we wouldn't be able to determine what they actually ACK'ed.
/// You MUST call send_commitment prior to any other calls on this Channel
- pub fn send_htlc(&mut self, amount_msat: u64, payment_hash: [u8; 32], cltv_expiry: u32, source: HTLCSource, onion_routing_packet: msgs::OnionPacket) -> Result<Option<msgs::UpdateAddHTLC>, HandleError> {
+ pub fn send_htlc(&mut self, amount_msat: u64, payment_hash: [u8; 32], cltv_expiry: u32, source: HTLCSource, onion_routing_packet: msgs::OnionPacket) -> Result<Option<msgs::UpdateAddHTLC>, ChannelError> {
if (self.channel_state & (ChannelState::ChannelFunded as u32 | BOTH_SIDES_SHUTDOWN_MASK)) != (ChannelState::ChannelFunded as u32) {
- return Err(HandleError{err: "Cannot send HTLC until channel is fully established and we haven't started shutting down", action: None});
+ return Err(ChannelError::Ignore("Cannot send HTLC until channel is fully established and we haven't started shutting down"));
}
if amount_msat > self.channel_value_satoshis * 1000 {
- return Err(HandleError{err: "Cannot send more than the total value of the channel", action: None});
+ return Err(ChannelError::Ignore("Cannot send more than the total value of the channel"));
}
if amount_msat < self.their_htlc_minimum_msat {
- return Err(HandleError{err: "Cannot send less than their minimum HTLC value", action: None});
+ return Err(ChannelError::Ignore("Cannot send less than their minimum HTLC value"));
}
if (self.channel_state & (ChannelState::PeerDisconnected as u32 | ChannelState::MonitorUpdateFailed as u32)) != 0 {
// disconnected during the time the previous hop was doing the commitment dance we may
// end up getting here after the forwarding delay. In any case, returning an
// IgnoreError will get ChannelManager to do the right thing and fail backwards now.
- return Err(HandleError{err: "Cannot send an HTLC while disconnected/frozen for channel monitor update", action: Some(ErrorAction::IgnoreError)});
+ return Err(ChannelError::Ignore("Cannot send an HTLC while disconnected/frozen for channel monitor update"));
}
let (outbound_htlc_count, htlc_outbound_value_msat) = self.get_outbound_pending_htlc_stats();
if outbound_htlc_count + 1 > self.their_max_accepted_htlcs as u32 {
- return Err(HandleError{err: "Cannot push more than their max accepted HTLCs", action: None});
+ return Err(ChannelError::Ignore("Cannot push more than their max accepted HTLCs"));
}
//TODO: Spec is unclear if this is per-direction or in total (I assume per direction):
// Check their_max_htlc_value_in_flight_msat
if htlc_outbound_value_msat + amount_msat > self.their_max_htlc_value_in_flight_msat {
- return Err(HandleError{err: "Cannot send value that would put us over our max HTLC value in flight", action: None});
+ return Err(ChannelError::Ignore("Cannot send value that would put us over our max HTLC value in flight"));
}
let mut holding_cell_outbound_amount_msat = 0;
// Check self.their_channel_reserve_satoshis (the amount we must keep as
// reserve for them to have something to claim if we misbehave)
if self.value_to_self_msat < self.their_channel_reserve_satoshis * 1000 + amount_msat + holding_cell_outbound_amount_msat + htlc_outbound_value_msat {
- return Err(HandleError{err: "Cannot send value that would put us over our reserve value", action: None});
+ return Err(ChannelError::Ignore("Cannot send value that would put us over our reserve value"));
}
//TODO: Check cltv_expiry? Do this in channel manager?
/// Always returns a Channel-failing HandleError::action if an immediately-preceding (read: the
/// last call to this Channel) send_htlc returned Ok(Some(_)) and there is an Err.
/// May panic if called except immediately after a successful, Ok(Some(_))-returning send_htlc.
- pub fn send_commitment(&mut self) -> Result<(msgs::CommitmentSigned, ChannelMonitor), HandleError> {
+ pub fn send_commitment(&mut self) -> Result<(msgs::CommitmentSigned, ChannelMonitor), ChannelError> {
if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) {
panic!("Cannot create commitment tx until channel is fully established");
}
self.send_commitment_no_status_check()
}
/// Only fails in case of bad keys
- fn send_commitment_no_status_check(&mut self) -> Result<(msgs::CommitmentSigned, ChannelMonitor), HandleError> {
+ fn send_commitment_no_status_check(&mut self) -> Result<(msgs::CommitmentSigned, ChannelMonitor), ChannelError> {
// We can upgrade the status of some HTLCs that are waiting on a commitment, even if we
// fail to generate this, we still are at least at a position where upgrading their status
// is acceptable.
match self.send_commitment_no_state_update() {
Ok((res, remote_commitment_tx)) => {
// Update state now that we've passed all the can-fail calls...
- self.channel_monitor.provide_latest_remote_commitment_tx_info(&remote_commitment_tx.0, remote_commitment_tx.1, self.cur_remote_commitment_transaction_number);
+ self.channel_monitor.provide_latest_remote_commitment_tx_info(&remote_commitment_tx.0, remote_commitment_tx.1, 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<HTLCOutputInCommitment>)), HandleError> {
+ fn send_commitment_no_state_update(&self) -> Result<(msgs::CommitmentSigned, (Transaction, Vec<HTLCOutputInCommitment>)), ChannelError> {
let funding_script = self.get_funding_redeemscript();
let mut feerate_per_kw = self.feerate_per_kw;
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_derived_key!(chan_utils::derive_private_key(&self.secp_ctx, &remote_keys.per_commitment_point, &self.local_keys.htlc_base_key), self.channel_id());
+ 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));
}
/// to send to the remote peer in one go.
/// Shorthand for calling send_htlc() followed by send_commitment(), see docs on those for
/// more info.
- pub fn send_htlc_and_commit(&mut self, amount_msat: u64, payment_hash: [u8; 32], cltv_expiry: u32, source: HTLCSource, onion_routing_packet: msgs::OnionPacket) -> Result<Option<(msgs::UpdateAddHTLC, msgs::CommitmentSigned, ChannelMonitor)>, HandleError> {
+ pub fn send_htlc_and_commit(&mut self, amount_msat: u64, payment_hash: [u8; 32], cltv_expiry: u32, source: HTLCSource, onion_routing_packet: msgs::OnionPacket) -> Result<Option<(msgs::UpdateAddHTLC, msgs::CommitmentSigned, ChannelMonitor)>, ChannelError> {
match self.send_htlc(amount_msat, payment_hash, cltv_expiry, source, onion_routing_packet)? {
Some(update_add_htlc) => {
let (commitment_signed, monitor_update) = self.send_commitment_no_status_check()?;
pub user_id: u64,
}
+macro_rules! handle_error {
+ ($self: ident, $internal: expr, $their_node_id: expr) => {
+ match $internal {
+ Ok(msg) => Ok(msg),
+ Err(MsgHandleErrInternal { err, needs_channel_force_close }) => {
+ if needs_channel_force_close {
+ match &err.action {
+ &Some(msgs::ErrorAction::DisconnectPeer { msg: Some(ref msg) }) => {
+ if msg.channel_id == [0; 32] {
+ $self.peer_disconnected(&$their_node_id, true);
+ } else {
+ $self.force_close_channel(&msg.channel_id);
+ }
+ },
+ &Some(msgs::ErrorAction::DisconnectPeer { msg: None }) => {},
+ &Some(msgs::ErrorAction::IgnoreError) => {},
+ &Some(msgs::ErrorAction::SendErrorMessage { ref msg }) => {
+ if msg.channel_id == [0; 32] {
+ $self.peer_disconnected(&$their_node_id, true);
+ } else {
+ $self.force_close_channel(&msg.channel_id);
+ }
+ },
+ &None => {},
+ }
+ }
+ Err(err)
+ },
+ }
+ }
+}
+
impl ChannelManager {
/// Constructs a new ChannelManager to hold several channels and route between them.
///
route: route.clone(),
session_priv: session_priv.clone(),
first_hop_htlc_msat: htlc_msat,
- }, onion_packet).map_err(|he| APIError::ChannelUnavailable{err: he.err})?
+ }, onion_packet).map_err(|he|
+ match he {
+ ChannelError::Close(err) => {
+ // TODO: We need to close the channel here, but for that to be safe we have
+ // to do all channel closure inside the channel_state lock which is a
+ // somewhat-larger refactor, so we leave that for later.
+ APIError::ChannelUnavailable { err }
+ },
+ ChannelError::Ignore(err) => APIError::ChannelUnavailable { err },
+ }
+ )?
};
match res {
Some((update_add, commitment_signed, chan_monitor)) => {
let _ = self.total_consistency_lock.read().unwrap();
let (chan, msg, chan_monitor) = {
- let mut channel_state = self.channel_state.lock().unwrap();
- match channel_state.by_id.remove(temporary_channel_id) {
- Some(mut chan) => {
- match chan.get_outbound_funding_created(funding_txo) {
- Ok(funding_msg) => {
- (chan, funding_msg.0, funding_msg.1)
- },
- Err(e) => {
- log_error!(self, "Got bad signatures: {}!", e.err);
- channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
- node_id: chan.get_their_node_id(),
- action: e.action,
- });
- return;
- },
- }
+ let (res, chan) = {
+ let mut channel_state = self.channel_state.lock().unwrap();
+ match channel_state.by_id.remove(temporary_channel_id) {
+ Some(mut chan) => {
+ (chan.get_outbound_funding_created(funding_txo)
+ .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, chan.channel_id()))
+ , chan)
+ },
+ None => return
+ }
+ };
+ match handle_error!(self, res, chan.get_their_node_id()) {
+ Ok(funding_msg) => {
+ (chan, funding_msg.0, funding_msg.1)
+ },
+ Err(e) => {
+ log_error!(self, "Got bad signatures: {}!", e.err);
+ let mut channel_state = self.channel_state.lock().unwrap();
+ channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
+ node_id: chan.get_their_node_id(),
+ action: e.action,
+ });
+ return;
},
- None => return
}
};
// Because we have exclusive ownership of the channel here we can release the channel_state
let (commitment_msg, monitor) = match forward_chan.send_commitment() {
Ok(res) => res,
Err(e) => {
- if let &Some(msgs::ErrorAction::DisconnectPeer{msg: Some(ref _err_msg)}) = &e.action {
- } else if let &Some(msgs::ErrorAction::SendErrorMessage{msg: ref _err_msg}) = &e.action {
- } else {
+ if let ChannelError::Ignore(_) = e {
panic!("Stated return value requirements in send_commitment() were not met");
}
//TODO: Handle...this is bad!
(chan.remove(), funding_msg, monitor_update)
},
Err(e) => {
- return Err(e).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
+ return Err(e).map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.temporary_channel_id))
}
}
},
//TODO: here and below MsgHandleErrInternal, #153 case
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
}
- let chan_monitor = chan.funding_signed(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
+ let chan_monitor = chan.funding_signed(&msg).map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
unimplemented!();
}
//TODO: here and below MsgHandleErrInternal, #153 case
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
}
- let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) = chan.commitment_signed(&msg, &*self.fee_estimator).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
+ let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) = chan.commitment_signed(&msg, &*self.fee_estimator)
+ .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
unimplemented!();
}
//TODO: here and below MsgHandleErrInternal, #153 case
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
}
- let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) = chan.revoke_and_ack(&msg, &*self.fee_estimator).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
+ let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) = chan.revoke_and_ack(&msg, &*self.fee_estimator)
+ .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
unimplemented!();
}
if !chan.is_live() {
return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
}
- if let Some((update_fee, commitment_signed, chan_monitor)) = chan.send_update_fee_and_commit(feerate_per_kw).map_err(|e| APIError::APIMisuseError{err: e.err})? {
+ if let Some((update_fee, commitment_signed, chan_monitor)) = chan.send_update_fee_and_commit(feerate_per_kw)
+ .map_err(|e| match e {
+ ChannelError::Ignore(err) => APIError::APIMisuseError{err},
+ ChannelError::Close(err) => {
+ // TODO: We need to close the channel here, but for that to be safe we have
+ // to do all channel closure inside the channel_state lock which is a
+ // somewhat-larger refactor, so we leave that for later.
+ APIError::APIMisuseError{err}
+ },
+ })? {
if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
unimplemented!();
}
}
}
-macro_rules! handle_error {
- ($self: ident, $internal: expr, $their_node_id: expr) => {
- match $internal {
- Ok(msg) => Ok(msg),
- Err(MsgHandleErrInternal { err, needs_channel_force_close }) => {
- if needs_channel_force_close {
- match &err.action {
- &Some(msgs::ErrorAction::DisconnectPeer { msg: Some(ref msg) }) => {
- if msg.channel_id == [0; 32] {
- $self.peer_disconnected(&$their_node_id, true);
- } else {
- $self.force_close_channel(&msg.channel_id);
- }
- },
- &Some(msgs::ErrorAction::DisconnectPeer { msg: None }) => {},
- &Some(msgs::ErrorAction::IgnoreError) => {},
- &Some(msgs::ErrorAction::SendErrorMessage { ref msg }) => {
- if msg.channel_id == [0; 32] {
- $self.peer_disconnected(&$their_node_id, true);
- } else {
- $self.force_close_channel(&msg.channel_id);
- }
- },
- &None => {},
- }
- }
- Err(err)
- },
- }
- }
-}
-
impl ChannelMessageHandler for ChannelManager {
//TODO: Handle errors and close channel (or so)
fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
use chain::chaininterface;
use chain::transaction::OutPoint;
use chain::chaininterface::{ChainListener, ChainWatchInterface};
- use chain::keysinterface::KeysInterface;
+ use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
use chain::keysinterface;
+ use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,PaymentFailReason,RAACommitmentOrder};
use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
use ln::router::{Route, RouteHop, Router};
use util::config::UserConfig;
use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
+ use bitcoin::util::bip143;
+ use bitcoin::util::address::Address;
+ use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
use bitcoin::blockdata::block::{Block, BlockHeader};
- use bitcoin::blockdata::transaction::{Transaction, TxOut};
+ use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
+ use bitcoin::blockdata::script::{Builder, Script};
+ use bitcoin::blockdata::opcodes;
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::network::constants::Network;
}
}
+ macro_rules! get_feerate {
+ ($node: expr, $channel_id: expr) => {
+ {
+ let chan_lock = $node.node.channel_state.lock().unwrap();
+ let chan = chan_lock.by_id.get(&$channel_id).unwrap();
+ chan.get_feerate()
+ }
+ }
+ }
+
+
fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id())).unwrap();
}
}
- fn close_channel(outbound_node: &Node, inbound_node: &Node, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate) {
+ fn close_channel(outbound_node: &Node, inbound_node: &Node, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, Transaction) {
let (node_a, broadcaster_a, struct_a) = if close_inbound_first { (&inbound_node.node, &inbound_node.tx_broadcaster, inbound_node) } else { (&outbound_node.node, &outbound_node.tx_broadcaster, outbound_node) };
let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
let (tx_a, tx_b);
assert_eq!(tx_a, tx_b);
check_spends!(tx_a, funding_tx);
- (as_update, bs_update)
+ (as_update, bs_update, tx_a)
}
struct SendEvent {
let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
let channel_id = chan.2;
- macro_rules! get_feerate {
- ($node: expr) => {{
- let chan_lock = $node.node.channel_state.lock().unwrap();
- let chan = chan_lock.by_id.get(&channel_id).unwrap();
- chan.get_feerate()
- }}
- }
-
// balancing
send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
// (6) RAA is delivered ->
// First nodes[0] generates an update_fee
- nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0]) + 20).unwrap();
+ nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
check_added_monitors!(nodes[0], 1);
let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
let channel_id = chan.2;
- macro_rules! get_feerate {
- ($node: expr) => {{
- let chan_lock = $node.node.channel_state.lock().unwrap();
- let chan = chan_lock.by_id.get(&channel_id).unwrap();
- chan.get_feerate()
- }}
- }
-
// balancing
send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
// First nodes[0] generates an update_fee
- nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0]) + 20).unwrap();
+ nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
check_added_monitors!(nodes[0], 1);
let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
let channel_id = chan.2;
- macro_rules! get_feerate {
- ($node: expr) => {{
- let chan_lock = $node.node.channel_state.lock().unwrap();
- let chan = chan_lock.by_id.get(&channel_id).unwrap();
- chan.get_feerate()
- }}
- }
-
// A B
// update_fee/commitment_signed ->
// .- send (1) RAA and (2) commitment_signed
// revoke_and_ack ->
// First nodes[0] generates an update_fee
- let initial_feerate = get_feerate!(nodes[0]);
+ let initial_feerate = get_feerate!(nodes[0], channel_id);
nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
check_added_monitors!(nodes[0], 1);
let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
let channel_id = chan.2;
- macro_rules! get_feerate {
- ($node: expr) => {{
- let chan_lock = $node.node.channel_state.lock().unwrap();
- let chan = chan_lock.by_id.get(&channel_id).unwrap();
- chan.get_feerate()
- }}
- }
-
- let feerate = get_feerate!(nodes[0]);
- nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
+ let feerate = get_feerate!(nodes[0], channel_id);
+ nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
check_added_monitors!(nodes[0], 1);
let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
check_added_monitors!(nodes[1], 1);
}
+ #[test]
+ fn test_update_fee_that_funder_cannot_afford() {
+ let nodes = create_network(2);
+ let channel_value = 1888;
+ let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
+ let channel_id = chan.2;
+
+ let feerate = 260;
+ nodes[0].node.update_fee(channel_id, feerate).unwrap();
+ check_added_monitors!(nodes[0], 1);
+ let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
+
+ nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
+
+ commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
+
+ //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
+ //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
+ {
+ let chan_lock = nodes[1].node.channel_state.lock().unwrap();
+ let chan = chan_lock.by_id.get(&channel_id).unwrap();
+
+ //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
+ let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
+ let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
+ let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
+ actual_fee = channel_value - actual_fee;
+ assert_eq!(total_fee, actual_fee);
+ } //drop the mutex
+
+ //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
+ //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
+ nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
+ check_added_monitors!(nodes[0], 1);
+
+ let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
+
+ nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
+
+ //While producing the commitment_signed response after handling a received update_fee request the
+ //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
+ //Should produce and error.
+ let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
+
+ assert!(match err.err {
+ "Funding remote cannot afford proposed new fee" => true,
+ _ => false,
+ });
+
+ //clear the message we could not handle
+ nodes[1].node.get_and_clear_pending_msg_events();
+ }
+
#[test]
fn test_update_fee_with_fundee_update_add_htlc() {
let mut nodes = create_network(2);
let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
let channel_id = chan.2;
- macro_rules! get_feerate {
- ($node: expr) => {{
- let chan_lock = $node.node.channel_state.lock().unwrap();
- let chan = chan_lock.by_id.get(&channel_id).unwrap();
- chan.get_feerate()
- }}
- }
-
// balancing
send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
- let feerate = get_feerate!(nodes[0]);
+ let feerate = get_feerate!(nodes[0], channel_id);
nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
check_added_monitors!(nodes[0], 1);
let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
let channel_id = chan.2;
- macro_rules! get_feerate {
- ($node: expr) => {{
- let chan_lock = $node.node.channel_state.lock().unwrap();
- let chan = chan_lock.by_id.get(&channel_id).unwrap();
- chan.get_feerate()
- }}
- }
-
// A B
// (1) update_fee/commitment_signed ->
// <- (2) revoke_and_ack
// revoke_and_ack ->
// Create and deliver (1)...
- let feerate = get_feerate!(nodes[0]);
+ let feerate = get_feerate!(nodes[0], channel_id);
nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
check_added_monitors!(nodes[0], 1);
check_added_monitors!(nodes[1], 1);
assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
- assert_eq!(get_feerate!(nodes[0]), feerate + 30);
- assert_eq!(get_feerate!(nodes[1]), feerate + 30);
+ assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
+ assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
}
assert_eq!(msg.channel_id, channel_id);
} else { panic!("Unexpected result"); }
}
+
+ macro_rules! check_dynamic_output_p2wsh {
+ ($node: expr) => {
+ {
+ let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
+ let mut txn = Vec::new();
+ for event in events {
+ match event {
+ Event::SpendableOutputs { ref outputs } => {
+ for outp in outputs {
+ match *outp {
+ SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
+ let input = TxIn {
+ previous_output: outpoint.clone(),
+ script_sig: Script::new(),
+ sequence: *to_self_delay as u32,
+ witness: Vec::new(),
+ };
+ let outp = TxOut {
+ script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
+ value: output.value,
+ };
+ let mut spend_tx = Transaction {
+ version: 2,
+ lock_time: 0,
+ input: vec![input],
+ output: vec![outp],
+ };
+ let secp_ctx = Secp256k1::new();
+ let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
+ let local_delaysig = secp_ctx.sign(&sighash, key);
+ spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
+ spend_tx.input[0].witness[0].push(SigHashType::All as u8);
+ spend_tx.input[0].witness.push(vec!(0));
+ spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
+ txn.push(spend_tx);
+ },
+ _ => panic!("Unexpected event"),
+ }
+ }
+ },
+ _ => panic!("Unexpected event"),
+ };
+ }
+ txn
+ }
+ }
+ }
+
+ macro_rules! check_dynamic_output_p2wpkh {
+ ($node: expr) => {
+ {
+ let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
+ let mut txn = Vec::new();
+ for event in events {
+ match event {
+ Event::SpendableOutputs { ref outputs } => {
+ for outp in outputs {
+ match *outp {
+ SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
+ let input = TxIn {
+ previous_output: outpoint.clone(),
+ script_sig: Script::new(),
+ sequence: 0,
+ witness: Vec::new(),
+ };
+ let outp = TxOut {
+ script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
+ value: output.value,
+ };
+ let mut spend_tx = Transaction {
+ version: 2,
+ lock_time: 0,
+ input: vec![input],
+ output: vec![outp],
+ };
+ let secp_ctx = Secp256k1::new();
+ let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
+ let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
+ let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
+ let remotesig = secp_ctx.sign(&sighash, key);
+ spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
+ spend_tx.input[0].witness[0].push(SigHashType::All as u8);
+ spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
+ txn.push(spend_tx);
+ },
+ _ => panic!("Unexpected event"),
+ }
+ }
+ },
+ _ => panic!("Unexpected event"),
+ };
+ }
+ txn
+ }
+ }
+ }
+
+ macro_rules! check_static_output {
+ ($event: expr, $node: expr, $event_idx: expr, $output_idx: expr, $der_idx: expr, $idx_node: expr) => {
+ match $event[$event_idx] {
+ Event::SpendableOutputs { ref outputs } => {
+ match outputs[$output_idx] {
+ SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
+ let secp_ctx = Secp256k1::new();
+ let input = TxIn {
+ previous_output: outpoint.clone(),
+ script_sig: Script::new(),
+ sequence: 0,
+ witness: Vec::new(),
+ };
+ let outp = TxOut {
+ script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
+ value: output.value,
+ };
+ let mut spend_tx = Transaction {
+ version: 2,
+ lock_time: 0,
+ input: vec![input],
+ output: vec![outp.clone()],
+ };
+ let secret = {
+ match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node[$idx_node].node_seed) {
+ Ok(master_key) => {
+ match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
+ Ok(key) => key,
+ Err(_) => panic!("Your RNG is busted"),
+ }
+ }
+ Err(_) => panic!("Your rng is busted"),
+ }
+ };
+ let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
+ let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
+ let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
+ let sig = secp_ctx.sign(&sighash, &secret.secret_key);
+ spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
+ spend_tx.input[0].witness[0].push(SigHashType::All as u8);
+ spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
+ spend_tx
+ },
+ _ => panic!("Unexpected event !"),
+ }
+ },
+ _ => panic!("Unexpected event !"),
+ };
+ }
+ }
+
+ #[test]
+ fn test_claim_sizeable_push_msat() {
+ // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
+ let nodes = create_network(2);
+
+ let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
+ nodes[1].node.force_close_channel(&chan.2);
+ let events = nodes[1].node.get_and_clear_pending_msg_events();
+ match events[0] {
+ MessageSendEvent::BroadcastChannelUpdate { .. } => {},
+ _ => panic!("Unexpected event"),
+ }
+ let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
+ assert_eq!(node_txn.len(), 1);
+ check_spends!(node_txn[0], chan.3.clone());
+ assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
+
+ let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
+ nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
+ let spend_txn = check_dynamic_output_p2wsh!(nodes[1]);
+ assert_eq!(spend_txn.len(), 1);
+ check_spends!(spend_txn[0], node_txn[0].clone());
+ }
+
+ #[test]
+ fn test_claim_on_remote_sizeable_push_msat() {
+ // Same test as precedent, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
+ // to_remote output is encumbered by a P2WPKH
+
+ let nodes = create_network(2);
+
+ let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
+ nodes[0].node.force_close_channel(&chan.2);
+ let events = nodes[0].node.get_and_clear_pending_msg_events();
+ match events[0] {
+ MessageSendEvent::BroadcastChannelUpdate { .. } => {},
+ _ => panic!("Unexpected event"),
+ }
+ let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
+ assert_eq!(node_txn.len(), 1);
+ check_spends!(node_txn[0], chan.3.clone());
+ assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
+
+ let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
+ nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
+ let events = nodes[1].node.get_and_clear_pending_msg_events();
+ match events[0] {
+ MessageSendEvent::BroadcastChannelUpdate { .. } => {},
+ _ => panic!("Unexpected event"),
+ }
+ let spend_txn = check_dynamic_output_p2wpkh!(nodes[1]);
+ assert_eq!(spend_txn.len(), 2);
+ assert_eq!(spend_txn[0], spend_txn[1]);
+ check_spends!(spend_txn[0], node_txn[0].clone());
+ }
+
+ #[test]
+ fn test_static_spendable_outputs_preimage_tx() {
+ let nodes = create_network(2);
+
+ // Create some initial channels
+ let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
+
+ let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
+
+ let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
+ assert_eq!(commitment_tx[0].input.len(), 1);
+ assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
+
+ // Settle A's commitment tx on B's chain
+ let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
+ assert!(nodes[1].node.claim_funds(payment_preimage));
+ check_added_monitors!(nodes[1], 1);
+ nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
+ let events = nodes[1].node.get_and_clear_pending_msg_events();
+ match events[0] {
+ MessageSendEvent::UpdateHTLCs { .. } => {},
+ _ => panic!("Unexpected event"),
+ }
+ match events[1] {
+ MessageSendEvent::BroadcastChannelUpdate { .. } => {},
+ _ => panic!("Unexepected event"),
+ }
+
+ // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
+ let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
+ check_spends!(node_txn[0], commitment_tx[0].clone());
+ assert_eq!(node_txn[0], node_txn[2]);
+ assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 133);
+ check_spends!(node_txn[1], chan_1.3.clone());
+
+ let events = nodes[1].chan_monitor.simple_monitor.get_and_clear_pending_events();
+ let spend_tx = check_static_output!(events, nodes, 0, 0, 1, 1);
+ check_spends!(spend_tx, node_txn[0].clone());
+ }
+
+ #[test]
+ fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
+ let nodes = create_network(2);
+
+ // Create some initial channels
+ let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
+
+ let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
+ let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
+ assert_eq!(revoked_local_txn[0].input.len(), 1);
+ assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
+
+ claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
+
+ let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
+ nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
+ let events = nodes[1].node.get_and_clear_pending_msg_events();
+ match events[0] {
+ MessageSendEvent::BroadcastChannelUpdate { .. } => {},
+ _ => panic!("Unexpected event"),
+ }
+ let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
+ assert_eq!(node_txn.len(), 3);
+ assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
+ assert_eq!(node_txn[0].input.len(), 2);
+ check_spends!(node_txn[0], revoked_local_txn[0].clone());
+
+ let events = nodes[1].chan_monitor.simple_monitor.get_and_clear_pending_events();
+ let spend_tx = check_static_output!(events, nodes, 0, 0, 1, 1);
+ check_spends!(spend_tx, node_txn[0].clone());
+ }
+
+ #[test]
+ fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
+ let nodes = create_network(2);
+
+ // Create some initial channels
+ let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
+
+ let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
+ let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
+ assert_eq!(revoked_local_txn[0].input.len(), 1);
+ assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
+
+ claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
+
+ let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
+ // A will generate HTLC-Timeout from revoked commitment tx
+ nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
+ let events = nodes[0].node.get_and_clear_pending_msg_events();
+ match events[0] {
+ MessageSendEvent::BroadcastChannelUpdate { .. } => {},
+ _ => panic!("Unexpected event"),
+ }
+ let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
+ assert_eq!(revoked_htlc_txn.len(), 2);
+ assert_eq!(revoked_htlc_txn[0].input.len(), 1);
+ assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), 133);
+ check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
+
+ // B will generate justice tx from A's revoked commitment/HTLC tx
+ nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
+ let events = nodes[1].node.get_and_clear_pending_msg_events();
+ match events[0] {
+ MessageSendEvent::BroadcastChannelUpdate { .. } => {},
+ _ => panic!("Unexpected event"),
+ }
+
+ let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
+ assert_eq!(node_txn.len(), 4);
+ assert_eq!(node_txn[3].input.len(), 1);
+ check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
+
+ let events = nodes[1].chan_monitor.simple_monitor.get_and_clear_pending_events();
+ // Check B's ChannelMonitor was able to generate the right spendable output descriptor
+ let spend_tx = check_static_output!(events, nodes, 1, 1, 1, 1);
+ check_spends!(spend_tx, node_txn[3].clone());
+ }
+
+ #[test]
+ fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
+ let nodes = create_network(2);
+
+ // Create some initial channels
+ let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
+
+ let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
+ let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
+ assert_eq!(revoked_local_txn[0].input.len(), 1);
+ assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
+
+ claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
+
+ let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
+ // B will generate HTLC-Success from revoked commitment tx
+ nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
+ let events = nodes[1].node.get_and_clear_pending_msg_events();
+ match events[0] {
+ MessageSendEvent::BroadcastChannelUpdate { .. } => {},
+ _ => panic!("Unexpected event"),
+ }
+ let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
+
+ assert_eq!(revoked_htlc_txn.len(), 2);
+ assert_eq!(revoked_htlc_txn[0].input.len(), 1);
+ assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), 138);
+ check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
+
+ // A will generate justice tx from B's revoked commitment/HTLC tx
+ nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
+ let events = nodes[0].node.get_and_clear_pending_msg_events();
+ match events[0] {
+ MessageSendEvent::BroadcastChannelUpdate { .. } => {},
+ _ => panic!("Unexpected event"),
+ }
+
+ let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
+ assert_eq!(node_txn.len(), 4);
+ assert_eq!(node_txn[3].input.len(), 1);
+ check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
+
+ let events = nodes[0].chan_monitor.simple_monitor.get_and_clear_pending_events();
+ // Check A's ChannelMonitor was able to generate the right spendable output descriptor
+ let spend_tx = check_static_output!(events, nodes, 1, 2, 1, 0);
+ check_spends!(spend_tx, node_txn[3].clone());
+ }
+
+ #[test]
+ fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
+ let nodes = create_network(2);
+
+ // Create some initial channels
+ let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
+
+ let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
+ let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
+ assert_eq!(local_txn[0].input.len(), 1);
+ check_spends!(local_txn[0], chan_1.3.clone());
+
+ // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
+ nodes[1].node.claim_funds(payment_preimage);
+ check_added_monitors!(nodes[1], 1);
+ let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
+ nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
+ let events = nodes[1].node.get_and_clear_pending_msg_events();
+ match events[0] {
+ MessageSendEvent::UpdateHTLCs { .. } => {},
+ _ => panic!("Unexpected event"),
+ }
+ match events[1] {
+ MessageSendEvent::BroadcastChannelUpdate { .. } => {},
+ _ => panic!("Unexepected event"),
+ }
+ let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
+ assert_eq!(node_txn[0].input.len(), 1);
+ assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 138);
+ check_spends!(node_txn[0], local_txn[0].clone());
+
+ // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
+ let spend_txn = check_dynamic_output_p2wsh!(nodes[1]);
+ assert_eq!(spend_txn.len(), 1);
+ check_spends!(spend_txn[0], node_txn[0].clone());
+ }
+
+ #[test]
+ fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
+ let nodes = create_network(2);
+
+ // Create some initial channels
+ let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
+
+ route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
+ let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
+ assert_eq!(local_txn[0].input.len(), 1);
+ check_spends!(local_txn[0], chan_1.3.clone());
+
+ // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
+ let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
+ nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
+ let events = nodes[0].node.get_and_clear_pending_msg_events();
+ match events[0] {
+ MessageSendEvent::BroadcastChannelUpdate { .. } => {},
+ _ => panic!("Unexepected event"),
+ }
+ let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
+ assert_eq!(node_txn[0].input.len(), 1);
+ assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 133);
+ check_spends!(node_txn[0], local_txn[0].clone());
+
+ // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
+ let spend_txn = check_dynamic_output_p2wsh!(nodes[0]);
+ assert_eq!(spend_txn.len(), 4);
+ assert_eq!(spend_txn[0], spend_txn[2]);
+ assert_eq!(spend_txn[1], spend_txn[3]);
+ check_spends!(spend_txn[0], local_txn[0].clone());
+ check_spends!(spend_txn[1], node_txn[0].clone());
+ }
+
+ #[test]
+ fn test_static_output_closing_tx() {
+ let nodes = create_network(2);
+
+ let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
+
+ send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
+ let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
+
+ let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
+ nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
+ let events = nodes[0].chan_monitor.simple_monitor.get_and_clear_pending_events();
+ let spend_tx = check_static_output!(events, nodes, 0, 0, 2, 0);
+ check_spends!(spend_tx, closing_tx.clone());
+
+ nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
+ let events = nodes[1].chan_monitor.simple_monitor.get_and_clear_pending_events();
+ let spend_tx = check_static_output!(events, nodes, 0, 0, 2, 1);
+ check_spends!(spend_tx, closing_tx);
+ }
}
use bitcoin::blockdata::block::BlockHeader;
use bitcoin::blockdata::transaction::{TxIn,TxOut,SigHashType,Transaction};
use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
-use bitcoin::blockdata::script::Script;
+use bitcoin::blockdata::script::{Script, Builder};
+use bitcoin::blockdata::opcodes;
use bitcoin::consensus::encode::{self, Decodable, Encodable};
-use bitcoin::util::hash::{BitcoinHash,Sha256dHash};
+use bitcoin::util::hash::{Hash160, BitcoinHash,Sha256dHash};
use bitcoin::util::bip143;
use crypto::digest::Digest;
use secp256k1::key::{SecretKey,PublicKey};
use secp256k1;
-use ln::msgs::{DecodeError, HandleError};
+use ln::msgs::DecodeError;
use ln::chan_utils;
use ln::chan_utils::HTLCOutputInCommitment;
use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface};
PermanentFailure,
}
+/// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
+/// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::insert_combine this
+/// means you tried to merge two monitors for different channels or for a channel which was
+/// restored from a backup and then generated new commitment updates.
+/// Contains a human-readable error message.
+#[derive(Debug)]
+pub struct MonitorUpdateError(pub &'static str);
+
/// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
/// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
/// events to it, while also taking any add_update_monitor events and passing them to some remote
}
/// Adds or udpates the monitor which monitors the channel referred to by the given key.
- pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), HandleError> {
+ pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), MonitorUpdateError> {
let mut monitors = self.monitors.lock().unwrap();
match monitors.get_mut(&key) {
Some(orig_monitor) => {
revocation_base_key: SecretKey,
htlc_base_key: SecretKey,
delayed_payment_base_key: SecretKey,
+ payment_base_key: SecretKey,
+ shutdown_pubkey: PublicKey,
prev_latest_per_commitment_point: Option<PublicKey>,
latest_per_commitment_point: Option<PublicKey>,
},
}
impl ChannelMonitor {
- pub(super) fn new(revocation_base_key: &SecretKey, delayed_payment_base_key: &SecretKey, htlc_base_key: &SecretKey, our_to_self_delay: u16, destination_script: Script, logger: Arc<Logger>) -> ChannelMonitor {
+ pub(super) fn new(revocation_base_key: &SecretKey, delayed_payment_base_key: &SecretKey, htlc_base_key: &SecretKey, payment_base_key: &SecretKey, shutdown_pubkey: &PublicKey, our_to_self_delay: u16, destination_script: Script, logger: Arc<Logger>) -> ChannelMonitor {
ChannelMonitor {
funding_txo: None,
commitment_transaction_number_obscure_factor: 0,
revocation_base_key: revocation_base_key.clone(),
htlc_base_key: htlc_base_key.clone(),
delayed_payment_base_key: delayed_payment_base_key.clone(),
+ payment_base_key: payment_base_key.clone(),
+ shutdown_pubkey: shutdown_pubkey.clone(),
prev_latest_per_commitment_point: None,
latest_per_commitment_point: None,
},
res
}
- /// Inserts a revocation secret into this channel monitor. Also optionally tracks the next
- /// revocation point which may be required to claim HTLC outputs which we know the preimage of
- /// in case the remote end force-closes using their latest state. Prunes old preimages if neither
+ /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
/// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
/// commitment transaction's secret, they are de facto pruned (we can use revocation key).
- pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32], their_next_revocation_point: Option<(u64, PublicKey)>) -> Result<(), HandleError> {
+ pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
let pos = ChannelMonitor::place_secret(idx);
for i in 0..pos {
let (old_secret, old_idx) = self.old_secrets[i as usize];
if ChannelMonitor::derive_secret(secret, pos, old_idx) != old_secret {
- return Err(HandleError{err: "Previous secret did not match new one", action: None})
+ return Err(MonitorUpdateError("Previous secret did not match new one"));
}
}
self.old_secrets[pos as usize] = (secret, idx);
- if let Some(new_revocation_point) = their_next_revocation_point {
- match self.their_cur_revocation_points {
- Some(old_points) => {
- if old_points.0 == new_revocation_point.0 + 1 {
- self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(new_revocation_point.1)));
- } else if old_points.0 == new_revocation_point.0 + 2 {
- if let Some(old_second_point) = old_points.2 {
- self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(new_revocation_point.1)));
- } else {
- self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
- }
- } else {
- self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
- }
- },
- None => {
- self.their_cur_revocation_points = Some((new_revocation_point.0, new_revocation_point.1, None));
- }
- }
- }
-
if !self.payment_preimages.is_empty() {
let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
/// The monitor watches for it to be broadcasted and then uses the HTLC information (and
/// possibly future revocation/preimage information) to claim outputs where possible.
/// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
- pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<HTLCOutputInCommitment>, commitment_number: u64) {
+ pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<HTLCOutputInCommitment>, commitment_number: u64, their_revocation_point: PublicKey) {
// TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
// so that a remote monitor doesn't learn anything unless there is a malicious close.
// (only maybe, sadly we cant do the same for local info, as we need to be aware of
}
self.remote_claimable_outpoints.insert(unsigned_commitment_tx.txid(), htlc_outputs);
self.current_remote_commitment_number = commitment_number;
+ //TODO: Merge this into the other per-remote-transaction output storage stuff
+ match self.their_cur_revocation_points {
+ Some(old_points) => {
+ if old_points.0 == commitment_number + 1 {
+ self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
+ } else if old_points.0 == commitment_number + 2 {
+ if let Some(old_second_point) = old_points.2 {
+ self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
+ } else {
+ self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
+ }
+ } else {
+ self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
+ }
+ },
+ None => {
+ self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
+ }
+ }
}
/// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
feerate_per_kw,
htlc_outputs,
});
- self.key_storage = if let KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, prev_latest_per_commitment_point: _, ref latest_per_commitment_point } = self.key_storage {
+ self.key_storage = if let KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, ref payment_base_key, ref shutdown_pubkey, ref latest_per_commitment_point, .. } = self.key_storage {
KeyStorage::PrivMode {
revocation_base_key: *revocation_base_key,
htlc_base_key: *htlc_base_key,
delayed_payment_base_key: *delayed_payment_base_key,
+ payment_base_key: *payment_base_key,
+ shutdown_pubkey: *shutdown_pubkey,
prev_latest_per_commitment_point: *latest_per_commitment_point,
latest_per_commitment_point: Some(local_keys.per_commitment_point),
}
/// Combines this ChannelMonitor with the information contained in the other ChannelMonitor.
/// After a successful call this ChannelMonitor is up-to-date and is safe to use to monitor the
/// chain for new blocks/transactions.
- pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), HandleError> {
+ pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), MonitorUpdateError> {
if self.funding_txo.is_some() {
// We should be able to compare the entire funding_txo, but in fuzztarget its trivially
// easy to collide the funding_txo hash and have a different scriptPubKey.
if other.funding_txo.is_some() && other.funding_txo.as_ref().unwrap().0 != self.funding_txo.as_ref().unwrap().0 {
- return Err(HandleError{err: "Funding transaction outputs are not identical!", action: None});
+ return Err(MonitorUpdateError("Funding transaction outputs are not identical!"));
}
} else {
self.funding_txo = other.funding_txo.take();
let other_min_secret = other.get_min_seen_secret();
let our_min_secret = self.get_min_seen_secret();
if our_min_secret > other_min_secret {
- self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap(), None)?;
+ self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap())?;
+ }
+ if let Some(ref local_tx) = self.current_local_signed_commitment_tx {
+ if let Some(ref other_local_tx) = other.current_local_signed_commitment_tx {
+ let our_commitment_number = 0xffffffffffff - ((((local_tx.tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (local_tx.tx.lock_time as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
+ let other_commitment_number = 0xffffffffffff - ((((other_local_tx.tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (other_local_tx.tx.lock_time as u64 & 0xffffff)) ^ other.commitment_transaction_number_obscure_factor);
+ if our_commitment_number >= other_commitment_number {
+ self.key_storage = other.key_storage;
+ }
+ }
}
// TODO: We should use current_remote_commitment_number and the commitment number out of
// local transactions to decide how to merge
}
self.payment_preimages = other.payment_preimages;
}
+
self.current_remote_commitment_number = cmp::min(self.current_remote_commitment_number, other.current_remote_commitment_number);
Ok(())
}
U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
match self.key_storage {
- KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, ref prev_latest_per_commitment_point, ref latest_per_commitment_point } => {
+ KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, ref payment_base_key, ref shutdown_pubkey, ref prev_latest_per_commitment_point, ref latest_per_commitment_point } => {
writer.write_all(&[0; 1])?;
writer.write_all(&revocation_base_key[..])?;
writer.write_all(&htlc_base_key[..])?;
writer.write_all(&delayed_payment_base_key[..])?;
+ writer.write_all(&payment_base_key[..])?;
+ writer.write_all(&shutdown_pubkey.serialize())?;
if let Some(ref prev_latest_per_commitment_point) = *prev_latest_per_commitment_point {
writer.write_all(&[1; 1])?;
writer.write_all(&prev_latest_per_commitment_point.serialize())?;
//we want to leave out (eg funding_txo, etc).
/// Can only fail if idx is < get_min_seen_secret
- pub(super) fn get_secret(&self, idx: u64) -> Result<[u8; 32], HandleError> {
+ pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
for i in 0..self.old_secrets.len() {
if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
- return Ok(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
+ return Some(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
}
}
assert!(idx < self.get_min_seen_secret());
- Err(HandleError{err: "idx too low", action: None})
+ None
}
pub(super) fn get_min_seen_secret(&self) -> u64 {
if commitment_number >= self.get_min_seen_secret() {
let secret = self.get_secret(commitment_number).unwrap();
let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
- let (revocation_pubkey, b_htlc_key) = match self.key_storage {
- KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key, .. } => {
+ let (revocation_pubkey, b_htlc_key, local_payment_key) = match self.key_storage {
+ KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key, ref payment_base_key, .. } => {
let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
(ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
- ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
+ ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))),
+ Some(ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &payment_base_key))))
},
KeyStorage::SigsMode { ref revocation_base_key, ref htlc_base_key, .. } => {
let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
(ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
- ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)))
+ ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)),
+ None)
},
};
let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.their_delayed_payment_base_key.unwrap()));
let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
+ let local_payment_p2wpkh = if let Some(payment_key) = local_payment_key {
+ // Note that the Network here is ignored as we immediately drop the address for the
+ // script_pubkey version.
+ let payment_hash160 = Hash160::from_data(&PublicKey::from_secret_key(&self.secp_ctx, &payment_key).serialize());
+ Some(Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0).push_slice(&payment_hash160[..]).into_script())
+ } else { None };
+
let mut total_value = 0;
let mut values = Vec::new();
let mut inputs = Vec::new();
htlc_idxs.push(None);
values.push(outp.value);
total_value += outp.value;
- break; // There can only be one of these
+ } else if Some(&outp.script_pubkey) == local_payment_p2wpkh.as_ref() {
+ spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
+ outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
+ key: local_payment_key.unwrap(),
+ output: outp.clone(),
+ });
}
}
Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
};
+ for (idx, outp) in tx.output.iter().enumerate() {
+ if outp.script_pubkey.is_v0_p2wpkh() {
+ match self.key_storage {
+ KeyStorage::PrivMode { ref payment_base_key, .. } => {
+ if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &revocation_point, &payment_base_key) {
+ spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
+ outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
+ key: local_key,
+ output: outp.clone(),
+ });
+ }
+ },
+ KeyStorage::SigsMode { .. } => {}
+ }
+ break; // Only to_remote ouput is claimable
+ }
+ }
+
let mut total_value = 0;
let mut values = Vec::new();
let mut inputs = Vec::new();
};
}
- let secret = ignore_error!(self.get_secret(commitment_number));
+ let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (None, None); };
let per_commitment_key = ignore_error!(SecretKey::from_slice(&self.secp_ctx, &secret));
let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
let revocation_pubkey = match self.key_storage {
let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
+ macro_rules! add_dynamic_output {
+ ($father_tx: expr, $vout: expr) => {
+ if let Some(ref per_commitment_point) = *per_commitment_point {
+ if let Some(ref delayed_payment_base_key) = *delayed_payment_base_key {
+ if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, per_commitment_point, delayed_payment_base_key) {
+ spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WSH {
+ outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
+ key: local_delayedkey,
+ witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
+ to_self_delay: self.our_to_self_delay,
+ output: $father_tx.output[$vout as usize].clone(),
+ });
+ }
+ }
+ }
+ }
+ }
+
+
+ let redeemscript = chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.their_to_self_delay.unwrap(), &local_tx.delayed_payment_key);
+ let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
+ for (idx, output) in local_tx.tx.output.iter().enumerate() {
+ if output.script_pubkey == revokeable_p2wsh {
+ add_dynamic_output!(local_tx.tx, idx as u32);
+ break;
+ }
+ }
+
for &(ref htlc, ref their_sig, ref our_sig) in local_tx.htlc_outputs.iter() {
if htlc.offered {
let mut htlc_timeout_tx = chan_utils::build_htlc_transaction(&local_tx.txid, local_tx.feerate_per_kw, self.their_to_self_delay.unwrap(), htlc, &local_tx.delayed_payment_key, &local_tx.revocation_key);
htlc_timeout_tx.input[0].witness.push(Vec::new());
htlc_timeout_tx.input[0].witness.push(chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &local_tx.a_htlc_key, &local_tx.b_htlc_key, &local_tx.revocation_key).into_bytes());
- if let Some(ref per_commitment_point) = *per_commitment_point {
- if let Some(ref delayed_payment_base_key) = *delayed_payment_base_key {
- if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, per_commitment_point, delayed_payment_base_key) {
- spendable_outputs.push(SpendableOutputDescriptor::DynamicOutput {
- outpoint: BitcoinOutPoint { txid: htlc_timeout_tx.txid(), vout: 0 },
- local_delayedkey,
- witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
- to_self_delay: self.our_to_self_delay
- });
- }
- }
- }
+ add_dynamic_output!(htlc_timeout_tx, 0);
res.push(htlc_timeout_tx);
} else {
if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
htlc_success_tx.input[0].witness.push(payment_preimage.to_vec());
htlc_success_tx.input[0].witness.push(chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &local_tx.a_htlc_key, &local_tx.b_htlc_key, &local_tx.revocation_key).into_bytes());
- if let Some(ref per_commitment_point) = *per_commitment_point {
- if let Some(ref delayed_payment_base_key) = *delayed_payment_base_key {
- if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, per_commitment_point, delayed_payment_base_key) {
- spendable_outputs.push(SpendableOutputDescriptor::DynamicOutput {
- outpoint: BitcoinOutPoint { txid: htlc_success_tx.txid(), vout: 0 },
- local_delayedkey,
- witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
- to_self_delay: self.our_to_self_delay
- });
- }
- }
- }
+ add_dynamic_output!(htlc_success_tx, 0);
res.push(htlc_success_tx);
}
}
if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
if local_tx.txid == commitment_txid {
match self.key_storage {
- KeyStorage::PrivMode { revocation_base_key: _, htlc_base_key: _, ref delayed_payment_base_key, prev_latest_per_commitment_point: _, ref latest_per_commitment_point } => {
+ KeyStorage::PrivMode { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
return self.broadcast_by_local_state(local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
},
KeyStorage::SigsMode { .. } => {
if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
if local_tx.txid == commitment_txid {
match self.key_storage {
- KeyStorage::PrivMode { revocation_base_key: _, htlc_base_key: _, ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
+ KeyStorage::PrivMode { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
return self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key));
},
KeyStorage::SigsMode { .. } => {
(Vec::new(), Vec::new())
}
+ /// Generate a spendable output event when closing_transaction get registered onchain.
+ fn check_spend_closing_transaction(&self, tx: &Transaction) -> Option<SpendableOutputDescriptor> {
+ if tx.input[0].sequence == 0xFFFFFFFF && tx.input[0].witness.last().unwrap().len() == 71 {
+ match self.key_storage {
+ KeyStorage::PrivMode { ref shutdown_pubkey, .. } => {
+ let our_channel_close_key_hash = Hash160::from_data(&shutdown_pubkey.serialize());
+ let shutdown_script = Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
+ for (idx, output) in tx.output.iter().enumerate() {
+ if shutdown_script == output.script_pubkey {
+ return Some(SpendableOutputDescriptor::StaticOutput {
+ outpoint: BitcoinOutPoint { txid: tx.txid(), vout: idx as u32 },
+ output: output.clone(),
+ });
+ }
+ }
+ }
+ KeyStorage::SigsMode { .. } => {
+ //TODO: we need to ensure an offline client will generate the event when it
+ // cames back online after only the watchtower saw the transaction
+ }
+ }
+ }
+ None
+ }
+
/// Used by ChannelManager deserialization to broadcast the latest local state if it's copy of
/// the Channel was out-of-date.
pub(super) fn get_latest_local_commitment_txn(&self) -> Vec<Transaction> {
spendable_outputs.append(&mut outputs);
txn = remote_txn;
}
+ if !self.funding_txo.is_none() && txn.is_empty() {
+ if let Some(spendable_output) = self.check_spend_closing_transaction(tx) {
+ spendable_outputs.push(spendable_output);
+ }
+ }
} else {
if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
let (tx, spendable_output) = self.check_spend_remote_htlc(tx, commitment_number);
if self.would_broadcast_at_height(height) {
broadcaster.broadcast_transaction(&cur_local_tx.tx);
match self.key_storage {
- KeyStorage::PrivMode { revocation_base_key: _, htlc_base_key: _, ref delayed_payment_base_key, prev_latest_per_commitment_point: _, ref latest_per_commitment_point } => {
+ KeyStorage::PrivMode { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
let (txs, mut outputs) = self.broadcast_by_local_state(&cur_local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key));
spendable_outputs.append(&mut outputs);
for tx in txs {
let revocation_base_key = Readable::read(reader)?;
let htlc_base_key = Readable::read(reader)?;
let delayed_payment_base_key = Readable::read(reader)?;
+ let payment_base_key = Readable::read(reader)?;
+ let shutdown_pubkey = Readable::read(reader)?;
let prev_latest_per_commitment_point = match <u8 as Readable<R>>::read(reader)? {
0 => None,
1 => Some(Readable::read(reader)?),
revocation_base_key,
htlc_base_key,
delayed_payment_base_key,
+ payment_base_key,
+ shutdown_pubkey,
prev_latest_per_commitment_point,
latest_per_commitment_point,
}
idx -= 1;
}
assert_eq!(monitor.get_min_seen_secret(), idx + 1);
- assert!(monitor.get_secret(idx).is_err());
+ assert!(monitor.get_secret(idx).is_none());
};
}
{
// insert_secret correct sequence
- monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), 0, Script::new(), logger.clone());
+ monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
secrets.clear();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
- monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
- monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
- monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
- monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
- monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
- monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
- monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
- monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
}
{
// insert_secret #1 incorrect
- monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), 0, Script::new(), logger.clone());
+ monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
secrets.clear();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
- monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
- assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap_err().err,
+ assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap_err().0,
"Previous secret did not match new one");
}
{
// insert_secret #2 incorrect (#1 derived from incorrect)
- monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), 0, Script::new(), logger.clone());
+ monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
secrets.clear();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
- monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
- monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
- monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
- assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
+ assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
"Previous secret did not match new one");
}
{
// insert_secret #3 incorrect
- monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), 0, Script::new(), logger.clone());
+ monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
secrets.clear();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
- monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
- monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
- monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
- assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap_err().err,
+ assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
"Previous secret did not match new one");
}
{
// insert_secret #4 incorrect (1,2,3 derived from incorrect)
- monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), 0, Script::new(), logger.clone());
+ monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
secrets.clear();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
- monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
- monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
- monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
- monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
- monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
- monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
- monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
- assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
+ assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
"Previous secret did not match new one");
}
{
// insert_secret #5 incorrect
- monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), 0, Script::new(), logger.clone());
+ monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
secrets.clear();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
- monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
- monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
- monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
- monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
- monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
- assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap_err().err,
+ assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap_err().0,
"Previous secret did not match new one");
}
{
// insert_secret #6 incorrect (5 derived from incorrect)
- monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), 0, Script::new(), logger.clone());
+ monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
secrets.clear();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
- monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
- monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
- monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
- monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
- monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
- monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
- monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
- assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
+ assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
"Previous secret did not match new one");
}
{
// insert_secret #7 incorrect
- monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), 0, Script::new(), logger.clone());
+ monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
secrets.clear();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
- monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
- monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
- monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
- monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
- monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
- monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
- monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
- assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
+ assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
"Previous secret did not match new one");
}
{
// insert_secret #8 incorrect
- monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), 0, Script::new(), logger.clone());
+ monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
secrets.clear();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
- monitor.provide_secret(281474976710655, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
- monitor.provide_secret(281474976710654, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
- monitor.provide_secret(281474976710653, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
- monitor.provide_secret(281474976710652, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
- monitor.provide_secret(281474976710651, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
- monitor.provide_secret(281474976710650, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
- monitor.provide_secret(281474976710649, secrets.last().unwrap().clone(), None).unwrap();
+ monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
test_secrets!();
secrets.push([0; 32]);
secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
- assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone(), None).unwrap_err().err,
+ assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
"Previous secret did not match new one");
}
}
let logger = Arc::new(TestLogger::new());
let dummy_sig = Signature::from_der(&secp_ctx, &hex::decode("3045022100fa86fa9a36a8cd6a7bb8f06a541787d51371d067951a9461d5404de6b928782e02201c8b7c334c10aed8976a3a465be9a28abff4cb23acbf00022295b378ce1fa3cd").unwrap()[..]).unwrap();
+ let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
macro_rules! dummy_keys {
() => {
{
- let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap());
TxCreationKeys {
per_commitment_point: dummy_key.clone(),
revocation_key: dummy_key.clone(),
// Prune with one old state and a local commitment tx holding a few overlaps with the
// old state.
- let mut monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), 0, Script::new(), logger.clone());
+ let mut monitor = ChannelMonitor::new(&SecretKey::from_slice(&secp_ctx, &[42; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[43; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &SecretKey::from_slice(&secp_ctx, &[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[45; 32]).unwrap()), 0, Script::new(), logger.clone());
monitor.set_their_to_self_delay(10);
monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
- monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655);
- monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654);
- monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653);
- monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652);
+ monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
+ monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
+ monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
+ monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key);
for &(ref preimage, ref hash) in preimages.iter() {
monitor.provide_payment_preimage(hash, preimage);
}
// Now provide a secret, pruning preimages 10-15
let mut secret = [0; 32];
secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
- monitor.provide_secret(281474976710655, secret.clone(), None).unwrap();
+ monitor.provide_secret(281474976710655, secret.clone()).unwrap();
assert_eq!(monitor.payment_preimages.len(), 15);
test_preimages_exist!(&preimages[0..10], monitor);
test_preimages_exist!(&preimages[15..20], monitor);
// Now provide a further secret, pruning preimages 15-17
secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
- monitor.provide_secret(281474976710654, secret.clone(), None).unwrap();
+ monitor.provide_secret(281474976710654, secret.clone()).unwrap();
assert_eq!(monitor.payment_preimages.len(), 13);
test_preimages_exist!(&preimages[0..10], monitor);
test_preimages_exist!(&preimages[17..20], monitor);
// previous commitment tx's preimages too
monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
- monitor.provide_secret(281474976710653, secret.clone(), None).unwrap();
+ monitor.provide_secret(281474976710653, secret.clone()).unwrap();
assert_eq!(monitor.payment_preimages.len(), 12);
test_preimages_exist!(&preimages[0..10], monitor);
test_preimages_exist!(&preimages[18..20], monitor);
// But if we do it again, we'll prune 5-10
monitor.provide_latest_local_commitment_tx_info(dummy_tx.clone(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]));
secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
- monitor.provide_secret(281474976710652, secret.clone(), None).unwrap();
+ monitor.provide_secret(281474976710652, secret.clone()).unwrap();
assert_eq!(monitor.payment_preimages.len(), 5);
test_preimages_exist!(&preimages[0..5], monitor);
}