Merge pull request #1863 from TheBlueMatt/2022-11-holding-cell-batch-update
authorMatt Corallo <649246+TheBlueMatt@users.noreply.github.com>
Wed, 7 Dec 2022 17:52:04 +0000 (17:52 +0000)
committerGitHub <noreply@github.com>
Wed, 7 Dec 2022 17:52:04 +0000 (17:52 +0000)
Lean on the holding cell when batch-forwarding/failing HTLCs

26 files changed:
fuzz/src/chanmon_consistency.rs
fuzz/src/full_stack.rs
fuzz/src/onion_message.rs
lightning-invoice/src/utils.rs
lightning/src/chain/channelmonitor.rs
lightning/src/chain/keysinterface.rs
lightning/src/chain/onchaintx.rs
lightning/src/chain/package.rs
lightning/src/ln/chan_utils.rs
lightning/src/ln/chanmon_update_fail_tests.rs
lightning/src/ln/channel.rs
lightning/src/ln/channelmanager.rs
lightning/src/ln/functional_test_utils.rs
lightning/src/ln/functional_tests.rs
lightning/src/ln/monitor_tests.rs
lightning/src/ln/onion_route_tests.rs
lightning/src/ln/onion_utils.rs
lightning/src/ln/payment_tests.rs
lightning/src/ln/priv_short_conf_tests.rs
lightning/src/ln/reload_tests.rs
lightning/src/util/byte_utils.rs
lightning/src/util/enforcing_trait_impls.rs
lightning/src/util/events.rs
lightning/src/util/ser_macros.rs
lightning/src/util/test_utils.rs
pending_changelog/elias-event-renaming.txt [new file with mode: 0644]

index 6c1d4348dc1ff97e36263d104117ee732ea2884f..605a8c29c291690cacff642d78454d00950517ee 100644 (file)
@@ -193,9 +193,14 @@ impl KeysInterface for KeyProvider {
                ShutdownScript::new_p2wpkh(&pubkey_hash)
        }
 
-       fn get_channel_signer(&self, _inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
+       fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] {
+               let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed) as u8;
+               [id; 32]
+       }
+
+       fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::Signer {
                let secp_ctx = Secp256k1::signing_only();
-               let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed);
+               let id = channel_keys_id[0];
                let keys = InMemorySigner::new(
                        &secp_ctx,
                        self.get_node_secret(Recipient::Node).unwrap(),
@@ -204,9 +209,9 @@ impl KeysInterface for KeyProvider {
                        SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, self.node_id]).unwrap(),
                        SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, self.node_id]).unwrap(),
                        SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, self.node_id]).unwrap(),
-                       [id as u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, self.node_id],
+                       [id, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, self.node_id],
                        channel_value_satoshis,
-                       [0; 32],
+                       channel_keys_id,
                );
                let revoked_commitment = self.make_enforcement_state_cell(keys.commitment_seed);
                EnforcingSigner::new_with_revoked(keys, revoked_commitment, false)
@@ -843,16 +848,16 @@ pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out) {
                                let mut events = nodes[$node].get_and_clear_pending_events();
                                // Sort events so that PendingHTLCsForwardable get processed last. This avoids a
                                // case where we first process a PendingHTLCsForwardable, then claim/fail on a
-                               // PaymentReceived, claiming/failing two HTLCs, but leaving a just-generated
-                               // PaymentReceived event for the second HTLC in our pending_events (and breaking
+                               // PaymentClaimable, claiming/failing two HTLCs, but leaving a just-generated
+                               // PaymentClaimable event for the second HTLC in our pending_events (and breaking
                                // our claim_set deduplication).
                                events.sort_by(|a, b| {
-                                       if let events::Event::PaymentReceived { .. } = a {
+                                       if let events::Event::PaymentClaimable { .. } = a {
                                                if let events::Event::PendingHTLCsForwardable { .. } = b {
                                                        Ordering::Less
                                                } else { Ordering::Equal }
                                        } else if let events::Event::PendingHTLCsForwardable { .. } = a {
-                                               if let events::Event::PaymentReceived { .. } = b {
+                                               if let events::Event::PaymentClaimable { .. } = b {
                                                        Ordering::Greater
                                                } else { Ordering::Equal }
                                        } else { Ordering::Equal }
@@ -860,7 +865,7 @@ pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out) {
                                let had_events = !events.is_empty();
                                for event in events.drain(..) {
                                        match event {
-                                               events::Event::PaymentReceived { payment_hash, .. } => {
+                                               events::Event::PaymentClaimable { payment_hash, .. } => {
                                                        if claim_set.insert(payment_hash.0) {
                                                                if $fail {
                                                                        nodes[$node].fail_htlc_backwards(&payment_hash);
index b6292c608b5b7d16f9b635d97e946985f59eee1b..6374328238892ad3727933e64075d6561c88d07e 100644 (file)
@@ -263,6 +263,7 @@ struct KeyProvider {
        node_secret: SecretKey,
        inbound_payment_key: KeyMaterial,
        counter: AtomicU64,
+       signer_state: RefCell<HashMap<u8, (bool, Arc<Mutex<EnforcementState>>)>>
 }
 impl KeysInterface for KeyProvider {
        type Signer = EnforcingSigner;
@@ -297,10 +298,17 @@ impl KeysInterface for KeyProvider {
                ShutdownScript::new_p2wpkh(&pubkey_hash)
        }
 
-       fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
+       fn generate_channel_keys_id(&self, inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] {
                let ctr = self.counter.fetch_add(1, Ordering::Relaxed) as u8;
+               self.signer_state.borrow_mut().insert(ctr, (inbound, Arc::new(Mutex::new(EnforcementState::new()))));
+               [ctr; 32]
+       }
+
+       fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::Signer {
                let secp_ctx = Secp256k1::signing_only();
-               EnforcingSigner::new(if inbound {
+               let ctr = channel_keys_id[0];
+               let (inbound, state) = self.signer_state.borrow().get(&ctr).unwrap().clone();
+               EnforcingSigner::new_with_revoked(if inbound {
                        InMemorySigner::new(
                                &secp_ctx,
                                self.node_secret.clone(),
@@ -311,7 +319,7 @@ impl KeysInterface for KeyProvider {
                                SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, ctr]).unwrap(),
                                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, ctr],
                                channel_value_satoshis,
-                               [0; 32],
+                               channel_keys_id,
                        )
                } else {
                        InMemorySigner::new(
@@ -324,9 +332,9 @@ impl KeysInterface for KeyProvider {
                                SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, ctr]).unwrap(),
                                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, ctr],
                                channel_value_satoshis,
-                               [0; 32],
+                               channel_keys_id,
                        )
-               })
+               }, state, false)
        }
 
        fn get_secure_random_bytes(&self) -> [u8; 32] {
@@ -390,7 +398,12 @@ pub fn do_test(data: &[u8], logger: &Arc<dyn Logger>) {
        let monitor = Arc::new(chainmonitor::ChainMonitor::new(None, broadcast.clone(), Arc::clone(&logger), fee_est.clone(),
                Arc::new(TestPersister { update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed) })));
 
-       let keys_manager = Arc::new(KeyProvider { node_secret: our_network_key.clone(), inbound_payment_key: KeyMaterial(inbound_payment_key.try_into().unwrap()), counter: AtomicU64::new(0) });
+       let keys_manager = Arc::new(KeyProvider {
+               node_secret: our_network_key.clone(),
+               inbound_payment_key: KeyMaterial(inbound_payment_key.try_into().unwrap()),
+               counter: AtomicU64::new(0),
+               signer_state: RefCell::new(HashMap::new())
+       });
        let mut config = UserConfig::default();
        config.channel_config.forwarding_fee_proportional_millionths =  slice_to_be32(get_slice!(4));
        config.channel_handshake_config.announced_channel = get_slice!(1)[0] != 0;
@@ -646,7 +659,7 @@ pub fn do_test(data: &[u8], logger: &Arc<dyn Logger>) {
                                Event::FundingGenerationReady { temporary_channel_id, counterparty_node_id, channel_value_satoshis, output_script, .. } => {
                                        pending_funding_generation.push((temporary_channel_id, counterparty_node_id, channel_value_satoshis, output_script));
                                },
-                               Event::PaymentReceived { payment_hash, .. } => {
+                               Event::PaymentClaimable { payment_hash, .. } => {
                                        //TODO: enhance by fetching random amounts from fuzz input?
                                        payments_received.push(payment_hash);
                                },
index 8fa6e4231be499a0e1ba989b68ed4c0c7dcc8e0c..b1f8fc33637f948cc0a6cf1c8b30ccfeaa45a0a1 100644 (file)
@@ -111,7 +111,9 @@ impl KeysInterface for KeyProvider {
 
        fn get_shutdown_scriptpubkey(&self) -> ShutdownScript { unreachable!() }
 
-       fn get_channel_signer(&self, _inbound: bool, _channel_value_satoshis: u64) -> EnforcingSigner {
+       fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { unreachable!() }
+
+       fn derive_channel_signer(&self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32]) -> Self::Signer {
                unreachable!()
        }
 
index 47856fb487cf8b4164d92433e95eabdee4b4e5a3..d19254c84649e78ddcab64516c6fceaf39e803b9 100644 (file)
@@ -957,7 +957,7 @@ mod test {
                nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
                commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true);
 
-               // Note that we have to "forward pending HTLCs" twice before we see the PaymentReceived as
+               // Note that we have to "forward pending HTLCs" twice before we see the PaymentClaimable as
                // this "emulates" the payment taking two hops, providing some privacy to make phantom node
                // payments "look real" by taking more time.
                expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
@@ -966,7 +966,7 @@ mod test {
                nodes[fwd_idx].node.process_pending_htlc_forwards();
 
                let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
-               expect_payment_received!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt, route.paths[0].last().unwrap().pubkey);
+               expect_payment_claimable!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt, route.paths[0].last().unwrap().pubkey);
                do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[fwd_idx])[..]), false, payment_preimage);
                let events = nodes[0].node.get_and_clear_pending_events();
                assert_eq!(events.len(), 2);
index 92f1a8df45d8e88bb75e9db80c7974fa89a430ec..5c1e102aefc8e2cc44350acc052f99ffdab5e224 100644 (file)
@@ -53,7 +53,7 @@ use crate::util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable,
 use crate::util::byte_utils;
 use crate::util::events::Event;
 #[cfg(anchors)]
-use crate::util::events::{AnchorDescriptor, BumpTransactionEvent};
+use crate::util::events::{AnchorDescriptor, HTLCDescriptor, BumpTransactionEvent};
 
 use crate::prelude::*;
 use core::{cmp, mem};
@@ -291,7 +291,7 @@ struct CounterpartyCommitmentParameters {
 
 impl Writeable for CounterpartyCommitmentParameters {
        fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
-               w.write_all(&byte_utils::be64_to_array(0))?;
+               w.write_all(&(0 as u64).to_be_bytes())?;
                write_tlv_fields!(w, {
                        (0, self.counterparty_delayed_payment_base_key, required),
                        (2, self.counterparty_htlc_base_key, required),
@@ -647,6 +647,7 @@ struct IrrevocablyResolvedHTLC {
        /// was not present in the confirmed commitment transaction), HTLC-Success, or HTLC-Timeout
        /// transaction.
        resolving_txid: Option<Txid>, // Added as optional, but always filled in, in 0.0.110
+       resolving_tx: Option<Transaction>,
        /// Only set if the HTLC claim was ours using a payment preimage
        payment_preimage: Option<PaymentPreimage>,
 }
@@ -662,6 +663,7 @@ impl Writeable for IrrevocablyResolvedHTLC {
                        (0, mapped_commitment_tx_output_idx, required),
                        (1, self.resolving_txid, option),
                        (2, self.payment_preimage, option),
+                       (3, self.resolving_tx, option),
                });
                Ok(())
        }
@@ -672,15 +674,18 @@ impl Readable for IrrevocablyResolvedHTLC {
                let mut mapped_commitment_tx_output_idx = 0;
                let mut resolving_txid = None;
                let mut payment_preimage = None;
+               let mut resolving_tx = None;
                read_tlv_fields!(reader, {
                        (0, mapped_commitment_tx_output_idx, required),
                        (1, resolving_txid, option),
                        (2, payment_preimage, option),
+                       (3, resolving_tx, option),
                });
                Ok(Self {
                        commitment_tx_output_idx: if mapped_commitment_tx_output_idx == u32::max_value() { None } else { Some(mapped_commitment_tx_output_idx) },
                        resolving_txid,
                        payment_preimage,
+                       resolving_tx,
                })
        }
 }
@@ -945,7 +950,7 @@ impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
                self.channel_keys_id.write(writer)?;
                self.holder_revocation_basepoint.write(writer)?;
                writer.write_all(&self.funding_info.0.txid[..])?;
-               writer.write_all(&byte_utils::be16_to_array(self.funding_info.0.index))?;
+               writer.write_all(&self.funding_info.0.index.to_be_bytes())?;
                self.funding_info.1.write(writer)?;
                self.current_counterparty_commitment_txid.write(writer)?;
                self.prev_counterparty_commitment_txid.write(writer)?;
@@ -972,24 +977,24 @@ impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
                        },
                }
 
-               writer.write_all(&byte_utils::be16_to_array(self.on_holder_tx_csv))?;
+               writer.write_all(&self.on_holder_tx_csv.to_be_bytes())?;
 
                self.commitment_secrets.write(writer)?;
 
                macro_rules! serialize_htlc_in_commitment {
                        ($htlc_output: expr) => {
                                writer.write_all(&[$htlc_output.offered as u8; 1])?;
-                               writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
-                               writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
+                               writer.write_all(&$htlc_output.amount_msat.to_be_bytes())?;
+                               writer.write_all(&$htlc_output.cltv_expiry.to_be_bytes())?;
                                writer.write_all(&$htlc_output.payment_hash.0[..])?;
                                $htlc_output.transaction_output_index.write(writer)?;
                        }
                }
 
-               writer.write_all(&byte_utils::be64_to_array(self.counterparty_claimable_outpoints.len() as u64))?;
+               writer.write_all(&(self.counterparty_claimable_outpoints.len() as u64).to_be_bytes())?;
                for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() {
                        writer.write_all(&txid[..])?;
-                       writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
+                       writer.write_all(&(htlc_infos.len() as u64).to_be_bytes())?;
                        for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
                                debug_assert!(htlc_source.is_none() || Some(**txid) == self.current_counterparty_commitment_txid
                                                || Some(**txid) == self.prev_counterparty_commitment_txid,
@@ -999,13 +1004,13 @@ impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
                        }
                }
 
-               writer.write_all(&byte_utils::be64_to_array(self.counterparty_commitment_txn_on_chain.len() as u64))?;
+               writer.write_all(&(self.counterparty_commitment_txn_on_chain.len() as u64).to_be_bytes())?;
                for (ref txid, commitment_number) in self.counterparty_commitment_txn_on_chain.iter() {
                        writer.write_all(&txid[..])?;
                        writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
                }
 
-               writer.write_all(&byte_utils::be64_to_array(self.counterparty_hash_commitment_number.len() as u64))?;
+               writer.write_all(&(self.counterparty_hash_commitment_number.len() as u64).to_be_bytes())?;
                for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() {
                        writer.write_all(&payment_hash.0[..])?;
                        writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
@@ -1023,7 +1028,7 @@ impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
                writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?;
                writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?;
 
-               writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
+               writer.write_all(&(self.payment_preimages.len() as u64).to_be_bytes())?;
                for payment_preimage in self.payment_preimages.values() {
                        writer.write_all(&payment_preimage.0[..])?;
                }
@@ -1044,15 +1049,15 @@ impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
                        }
                }
 
-               writer.write_all(&byte_utils::be64_to_array(self.pending_events.len() as u64))?;
+               writer.write_all(&(self.pending_events.len() as u64).to_be_bytes())?;
                for event in self.pending_events.iter() {
                        event.write(writer)?;
                }
 
                self.best_block.block_hash().write(writer)?;
-               writer.write_all(&byte_utils::be32_to_array(self.best_block.height()))?;
+               writer.write_all(&self.best_block.height().to_be_bytes())?;
 
-               writer.write_all(&byte_utils::be64_to_array(self.onchain_events_awaiting_threshold_conf.len() as u64))?;
+               writer.write_all(&(self.onchain_events_awaiting_threshold_conf.len() as u64).to_be_bytes())?;
                for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
                        entry.write(writer)?;
                }
@@ -1526,6 +1531,7 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
                        if let Some(v) = htlc.transaction_output_index { v } else { return None; };
 
                let mut htlc_spend_txid_opt = None;
+               let mut htlc_spend_tx_opt = None;
                let mut holder_timeout_spend_pending = None;
                let mut htlc_spend_pending = None;
                let mut holder_delayed_output_pending = None;
@@ -1534,7 +1540,9 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
                                OnchainEvent::HTLCUpdate { commitment_tx_output_idx, htlc_value_satoshis, .. }
                                if commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) => {
                                        debug_assert!(htlc_spend_txid_opt.is_none());
-                                       htlc_spend_txid_opt = event.transaction.as_ref().map(|tx| tx.txid());
+                                       htlc_spend_txid_opt = Some(&event.txid);
+                                       debug_assert!(htlc_spend_tx_opt.is_none());
+                                       htlc_spend_tx_opt = event.transaction.as_ref();
                                        debug_assert!(holder_timeout_spend_pending.is_none());
                                        debug_assert_eq!(htlc_value_satoshis.unwrap(), htlc.amount_msat / 1000);
                                        holder_timeout_spend_pending = Some(event.confirmation_threshold());
@@ -1542,7 +1550,9 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
                                OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. }
                                if commitment_tx_output_idx == htlc_commitment_tx_output_idx => {
                                        debug_assert!(htlc_spend_txid_opt.is_none());
-                                       htlc_spend_txid_opt = event.transaction.as_ref().map(|tx| tx.txid());
+                                       htlc_spend_txid_opt = Some(&event.txid);
+                                       debug_assert!(htlc_spend_tx_opt.is_none());
+                                       htlc_spend_tx_opt = event.transaction.as_ref();
                                        debug_assert!(htlc_spend_pending.is_none());
                                        htlc_spend_pending = Some((event.confirmation_threshold(), preimage.is_some()));
                                },
@@ -1558,19 +1568,32 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
                let htlc_resolved = self.htlcs_resolved_on_chain.iter()
                        .find(|v| if v.commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) {
                                debug_assert!(htlc_spend_txid_opt.is_none());
-                               htlc_spend_txid_opt = v.resolving_txid;
+                               htlc_spend_txid_opt = v.resolving_txid.as_ref();
+                               debug_assert!(htlc_spend_tx_opt.is_none());
+                               htlc_spend_tx_opt = v.resolving_tx.as_ref();
                                true
                        } else { false });
                debug_assert!(holder_timeout_spend_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved.is_some() as u8 <= 1);
 
+               let htlc_commitment_outpoint = BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx);
                let htlc_output_to_spend =
                        if let Some(txid) = htlc_spend_txid_opt {
-                               debug_assert!(
-                                       self.onchain_tx_handler.channel_transaction_parameters.opt_anchors.is_none(),
-                                       "This code needs updating for anchors");
-                               BitcoinOutPoint::new(txid, 0)
+                               // Because HTLC transactions either only have 1 input and 1 output (pre-anchors) or
+                               // are signed with SIGHASH_SINGLE|ANYONECANPAY under BIP-0143 (post-anchors), we can
+                               // locate the correct output by ensuring its adjacent input spends the HTLC output
+                               // in the commitment.
+                               if let Some(ref tx) = htlc_spend_tx_opt {
+                                       let htlc_input_idx_opt = tx.input.iter().enumerate()
+                                               .find(|(_, input)| input.previous_output == htlc_commitment_outpoint)
+                                               .map(|(idx, _)| idx as u32);
+                                       debug_assert!(htlc_input_idx_opt.is_some());
+                                       BitcoinOutPoint::new(*txid, htlc_input_idx_opt.unwrap_or(0))
+                               } else {
+                                       debug_assert!(!self.onchain_tx_handler.opt_anchors());
+                                       BitcoinOutPoint::new(*txid, 0)
+                               }
                        } else {
-                               BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx)
+                               htlc_commitment_outpoint
                        };
                let htlc_output_spend_pending = self.onchain_tx_handler.is_output_spend_pending(&htlc_output_to_spend);
 
@@ -1594,8 +1617,7 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
                                } = &event.event {
                                        if event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
                                                if let Some(htlc_spend_txid) = htlc_spend_txid_opt {
-                                                       Some(tx.txid()) == htlc_spend_txid_opt ||
-                                                               inp.previous_output.txid == htlc_spend_txid
+                                                       tx.txid() == *htlc_spend_txid || inp.previous_output.txid == *htlc_spend_txid
                                                } else {
                                                        Some(inp.previous_output.txid) == confirmed_txid &&
                                                                inp.previous_output.vout == htlc_commitment_tx_output_idx
@@ -1837,12 +1859,60 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
                res
        }
 
+       /// Gets the set of outbound HTLCs which can be (or have been) resolved by this
+       /// `ChannelMonitor`. This is used to determine if an HTLC was removed from the channel prior
+       /// to the `ChannelManager` having been persisted.
+       ///
+       /// This is similar to [`Self::get_pending_outbound_htlcs`] except it includes HTLCs which were
+       /// resolved by this `ChannelMonitor`.
+       pub(crate) fn get_all_current_outbound_htlcs(&self) -> HashMap<HTLCSource, HTLCOutputInCommitment> {
+               let mut res = HashMap::new();
+               // Just examine the available counterparty commitment transactions. See docs on
+               // `fail_unbroadcast_htlcs`, below, for justification.
+               let us = self.inner.lock().unwrap();
+               macro_rules! walk_counterparty_commitment {
+                       ($txid: expr) => {
+                               if let Some(ref latest_outpoints) = us.counterparty_claimable_outpoints.get($txid) {
+                                       for &(ref htlc, ref source_option) in latest_outpoints.iter() {
+                                               if let &Some(ref source) = source_option {
+                                                       res.insert((**source).clone(), htlc.clone());
+                                               }
+                                       }
+                               }
+                       }
+               }
+               if let Some(ref txid) = us.current_counterparty_commitment_txid {
+                       walk_counterparty_commitment!(txid);
+               }
+               if let Some(ref txid) = us.prev_counterparty_commitment_txid {
+                       walk_counterparty_commitment!(txid);
+               }
+               res
+       }
+
        /// Gets the set of outbound HTLCs which are pending resolution in this channel.
        /// This is used to reconstruct pending outbound payments on restart in the ChannelManager.
        pub(crate) fn get_pending_outbound_htlcs(&self) -> HashMap<HTLCSource, HTLCOutputInCommitment> {
-               let mut res = HashMap::new();
                let us = self.inner.lock().unwrap();
+               // We're only concerned with the confirmation count of HTLC transactions, and don't
+               // actually care how many confirmations a commitment transaction may or may not have. Thus,
+               // we look for either a FundingSpendConfirmation event or a funding_spend_confirmed.
+               let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
+                       us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
+                               if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
+                                       Some(event.txid)
+                               } else { None }
+                       })
+               });
 
+               if confirmed_txid.is_none() {
+                       // If we have not seen a commitment transaction on-chain (ie the channel is not yet
+                       // closed), just get the full set.
+                       mem::drop(us);
+                       return self.get_all_current_outbound_htlcs();
+               }
+
+               let mut res = HashMap::new();
                macro_rules! walk_htlcs {
                        ($holder_commitment: expr, $htlc_iter: expr) => {
                                for (htlc, source) in $htlc_iter {
@@ -1878,54 +1948,22 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
                        }
                }
 
-               // We're only concerned with the confirmation count of HTLC transactions, and don't
-               // actually care how many confirmations a commitment transaction may or may not have. Thus,
-               // we look for either a FundingSpendConfirmation event or a funding_spend_confirmed.
-               let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
-                       us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
-                               if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
-                                       Some(event.txid)
+               let txid = confirmed_txid.unwrap();
+               if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
+                       walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().filter_map(|(a, b)| {
+                               if let &Some(ref source) = b {
+                                       Some((a, &**source))
                                } else { None }
-                       })
-               });
-               if let Some(txid) = confirmed_txid {
-                       if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
-                               walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().filter_map(|(a, b)| {
-                                       if let &Some(ref source) = b {
-                                               Some((a, &**source))
-                                       } else { None }
-                               }));
-                       } else if txid == us.current_holder_commitment_tx.txid {
-                               walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().filter_map(|(a, _, c)| {
+                       }));
+               } else if txid == us.current_holder_commitment_tx.txid {
+                       walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().filter_map(|(a, _, c)| {
+                               if let Some(source) = c { Some((a, source)) } else { None }
+                       }));
+               } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
+                       if txid == prev_commitment.txid {
+                               walk_htlcs!(true, prev_commitment.htlc_outputs.iter().filter_map(|(a, _, c)| {
                                        if let Some(source) = c { Some((a, source)) } else { None }
                                }));
-                       } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
-                               if txid == prev_commitment.txid {
-                                       walk_htlcs!(true, prev_commitment.htlc_outputs.iter().filter_map(|(a, _, c)| {
-                                               if let Some(source) = c { Some((a, source)) } else { None }
-                                       }));
-                               }
-                       }
-               } else {
-                       // If we have not seen a commitment transaction on-chain (ie the channel is not yet
-                       // closed), just examine the available counterparty commitment transactions. See docs
-                       // on `fail_unbroadcast_htlcs`, below, for justification.
-                       macro_rules! walk_counterparty_commitment {
-                               ($txid: expr) => {
-                                       if let Some(ref latest_outpoints) = us.counterparty_claimable_outpoints.get($txid) {
-                                               for &(ref htlc, ref source_option) in latest_outpoints.iter() {
-                                                       if let &Some(ref source) = source_option {
-                                                               res.insert((**source).clone(), htlc.clone());
-                                                       }
-                                               }
-                                       }
-                               }
-                       }
-                       if let Some(ref txid) = us.current_counterparty_commitment_txid {
-                               walk_counterparty_commitment!(txid);
-                       }
-                       if let Some(ref txid) = us.prev_counterparty_commitment_txid {
-                               walk_counterparty_commitment!(txid);
                        }
                }
 
@@ -2387,6 +2425,27 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
                                                pending_htlcs,
                                        }));
                                },
+                               ClaimEvent::BumpHTLC {
+                                       target_feerate_sat_per_1000_weight, htlcs,
+                               } => {
+                                       let mut htlc_descriptors = Vec::with_capacity(htlcs.len());
+                                       for htlc in htlcs {
+                                               htlc_descriptors.push(HTLCDescriptor {
+                                                       channel_keys_id: self.channel_keys_id,
+                                                       channel_value_satoshis: self.channel_value_satoshis,
+                                                       channel_parameters: self.onchain_tx_handler.channel_transaction_parameters.clone(),
+                                                       commitment_txid: htlc.commitment_txid,
+                                                       per_commitment_number: htlc.per_commitment_number,
+                                                       htlc: htlc.htlc,
+                                                       preimage: htlc.preimage,
+                                                       counterparty_sig: htlc.counterparty_sig,
+                                               });
+                                       }
+                                       ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
+                                               target_feerate_sat_per_1000_weight,
+                                               htlc_descriptors,
+                                       }));
+                               }
                        }
                }
                ret
@@ -2443,8 +2502,8 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
                        let secret = self.get_secret(commitment_number).unwrap();
                        let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
                        let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
-                       let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint));
-                       let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.counterparty_commitment_params.counterparty_delayed_payment_base_key));
+                       let revocation_pubkey = chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint);
+                       let delayed_key = chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.counterparty_commitment_params.counterparty_delayed_payment_base_key);
 
                        let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
                        let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
@@ -2556,31 +2615,18 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
                        } else { return (claimable_outpoints, to_counterparty_output_info); };
 
                if let Some(transaction) = tx {
-                       let revokeable_p2wsh_opt =
-                               if let Ok(revocation_pubkey) = chan_utils::derive_public_revocation_key(
-                                       &self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint)
-                               {
-                                       if let Ok(delayed_key) = chan_utils::derive_public_key(&self.secp_ctx,
-                                               &per_commitment_point,
-                                               &self.counterparty_commitment_params.counterparty_delayed_payment_base_key)
-                                       {
-                                               Some(chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
-                                                       self.counterparty_commitment_params.on_counterparty_tx_csv,
-                                                       &delayed_key).to_v0_p2wsh())
-                                       } else {
-                                               debug_assert!(false, "Failed to derive a delayed payment key for a commitment state we accepted");
-                                               None
-                                       }
-                               } else {
-                                       debug_assert!(false, "Failed to derive a revocation pubkey key for a commitment state we accepted");
-                                       None
-                               };
-                       if let Some(revokeable_p2wsh) = revokeable_p2wsh_opt {
-                               for (idx, outp) in transaction.output.iter().enumerate() {
-                                       if outp.script_pubkey == revokeable_p2wsh {
-                                               to_counterparty_output_info =
-                                                       Some((idx.try_into().expect("Can't have > 2^32 outputs"), outp.value));
-                                       }
+                       let revocation_pubkey = chan_utils::derive_public_revocation_key(
+                               &self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint);
+                       let delayed_key = chan_utils::derive_public_key(&self.secp_ctx,
+                               &per_commitment_point,
+                               &self.counterparty_commitment_params.counterparty_delayed_payment_base_key);
+                       let revokeable_p2wsh = chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
+                               self.counterparty_commitment_params.on_counterparty_tx_csv,
+                               &delayed_key).to_v0_p2wsh();
+                       for (idx, outp) in transaction.output.iter().enumerate() {
+                               if outp.script_pubkey == revokeable_p2wsh {
+                                       to_counterparty_output_info =
+                                               Some((idx.try_into().expect("Can't have > 2^32 outputs"), outp.value));
                                }
                        }
                }
@@ -2620,31 +2666,49 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
        }
 
        /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
-       fn check_spend_counterparty_htlc<L: Deref>(&mut self, tx: &Transaction, commitment_number: u64, height: u32, logger: &L) -> (Vec<PackageTemplate>, Option<TransactionOutputs>) where L::Target: Logger {
-               let htlc_txid = tx.txid();
-               if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
-                       return (Vec::new(), None)
-               }
-
-               macro_rules! ignore_error {
-                       ( $thing : expr ) => {
-                               match $thing {
-                                       Ok(a) => a,
-                                       Err(_) => return (Vec::new(), None)
-                               }
-                       };
-               }
-
+       fn check_spend_counterparty_htlc<L: Deref>(
+               &mut self, tx: &Transaction, commitment_number: u64, commitment_txid: &Txid, height: u32, logger: &L
+       ) -> (Vec<PackageTemplate>, Option<TransactionOutputs>) where L::Target: Logger {
                let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
-               let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
+               let per_commitment_key = match SecretKey::from_slice(&secret) {
+                       Ok(key) => key,
+                       Err(_) => return (Vec::new(), None)
+               };
                let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
 
-               log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, 0);
-               let revk_outp = RevokedOutput::build(per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key, tx.output[0].value, self.counterparty_commitment_params.on_counterparty_tx_csv);
-               let justice_package = PackageTemplate::build_package(htlc_txid, 0, PackageSolvingData::RevokedOutput(revk_outp), height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32, true, height);
-               let claimable_outpoints = vec!(justice_package);
-               let outputs = vec![(0, tx.output[0].clone())];
-               (claimable_outpoints, Some((htlc_txid, outputs)))
+               let htlc_txid = tx.txid();
+               let mut claimable_outpoints = vec![];
+               let mut outputs_to_watch = None;
+               // Previously, we would only claim HTLCs from revoked HTLC transactions if they had 1 input
+               // with a witness of 5 elements and 1 output. This wasn't enough for anchor outputs, as the
+               // counterparty can now aggregate multiple HTLCs into a single transaction thanks to
+               // `SIGHASH_SINGLE` remote signatures, leading us to not claim any HTLCs upon seeing a
+               // confirmed revoked HTLC transaction (for more details, see
+               // https://lists.linuxfoundation.org/pipermail/lightning-dev/2022-April/003561.html).
+               //
+               // We make sure we're not vulnerable to this case by checking all inputs of the transaction,
+               // and claim those which spend the commitment transaction, have a witness of 5 elements, and
+               // have a corresponding output at the same index within the transaction.
+               for (idx, input) in tx.input.iter().enumerate() {
+                       if input.previous_output.txid == *commitment_txid && input.witness.len() == 5 && tx.output.get(idx).is_some() {
+                               log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, idx);
+                               let revk_outp = RevokedOutput::build(
+                                       per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
+                                       self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key,
+                                       tx.output[idx].value, self.counterparty_commitment_params.on_counterparty_tx_csv
+                               );
+                               let justice_package = PackageTemplate::build_package(
+                                       htlc_txid, idx as u32, PackageSolvingData::RevokedOutput(revk_outp),
+                                       height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32, true, height
+                               );
+                               claimable_outpoints.push(justice_package);
+                               if outputs_to_watch.is_none() {
+                                       outputs_to_watch = Some((htlc_txid, vec![]));
+                               }
+                               outputs_to_watch.as_mut().unwrap().1.push((idx as u32, tx.output[idx].clone()));
+                       }
+               }
+               (claimable_outpoints, outputs_to_watch)
        }
 
        // Returns (1) `PackageTemplate`s that can be given to the OnchainTxHandler, so that the handler can
@@ -2658,18 +2722,28 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
 
                for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
                        if let Some(transaction_output_index) = htlc.transaction_output_index {
-                               let htlc_output = if htlc.offered {
-                                               HolderHTLCOutput::build_offered(htlc.amount_msat, htlc.cltv_expiry)
+                               let (htlc_output, aggregable) = if htlc.offered {
+                                       let htlc_output = HolderHTLCOutput::build_offered(
+                                               htlc.amount_msat, htlc.cltv_expiry, self.onchain_tx_handler.opt_anchors()
+                                       );
+                                       (htlc_output, false)
+                               } else {
+                                       let payment_preimage = if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
+                                               preimage.clone()
                                        } else {
-                                               let payment_preimage = if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
-                                                       preimage.clone()
-                                               } else {
-                                                       // We can't build an HTLC-Success transaction without the preimage
-                                                       continue;
-                                               };
-                                               HolderHTLCOutput::build_accepted(payment_preimage, htlc.amount_msat)
+                                               // We can't build an HTLC-Success transaction without the preimage
+                                               continue;
                                        };
-                               let htlc_package = PackageTemplate::build_package(holder_tx.txid, transaction_output_index, PackageSolvingData::HolderHTLCOutput(htlc_output), htlc.cltv_expiry, false, conf_height);
+                                       let htlc_output = HolderHTLCOutput::build_accepted(
+                                               payment_preimage, htlc.amount_msat, self.onchain_tx_handler.opt_anchors()
+                                       );
+                                       (htlc_output, self.onchain_tx_handler.opt_anchors())
+                               };
+                               let htlc_package = PackageTemplate::build_package(
+                                       holder_tx.txid, transaction_output_index,
+                                       PackageSolvingData::HolderHTLCOutput(htlc_output),
+                                       htlc.cltv_expiry, aggregable, conf_height
+                               );
                                claim_requests.push(htlc_package);
                        }
                }
@@ -2902,9 +2976,9 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
 
                        if tx.input.len() == 1 {
                                // Assuming our keys were not leaked (in which case we're screwed no matter what),
-                               // commitment transactions and HTLC transactions will all only ever have one input,
-                               // which is an easy way to filter out any potential non-matching txn for lazy
-                               // filters.
+                               // commitment transactions and HTLC transactions will all only ever have one input
+                               // (except for HTLC transactions for channels with anchor outputs), which is an easy
+                               // way to filter out any potential non-matching txn for lazy filters.
                                let prevout = &tx.input[0].previous_output;
                                if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
                                        let mut balance_spendable_csv = None;
@@ -2942,22 +3016,33 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
                                                        commitment_tx_to_counterparty_output,
                                                },
                                        });
-                               } else {
-                                       if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&prevout.txid) {
-                                               let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(&tx, commitment_number, height, &logger);
+                               }
+                       }
+                       if tx.input.len() >= 1 {
+                               // While all commitment transactions have one input, HTLC transactions may have more
+                               // if the HTLC was present in an anchor channel. HTLCs can also be resolved in a few
+                               // other ways which can have more than one output.
+                               for tx_input in &tx.input {
+                                       let commitment_txid = tx_input.previous_output.txid;
+                                       if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&commitment_txid) {
+                                               let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(
+                                                       &tx, commitment_number, &commitment_txid, height, &logger
+                                               );
                                                claimable_outpoints.append(&mut new_outpoints);
                                                if let Some(new_outputs) = new_outputs_option {
                                                        watch_outputs.push(new_outputs);
                                                }
+                                               // Since there may be multiple HTLCs (all from the same commitment) being
+                                               // claimed by the counterparty within the same transaction, and
+                                               // `check_spend_counterparty_htlc` already checks for all of them, we can
+                                               // safely break from our loop.
+                                               break;
                                        }
                                }
-                       }
-                       // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
-                       // can also be resolved in a few other ways which can have more than one output. Thus,
-                       // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
-                       self.is_resolving_htlc_output(&tx, height, &block_hash, &logger);
+                               self.is_resolving_htlc_output(&tx, height, &block_hash, &logger);
 
-                       self.is_paying_spendable_output(&tx, height, &block_hash, &logger);
+                               self.is_paying_spendable_output(&tx, height, &block_hash, &logger);
+                       }
                }
 
                if height > self.best_block.height() {
@@ -3071,7 +3156,9 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
                                                htlc_value_satoshis,
                                        }));
                                        self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
-                                               commitment_tx_output_idx, resolving_txid: Some(entry.txid),
+                                               commitment_tx_output_idx,
+                                               resolving_txid: Some(entry.txid),
+                                               resolving_tx: entry.transaction,
                                                payment_preimage: None,
                                        });
                                },
@@ -3084,7 +3171,9 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
                                },
                                OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } => {
                                        self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
-                                               commitment_tx_output_idx: Some(commitment_tx_output_idx), resolving_txid: Some(entry.txid),
+                                               commitment_tx_output_idx: Some(commitment_tx_output_idx),
+                                               resolving_txid: Some(entry.txid),
+                                               resolving_tx: entry.transaction,
                                                payment_preimage: preimage,
                                        });
                                },
@@ -3789,7 +3878,9 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K>
                                return Err(DecodeError::InvalidValue);
                        }
                }
-               let onchain_tx_handler: OnchainTxHandler<K::Signer> = ReadableArgs::read(reader, keys_manager)?;
+               let onchain_tx_handler: OnchainTxHandler<K::Signer> = ReadableArgs::read(
+                       reader, (keys_manager, channel_value_satoshis, channel_keys_id)
+               )?;
 
                let lockdown_from_offchain = Readable::read(reader)?;
                let holder_tx_signed = Readable::read(reader)?;
index 9f81976906cf7fa3b31961869ed4132435513d18..f2d198bbfa101d97d129c251381a637a76aaf348 100644 (file)
@@ -31,10 +31,11 @@ use bitcoin::secp256k1::ecdh::SharedSecret;
 use bitcoin::secp256k1::ecdsa::RecoverableSignature;
 use bitcoin::{PackedLockTime, secp256k1, Sequence, Witness};
 
-use crate::util::{byte_utils, transaction_utils};
+use crate::util::transaction_utils;
 use crate::util::crypto::{hkdf_extract_expand_twice, sign};
 use crate::util::ser::{Writeable, Writer, Readable, ReadableArgs};
-
+#[cfg(anchors)]
+use crate::util::events::HTLCDescriptor;
 use crate::chain::transaction::OutPoint;
 use crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI;
 use crate::ln::{chan_utils, PaymentPreimage};
@@ -43,6 +44,7 @@ use crate::ln::msgs::UnsignedChannelAnnouncement;
 use crate::ln::script::ShutdownScript;
 
 use crate::prelude::*;
+use core::convert::TryInto;
 use core::sync::atomic::{AtomicUsize, Ordering};
 use crate::io::{self, Error};
 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
@@ -161,7 +163,7 @@ pub enum SpendableOutputDescriptor {
        ///
        /// To derive the revocation_pubkey provided here (which is used in the witness
        /// script generation), you must pass the counterparty revocation_basepoint (which appears in the
-       /// call to Sign::ready_channel) and the provided per_commitment point
+       /// call to Sign::provide_channel_parameters) and the provided per_commitment point
        /// to chan_utils::derive_public_revocation_key.
        ///
        /// The witness script which is hashed and included in the output script_pubkey may be
@@ -324,6 +326,19 @@ pub trait BaseSign {
        /// (which is committed to in the BIP 143 signatures).
        fn sign_justice_revoked_htlc(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()>;
 
+       #[cfg(anchors)]
+       /// Computes the signature for a commitment transaction's HTLC output used as an input within
+       /// `htlc_tx`, which spends the commitment transaction, at index `input`. The signature returned
+       /// must be be computed using [`EcdsaSighashType::All`]. Note that this should only be used to
+       /// sign HTLC transactions from channels supporting anchor outputs after all additional
+       /// inputs/outputs have been added to the transaction.
+       ///
+       /// [`EcdsaSighashType::All`]: bitcoin::blockdata::transaction::EcdsaSighashType::All
+       fn sign_holder_htlc_transaction(
+               &self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
+               secp_ctx: &Secp256k1<secp256k1::All>
+       ) -> Result<Signature, ()>;
+
        /// Create a signature for a claiming transaction for a HTLC output on a counterparty's commitment
        /// transaction, either offered or received.
        ///
@@ -368,24 +383,22 @@ pub trait BaseSign {
                -> Result<(Signature, Signature), ()>;
 
        /// Set the counterparty static channel data, including basepoints,
-       /// counterparty_selected/holder_selected_contest_delay and funding outpoint.
-       /// This is done as soon as the funding outpoint is known.  Since these are static channel data,
-       /// they MUST NOT be allowed to change to different values once set.
+       /// counterparty_selected/holder_selected_contest_delay and funding outpoint. Since these are
+       /// static channel data, they MUST NOT be allowed to change to different values once set, as LDK
+       /// may call this method more than once.
        ///
        /// channel_parameters.is_populated() MUST be true.
-       ///
-       /// We bind holder_selected_contest_delay late here for API convenience.
-       ///
-       /// Will be called before any signatures are applied.
-       fn ready_channel(&mut self, channel_parameters: &ChannelTransactionParameters);
+       fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters);
 }
 
-/// A cloneable signer.
+/// A writeable signer.
 ///
-/// Although we require signers to be cloneable, it may be useful for developers to be able to use
-/// signers in an un-sized way, for example as `dyn BaseSign`. Therefore we separate the Clone trait,
-/// which implies Sized, into this derived trait.
-pub trait Sign: BaseSign + Writeable + Clone {
+/// There will always be two instances of a signer per channel, one occupied by the
+/// [`ChannelManager`] and another by the channel's [`ChannelMonitor`].
+///
+/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
+/// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
+pub trait Sign: BaseSign + Writeable {
 }
 
 /// Specifies the recipient of an invoice, to indicate to [`KeysInterface::sign_invoice`] what node
@@ -402,7 +415,7 @@ pub enum Recipient {
 
 /// A trait to describe an object which can get user secrets and key material.
 pub trait KeysInterface {
-       /// A type which implements Sign which will be returned by get_channel_signer.
+       /// A type which implements Sign which will be returned by derive_channel_signer.
        type Signer : Sign;
 
        /// Get node secret key based on the provided [`Recipient`].
@@ -445,11 +458,20 @@ pub trait KeysInterface {
        /// This method should return a different value each time it is called, to avoid linking
        /// on-chain funds across channels as controlled to the same user.
        fn get_shutdown_scriptpubkey(&self) -> ShutdownScript;
-       /// Get a new set of Sign for per-channel secrets. These MUST be unique even if you
-       /// restarted with some stale data!
+       /// Generates a unique `channel_keys_id` that can be used to obtain a `Signer` through
+       /// [`KeysInterface::derive_channel_signer`]. The `user_channel_id` is provided to allow
+       /// implementations of `KeysInterface` to maintain a mapping between it and the generated
+       /// `channel_keys_id`.
        ///
        /// This method must return a different value each time it is called.
-       fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> Self::Signer;
+       fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32];
+       /// Derives the private key material backing a `Signer`.
+       ///
+       /// To derive a new `Signer`, a fresh `channel_keys_id` should be obtained through
+       /// [`KeysInterface::generate_channel_keys_id`]. Otherwise, an existing `Signer` can be
+       /// re-derived from its `channel_keys_id`, which can be obtained through its trait method
+       /// [`BaseSign::channel_keys_id`].
+       fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::Signer;
        /// Gets a unique, cryptographically-secure, random 32 byte value. This is used for encrypting
        /// onion packets and for temporary channel IDs. There is no requirement that these be
        /// persisted anywhere, though they must be unique across restarts.
@@ -463,6 +485,9 @@ pub trait KeysInterface {
        /// The bytes are exactly those which `<Self::Signer as Writeable>::write()` writes, and
        /// contain no versioning scheme. You may wish to include your own version prefix and ensure
        /// you've read all of the provided bytes to ensure no corruption occurred.
+       ///
+       /// This method is slowly being phased out -- it will only be called when reading objects
+       /// written by LDK versions prior to 0.0.113.
        fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, DecodeError>;
 
        /// Sign an invoice.
@@ -571,39 +596,39 @@ impl InMemorySigner {
        }
 
        /// Counterparty pubkeys.
-       /// Will panic if ready_channel wasn't called.
+       /// Will panic if provide_channel_parameters wasn't called.
        pub fn counterparty_pubkeys(&self) -> &ChannelPublicKeys { &self.get_channel_parameters().counterparty_parameters.as_ref().unwrap().pubkeys }
 
        /// The contest_delay value specified by our counterparty and applied on holder-broadcastable
        /// transactions, ie the amount of time that we have to wait to recover our funds if we
        /// broadcast a transaction.
-       /// Will panic if ready_channel wasn't called.
+       /// Will panic if provide_channel_parameters wasn't called.
        pub fn counterparty_selected_contest_delay(&self) -> u16 { self.get_channel_parameters().counterparty_parameters.as_ref().unwrap().selected_contest_delay }
 
        /// The contest_delay value specified by us and applied on transactions broadcastable
        /// by our counterparty, ie the amount of time that they have to wait to recover their funds
        /// if they broadcast a transaction.
-       /// Will panic if ready_channel wasn't called.
+       /// Will panic if provide_channel_parameters wasn't called.
        pub fn holder_selected_contest_delay(&self) -> u16 { self.get_channel_parameters().holder_selected_contest_delay }
 
        /// Whether the holder is the initiator
-       /// Will panic if ready_channel wasn't called.
+       /// Will panic if provide_channel_parameters wasn't called.
        pub fn is_outbound(&self) -> bool { self.get_channel_parameters().is_outbound_from_holder }
 
        /// Funding outpoint
-       /// Will panic if ready_channel wasn't called.
+       /// Will panic if provide_channel_parameters wasn't called.
        pub fn funding_outpoint(&self) -> &OutPoint { self.get_channel_parameters().funding_outpoint.as_ref().unwrap() }
 
        /// Obtain a ChannelTransactionParameters for this channel, to be used when verifying or
        /// building transactions.
        ///
-       /// Will panic if ready_channel wasn't called.
+       /// Will panic if provide_channel_parameters wasn't called.
        pub fn get_channel_parameters(&self) -> &ChannelTransactionParameters {
                self.channel_parameters.as_ref().unwrap()
        }
 
        /// Whether anchors should be used.
-       /// Will panic if ready_channel wasn't called.
+       /// Will panic if provide_channel_parameters wasn't called.
        pub fn opt_anchors(&self) -> bool {
                self.get_channel_parameters().opt_anchors.is_some()
        }
@@ -655,8 +680,7 @@ impl InMemorySigner {
                if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint() { return Err(()); }
                if spend_tx.input[input_idx].sequence.0 != descriptor.to_self_delay as u32 { return Err(()); }
 
-               let delayed_payment_key = chan_utils::derive_private_key(&secp_ctx, &descriptor.per_commitment_point, &self.delayed_payment_base_key)
-                       .expect("We constructed the payment_base_key, so we can only fail here if the RNG is busted.");
+               let delayed_payment_key = chan_utils::derive_private_key(&secp_ctx, &descriptor.per_commitment_point, &self.delayed_payment_base_key);
                let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
                let witness_script = chan_utils::get_revokeable_redeemscript(&descriptor.revocation_pubkey, descriptor.to_self_delay, &delayed_payment_pubkey);
                let sighash = hash_to_message!(&sighash::SighashCache::new(spend_tx).segwit_signature_hash(input_idx, &witness_script, descriptor.output.value, EcdsaSighashType::All).unwrap()[..]);
@@ -672,7 +696,6 @@ impl InMemorySigner {
                witness.push(witness_script.clone().into_bytes());
                Ok(witness)
        }
-
 }
 
 impl BaseSign for InMemorySigner {
@@ -710,7 +733,7 @@ impl BaseSign for InMemorySigner {
                        let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, self.opt_anchors(), &keys);
                        let htlc_sighashtype = if self.opt_anchors() { EcdsaSighashType::SinglePlusAnyoneCanPay } else { EcdsaSighashType::All };
                        let htlc_sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, htlc.amount_msat / 1000, htlc_sighashtype).unwrap()[..]);
-                       let holder_htlc_key = chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key).map_err(|_| ())?;
+                       let holder_htlc_key = chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key);
                        htlc_sigs.push(sign(secp_ctx, &htlc_sighash, &holder_htlc_key));
                }
 
@@ -743,11 +766,11 @@ impl BaseSign for InMemorySigner {
        }
 
        fn sign_justice_revoked_output(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
-               let revocation_key = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key).map_err(|_| ())?;
+               let revocation_key = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key);
                let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
-               let revocation_pubkey = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint).map_err(|_| ())?;
+               let revocation_pubkey = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint);
                let witness_script = {
-                       let counterparty_delayedpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().delayed_payment_basepoint).map_err(|_| ())?;
+                       let counterparty_delayedpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().delayed_payment_basepoint);
                        chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.holder_selected_contest_delay(), &counterparty_delayedpubkey)
                };
                let mut sighash_parts = sighash::SighashCache::new(justice_tx);
@@ -756,12 +779,12 @@ impl BaseSign for InMemorySigner {
        }
 
        fn sign_justice_revoked_htlc(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
-               let revocation_key = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key).map_err(|_| ())?;
+               let revocation_key = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key);
                let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
-               let revocation_pubkey = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint).map_err(|_| ())?;
+               let revocation_pubkey = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint);
                let witness_script = {
-                       let counterparty_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().htlc_basepoint).map_err(|_| ())?;
-                       let holder_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint).map_err(|_| ())?;
+                       let counterparty_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().htlc_basepoint);
+                       let holder_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint);
                        chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, self.opt_anchors(), &counterparty_htlcpubkey, &holder_htlcpubkey, &revocation_pubkey)
                };
                let mut sighash_parts = sighash::SighashCache::new(justice_tx);
@@ -769,20 +792,33 @@ impl BaseSign for InMemorySigner {
                return Ok(sign(secp_ctx, &sighash, &revocation_key))
        }
 
+       #[cfg(anchors)]
+       fn sign_holder_htlc_transaction(
+               &self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
+               secp_ctx: &Secp256k1<secp256k1::All>
+       ) -> Result<Signature, ()> {
+               let per_commitment_point = self.get_per_commitment_point(
+                       htlc_descriptor.per_commitment_number, &secp_ctx
+               );
+               let witness_script = htlc_descriptor.witness_script(&per_commitment_point, secp_ctx);
+               let sighash = &sighash::SighashCache::new(&*htlc_tx).segwit_signature_hash(
+                       input, &witness_script, htlc_descriptor.htlc.amount_msat / 1000, EcdsaSighashType::All
+               ).map_err(|_| ())?;
+               let our_htlc_private_key = chan_utils::derive_private_key(
+                       &secp_ctx, &per_commitment_point, &self.htlc_base_key
+               );
+               Ok(sign(&secp_ctx, &hash_to_message!(sighash), &our_htlc_private_key))
+       }
+
        fn sign_counterparty_htlc_transaction(&self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
-               if let Ok(htlc_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key) {
-                       let witness_script = if let Ok(revocation_pubkey) = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint) {
-                               if let Ok(counterparty_htlcpubkey) = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().htlc_basepoint) {
-                                       if let Ok(htlcpubkey) = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint) {
-                                               chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, self.opt_anchors(), &counterparty_htlcpubkey, &htlcpubkey, &revocation_pubkey)
-                                       } else { return Err(()) }
-                               } else { return Err(()) }
-                       } else { return Err(()) };
-                       let mut sighash_parts = sighash::SighashCache::new(htlc_tx);
-                       let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
-                       return Ok(sign(secp_ctx, &sighash, &htlc_key))
-               }
-               Err(())
+               let htlc_key = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key);
+               let revocation_pubkey = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint);
+               let counterparty_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().htlc_basepoint);
+               let htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint);
+               let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, self.opt_anchors(), &counterparty_htlcpubkey, &htlcpubkey, &revocation_pubkey);
+               let mut sighash_parts = sighash::SighashCache::new(htlc_tx);
+               let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
+               Ok(sign(secp_ctx, &sighash, &htlc_key))
        }
 
        fn sign_closing_transaction(&self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
@@ -807,8 +843,12 @@ impl BaseSign for InMemorySigner {
                Ok((sign(secp_ctx, &msghash, &self.node_secret), sign(secp_ctx, &msghash, &self.funding_key)))
        }
 
-       fn ready_channel(&mut self, channel_parameters: &ChannelTransactionParameters) {
-               assert!(self.channel_parameters.is_none(), "Acceptance already noted");
+       fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters) {
+               assert!(self.channel_parameters.is_none() || self.channel_parameters.as_ref().unwrap() == channel_parameters);
+               if self.channel_parameters.is_some() {
+                       // The channel parameters were already set and they match, return early.
+                       return;
+               }
                assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
                self.channel_parameters = Some(channel_parameters.clone());
        }
@@ -955,8 +995,8 @@ impl KeysManager {
                                inbound_pmt_key_bytes.copy_from_slice(&inbound_payment_key[..]);
 
                                let mut rand_bytes_unique_start = Sha256::engine();
-                               rand_bytes_unique_start.input(&byte_utils::be64_to_array(starting_time_secs));
-                               rand_bytes_unique_start.input(&byte_utils::be32_to_array(starting_time_nanos));
+                               rand_bytes_unique_start.input(&starting_time_secs.to_be_bytes());
+                               rand_bytes_unique_start.input(&starting_time_nanos.to_be_bytes());
                                rand_bytes_unique_start.input(seed);
 
                                let mut res = KeysManager {
@@ -987,13 +1027,8 @@ impl KeysManager {
                }
        }
        /// Derive an old Sign containing per-channel secrets based on a key derivation parameters.
-       ///
-       /// Key derivation parameters are accessible through a per-channel secrets
-       /// Sign::channel_keys_id and is provided inside DynamicOuputP2WSH in case of
-       /// onchain output detection for which a corresponding delayed_payment_key must be derived.
        pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner {
-               let chan_id = byte_utils::slice_to_be64(&params[0..8]);
-               assert!(chan_id <= core::u32::MAX as u64); // Otherwise the params field wasn't created by us
+               let chan_id = u64::from_be_bytes(params[0..8].try_into().unwrap());
                let mut unique_start = Sha256::engine();
                unique_start.input(params);
                unique_start.input(&self.seed);
@@ -1209,14 +1244,19 @@ impl KeysInterface for KeysManager {
                ShutdownScript::new_p2wpkh_from_pubkey(self.shutdown_pubkey.clone())
        }
 
-       fn get_channel_signer(&self, _inbound: bool, channel_value_satoshis: u64) -> Self::Signer {
-               let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
-               assert!(child_ix <= core::u32::MAX as usize);
+       fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
+               let child_idx = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
+               assert!(child_idx <= core::u32::MAX as usize);
                let mut id = [0; 32];
-               id[0..8].copy_from_slice(&byte_utils::be64_to_array(child_ix as u64));
-               id[8..16].copy_from_slice(&byte_utils::be64_to_array(self.starting_time_nanos as u64));
-               id[16..24].copy_from_slice(&byte_utils::be64_to_array(self.starting_time_secs));
-               self.derive_channel_keys(channel_value_satoshis, &id)
+               id[0..4].copy_from_slice(&(child_idx as u32).to_be_bytes());
+               id[4..8].copy_from_slice(&self.starting_time_nanos.to_be_bytes());
+               id[8..16].copy_from_slice(&self.starting_time_secs.to_be_bytes());
+               id[16..32].copy_from_slice(&user_channel_id.to_be_bytes());
+               id
+       }
+
+       fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::Signer {
+               self.derive_channel_keys(channel_value_satoshis, &channel_keys_id)
        }
 
        fn get_secure_random_bytes(&self) -> [u8; 32] {
@@ -1309,8 +1349,12 @@ impl KeysInterface for PhantomKeysManager {
                self.inner.get_shutdown_scriptpubkey()
        }
 
-       fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> Self::Signer {
-               self.inner.get_channel_signer(inbound, channel_value_satoshis)
+       fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
+               self.inner.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
+       }
+
+       fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::Signer {
+               self.inner.derive_channel_signer(channel_value_satoshis, channel_keys_id)
        }
 
        fn get_secure_random_bytes(&self) -> [u8; 32] {
index 2ce2ed41ba1fcf0e00325aec5005e8757d10c76b..5bf3a8fd4823369902fba99752ef4b546aebaad3 100644 (file)
@@ -21,10 +21,11 @@ use bitcoin::hash_types::{Txid, BlockHash};
 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
 use bitcoin::secp256k1;
 
+use crate::chain::keysinterface::BaseSign;
 use crate::ln::msgs::DecodeError;
 use crate::ln::PaymentPreimage;
 #[cfg(anchors)]
-use crate::ln::chan_utils;
+use crate::ln::chan_utils::{self, HTLCOutputInCommitment};
 use crate::ln::chan_utils::{ChannelTransactionParameters, HolderCommitmentTransaction};
 #[cfg(anchors)]
 use crate::chain::chaininterface::ConfirmationTarget;
@@ -36,7 +37,6 @@ use crate::chain::package::PackageSolvingData;
 use crate::chain::package::PackageTemplate;
 use crate::util::logger::Logger;
 use crate::util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, VecWriter};
-use crate::util::byte_utils;
 
 use crate::io;
 use crate::prelude::*;
@@ -174,6 +174,16 @@ impl Writeable for Option<Vec<Option<(usize, Signature)>>> {
        }
 }
 
+#[cfg(anchors)]
+/// The claim commonly referred to as the pre-signed second-stage HTLC transaction.
+pub(crate) struct ExternalHTLCClaim {
+       pub(crate) commitment_txid: Txid,
+       pub(crate) per_commitment_number: u64,
+       pub(crate) htlc: HTLCOutputInCommitment,
+       pub(crate) preimage: Option<PaymentPreimage>,
+       pub(crate) counterparty_sig: Signature,
+}
+
 // Represents the different types of claims for which events are yielded externally to satisfy said
 // claims.
 #[cfg(anchors)]
@@ -185,6 +195,12 @@ pub(crate) enum ClaimEvent {
                commitment_tx: Transaction,
                anchor_output_idx: u32,
        },
+       /// Event yielded to signal that the commitment transaction has confirmed and its HTLCs must be
+       /// resolved by broadcasting a transaction with sufficient fee to claim them.
+       BumpHTLC {
+               target_feerate_sat_per_1000_weight: u32,
+               htlcs: Vec<ExternalHTLCClaim>,
+       },
 }
 
 /// Represents the different ways an output can be claimed (i.e., spent to an address under our
@@ -198,6 +214,9 @@ pub(crate) enum OnchainClaim {
        Event(ClaimEvent),
 }
 
+/// An internal identifier to track pending package claims within the `OnchainTxHandler`.
+type PackageID = [u8; 32];
+
 /// OnchainTxHandler receives claiming requests, aggregates them if it's sound, broadcast and
 /// do RBF bumping if possible.
 pub struct OnchainTxHandler<ChannelSigner: Sign> {
@@ -225,11 +244,11 @@ pub struct OnchainTxHandler<ChannelSigner: Sign> {
        // us and is immutable until all outpoint of the claimable set are post-anti-reorg-delay solved.
        // Entry is cache of elements need to generate a bumped claiming transaction (see ClaimTxBumpMaterial)
        #[cfg(test)] // Used in functional_test to verify sanitization
-       pub(crate) pending_claim_requests: HashMap<Txid, PackageTemplate>,
+       pub(crate) pending_claim_requests: HashMap<PackageID, PackageTemplate>,
        #[cfg(not(test))]
-       pending_claim_requests: HashMap<Txid, PackageTemplate>,
+       pending_claim_requests: HashMap<PackageID, PackageTemplate>,
        #[cfg(anchors)]
-       pending_claim_events: HashMap<Txid, ClaimEvent>,
+       pending_claim_events: HashMap<PackageID, ClaimEvent>,
 
        // Used to link outpoints claimed in a connected block to a pending claim request.
        // Key is outpoint than monitor parsing has detected we have keys/scripts to claim
@@ -238,9 +257,9 @@ pub struct OnchainTxHandler<ChannelSigner: Sign> {
        // post-anti-reorg-delay solved, confirmaiton_block is used to erase entry if
        // block with output gets disconnected.
        #[cfg(test)] // Used in functional_test to verify sanitization
-       pub claimable_outpoints: HashMap<BitcoinOutPoint, (Txid, u32)>,
+       pub claimable_outpoints: HashMap<BitcoinOutPoint, (PackageID, u32)>,
        #[cfg(not(test))]
-       claimable_outpoints: HashMap<BitcoinOutPoint, (Txid, u32)>,
+       claimable_outpoints: HashMap<BitcoinOutPoint, (PackageID, u32)>,
 
        locktimed_packages: BTreeMap<u32, Vec<PackageTemplate>>,
 
@@ -271,29 +290,29 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                (key_data.0.len() as u32).write(writer)?;
                writer.write_all(&key_data.0[..])?;
 
-               writer.write_all(&byte_utils::be64_to_array(self.pending_claim_requests.len() as u64))?;
+               writer.write_all(&(self.pending_claim_requests.len() as u64).to_be_bytes())?;
                for (ref ancestor_claim_txid, request) in self.pending_claim_requests.iter() {
                        ancestor_claim_txid.write(writer)?;
                        request.write(writer)?;
                }
 
-               writer.write_all(&byte_utils::be64_to_array(self.claimable_outpoints.len() as u64))?;
+               writer.write_all(&(self.claimable_outpoints.len() as u64).to_be_bytes())?;
                for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
                        outp.write(writer)?;
                        claim_and_height.0.write(writer)?;
                        claim_and_height.1.write(writer)?;
                }
 
-               writer.write_all(&byte_utils::be64_to_array(self.locktimed_packages.len() as u64))?;
+               writer.write_all(&(self.locktimed_packages.len() as u64).to_be_bytes())?;
                for (ref locktime, ref packages) in self.locktimed_packages.iter() {
                        locktime.write(writer)?;
-                       writer.write_all(&byte_utils::be64_to_array(packages.len() as u64))?;
+                       writer.write_all(&(packages.len() as u64).to_be_bytes())?;
                        for ref package in packages.iter() {
                                package.write(writer)?;
                        }
                }
 
-               writer.write_all(&byte_utils::be64_to_array(self.onchain_events_awaiting_threshold_conf.len() as u64))?;
+               writer.write_all(&(self.onchain_events_awaiting_threshold_conf.len() as u64).to_be_bytes())?;
                for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
                        entry.write(writer)?;
                }
@@ -303,8 +322,12 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
        }
 }
 
-impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
-       fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
+impl<'a, K: KeysInterface> ReadableArgs<(&'a K, u64, [u8; 32])> for OnchainTxHandler<K::Signer> {
+       fn read<R: io::Read>(reader: &mut R, args: (&'a K, u64, [u8; 32])) -> Result<Self, DecodeError> {
+               let keys_manager = args.0;
+               let channel_value_satoshis = args.1;
+               let channel_keys_id = args.2;
+
                let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
 
                let destination_script = Readable::read(reader)?;
@@ -316,16 +339,21 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
 
                let channel_parameters = Readable::read(reader)?;
 
+               // Read the serialized signer bytes, but don't deserialize them, as we'll obtain our signer
+               // by re-deriving the private key material.
                let keys_len: u32 = Readable::read(reader)?;
-               let mut keys_data = Vec::with_capacity(cmp::min(keys_len as usize, MAX_ALLOC_SIZE));
-               while keys_data.len() != keys_len as usize {
+               let mut bytes_read = 0;
+               while bytes_read != keys_len as usize {
                        // Read 1KB at a time to avoid accidentally allocating 4GB on corrupted channel keys
                        let mut data = [0; 1024];
-                       let read_slice = &mut data[0..cmp::min(1024, keys_len as usize - keys_data.len())];
+                       let bytes_to_read = cmp::min(1024, keys_len as usize - bytes_read);
+                       let read_slice = &mut data[0..bytes_to_read];
                        reader.read_exact(read_slice)?;
-                       keys_data.extend_from_slice(read_slice);
+                       bytes_read += bytes_to_read;
                }
-               let signer = keys_manager.read_chan_signer(&keys_data)?;
+
+               let mut signer = keys_manager.derive_channel_signer(channel_value_satoshis, channel_keys_id);
+               signer.provide_channel_parameters(&channel_parameters);
 
                let pending_claim_requests_len: u64 = Readable::read(reader)?;
                let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
@@ -453,7 +481,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                                // since requests can have outpoints split off.
                                if !self.onchain_events_awaiting_threshold_conf.iter()
                                        .any(|event_entry| if let OnchainEvent::Claim { claim_request } = event_entry.event {
-                                               first_claim_txid_height.0 == claim_request
+                                               first_claim_txid_height.0 == claim_request.into_inner()
                                        } else {
                                                // The onchain event is not a claim, keep seeking until we find one.
                                                false
@@ -476,15 +504,36 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                // didn't receive confirmation of it before, or not enough reorg-safe depth on top of it).
                let new_timer = Some(cached_request.get_height_timer(cur_height));
                if cached_request.is_malleable() {
+                       #[cfg(anchors)]
+                       { // Attributes are not allowed on if expressions on our current MSRV of 1.41.
+                               if cached_request.requires_external_funding() {
+                                       let target_feerate_sat_per_1000_weight = cached_request
+                                               .compute_package_feerate(fee_estimator, ConfirmationTarget::HighPriority);
+                                       if let Some(htlcs) = cached_request.construct_malleable_package_with_external_funding(self) {
+                                               return Some((
+                                                       new_timer,
+                                                       target_feerate_sat_per_1000_weight as u64,
+                                                       OnchainClaim::Event(ClaimEvent::BumpHTLC {
+                                                               target_feerate_sat_per_1000_weight,
+                                                               htlcs,
+                                                       }),
+                                               ));
+                                       } else {
+                                               return None;
+                                       }
+                               }
+                       }
+
                        let predicted_weight = cached_request.package_weight(&self.destination_script);
-                       if let Some((output_value, new_feerate)) =
-                                       cached_request.compute_package_output(predicted_weight, self.destination_script.dust_value().to_sat(), fee_estimator, logger) {
+                       if let Some((output_value, new_feerate)) = cached_request.compute_package_output(
+                               predicted_weight, self.destination_script.dust_value().to_sat(), fee_estimator, logger,
+                       ) {
                                assert!(new_feerate != 0);
 
                                let transaction = cached_request.finalize_malleable_package(self, output_value, self.destination_script.clone(), logger).unwrap();
                                log_trace!(logger, "...with timer {} and feerate {}", new_timer.unwrap(), new_feerate);
                                assert!(predicted_weight >= transaction.weight());
-                               return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)))
+                               return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)));
                        }
                } else {
                        // Untractable packages cannot have their fees bumped through Replace-By-Fee. Some
@@ -540,7 +589,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                                        debug_assert!(false, "Only HolderFundingOutput inputs should be untractable and require external funding");
                                        None
                                },
-                       });
+                       })
                }
                None
        }
@@ -619,27 +668,38 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                        if let Some((new_timer, new_feerate, claim)) = self.generate_claim(cur_height, &req, &*fee_estimator, &*logger) {
                                req.set_timer(new_timer);
                                req.set_feerate(new_feerate);
-                               let txid = match claim {
+                               let package_id = match claim {
                                        OnchainClaim::Tx(tx) => {
                                                log_info!(logger, "Broadcasting onchain {}", log_tx!(tx));
                                                broadcaster.broadcast_transaction(&tx);
-                                               tx.txid()
+                                               tx.txid().into_inner()
                                        },
                                        #[cfg(anchors)]
                                        OnchainClaim::Event(claim_event) => {
                                                log_info!(logger, "Yielding onchain event to spend inputs {:?}", req.outpoints());
-                                               let txid = match claim_event {
-                                                       ClaimEvent::BumpCommitment { ref commitment_tx, .. } => commitment_tx.txid(),
+                                               let package_id = match claim_event {
+                                                       ClaimEvent::BumpCommitment { ref commitment_tx, .. } => commitment_tx.txid().into_inner(),
+                                                       ClaimEvent::BumpHTLC { ref htlcs, .. } => {
+                                                               // Use the same construction as a lightning channel id to generate
+                                                               // the package id for this request based on the first HTLC. It
+                                                               // doesn't matter what we use as long as it's unique per request.
+                                                               let mut package_id = [0; 32];
+                                                               package_id[..].copy_from_slice(&htlcs[0].commitment_txid[..]);
+                                                               let htlc_output_index = htlcs[0].htlc.transaction_output_index.unwrap();
+                                                               package_id[30] ^= ((htlc_output_index >> 8) & 0xff) as u8;
+                                                               package_id[31] ^= ((htlc_output_index >> 0) & 0xff) as u8;
+                                                               package_id
+                                                       },
                                                };
-                                               self.pending_claim_events.insert(txid, claim_event);
-                                               txid
+                                               self.pending_claim_events.insert(package_id, claim_event);
+                                               package_id
                                        },
                                };
                                for k in req.outpoints() {
                                        log_info!(logger, "Registering claiming request for {}:{}", k.txid, k.vout);
-                                       self.claimable_outpoints.insert(k.clone(), (txid, conf_height));
+                                       self.claimable_outpoints.insert(k.clone(), (package_id, conf_height));
                                }
-                               self.pending_claim_requests.insert(txid, req);
+                               self.pending_claim_requests.insert(package_id, req);
                        }
                }
        }
@@ -672,15 +732,32 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                                                //... we need to verify equality between transaction outpoints and claim request
                                                // outpoints to know if transaction is the original claim or a bumped one issued
                                                // by us.
-                                               let mut set_equality = true;
-                                               if request.outpoints().len() != tx.input.len() {
-                                                       set_equality = false;
+                                               let mut are_sets_equal = true;
+                                               if !request.requires_external_funding() || !request.is_malleable() {
+                                                       // If the claim does not require external funds to be allocated through
+                                                       // additional inputs we can simply check the inputs in order as they
+                                                       // cannot change under us.
+                                                       if request.outpoints().len() != tx.input.len() {
+                                                               are_sets_equal = false;
+                                                       } else {
+                                                               for (claim_inp, tx_inp) in request.outpoints().iter().zip(tx.input.iter()) {
+                                                                       if **claim_inp != tx_inp.previous_output {
+                                                                               are_sets_equal = false;
+                                                                       }
+                                                               }
+                                                       }
                                                } else {
-                                                       for (claim_inp, tx_inp) in request.outpoints().iter().zip(tx.input.iter()) {
-                                                               if **claim_inp != tx_inp.previous_output {
-                                                                       set_equality = false;
+                                                       // Otherwise, we'll do a linear search for each input (we don't expect
+                                                       // large input sets to exist) to ensure the request's input set is fully
+                                                       // spent to be resilient against the external claim reordering inputs.
+                                                       let mut spends_all_inputs = true;
+                                                       for request_input in request.outpoints() {
+                                                               if tx.input.iter().find(|input| input.previous_output == *request_input).is_none() {
+                                                                       spends_all_inputs = false;
+                                                                       break;
                                                                }
                                                        }
+                                                       are_sets_equal = spends_all_inputs;
                                                }
 
                                                macro_rules! clean_claim_request_after_safety_delay {
@@ -689,7 +766,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                                                                        txid: tx.txid(),
                                                                        height: conf_height,
                                                                        block_hash: Some(conf_hash),
-                                                                       event: OnchainEvent::Claim { claim_request: first_claim_txid_height.0.clone() }
+                                                                       event: OnchainEvent::Claim { claim_request: Txid::from_inner(first_claim_txid_height.0) }
                                                                };
                                                                if !self.onchain_events_awaiting_threshold_conf.contains(&entry) {
                                                                        self.onchain_events_awaiting_threshold_conf.push(entry);
@@ -700,7 +777,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                                                // If this is our transaction (or our counterparty spent all the outputs
                                                // before we could anyway with same inputs order than us), wait for
                                                // ANTI_REORG_DELAY and clean the RBF tracking map.
-                                               if set_equality {
+                                               if are_sets_equal {
                                                        clean_claim_request_after_safety_delay!();
                                                } else { // If false, generate new claim request with update outpoint set
                                                        let mut at_least_one_drop = false;
@@ -745,14 +822,15 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                        if entry.has_reached_confirmation_threshold(cur_height) {
                                match entry.event {
                                        OnchainEvent::Claim { claim_request } => {
+                                               let package_id = claim_request.into_inner();
                                                // We may remove a whole set of claim outpoints here, as these one may have
                                                // been aggregated in a single tx and claimed so atomically
-                                               if let Some(request) = self.pending_claim_requests.remove(&claim_request) {
+                                               if let Some(request) = self.pending_claim_requests.remove(&package_id) {
                                                        for outpoint in request.outpoints() {
                                                                log_debug!(logger, "Removing claim tracking for {} due to maturation of claim tx {}.", outpoint, claim_request);
                                                                self.claimable_outpoints.remove(&outpoint);
                                                                #[cfg(anchors)]
-                                                               self.pending_claim_events.remove(&claim_request);
+                                                               self.pending_claim_events.remove(&package_id);
                                                        }
                                                }
                                        },
@@ -985,6 +1063,37 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
                htlc_tx
        }
 
+       #[cfg(anchors)]
+       pub(crate) fn generate_external_htlc_claim(
+               &mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>
+       ) -> Option<ExternalHTLCClaim> {
+               let find_htlc = |holder_commitment: &HolderCommitmentTransaction| -> Option<ExternalHTLCClaim> {
+                       let trusted_tx = holder_commitment.trust();
+                       if outp.txid != trusted_tx.txid() {
+                               return None;
+                       }
+                       trusted_tx.htlcs().iter().enumerate()
+                               .find(|(_, htlc)| if let Some(output_index) = htlc.transaction_output_index {
+                                       output_index == outp.vout
+                               } else {
+                                       false
+                               })
+                               .map(|(htlc_idx, htlc)| {
+                                       let counterparty_htlc_sig = holder_commitment.counterparty_htlc_sigs[htlc_idx];
+                                       ExternalHTLCClaim {
+                                               commitment_txid: trusted_tx.txid(),
+                                               per_commitment_number: trusted_tx.commitment_number(),
+                                               htlc: htlc.clone(),
+                                               preimage: *preimage,
+                                               counterparty_sig: counterparty_htlc_sig,
+                                       }
+                               })
+               };
+               // Check if the HTLC spends from the current holder commitment or the previous one otherwise.
+               find_htlc(&self.holder_commitment)
+                       .or_else(|| self.prev_holder_commitment.as_ref().map(|c| find_htlc(c)).flatten())
+       }
+
        pub(crate) fn opt_anchors(&self) -> bool {
                self.channel_transaction_parameters.opt_anchors.is_some()
        }
index 1307ad0eb3f1a23bc7eed7f613eb61900cbbcb64..dbf46298888ce20a8225c6a11bd88e1394c2552e 100644 (file)
@@ -26,8 +26,9 @@ use crate::ln::chan_utils;
 use crate::ln::msgs::DecodeError;
 use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT};
 use crate::chain::keysinterface::Sign;
+#[cfg(anchors)]
+use crate::chain::onchaintx::ExternalHTLCClaim;
 use crate::chain::onchaintx::OnchainTxHandler;
-use crate::util::byte_utils;
 use crate::util::logger::Logger;
 use crate::util::ser::{Readable, Writer, Writeable};
 
@@ -253,33 +254,41 @@ impl_writeable_tlv_based!(CounterpartyReceivedHTLCOutput, {
 #[derive(Clone, PartialEq, Eq)]
 pub(crate) struct HolderHTLCOutput {
        preimage: Option<PaymentPreimage>,
-       amount: u64,
+       amount_msat: u64,
        /// Defaults to 0 for HTLC-Success transactions, which have no expiry
        cltv_expiry: u32,
+       opt_anchors: Option<()>,
 }
 
 impl HolderHTLCOutput {
-       pub(crate) fn build_offered(amount: u64, cltv_expiry: u32) -> Self {
+       pub(crate) fn build_offered(amount_msat: u64, cltv_expiry: u32, opt_anchors: bool) -> Self {
                HolderHTLCOutput {
                        preimage: None,
-                       amount,
+                       amount_msat,
                        cltv_expiry,
+                       opt_anchors: if opt_anchors { Some(()) } else { None } ,
                }
        }
 
-       pub(crate) fn build_accepted(preimage: PaymentPreimage, amount: u64) -> Self {
+       pub(crate) fn build_accepted(preimage: PaymentPreimage, amount_msat: u64, opt_anchors: bool) -> Self {
                HolderHTLCOutput {
                        preimage: Some(preimage),
-                       amount,
+                       amount_msat,
                        cltv_expiry: 0,
+                       opt_anchors: if opt_anchors { Some(()) } else { None } ,
                }
        }
+
+       fn opt_anchors(&self) -> bool {
+               self.opt_anchors.is_some()
+       }
 }
 
 impl_writeable_tlv_based!(HolderHTLCOutput, {
-       (0, amount, required),
+       (0, amount_msat, required),
        (2, cltv_expiry, required),
-       (4, preimage, option)
+       (4, preimage, option),
+       (6, opt_anchors, option)
 });
 
 /// A struct to describe the channel output on the funding transaction.
@@ -334,10 +343,10 @@ impl PackageSolvingData {
                        PackageSolvingData::RevokedHTLCOutput(ref outp) => outp.amount,
                        PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => outp.htlc.amount_msat / 1000,
                        PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => outp.htlc.amount_msat / 1000,
-                       // Note: Currently, amounts of holder outputs spending witnesses aren't used
-                       // as we can't malleate spending package to increase their feerate. This
-                       // should change with the remaining anchor output patchset.
-                       PackageSolvingData::HolderHTLCOutput(..) => unreachable!(),
+                       PackageSolvingData::HolderHTLCOutput(ref outp) => {
+                               debug_assert!(outp.opt_anchors());
+                               outp.amount_msat / 1000
+                       },
                        PackageSolvingData::HolderFundingOutput(ref outp) => {
                                debug_assert!(outp.opt_anchors());
                                outp.funding_amount.unwrap()
@@ -346,18 +355,23 @@ impl PackageSolvingData {
                amt
        }
        fn weight(&self) -> usize {
-               let weight = match self {
-                       PackageSolvingData::RevokedOutput(ref outp) => { outp.weight as usize },
-                       PackageSolvingData::RevokedHTLCOutput(ref outp) => { outp.weight as usize },
-                       PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => { weight_offered_htlc(outp.opt_anchors()) as usize },
-                       PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => { weight_received_htlc(outp.opt_anchors()) as usize },
-                       // Note: Currently, weights of holder outputs spending witnesses aren't used
-                       // as we can't malleate spending package to increase their feerate. This
-                       // should change with the remaining anchor output patchset.
-                       PackageSolvingData::HolderHTLCOutput(..) => { unreachable!() },
-                       PackageSolvingData::HolderFundingOutput(..) => { unreachable!() },
-               };
-               weight
+               match self {
+                       PackageSolvingData::RevokedOutput(ref outp) => outp.weight as usize,
+                       PackageSolvingData::RevokedHTLCOutput(ref outp) => outp.weight as usize,
+                       PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => weight_offered_htlc(outp.opt_anchors()) as usize,
+                       PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => weight_received_htlc(outp.opt_anchors()) as usize,
+                       PackageSolvingData::HolderHTLCOutput(ref outp) => {
+                               debug_assert!(outp.opt_anchors());
+                               if outp.preimage.is_none() {
+                                       weight_offered_htlc(true) as usize
+                               } else {
+                                       weight_received_htlc(true) as usize
+                               }
+                       },
+                       // Since HolderFundingOutput maps to an untractable package that is already signed, its
+                       // weight can be determined from the transaction itself.
+                       PackageSolvingData::HolderFundingOutput(..) => unreachable!(),
+               }
        }
        fn is_compatible(&self, input: &PackageSolvingData) -> bool {
                match self {
@@ -381,57 +395,53 @@ impl PackageSolvingData {
        fn finalize_input<Signer: Sign>(&self, bumped_tx: &mut Transaction, i: usize, onchain_handler: &mut OnchainTxHandler<Signer>) -> bool {
                match self {
                        PackageSolvingData::RevokedOutput(ref outp) => {
-                               if let Ok(chan_keys) = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint) {
-                                       let witness_script = chan_utils::get_revokeable_redeemscript(&chan_keys.revocation_key, outp.on_counterparty_tx_csv, &chan_keys.broadcaster_delayed_payment_key);
-                                       //TODO: should we panic on signer failure ?
-                                       if let Ok(sig) = onchain_handler.signer.sign_justice_revoked_output(&bumped_tx, i, outp.amount, &outp.per_commitment_key, &onchain_handler.secp_ctx) {
-                                               let mut ser_sig = sig.serialize_der().to_vec();
-                                               ser_sig.push(EcdsaSighashType::All as u8);
-                                               bumped_tx.input[i].witness.push(ser_sig);
-                                               bumped_tx.input[i].witness.push(vec!(1));
-                                               bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
-                                       } else { return false; }
-                               }
+                               let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
+                               let witness_script = chan_utils::get_revokeable_redeemscript(&chan_keys.revocation_key, outp.on_counterparty_tx_csv, &chan_keys.broadcaster_delayed_payment_key);
+                               //TODO: should we panic on signer failure ?
+                               if let Ok(sig) = onchain_handler.signer.sign_justice_revoked_output(&bumped_tx, i, outp.amount, &outp.per_commitment_key, &onchain_handler.secp_ctx) {
+                                       let mut ser_sig = sig.serialize_der().to_vec();
+                                       ser_sig.push(EcdsaSighashType::All as u8);
+                                       bumped_tx.input[i].witness.push(ser_sig);
+                                       bumped_tx.input[i].witness.push(vec!(1));
+                                       bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
+                               } else { return false; }
                        },
                        PackageSolvingData::RevokedHTLCOutput(ref outp) => {
-                               if let Ok(chan_keys) = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint) {
-                                       let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, onchain_handler.opt_anchors(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);
-                                       //TODO: should we panic on signer failure ?
-                                       if let Ok(sig) = onchain_handler.signer.sign_justice_revoked_htlc(&bumped_tx, i, outp.amount, &outp.per_commitment_key, &outp.htlc, &onchain_handler.secp_ctx) {
-                                               let mut ser_sig = sig.serialize_der().to_vec();
-                                               ser_sig.push(EcdsaSighashType::All as u8);
-                                               bumped_tx.input[i].witness.push(ser_sig);
-                                               bumped_tx.input[i].witness.push(chan_keys.revocation_key.clone().serialize().to_vec());
-                                               bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
-                                       } else { return false; }
-                               }
+                               let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
+                               let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, onchain_handler.opt_anchors(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);
+                               //TODO: should we panic on signer failure ?
+                               if let Ok(sig) = onchain_handler.signer.sign_justice_revoked_htlc(&bumped_tx, i, outp.amount, &outp.per_commitment_key, &outp.htlc, &onchain_handler.secp_ctx) {
+                                       let mut ser_sig = sig.serialize_der().to_vec();
+                                       ser_sig.push(EcdsaSighashType::All as u8);
+                                       bumped_tx.input[i].witness.push(ser_sig);
+                                       bumped_tx.input[i].witness.push(chan_keys.revocation_key.clone().serialize().to_vec());
+                                       bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
+                               } else { return false; }
                        },
                        PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => {
-                               if let Ok(chan_keys) = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint) {
-                                       let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, onchain_handler.opt_anchors(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);
-
-                                       if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
-                                               let mut ser_sig = sig.serialize_der().to_vec();
-                                               ser_sig.push(EcdsaSighashType::All as u8);
-                                               bumped_tx.input[i].witness.push(ser_sig);
-                                               bumped_tx.input[i].witness.push(outp.preimage.0.to_vec());
-                                               bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
-                                       }
+                               let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
+                               let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, onchain_handler.opt_anchors(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);
+
+                               if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
+                                       let mut ser_sig = sig.serialize_der().to_vec();
+                                       ser_sig.push(EcdsaSighashType::All as u8);
+                                       bumped_tx.input[i].witness.push(ser_sig);
+                                       bumped_tx.input[i].witness.push(outp.preimage.0.to_vec());
+                                       bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
                                }
                        },
                        PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => {
-                               if let Ok(chan_keys) = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint) {
-                                       let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, onchain_handler.opt_anchors(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);
-
-                                       bumped_tx.lock_time = PackedLockTime(outp.htlc.cltv_expiry); // Right now we don't aggregate time-locked transaction, if we do we should set lock_time before to avoid breaking hash computation
-                                       if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
-                                               let mut ser_sig = sig.serialize_der().to_vec();
-                                               ser_sig.push(EcdsaSighashType::All as u8);
-                                               bumped_tx.input[i].witness.push(ser_sig);
-                                               // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
-                                               bumped_tx.input[i].witness.push(vec![]);
-                                               bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
-                                       }
+                               let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
+                               let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, onchain_handler.opt_anchors(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);
+
+                               bumped_tx.lock_time = PackedLockTime(outp.htlc.cltv_expiry); // Right now we don't aggregate time-locked transaction, if we do we should set lock_time before to avoid breaking hash computation
+                               if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
+                                       let mut ser_sig = sig.serialize_der().to_vec();
+                                       ser_sig.push(EcdsaSighashType::All as u8);
+                                       bumped_tx.input[i].witness.push(ser_sig);
+                                       // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
+                                       bumped_tx.input[i].witness.push(vec![]);
+                                       bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
                                }
                        },
                        _ => { panic!("API Error!"); }
@@ -440,8 +450,13 @@ impl PackageSolvingData {
        }
        fn get_finalized_tx<Signer: Sign>(&self, outpoint: &BitcoinOutPoint, onchain_handler: &mut OnchainTxHandler<Signer>) -> Option<Transaction> {
                match self {
-                       PackageSolvingData::HolderHTLCOutput(ref outp) => { return onchain_handler.get_fully_signed_htlc_tx(outpoint, &outp.preimage); }
-                       PackageSolvingData::HolderFundingOutput(ref outp) => { return Some(onchain_handler.get_fully_signed_holder_tx(&outp.funding_redeemscript)); }
+                       PackageSolvingData::HolderHTLCOutput(ref outp) => {
+                               debug_assert!(!outp.opt_anchors());
+                               return onchain_handler.get_fully_signed_htlc_tx(outpoint, &outp.preimage);
+                       }
+                       PackageSolvingData::HolderFundingOutput(ref outp) => {
+                               return Some(onchain_handler.get_fully_signed_holder_tx(&outp.funding_redeemscript));
+                       }
                        _ => { panic!("API Error!"); }
                }
        }
@@ -641,6 +656,25 @@ impl PackageTemplate {
                let output_weight = (8 + 1 + destination_script.len()) * WITNESS_SCALE_FACTOR;
                inputs_weight + witnesses_weight + transaction_weight + output_weight
        }
+       #[cfg(anchors)]
+       pub(crate) fn construct_malleable_package_with_external_funding<Signer: Sign>(
+               &self, onchain_handler: &mut OnchainTxHandler<Signer>,
+       ) -> Option<Vec<ExternalHTLCClaim>> {
+               debug_assert!(self.requires_external_funding());
+               let mut htlcs: Option<Vec<ExternalHTLCClaim>> = None;
+               for (previous_output, input) in &self.inputs {
+                       match input {
+                               PackageSolvingData::HolderHTLCOutput(ref outp) => {
+                                       debug_assert!(outp.opt_anchors());
+                                       onchain_handler.generate_external_htlc_claim(&previous_output, &outp.preimage).map(|htlc| {
+                                               htlcs.get_or_insert_with(|| Vec::with_capacity(self.inputs.len())).push(htlc);
+                                       });
+                               }
+                               _ => debug_assert!(false, "Expected HolderHTLCOutputs to not be aggregated with other input types"),
+                       }
+               }
+               htlcs
+       }
        pub(crate) fn finalize_malleable_package<L: Deref, Signer: Sign>(
                &self, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64, destination_script: Script, logger: &L
        ) -> Option<Transaction> where L::Target: Logger {
@@ -745,6 +779,7 @@ impl PackageTemplate {
        pub(crate) fn requires_external_funding(&self) -> bool {
                self.inputs.iter().find(|input| match input.1 {
                        PackageSolvingData::HolderFundingOutput(ref outp) => outp.opt_anchors(),
+                       PackageSolvingData::HolderHTLCOutput(ref outp) => outp.opt_anchors(),
                        _ => false,
                }).is_some()
        }
@@ -755,7 +790,11 @@ impl PackageTemplate {
                        PackageSolvingData::RevokedHTLCOutput(..) => PackageMalleability::Malleable,
                        PackageSolvingData::CounterpartyOfferedHTLCOutput(..) => PackageMalleability::Malleable,
                        PackageSolvingData::CounterpartyReceivedHTLCOutput(..) => PackageMalleability::Malleable,
-                       PackageSolvingData::HolderHTLCOutput(..) => PackageMalleability::Untractable,
+                       PackageSolvingData::HolderHTLCOutput(ref outp) => if outp.opt_anchors() {
+                               PackageMalleability::Malleable
+                       } else {
+                               PackageMalleability::Untractable
+                       },
                        PackageSolvingData::HolderFundingOutput(..) => PackageMalleability::Untractable,
                };
                let mut inputs = Vec::with_capacity(1);
@@ -774,7 +813,7 @@ impl PackageTemplate {
 
 impl Writeable for PackageTemplate {
        fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
-               writer.write_all(&byte_utils::be64_to_array(self.inputs.len() as u64))?;
+               writer.write_all(&(self.inputs.len() as u64).to_be_bytes())?;
                for (ref outpoint, ref rev_outp) in self.inputs.iter() {
                        outpoint.write(writer)?;
                        rev_outp.write(writer)?;
@@ -804,7 +843,11 @@ impl Readable for PackageTemplate {
                                PackageSolvingData::RevokedHTLCOutput(..) => { (PackageMalleability::Malleable, true) },
                                PackageSolvingData::CounterpartyOfferedHTLCOutput(..) => { (PackageMalleability::Malleable, true) },
                                PackageSolvingData::CounterpartyReceivedHTLCOutput(..) => { (PackageMalleability::Malleable, false) },
-                               PackageSolvingData::HolderHTLCOutput(..) => { (PackageMalleability::Untractable, false) },
+                               PackageSolvingData::HolderHTLCOutput(ref outp) => if outp.opt_anchors() {
+                                       (PackageMalleability::Malleable, outp.preimage.is_some())
+                               } else {
+                                       (PackageMalleability::Untractable, false)
+                               },
                                PackageSolvingData::HolderFundingOutput(..) => { (PackageMalleability::Untractable, false) },
                        }
                } else { return Err(DecodeError::InvalidValue); };
@@ -964,7 +1007,7 @@ mod tests {
                () => {
                        {
                                let preimage = PaymentPreimage([2;32]);
-                               PackageSolvingData::HolderHTLCOutput(HolderHTLCOutput::build_accepted(preimage, 0))
+                               PackageSolvingData::HolderHTLCOutput(HolderHTLCOutput::build_accepted(preimage, 0, false))
                        }
                }
        }
index 7fc817995fbdba393809c73c264e6e010a5e27c0..729425d70d5bd705bfe65e345567794c8381e64e 100644 (file)
@@ -24,11 +24,10 @@ use bitcoin::hash_types::{Txid, PubkeyHash};
 use crate::ln::{PaymentHash, PaymentPreimage};
 use crate::ln::msgs::DecodeError;
 use crate::util::ser::{Readable, Writeable, Writer};
-use crate::util::{byte_utils, transaction_utils};
+use crate::util::transaction_utils;
 
 use bitcoin::secp256k1::{SecretKey, PublicKey, Scalar};
 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Message};
-use bitcoin::secp256k1::Error as SecpError;
 use bitcoin::{PackedLockTime, secp256k1, Sequence, Witness};
 use bitcoin::PublicKey as BitcoinPublicKey;
 
@@ -310,7 +309,7 @@ impl Writeable for CounterpartyCommitmentSecrets {
        fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
                for &(ref secret, ref idx) in self.old_secrets.iter() {
                        writer.write_all(secret)?;
-                       writer.write_all(&byte_utils::be64_to_array(*idx))?;
+                       writer.write_all(&idx.to_be_bytes())?;
                }
                write_tlv_fields!(writer, {});
                Ok(())
@@ -330,32 +329,29 @@ impl Readable for CounterpartyCommitmentSecrets {
 
 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
 /// from the base secret and the per_commitment_point.
-///
-/// Note that this is infallible iff we trust that at least one of the two input keys are randomly
-/// generated (ie our own).
-pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> Result<SecretKey, SecpError> {
+pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> SecretKey {
        let mut sha = Sha256::engine();
        sha.input(&per_commitment_point.serialize());
        sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
        let res = Sha256::from_engine(sha).into_inner();
 
        base_secret.clone().add_tweak(&Scalar::from_be_bytes(res).unwrap())
+               .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak contains the hash of the key.")
 }
 
 /// Derives a per-commitment-transaction public key (eg an htlc key or a delayed_payment key)
 /// from the base point and the per_commitment_key. This is the public equivalent of
 /// derive_private_key - using only public keys to derive a public key instead of private keys.
-///
-/// Note that this is infallible iff we trust that at least one of the two input keys are randomly
-/// generated (ie our own).
-pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> Result<PublicKey, SecpError> {
+pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> PublicKey {
        let mut sha = Sha256::engine();
        sha.input(&per_commitment_point.serialize());
        sha.input(&base_point.serialize());
        let res = Sha256::from_engine(sha).into_inner();
 
-       let hashkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&res)?);
+       let hashkey = PublicKey::from_secret_key(&secp_ctx,
+               &SecretKey::from_slice(&res).expect("Hashes should always be valid keys unless SHA-256 is broken"));
        base_point.combine(&hashkey)
+               .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak contains the hash of the key.")
 }
 
 /// Derives a per-commitment-transaction revocation key from its constituent parts.
@@ -364,10 +360,9 @@ pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_com
 /// commitment transaction, thus per_commitment_secret always come from cheater
 /// and revocation_base_secret always come from punisher, which is the broadcaster
 /// of the transaction spending with this key knowledge.
-///
-/// Note that this is infallible iff we trust that at least one of the two input keys are randomly
-/// generated (ie our own).
-pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey) -> Result<SecretKey, SecpError> {
+pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>,
+       per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey)
+-> SecretKey {
        let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
        let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
 
@@ -386,9 +381,12 @@ pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1
                Sha256::from_engine(sha).into_inner()
        };
 
-       let countersignatory_contrib = countersignatory_revocation_base_secret.clone().mul_tweak(&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())?;
-       let broadcaster_contrib = per_commitment_secret.clone().mul_tweak(&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())?;
+       let countersignatory_contrib = countersignatory_revocation_base_secret.clone().mul_tweak(&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
+               .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
+       let broadcaster_contrib = per_commitment_secret.clone().mul_tweak(&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
+               .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
        countersignatory_contrib.add_tweak(&Scalar::from_be_bytes(broadcaster_contrib.secret_bytes()).unwrap())
+               .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
 }
 
 /// Derives a per-commitment-transaction revocation public key from its constituent parts. This is
@@ -402,7 +400,9 @@ pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1
 ///
 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
 /// generated (ie our own).
-pub fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, countersignatory_revocation_base_point: &PublicKey) -> Result<PublicKey, SecpError> {
+pub fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>,
+       per_commitment_point: &PublicKey, countersignatory_revocation_base_point: &PublicKey)
+-> PublicKey {
        let rev_append_commit_hash_key = {
                let mut sha = Sha256::engine();
                sha.input(&countersignatory_revocation_base_point.serialize());
@@ -418,9 +418,12 @@ pub fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp2
                Sha256::from_engine(sha).into_inner()
        };
 
-       let countersignatory_contrib = countersignatory_revocation_base_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())?;
-       let broadcaster_contrib = per_commitment_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())?;
+       let countersignatory_contrib = countersignatory_revocation_base_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
+               .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
+       let broadcaster_contrib = per_commitment_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
+               .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
        countersignatory_contrib.combine(&broadcaster_contrib)
+               .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
 }
 
 /// The set of public keys which are used in the creation of one commitment transaction.
@@ -459,7 +462,7 @@ impl_writeable_tlv_based!(TxCreationKeys, {
 });
 
 /// One counterparty's public keys which do not change over the life of a channel.
-#[derive(Clone, PartialEq, Eq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
 pub struct ChannelPublicKeys {
        /// The public key which is used to sign all commitment transactions, as it appears in the
        /// on-chain channel lock-in 2-of-2 multisig output.
@@ -493,19 +496,19 @@ impl_writeable_tlv_based!(ChannelPublicKeys, {
 impl TxCreationKeys {
        /// Create per-state keys from channel base points and the per-commitment point.
        /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
-       pub fn derive_new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, broadcaster_delayed_payment_base: &PublicKey, broadcaster_htlc_base: &PublicKey, countersignatory_revocation_base: &PublicKey, countersignatory_htlc_base: &PublicKey) -> Result<TxCreationKeys, SecpError> {
-               Ok(TxCreationKeys {
+       pub fn derive_new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, broadcaster_delayed_payment_base: &PublicKey, broadcaster_htlc_base: &PublicKey, countersignatory_revocation_base: &PublicKey, countersignatory_htlc_base: &PublicKey) -> TxCreationKeys {
+               TxCreationKeys {
                        per_commitment_point: per_commitment_point.clone(),
-                       revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &countersignatory_revocation_base)?,
-                       broadcaster_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_htlc_base)?,
-                       countersignatory_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &countersignatory_htlc_base)?,
-                       broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base)?,
-               })
+                       revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &countersignatory_revocation_base),
+                       broadcaster_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_htlc_base),
+                       countersignatory_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &countersignatory_htlc_base),
+                       broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base),
+               }
        }
 
        /// Generate per-state keys from channel static keys.
        /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
-       pub fn from_channel_static_keys<T: secp256k1::Signing + secp256k1::Verification>(per_commitment_point: &PublicKey, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TxCreationKeys, SecpError> {
+       pub fn from_channel_static_keys<T: secp256k1::Signing + secp256k1::Verification>(per_commitment_point: &PublicKey, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> TxCreationKeys {
                TxCreationKeys::derive_new(
                        &secp_ctx,
                        &per_commitment_point,
@@ -676,7 +679,24 @@ pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &Pub
 /// commitment transaction).
 pub fn build_htlc_transaction(commitment_txid: &Txid, feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, opt_anchors: bool, use_non_zero_fee_anchors: bool, broadcaster_delayed_payment_key: &PublicKey, revocation_key: &PublicKey) -> Transaction {
        let mut txins: Vec<TxIn> = Vec::new();
-       txins.push(TxIn {
+       txins.push(build_htlc_input(commitment_txid, htlc, opt_anchors));
+
+       let mut txouts: Vec<TxOut> = Vec::new();
+       txouts.push(build_htlc_output(
+               feerate_per_kw, contest_delay, htlc, opt_anchors, use_non_zero_fee_anchors,
+               broadcaster_delayed_payment_key, revocation_key
+       ));
+
+       Transaction {
+               version: 2,
+               lock_time: PackedLockTime(if htlc.offered { htlc.cltv_expiry } else { 0 }),
+               input: txins,
+               output: txouts,
+       }
+}
+
+pub(crate) fn build_htlc_input(commitment_txid: &Txid, htlc: &HTLCOutputInCommitment, opt_anchors: bool) -> TxIn {
+       TxIn {
                previous_output: OutPoint {
                        txid: commitment_txid.clone(),
                        vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
@@ -684,8 +704,13 @@ pub fn build_htlc_transaction(commitment_txid: &Txid, feerate_per_kw: u32, conte
                script_sig: Script::new(),
                sequence: Sequence(if opt_anchors { 1 } else { 0 }),
                witness: Witness::new(),
-       });
+       }
+}
 
+pub(crate) fn build_htlc_output(
+       feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, opt_anchors: bool,
+       use_non_zero_fee_anchors: bool, broadcaster_delayed_payment_key: &PublicKey, revocation_key: &PublicKey
+) -> TxOut {
        let weight = if htlc.offered {
                htlc_timeout_tx_weight(opt_anchors)
        } else {
@@ -698,18 +723,41 @@ pub fn build_htlc_transaction(commitment_txid: &Txid, feerate_per_kw: u32, conte
                htlc.amount_msat / 1000 - total_fee
        };
 
-       let mut txouts: Vec<TxOut> = Vec::new();
-       txouts.push(TxOut {
+       TxOut {
                script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
                value: output_value,
-       });
+       }
+}
 
-       Transaction {
-               version: 2,
-               lock_time: PackedLockTime(if htlc.offered { htlc.cltv_expiry } else { 0 }),
-               input: txins,
-               output: txouts,
+/// Returns the witness required to satisfy and spend a HTLC input.
+pub fn build_htlc_input_witness(
+       local_sig: &Signature, remote_sig: &Signature, preimage: &Option<PaymentPreimage>,
+       redeem_script: &Script, opt_anchors: bool,
+) -> Witness {
+       let remote_sighash_type = if opt_anchors {
+               EcdsaSighashType::SinglePlusAnyoneCanPay
+       } else {
+               EcdsaSighashType::All
+       };
+       let mut remote_sig = remote_sig.serialize_der().to_vec();
+       remote_sig.push(remote_sighash_type as u8);
+
+       let mut local_sig = local_sig.serialize_der().to_vec();
+       local_sig.push(EcdsaSighashType::All as u8);
+
+       let mut witness = Witness::new();
+       // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
+       witness.push(vec![]);
+       witness.push(remote_sig);
+       witness.push(local_sig);
+       if let Some(preimage) = preimage {
+               witness.push(preimage.0.to_vec());
+       } else {
+               // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
+               witness.push(vec![]);
        }
+       witness.push(redeem_script.to_bytes());
+       witness
 }
 
 /// Gets the witnessScript for the to_remote output when anchors are enabled.
@@ -763,7 +811,7 @@ pub fn build_anchor_input_witness(funding_key: &PublicKey, funding_sig: &Signatu
 ///
 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
-#[derive(Clone)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct ChannelTransactionParameters {
        /// Holder public keys
        pub holder_pubkeys: ChannelPublicKeys,
@@ -787,7 +835,7 @@ pub struct ChannelTransactionParameters {
 }
 
 /// Late-bound per-channel counterparty data used to build transactions.
-#[derive(Clone)]
+#[derive(Clone, Debug, PartialEq)]
 pub struct CounterpartyChannelTransactionParameters {
        /// Counter-party public keys
        pub pubkeys: ChannelPublicKeys,
@@ -1460,7 +1508,7 @@ impl CommitmentTransaction {
        pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
                // This is the only field of the key cache that we trust
                let per_commitment_point = self.keys.per_commitment_point;
-               let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx).unwrap();
+               let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx);
                if keys != self.keys {
                        return Err(());
                }
@@ -1520,7 +1568,7 @@ impl<'a> TrustedCommitmentTransaction<'a> {
                let keys = &inner.keys;
                let txid = inner.built.txid;
                let mut ret = Vec::with_capacity(inner.htlcs.len());
-               let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key).map_err(|_| ())?;
+               let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key);
 
                for this_htlc in inner.htlcs.iter() {
                        assert!(this_htlc.transaction_output_index.is_some());
@@ -1550,26 +1598,9 @@ impl<'a> TrustedCommitmentTransaction<'a> {
 
                let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, self.opt_anchors(), &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
 
-               let sighashtype = if self.opt_anchors() { EcdsaSighashType::SinglePlusAnyoneCanPay } else { EcdsaSighashType::All };
-
-               // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
-               htlc_tx.input[0].witness.push(Vec::new());
-
-               let mut cp_sig_ser = counterparty_signature.serialize_der().to_vec();
-               cp_sig_ser.push(sighashtype as u8);
-               htlc_tx.input[0].witness.push(cp_sig_ser);
-               let mut holder_sig_ser = signature.serialize_der().to_vec();
-               holder_sig_ser.push(EcdsaSighashType::All as u8);
-               htlc_tx.input[0].witness.push(holder_sig_ser);
-
-               if this_htlc.offered {
-                       // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
-                       htlc_tx.input[0].witness.push(Vec::new());
-               } else {
-                       htlc_tx.input[0].witness.push(preimage.unwrap().0.to_vec());
-               }
-
-               htlc_tx.input[0].witness.push(htlc_redeemscript.as_bytes().to_vec());
+               htlc_tx.input[0].witness = chan_utils::build_htlc_input_witness(
+                       signature, counterparty_signature, preimage, &htlc_redeemscript, self.opt_anchors(),
+               );
                htlc_tx
        }
 }
@@ -1627,15 +1658,15 @@ mod tests {
                let seed = [42; 32];
                let network = Network::Testnet;
                let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
-               let signer = keys_provider.get_channel_signer(false, 3000);
-               let counterparty_signer = keys_provider.get_channel_signer(false, 3000);
+               let signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(false, 1_000_000, 0));
+               let counterparty_signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(true, 1_000_000, 1));
                let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
                let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
                let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
                let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
                let holder_pubkeys = signer.pubkeys();
                let counterparty_pubkeys = counterparty_signer.pubkeys();
-               let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint).unwrap();
+               let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint);
                let mut channel_parameters = ChannelTransactionParameters {
                        holder_pubkeys: holder_pubkeys.clone(),
                        holder_selected_contest_delay: 0,
@@ -1724,9 +1755,9 @@ mod tests {
                assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, false, &keys).to_v0_p2wsh());
                assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, false, &keys).to_v0_p2wsh());
                assert_eq!(get_htlc_redeemscript(&received_htlc, false, &keys).to_v0_p2wsh().to_hex(),
-                                  "002085cf52e41ba7c099a39df504e7b61f6de122971ceb53b06731876eaeb85e8dc5");
+                                  "0020e43a7c068553003fe68fcae424fb7b28ec5ce48cd8b6744b3945631389bad2fb");
                assert_eq!(get_htlc_redeemscript(&offered_htlc, false, &keys).to_v0_p2wsh().to_hex(),
-                                  "002049f0736bb335c61a04d2623a24df878a7592a3c51fa7258d41b2c85318265e73");
+                                  "0020215d61bba56b19e9eadb6107f5a85d7f99c40f65992443f69229c290165bc00d");
 
                // Generate broadcaster output and received and offered HTLC outputs,  with anchors
                channel_parameters.opt_anchors = Some(());
@@ -1743,9 +1774,9 @@ mod tests {
                assert_eq!(tx.built.transaction.output[2].script_pubkey, get_htlc_redeemscript(&received_htlc, true, &keys).to_v0_p2wsh());
                assert_eq!(tx.built.transaction.output[3].script_pubkey, get_htlc_redeemscript(&offered_htlc, true, &keys).to_v0_p2wsh());
                assert_eq!(get_htlc_redeemscript(&received_htlc, true, &keys).to_v0_p2wsh().to_hex(),
-                                  "002067114123af3f95405bae4fd930fc95de03e3c86baaee8b2dd29b43dd26cf613c");
+                                  "0020b70d0649c72b38756885c7a30908d912a7898dd5d79457a7280b8e9a20f3f2bc");
                assert_eq!(get_htlc_redeemscript(&offered_htlc, true, &keys).to_v0_p2wsh().to_hex(),
-                                  "0020a06e3b0d4fcf704f2b9c41e16a70099e39989466c3142b8573a1154542f28f57");
+                                  "002087a3faeb1950a469c0e2db4a79b093a41b9526e5a6fc6ef5cb949bde3be379c7");
        }
 
        #[test]
index b1b6b79712dc75fad8ccd2e2a2126dc1cf3f9d16..2721cc81e509b5c93f5d99095b8fb90b51b6c6cf 100644 (file)
@@ -112,7 +112,7 @@ fn test_monitor_and_persister_update_fail() {
                let mut w = test_utils::TestVecWriter(Vec::new());
                monitor.write(&mut w).unwrap();
                let new_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
-                       &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
+                       &mut io::Cursor::new(&w.0), nodes[0].keys_manager).unwrap().1;
                assert!(new_monitor == *monitor);
                let chain_mon = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
                assert_eq!(chain_mon.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
@@ -200,7 +200,7 @@ fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
        let events_3 = nodes[1].node.get_and_clear_pending_events();
        assert_eq!(events_3.len(), 1);
        match events_3[0] {
-               Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
+               Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
                        assert_eq!(payment_hash_1, *payment_hash);
                        assert_eq!(amount_msat, 1_000_000);
                        assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
@@ -569,7 +569,7 @@ fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
        let events_5 = nodes[1].node.get_and_clear_pending_events();
        assert_eq!(events_5.len(), 1);
        match events_5[0] {
-               Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
+               Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
                        assert_eq!(payment_hash_2, *payment_hash);
                        assert_eq!(amount_msat, 1_000_000);
                        assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
@@ -686,7 +686,7 @@ fn test_monitor_update_fail_cs() {
        let events = nodes[1].node.get_and_clear_pending_events();
        assert_eq!(events.len(), 1);
        match events[0] {
-               Event::PaymentReceived { payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
+               Event::PaymentClaimable { payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
                        assert_eq!(payment_hash, our_payment_hash);
                        assert_eq!(amount_msat, 1_000_000);
                        assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
@@ -743,7 +743,7 @@ fn test_monitor_update_fail_no_rebroadcast() {
        let events = nodes[1].node.get_and_clear_pending_events();
        assert_eq!(events.len(), 1);
        match events[0] {
-               Event::PaymentReceived { payment_hash, .. } => {
+               Event::PaymentClaimable { payment_hash, .. } => {
                        assert_eq!(payment_hash, our_payment_hash);
                },
                _ => panic!("Unexpected event"),
@@ -814,12 +814,12 @@ fn test_monitor_update_raa_while_paused() {
        nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
        check_added_monitors!(nodes[0], 1);
        expect_pending_htlcs_forwardable!(nodes[0]);
-       expect_payment_received!(nodes[0], our_payment_hash_2, our_payment_secret_2, 1000000);
+       expect_payment_claimable!(nodes[0], our_payment_hash_2, our_payment_secret_2, 1000000);
 
        nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
        check_added_monitors!(nodes[1], 1);
        expect_pending_htlcs_forwardable!(nodes[1]);
-       expect_payment_received!(nodes[1], our_payment_hash_1, our_payment_secret_1, 1000000);
+       expect_payment_claimable!(nodes[1], our_payment_hash_1, our_payment_secret_1, 1000000);
 
        claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
        claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_2);
@@ -1049,11 +1049,11 @@ fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
        let events_6 = nodes[2].node.get_and_clear_pending_events();
        assert_eq!(events_6.len(), 2);
        match events_6[0] {
-               Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
+               Event::PaymentClaimable { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
                _ => panic!("Unexpected event"),
        };
        match events_6[1] {
-               Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_3); },
+               Event::PaymentClaimable { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_3); },
                _ => panic!("Unexpected event"),
        };
 
@@ -1072,7 +1072,7 @@ fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
                let events_9 = nodes[0].node.get_and_clear_pending_events();
                assert_eq!(events_9.len(), 1);
                match events_9[0] {
-                       Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
+                       Event::PaymentClaimable { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
                        _ => panic!("Unexpected event"),
                };
                claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
@@ -1240,7 +1240,7 @@ fn raa_no_response_awaiting_raa_state() {
        check_added_monitors!(nodes[1], 0);
        let bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
        expect_pending_htlcs_forwardable!(nodes[1]);
-       expect_payment_received!(nodes[1], payment_hash_1, payment_secret_1, 1000000);
+       expect_payment_claimable!(nodes[1], payment_hash_1, payment_secret_1, 1000000);
 
        // We send a third payment here, which is somewhat of a redundant test, but the
        // chanmon_fail_consistency test required it to actually find the bug (by seeing out-of-sync
@@ -1269,7 +1269,7 @@ fn raa_no_response_awaiting_raa_state() {
        nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
        check_added_monitors!(nodes[1], 1);
        expect_pending_htlcs_forwardable!(nodes[1]);
-       expect_payment_received!(nodes[1], payment_hash_2, payment_secret_2, 1000000);
+       expect_payment_claimable!(nodes[1], payment_hash_2, payment_secret_2, 1000000);
        let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
 
        nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
@@ -1282,7 +1282,7 @@ fn raa_no_response_awaiting_raa_state() {
        nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
        check_added_monitors!(nodes[1], 1);
        expect_pending_htlcs_forwardable!(nodes[1]);
-       expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 1000000);
+       expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 1000000);
 
        claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
        claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
@@ -1394,7 +1394,7 @@ fn claim_while_disconnected_monitor_update_fail() {
        check_added_monitors!(nodes[1], 1);
 
        expect_pending_htlcs_forwardable!(nodes[1]);
-       expect_payment_received!(nodes[1], payment_hash_2, payment_secret_2, 1000000);
+       expect_payment_claimable!(nodes[1], payment_hash_2, payment_secret_2, 1000000);
 
        nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
        check_added_monitors!(nodes[0], 1);
@@ -1469,7 +1469,7 @@ fn monitor_failed_no_reestablish_response() {
        check_added_monitors!(nodes[1], 1);
 
        expect_pending_htlcs_forwardable!(nodes[1]);
-       expect_payment_received!(nodes[1], payment_hash_1, payment_secret_1, 1000000);
+       expect_payment_claimable!(nodes[1], payment_hash_1, payment_secret_1, 1000000);
 
        claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
 }
@@ -1550,7 +1550,7 @@ fn first_message_on_recv_ordering() {
        check_added_monitors!(nodes[1], 0);
 
        expect_pending_htlcs_forwardable!(nodes[1]);
-       expect_payment_received!(nodes[1], payment_hash_1, payment_secret_1, 1000000);
+       expect_payment_claimable!(nodes[1], payment_hash_1, payment_secret_1, 1000000);
 
        let bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
        nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_responses.0);
@@ -1563,7 +1563,7 @@ fn first_message_on_recv_ordering() {
        check_added_monitors!(nodes[1], 1);
 
        expect_pending_htlcs_forwardable!(nodes[1]);
-       expect_payment_received!(nodes[1], payment_hash_2, payment_secret_2, 1000000);
+       expect_payment_claimable!(nodes[1], payment_hash_2, payment_secret_2, 1000000);
 
        claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
        claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
@@ -1652,7 +1652,7 @@ fn test_monitor_update_fail_claim() {
        let events = nodes[0].node.get_and_clear_pending_events();
        assert_eq!(events.len(), 2);
        match events[0] {
-               Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id } => {
+               Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id } => {
                        assert_eq!(payment_hash_2, *payment_hash);
                        assert_eq!(1_000_000, amount_msat);
                        assert_eq!(receiver_node_id.unwrap(), nodes[0].node.get_our_node_id());
@@ -1669,7 +1669,7 @@ fn test_monitor_update_fail_claim() {
                _ => panic!("Unexpected event"),
        }
        match events[1] {
-               Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
+               Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
                        assert_eq!(payment_hash_3, *payment_hash);
                        assert_eq!(1_000_000, amount_msat);
                        assert_eq!(receiver_node_id.unwrap(), nodes[0].node.get_our_node_id());
@@ -1750,7 +1750,7 @@ fn test_monitor_update_on_pending_forwards() {
                _ => panic!("Unexpected event"),
        };
        nodes[0].node.process_pending_htlc_forwards();
-       expect_payment_received!(nodes[0], payment_hash_2, payment_secret_2, 1000000);
+       expect_payment_claimable!(nodes[0], payment_hash_2, payment_secret_2, 1000000);
 
        claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_2);
 }
@@ -1799,7 +1799,7 @@ fn monitor_update_claim_fail_no_response() {
        nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
        check_added_monitors!(nodes[1], 1);
        expect_pending_htlcs_forwardable!(nodes[1]);
-       expect_payment_received!(nodes[1], payment_hash_2, payment_secret_2, 1000000);
+       expect_payment_claimable!(nodes[1], payment_hash_2, payment_secret_2, 1000000);
 
        let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
        nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
@@ -2073,7 +2073,7 @@ fn test_pending_update_fee_ack_on_reconnect() {
        check_added_monitors!(nodes[1], 1);
 
        expect_pending_htlcs_forwardable!(nodes[0]);
-       expect_payment_received!(nodes[0], payment_hash, payment_secret, 1_000_000);
+       expect_payment_claimable!(nodes[0], payment_hash, payment_secret, 1_000_000);
 
        claim_payment(&nodes[1], &[&nodes[0]], payment_preimage);
 }
@@ -2368,7 +2368,7 @@ fn do_channel_holding_cell_serialize(disconnect: bool, reload_a: bool) {
        let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
        nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
        expect_pending_htlcs_forwardable!(nodes[1]);
-       expect_payment_received!(nodes[1], payment_hash_1, payment_secret_1, 100000);
+       expect_payment_claimable!(nodes[1], payment_hash_1, payment_secret_1, 100000);
        check_added_monitors!(nodes[1], 1);
 
        commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
@@ -2385,7 +2385,7 @@ fn do_channel_holding_cell_serialize(disconnect: bool, reload_a: bool) {
        };
 
        nodes[1].node.process_pending_htlc_forwards();
-       expect_payment_received!(nodes[1], payment_hash_2, payment_secret_2, 100000);
+       expect_payment_claimable!(nodes[1], payment_hash_2, payment_secret_2, 100000);
 
        claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
        claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
index b28efad0b670eb6fba7c893b0eba8f7a21c06b9c..67e894a9d3526886ecfe5d2f1fd5c1b3375a5159 100644 (file)
@@ -27,14 +27,15 @@ use crate::ln::features::{ChannelTypeFeatures, InitFeatures};
 use crate::ln::msgs;
 use crate::ln::msgs::{DecodeError, OptionalField, DataLossProtect};
 use crate::ln::script::{self, ShutdownScript};
-use crate::ln::channelmanager::{self, CounterpartyForwardingInfo, PendingHTLCStatus, HTLCSource, HTLCFailReason, HTLCFailureMsg, PendingHTLCInfo, RAACommitmentOrder, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, MAX_LOCAL_BREAKDOWN_TIMEOUT};
+use crate::ln::channelmanager::{self, CounterpartyForwardingInfo, PendingHTLCStatus, HTLCSource, HTLCFailureMsg, PendingHTLCInfo, RAACommitmentOrder, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, MAX_LOCAL_BREAKDOWN_TIMEOUT};
 use crate::ln::chan_utils::{CounterpartyCommitmentSecrets, TxCreationKeys, HTLCOutputInCommitment, htlc_success_tx_weight, htlc_timeout_tx_weight, make_funding_redeemscript, ChannelPublicKeys, CommitmentTransaction, HolderCommitmentTransaction, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, MAX_HTLCS, get_commitment_transaction_number_obscure_factor, ClosingTransaction};
 use crate::ln::chan_utils;
+use crate::ln::onion_utils::HTLCFailReason;
 use crate::chain::BestBlock;
 use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, LowerBoundedFeeEstimator};
 use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, LATENCY_GRACE_PERIOD_BLOCKS};
 use crate::chain::transaction::{OutPoint, TransactionData};
-use crate::chain::keysinterface::{Sign, KeysInterface};
+use crate::chain::keysinterface::{Sign, KeysInterface, BaseSign};
 use crate::util::events::ClosureReason;
 use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer, VecWriter};
 use crate::util::logger::Logger;
@@ -737,6 +738,10 @@ pub(super) struct Channel<Signer: Sign> {
 
        // We track whether we already emitted a `ChannelReady` event.
        channel_ready_event_emitted: bool,
+
+       /// The unique identifier used to re-derive the private key material for the channel through
+       /// [`KeysInterface::derive_channel_signer`].
+       channel_keys_id: [u8; 32],
 }
 
 #[cfg(any(test, fuzzing))]
@@ -909,7 +914,8 @@ impl<Signer: Sign> Channel<Signer> {
                let opt_anchors = false; // TODO - should be based on features
 
                let holder_selected_contest_delay = config.channel_handshake_config.our_to_self_delay;
-               let holder_signer = keys_provider.get_channel_signer(false, channel_value_satoshis);
+               let channel_keys_id = keys_provider.generate_channel_keys_id(false, channel_value_satoshis, user_id);
+               let holder_signer = keys_provider.derive_channel_signer(channel_value_satoshis, channel_keys_id);
                let pubkeys = holder_signer.pubkeys().clone();
 
                if !their_features.supports_wumbo() && channel_value_satoshis > MAX_FUNDING_SATOSHIS_NO_WUMBO {
@@ -1071,6 +1077,7 @@ impl<Signer: Sign> Channel<Signer> {
                        historical_inbound_htlc_fulfills: HashSet::new(),
 
                        channel_type: Self::get_initial_channel_type(&config),
+                       channel_keys_id,
                })
        }
 
@@ -1153,7 +1160,8 @@ impl<Signer: Sign> Channel<Signer> {
                        return Err(ChannelError::Close("Channel Type was not understood - we require static remote key".to_owned()));
                }
 
-               let holder_signer = keys_provider.get_channel_signer(true, msg.funding_satoshis);
+               let channel_keys_id = keys_provider.generate_channel_keys_id(true, msg.funding_satoshis, user_id);
+               let holder_signer = keys_provider.derive_channel_signer(msg.funding_satoshis, channel_keys_id);
                let pubkeys = holder_signer.pubkeys().clone();
                let counterparty_pubkeys = ChannelPublicKeys {
                        funding_pubkey: msg.funding_pubkey,
@@ -1417,6 +1425,7 @@ impl<Signer: Sign> Channel<Signer> {
                        historical_inbound_htlc_fulfills: HashSet::new(),
 
                        channel_type,
+                       channel_keys_id,
                };
 
                Ok(chan)
@@ -1749,27 +1758,27 @@ impl<Signer: Sign> Channel<Signer> {
        /// our counterparty!)
        /// The result is a transaction which we can revoke broadcastership of (ie a "local" transaction)
        /// TODO Some magic rust shit to compile-time check this?
-       fn build_holder_transaction_keys(&self, commitment_number: u64) -> Result<TxCreationKeys, ChannelError> {
+       fn build_holder_transaction_keys(&self, commitment_number: u64) -> TxCreationKeys {
                let per_commitment_point = self.holder_signer.get_per_commitment_point(commitment_number, &self.secp_ctx);
                let delayed_payment_base = &self.get_holder_pubkeys().delayed_payment_basepoint;
                let htlc_basepoint = &self.get_holder_pubkeys().htlc_basepoint;
                let counterparty_pubkeys = self.get_counterparty_pubkeys();
 
-               Ok(secp_check!(TxCreationKeys::derive_new(&self.secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint), "Local tx keys generation got bogus keys".to_owned()))
+               TxCreationKeys::derive_new(&self.secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint)
        }
 
        #[inline]
        /// Creates a set of keys for build_commitment_transaction to generate a transaction which we
        /// will sign and send to our counterparty.
        /// If an Err is returned, it is a ChannelError::Close (for get_outbound_funding_created)
-       fn build_remote_transaction_keys(&self) -> Result<TxCreationKeys, ChannelError> {
+       fn build_remote_transaction_keys(&self) -> TxCreationKeys {
                //TODO: Ensure that the payment_key derived here ends up in the library users' wallet as we
                //may see payments to it!
                let revocation_basepoint = &self.get_holder_pubkeys().revocation_basepoint;
                let htlc_basepoint = &self.get_holder_pubkeys().htlc_basepoint;
                let counterparty_pubkeys = self.get_counterparty_pubkeys();
 
-               Ok(secp_check!(TxCreationKeys::derive_new(&self.secp_ctx, &self.counterparty_cur_commitment_point.unwrap(), &counterparty_pubkeys.delayed_payment_basepoint, &counterparty_pubkeys.htlc_basepoint, revocation_basepoint, htlc_basepoint), "Remote tx keys generation got bogus keys".to_owned()))
+               TxCreationKeys::derive_new(&self.secp_ctx, &self.counterparty_cur_commitment_point.unwrap(), &counterparty_pubkeys.delayed_payment_basepoint, &counterparty_pubkeys.htlc_basepoint, revocation_basepoint, htlc_basepoint)
        }
 
        /// Gets the redeemscript for the funding transaction output (ie the funding transaction output
@@ -2179,7 +2188,7 @@ impl<Signer: Sign> Channel<Signer> {
        fn funding_created_signature<L: Deref>(&mut self, sig: &Signature, logger: &L) -> Result<(Txid, CommitmentTransaction, Signature), ChannelError> where L::Target: Logger {
                let funding_script = self.get_funding_redeemscript();
 
-               let keys = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number)?;
+               let keys = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number);
                let initial_commitment_tx = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &keys, true, false, logger).tx;
                {
                        let trusted_tx = initial_commitment_tx.trust();
@@ -2193,7 +2202,7 @@ impl<Signer: Sign> Channel<Signer> {
                        secp_check!(self.secp_ctx.verify_ecdsa(&sighash, &sig, self.counterparty_funding_pubkey()), "Invalid funding_created signature from peer".to_owned());
                }
 
-               let counterparty_keys = self.build_remote_transaction_keys()?;
+               let counterparty_keys = self.build_remote_transaction_keys();
                let counterparty_initial_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, false, false, logger).tx;
 
                let counterparty_trusted_tx = counterparty_initial_commitment_tx.trust();
@@ -2212,7 +2221,13 @@ impl<Signer: Sign> Channel<Signer> {
                &self.get_counterparty_pubkeys().funding_pubkey
        }
 
-       pub fn funding_created<L: Deref>(&mut self, msg: &msgs::FundingCreated, best_block: BestBlock, logger: &L) -> Result<(msgs::FundingSigned, ChannelMonitor<Signer>, Option<msgs::ChannelReady>), ChannelError> where L::Target: Logger {
+       pub fn funding_created<K: Deref, L: Deref>(
+               &mut self, msg: &msgs::FundingCreated, best_block: BestBlock, keys_source: &K, logger: &L
+       ) -> Result<(msgs::FundingSigned, ChannelMonitor<<K::Target as KeysInterface>::Signer>, Option<msgs::ChannelReady>), ChannelError>
+       where
+               K::Target: KeysInterface,
+               L::Target: Logger
+       {
                if self.is_outbound() {
                        return Err(ChannelError::Close("Received funding_created for an outbound channel?".to_owned()));
                }
@@ -2235,7 +2250,7 @@ impl<Signer: Sign> Channel<Signer> {
                self.channel_transaction_parameters.funding_outpoint = Some(funding_txo);
                // This is an externally observable change before we finish all our checks.  In particular
                // funding_created_signature may fail.
-               self.holder_signer.ready_channel(&self.channel_transaction_parameters);
+               self.holder_signer.provide_channel_parameters(&self.channel_transaction_parameters);
 
                let (counterparty_initial_commitment_txid, initial_commitment_tx, signature) = match self.funding_created_signature(&msg.signature, logger) {
                        Ok(res) => res,
@@ -2267,7 +2282,9 @@ impl<Signer: Sign> Channel<Signer> {
                let funding_txo_script = funding_redeemscript.to_v0_p2wsh();
                let obscure_factor = get_commitment_transaction_number_obscure_factor(&self.get_holder_pubkeys().payment_point, &self.get_counterparty_pubkeys().payment_point, self.is_outbound());
                let shutdown_script = self.shutdown_scriptpubkey.clone().map(|script| script.into_inner());
-               let channel_monitor = ChannelMonitor::new(self.secp_ctx.clone(), self.holder_signer.clone(),
+               let mut monitor_signer = keys_source.derive_channel_signer(self.channel_value_satoshis, self.channel_keys_id);
+               monitor_signer.provide_channel_parameters(&self.channel_transaction_parameters);
+               let channel_monitor = ChannelMonitor::new(self.secp_ctx.clone(), monitor_signer,
                                                          shutdown_script, self.get_holder_selected_contest_delay(),
                                                          &self.destination_script, (funding_txo, funding_txo_script.clone()),
                                                          &self.channel_transaction_parameters,
@@ -2292,7 +2309,13 @@ impl<Signer: Sign> Channel<Signer> {
 
        /// 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<L: Deref>(&mut self, msg: &msgs::FundingSigned, best_block: BestBlock, logger: &L) -> Result<(ChannelMonitor<Signer>, Transaction, Option<msgs::ChannelReady>), ChannelError> where L::Target: Logger {
+       pub fn funding_signed<K: Deref, L: Deref>(
+               &mut self, msg: &msgs::FundingSigned, best_block: BestBlock, keys_source: &K, logger: &L
+       ) -> Result<(ChannelMonitor<<K::Target as KeysInterface>::Signer>, Transaction, Option<msgs::ChannelReady>), ChannelError>
+       where
+               K::Target: KeysInterface,
+               L::Target: Logger
+       {
                if !self.is_outbound() {
                        return Err(ChannelError::Close("Received funding_signed for an inbound channel?".to_owned()));
                }
@@ -2307,7 +2330,7 @@ impl<Signer: Sign> Channel<Signer> {
 
                let funding_script = self.get_funding_redeemscript();
 
-               let counterparty_keys = self.build_remote_transaction_keys()?;
+               let counterparty_keys = self.build_remote_transaction_keys();
                let counterparty_initial_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, false, false, logger).tx;
                let counterparty_trusted_tx = counterparty_initial_commitment_tx.trust();
                let counterparty_initial_bitcoin_tx = counterparty_trusted_tx.built_transaction();
@@ -2315,7 +2338,7 @@ impl<Signer: Sign> Channel<Signer> {
                log_trace!(logger, "Initial counterparty tx for channel {} is: txid {} tx {}",
                        log_bytes!(self.channel_id()), counterparty_initial_bitcoin_tx.txid, encode::serialize_hex(&counterparty_initial_bitcoin_tx.transaction));
 
-               let holder_signer = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number)?;
+               let holder_signer = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number);
                let initial_commitment_tx = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &holder_signer, true, false, logger).tx;
                {
                        let trusted_tx = initial_commitment_tx.trust();
@@ -2344,7 +2367,9 @@ impl<Signer: Sign> Channel<Signer> {
                let funding_txo_script = funding_redeemscript.to_v0_p2wsh();
                let obscure_factor = get_commitment_transaction_number_obscure_factor(&self.get_holder_pubkeys().payment_point, &self.get_counterparty_pubkeys().payment_point, self.is_outbound());
                let shutdown_script = self.shutdown_scriptpubkey.clone().map(|script| script.into_inner());
-               let channel_monitor = ChannelMonitor::new(self.secp_ctx.clone(), self.holder_signer.clone(),
+               let mut monitor_signer = keys_source.derive_channel_signer(self.channel_value_satoshis, self.channel_keys_id);
+               monitor_signer.provide_channel_parameters(&self.channel_transaction_parameters);
+               let channel_monitor = ChannelMonitor::new(self.secp_ctx.clone(), monitor_signer,
                                                          shutdown_script, self.get_holder_selected_contest_delay(),
                                                          &self.destination_script, (funding_txo, funding_txo_script),
                                                          &self.channel_transaction_parameters,
@@ -2981,7 +3006,7 @@ impl<Signer: Sign> Channel<Signer> {
 
                let funding_script = self.get_funding_redeemscript();
 
-               let keys = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number).map_err(|e| (None, e))?;
+               let keys = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number);
 
                let commitment_stats = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &keys, true, false, logger);
                let commitment_txid = {
@@ -3583,7 +3608,7 @@ impl<Signer: Sign> Channel<Signer> {
                // Before proposing a feerate update, check that we can actually afford the new fee.
                let inbound_stats = self.get_inbound_pending_htlc_stats(Some(feerate_per_kw));
                let outbound_stats = self.get_outbound_pending_htlc_stats(Some(feerate_per_kw));
-               let keys = if let Ok(keys) = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number) { keys } else { return None; };
+               let keys = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number);
                let commitment_stats = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &keys, true, true, logger);
                let buffer_fee_msat = Channel::<Signer>::commit_tx_fee_sat(feerate_per_kw, commitment_stats.num_nondust_htlcs + outbound_stats.on_holder_tx_holding_cell_htlcs_count as usize + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as usize, self.opt_anchors()) * 1000;
                let holder_balance_msat = commitment_stats.local_balance_msat - outbound_stats.holding_cell_msat;
@@ -5247,7 +5272,7 @@ impl<Signer: Sign> Channel<Signer> {
 
        /// If an Err is returned, it is a ChannelError::Close (for get_outbound_funding_created)
        fn get_outbound_funding_created_signature<L: Deref>(&mut self, logger: &L) -> Result<Signature, ChannelError> where L::Target: Logger {
-               let counterparty_keys = self.build_remote_transaction_keys()?;
+               let counterparty_keys = self.build_remote_transaction_keys();
                let counterparty_initial_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, false, false, logger).tx;
                Ok(self.holder_signer.sign_counterparty_commitment(&counterparty_initial_commitment_tx, Vec::new(), &self.secp_ctx)
                                .map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed".to_owned()))?.0)
@@ -5274,7 +5299,7 @@ impl<Signer: Sign> Channel<Signer> {
                }
 
                self.channel_transaction_parameters.funding_outpoint = Some(funding_txo);
-               self.holder_signer.ready_channel(&self.channel_transaction_parameters);
+               self.holder_signer.provide_channel_parameters(&self.channel_transaction_parameters);
 
                let signature = match self.get_outbound_funding_created_signature(logger) {
                        Ok(res) => res,
@@ -5569,7 +5594,7 @@ impl<Signer: Sign> Channel<Signer> {
                        return Err(ChannelError::Ignore(format!("Cannot send value that would put us over the max HTLC value in flight our peer will accept ({})", self.counterparty_max_htlc_value_in_flight_msat)));
                }
 
-               let keys = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number)?;
+               let keys = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number);
                let commitment_stats = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &keys, true, true, logger);
                if !self.is_outbound() {
                        // Check that we won't violate the remote channel reserve by adding this HTLC.
@@ -5730,7 +5755,7 @@ impl<Signer: Sign> Channel<Signer> {
        /// 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<L: Deref>(&self, logger: &L) -> Result<(msgs::CommitmentSigned, (Txid, Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>)), ChannelError> where L::Target: Logger {
-               let counterparty_keys = self.build_remote_transaction_keys()?;
+               let counterparty_keys = self.build_remote_transaction_keys();
                let commitment_stats = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, false, true, logger);
                let counterparty_commitment_txid = commitment_stats.tx.trust().txid();
                let (signature, htlc_signatures);
@@ -5939,19 +5964,20 @@ impl<Signer: Sign> Channel<Signer> {
                (monitor_update, dropped_outbound_htlcs)
        }
 
-       pub fn inflight_htlc_sources(&self) -> impl Iterator<Item=&HTLCSource> {
+       pub fn inflight_htlc_sources(&self) -> impl Iterator<Item=(&HTLCSource, &PaymentHash)> {
                self.holding_cell_htlc_updates.iter()
                        .flat_map(|htlc_update| {
                                match htlc_update {
-                                       HTLCUpdateAwaitingACK::AddHTLC { source, .. } => { Some(source) }
-                                       _ => None
+                                       HTLCUpdateAwaitingACK::AddHTLC { source, payment_hash, .. }
+                                               => Some((source, payment_hash)),
+                                       _ => None,
                                }
                        })
-                       .chain(self.pending_outbound_htlcs.iter().map(|htlc| &htlc.source))
+                       .chain(self.pending_outbound_htlcs.iter().map(|htlc| (&htlc.source, &htlc.payment_hash)))
        }
 }
 
-const SERIALIZATION_VERSION: u8 = 2;
+const SERIALIZATION_VERSION: u8 = 3;
 const MIN_SERIALIZATION_VERSION: u8 = 2;
 
 impl_writeable_tlv_based_enum!(InboundHTLCRemovalReason,;
@@ -6013,7 +6039,7 @@ impl<Signer: Sign> Writeable for Channel<Signer> {
                // Note that we write out as if remove_uncommitted_htlcs_and_mark_paused had just been
                // called.
 
-               write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
+               write_ver_prefix!(writer, MIN_SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
 
                // `user_id` used to be a single u64 value. In order to remain backwards compatible with
                // versions prior to 0.0.113, the u128 is serialized as two separate u64 values. We write
@@ -6295,6 +6321,7 @@ impl<Signer: Sign> Writeable for Channel<Signer> {
                        (21, self.outbound_scid_alias, required),
                        (23, channel_ready_event_emitted, option),
                        (25, user_id_high_opt, option),
+                       (27, self.channel_keys_id, required),
                });
 
                Ok(())
@@ -6331,16 +6358,20 @@ impl<'a, K: Deref> ReadableArgs<(&'a K, u32)> for Channel<<K::Target as KeysInte
 
                let latest_monitor_update_id = Readable::read(reader)?;
 
-               let keys_len: u32 = Readable::read(reader)?;
-               let mut keys_data = Vec::with_capacity(cmp::min(keys_len as usize, MAX_ALLOC_SIZE));
-               while keys_data.len() != keys_len as usize {
-                       // Read 1KB at a time to avoid accidentally allocating 4GB on corrupted channel keys
-                       let mut data = [0; 1024];
-                       let read_slice = &mut data[0..cmp::min(1024, keys_len as usize - keys_data.len())];
-                       reader.read_exact(read_slice)?;
-                       keys_data.extend_from_slice(read_slice);
+               let mut keys_data = None;
+               if ver <= 2 {
+                       // Read the serialize signer bytes. We'll choose to deserialize them or not based on whether
+                       // the `channel_keys_id` TLV is present below.
+                       let keys_len: u32 = Readable::read(reader)?;
+                       keys_data = Some(Vec::with_capacity(cmp::min(keys_len as usize, MAX_ALLOC_SIZE)));
+                       while keys_data.as_ref().unwrap().len() != keys_len as usize {
+                               // Read 1KB at a time to avoid accidentally allocating 4GB on corrupted channel keys
+                               let mut data = [0; 1024];
+                               let read_slice = &mut data[0..cmp::min(1024, keys_len as usize - keys_data.as_ref().unwrap().len())];
+                               reader.read_exact(read_slice)?;
+                               keys_data.as_mut().unwrap().extend_from_slice(read_slice);
+                       }
                }
-               let holder_signer = keys_source.read_chan_signer(&keys_data)?;
 
                // Read the old serialization for shutdown_pubkey, preferring the TLV field later if set.
                let mut shutdown_scriptpubkey = match <PublicKey as Readable>::read(reader) {
@@ -6558,6 +6589,7 @@ impl<'a, K: Deref> ReadableArgs<(&'a K, u32)> for Channel<<K::Target as KeysInte
                let mut channel_ready_event_emitted = None;
 
                let mut user_id_high_opt: Option<u64> = None;
+               let mut channel_keys_id: Option<[u8; 32]> = None;
 
                read_tlv_fields!(reader, {
                        (0, announcement_sigs, option),
@@ -6577,8 +6609,25 @@ impl<'a, K: Deref> ReadableArgs<(&'a K, u32)> for Channel<<K::Target as KeysInte
                        (21, outbound_scid_alias, option),
                        (23, channel_ready_event_emitted, option),
                        (25, user_id_high_opt, option),
+                       (27, channel_keys_id, option),
                });
 
+               let (channel_keys_id, holder_signer) = if let Some(channel_keys_id) = channel_keys_id {
+                       let mut holder_signer = keys_source.derive_channel_signer(channel_value_satoshis, channel_keys_id);
+                       // If we've gotten to the funding stage of the channel, populate the signer with its
+                       // required channel parameters.
+                       let non_shutdown_state = channel_state & (!MULTI_STATE_FLAGS);
+                       if non_shutdown_state >= (ChannelState::FundingCreated as u32) {
+                               holder_signer.provide_channel_parameters(&channel_parameters);
+                       }
+                       (channel_keys_id, holder_signer)
+               } else {
+                       // `keys_data` can be `None` if we had corrupted data.
+                       let keys_data = keys_data.ok_or(DecodeError::InvalidValue)?;
+                       let holder_signer = keys_source.read_chan_signer(&keys_data)?;
+                       (holder_signer.channel_keys_id(), holder_signer)
+               };
+
                if let Some(preimages) = preimages_opt {
                        let mut iter = preimages.into_iter();
                        for htlc in pending_outbound_htlcs.iter_mut() {
@@ -6728,6 +6777,7 @@ impl<'a, K: Deref> ReadableArgs<(&'a K, u32)> for Channel<<K::Target as KeysInte
                        historical_inbound_htlc_fulfills,
 
                        channel_type: channel_type.unwrap(),
+                       channel_keys_id,
                })
        }
 }
@@ -6752,7 +6802,7 @@ mod tests {
        use crate::ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight};
        use crate::chain::BestBlock;
        use crate::chain::chaininterface::{FeeEstimator, LowerBoundedFeeEstimator, ConfirmationTarget};
-       use crate::chain::keysinterface::{InMemorySigner, Recipient, KeyMaterial, KeysInterface};
+       use crate::chain::keysinterface::{BaseSign, InMemorySigner, Recipient, KeyMaterial, KeysInterface};
        use crate::chain::transaction::OutPoint;
        use crate::util::config::UserConfig;
        use crate::util::enforcing_trait_impls::EnforcingSigner;
@@ -6820,7 +6870,10 @@ mod tests {
                        ShutdownScript::new_p2wpkh_from_pubkey(PublicKey::from_secret_key(&secp_ctx, &channel_close_key))
                }
 
-               fn get_channel_signer(&self, _inbound: bool, _channel_value_satoshis: u64) -> InMemorySigner {
+               fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] {
+                       self.signer.channel_keys_id()
+               }
+               fn derive_channel_signer(&self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32]) -> Self::Signer {
                        self.signer.clone()
                }
                fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }
@@ -7035,10 +7088,10 @@ mod tests {
                }]};
                let funding_outpoint = OutPoint{ txid: tx.txid(), index: 0 };
                let funding_created_msg = node_a_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap();
-               let (funding_signed_msg, _, _) = node_b_chan.funding_created(&funding_created_msg, best_block, &&logger).unwrap();
+               let (funding_signed_msg, _, _) = node_b_chan.funding_created(&funding_created_msg, best_block, &&keys_provider, &&logger).unwrap();
 
                // Node B --> Node A: funding signed
-               let _ = node_a_chan.funding_signed(&funding_signed_msg, best_block, &&logger);
+               let _ = node_a_chan.funding_signed(&funding_signed_msg, best_block, &&keys_provider, &&logger);
 
                // Now disconnect the two nodes and check that the commitment point in
                // Node B's channel_reestablish message is sane.
@@ -7308,7 +7361,7 @@ mod tests {
                                selected_contest_delay: 144
                        });
                chan.channel_transaction_parameters.funding_outpoint = Some(funding_info);
-               signer.ready_channel(&chan.channel_transaction_parameters);
+               signer.provide_channel_parameters(&chan.channel_transaction_parameters);
 
                assert_eq!(counterparty_pubkeys.payment_point.serialize()[..],
                           hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]);
@@ -7326,7 +7379,7 @@ mod tests {
                let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
                let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
                let htlc_basepoint = &chan.holder_signer.pubkeys().htlc_basepoint;
-               let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint).unwrap();
+               let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint);
 
                macro_rules! test_commitment {
                        ( $counterparty_sig_hex: expr, $sig_hex: expr, $tx_hex: expr, $($remain:tt)* ) => {
@@ -7979,16 +8032,16 @@ mod tests {
                let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
                assert_eq!(per_commitment_point.serialize()[..], hex::decode("025f7117a78150fe2ef97db7cfc83bd57b2e2c0d0dd25eaf467a4a1c2a45ce1486").unwrap()[..]);
 
-               assert_eq!(chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &base_point).unwrap().serialize()[..],
+               assert_eq!(chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &base_point).serialize()[..],
                                hex::decode("0235f2dbfaa89b57ec7b055afe29849ef7ddfeb1cefdb9ebdc43f5494984db29e5").unwrap()[..]);
 
-               assert_eq!(chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &base_secret).unwrap(),
+               assert_eq!(chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &base_secret),
                                SecretKey::from_slice(&hex::decode("cbced912d3b21bf196a766651e436aff192362621ce317704ea2f75d87e7be0f").unwrap()[..]).unwrap());
 
-               assert_eq!(chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &base_point).unwrap().serialize()[..],
+               assert_eq!(chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &base_point).serialize()[..],
                                hex::decode("02916e326636d19c33f13e8c0c3a03dd157f332f3e99c317c141dd865eb01f8ff0").unwrap()[..]);
 
-               assert_eq!(chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_secret, &base_secret).unwrap(),
+               assert_eq!(chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_secret, &base_secret),
                                SecretKey::from_slice(&hex::decode("d09ffff62ddb2297ab000cc85bcb4283fdeb6aa052affbc9dddcf33b61078110").unwrap()[..]).unwrap());
        }
 
index 63e70f83a398f146dd16f538b3fe85fcf3cff105..bb99b02d9f9a90bdafee770671100a22a95e2e70 100644 (file)
@@ -49,12 +49,13 @@ use crate::ln::features::InvoiceFeatures;
 use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RoutePath, RouteParameters};
 use crate::ln::msgs;
 use crate::ln::onion_utils;
+use crate::ln::onion_utils::HTLCFailReason;
 use crate::ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, MAX_VALUE_MSAT};
 use crate::ln::wire::Encode;
 use crate::chain::keysinterface::{Sign, KeysInterface, KeysManager, Recipient};
 use crate::util::config::{UserConfig, ChannelConfig};
 use crate::util::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
-use crate::util::{byte_utils, events};
+use crate::util::events;
 use crate::util::wakers::{Future, Notifier};
 use crate::util::scid_utils::fake_scid;
 use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
@@ -276,27 +277,6 @@ impl HTLCSource {
        }
 }
 
-#[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
-pub(super) enum HTLCFailReason {
-       LightningError {
-               err: msgs::OnionErrorPacket,
-       },
-       Reason {
-               failure_code: u16,
-               data: Vec<u8>,
-       }
-}
-
-impl HTLCFailReason {
-       pub(super) fn reason(failure_code: u16, data: Vec<u8>) -> Self {
-               Self::Reason { failure_code, data }
-       }
-
-       pub(super) fn from_failure_code(failure_code: u16) -> Self {
-               Self::Reason { failure_code, data: Vec::new() }
-       }
-}
-
 struct ReceiveError {
        err_code: u16,
        err_data: Vec<u8>,
@@ -746,9 +726,9 @@ pub struct ChannelManager<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
        channel_state: Mutex<ChannelHolder<<K::Target as KeysInterface>::Signer>>,
 
        /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
-       /// expose them to users via a PaymentReceived event. HTLCs which do not meet the requirements
+       /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
        /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
-       /// after we generate a PaymentReceived upon receipt of all MPP parts or when they time out.
+       /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
        ///
        /// See `ChannelManager` struct-level documentation for lock order requirements.
        pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
@@ -2053,7 +2033,7 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                        return Err(ReceiveError {
                                msg: "Upstream node set CLTV to the wrong value",
                                err_code: 18,
-                               err_data: byte_utils::be32_to_array(cltv_expiry).to_vec()
+                               err_data: cltv_expiry.to_be_bytes().to_vec()
                        })
                }
                // final_expiry_too_soon
@@ -2062,17 +2042,20 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                // Also, ensure that, in the case of an unknown preimage for the received payment hash, our
                // payment logic has enough time to fail the HTLC backward before our onchain logic triggers a
                // channel closure (see HTLC_FAIL_BACK_BUFFER rationale).
-               if (hop_data.outgoing_cltv_value as u64) <= self.best_block.read().unwrap().height() as u64 + HTLC_FAIL_BACK_BUFFER as u64 + 1  {
+               let current_height: u32 = self.best_block.read().unwrap().height();
+               if (hop_data.outgoing_cltv_value as u64) <= current_height as u64 + HTLC_FAIL_BACK_BUFFER as u64 + 1 {
+                       let mut err_data = Vec::with_capacity(12);
+                       err_data.extend_from_slice(&amt_msat.to_be_bytes());
+                       err_data.extend_from_slice(&current_height.to_be_bytes());
                        return Err(ReceiveError {
-                               err_code: 17,
-                               err_data: Vec::new(),
+                               err_code: 0x4000 | 15, err_data,
                                msg: "The final CLTV expiry is too soon to handle",
                        });
                }
                if hop_data.amt_to_forward > amt_msat {
                        return Err(ReceiveError {
                                err_code: 19,
-                               err_data: byte_utils::be64_to_array(amt_msat).to_vec(),
+                               err_data: amt_msat.to_be_bytes().to_vec(),
                                msg: "Upstream node sent less than we were supposed to receive in payment",
                        });
                }
@@ -2173,7 +2156,8 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                                        return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
                                                channel_id: msg.channel_id,
                                                htlc_id: msg.htlc_id,
-                                               reason: onion_utils::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
+                                               reason: HTLCFailReason::reason($err_code, $data.to_vec())
+                                                       .get_encrypted_failure_packet(&shared_secret, &None),
                                        }));
                                }
                        }
@@ -2238,7 +2222,7 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                        // with a short_channel_id of 0. This is important as various things later assume
                        // short_channel_id is non-0 in any ::Forward.
                        if let &PendingHTLCRouting::Forward { ref short_channel_id, .. } = routing {
-                               if let Some((err, code, chan_update)) = loop {
+                               if let Some((err, mut code, chan_update)) = loop {
                                        let id_option = self.short_to_chan_info.read().unwrap().get(&short_channel_id).cloned();
                                        let mut channel_state = self.channel_state.lock().unwrap();
                                        let forwarding_id_opt = match id_option {
@@ -2295,10 +2279,13 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                                                }
                                                chan_update_opt
                                        } else {
-                                               if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + MIN_CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
+                                               if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + MIN_CLTV_EXPIRY_DELTA as u64 {
+                                                       // We really should set `incorrect_cltv_expiry` here but as we're not
+                                                       // forwarding over a real channel we can't generate a channel_update
+                                                       // for it. Instead we just return a generic temporary_node_failure.
                                                        break Some((
                                                                "Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta",
-                                                               0x1000 | 13, None,
+                                                               0x2000 | 2, None,
                                                        ));
                                                }
                                                None
@@ -2344,6 +2331,12 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                                                (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
                                                msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
                                                chan_update.write(&mut res).expect("Writes cannot fail");
+                                       } else if code & 0x1000 == 0x1000 {
+                                               // If we're trying to return an error that requires a `channel_update` but
+                                               // we're forwarding to a phantom or intercept "channel" (i.e. cannot
+                                               // generate an update), just use the generic "temporary_node_failure"
+                                               // instead.
+                                               code = 0x2000 | 2;
                                        }
                                        return_err!(err, code, &res.0[..]);
                                }
@@ -3380,9 +3373,9 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
 
                                                                macro_rules! fail_htlc {
                                                                        ($htlc: expr, $payment_hash: expr) => {
-                                                                               let mut htlc_msat_height_data = byte_utils::be64_to_array($htlc.value).to_vec();
+                                                                               let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
                                                                                htlc_msat_height_data.extend_from_slice(
-                                                                                       &byte_utils::be32_to_array(self.best_block.read().unwrap().height()),
+                                                                                       &self.best_block.read().unwrap().height().to_be_bytes(),
                                                                                );
                                                                                failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
                                                                                                short_channel_id: $htlc.prev_hop.short_channel_id,
@@ -3405,7 +3398,7 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
 
                                                                macro_rules! check_total_value {
                                                                        ($payment_data: expr, $payment_preimage: expr) => {{
-                                                                               let mut payment_received_generated = false;
+                                                                               let mut payment_claimable_generated = false;
                                                                                let purpose = || {
                                                                                        events::PaymentPurpose::InvoicePayment {
                                                                                                payment_preimage: $payment_preimage,
@@ -3444,7 +3437,7 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                                                                                } else if total_value == $payment_data.total_msat {
                                                                                        let prev_channel_id = prev_funding_outpoint.to_channel_id();
                                                                                        htlcs.push(claimable_htlc);
-                                                                                       new_events.push(events::Event::PaymentReceived {
+                                                                                       new_events.push(events::Event::PaymentClaimable {
                                                                                                receiver_node_id: Some(receiver_node_id),
                                                                                                payment_hash,
                                                                                                purpose: purpose(),
@@ -3452,14 +3445,14 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                                                                                                via_channel_id: Some(prev_channel_id),
                                                                                                via_user_channel_id: Some(prev_user_channel_id),
                                                                                        });
-                                                                                       payment_received_generated = true;
+                                                                                       payment_claimable_generated = true;
                                                                                } else {
                                                                                        // Nothing to do - we haven't reached the total
                                                                                        // payment value yet, wait until we receive more
                                                                                        // MPP parts.
                                                                                        htlcs.push(claimable_htlc);
                                                                                }
-                                                                               payment_received_generated
+                                                                               payment_claimable_generated
                                                                        }}
                                                                }
 
@@ -3490,7 +3483,7 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                                                                                                                let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
                                                                                                                e.insert((purpose.clone(), vec![claimable_htlc]));
                                                                                                                let prev_channel_id = prev_funding_outpoint.to_channel_id();
-                                                                                                               new_events.push(events::Event::PaymentReceived {
+                                                                                                               new_events.push(events::Event::PaymentClaimable {
                                                                                                                        receiver_node_id: Some(receiver_node_id),
                                                                                                                        payment_hash,
                                                                                                                        amount_msat: outgoing_amt_msat,
@@ -3522,8 +3515,8 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                                                                                                log_bytes!(payment_hash.0), payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
                                                                                        fail_htlc!(claimable_htlc, payment_hash);
                                                                                } else {
-                                                                                       let payment_received_generated = check_total_value!(payment_data, inbound_payment.get().payment_preimage);
-                                                                                       if payment_received_generated {
+                                                                                       let payment_claimable_generated = check_total_value!(payment_data, inbound_payment.get().payment_preimage);
+                                                                                       if payment_claimable_generated {
                                                                                                inbound_payment.remove_entry();
                                                                                        }
                                                                                }
@@ -3780,12 +3773,12 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
        }
 
        /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
-       /// after a PaymentReceived event, failing the HTLC back to its origin and freeing resources
+       /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
        /// along the path (including in our own channel on which we received it).
        ///
        /// Note that in some cases around unclean shutdown, it is possible the payment may have
        /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
-       /// second copy of) the [`events::Event::PaymentReceived`] event. Alternatively, the payment
+       /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
        /// may have already been failed automatically by LDK if it was nearing its expiration time.
        ///
        /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
@@ -3798,9 +3791,8 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                let removed_source = self.claimable_htlcs.lock().unwrap().remove(payment_hash);
                if let Some((_, mut sources)) = removed_source {
                        for htlc in sources.drain(..) {
-                               let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
-                               htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(
-                                               self.best_block.read().unwrap().height()));
+                               let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
+                               htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
                                let source = HTLCSource::PreviousHopData(htlc.prev_hop);
                                let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
                                let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
@@ -3938,90 +3930,48 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                                } else { None };
                                log_trace!(self.logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
 
-                               let path_failure = match &onion_error {
-                                       &HTLCFailReason::LightningError { ref err } => {
+                               let path_failure = {
 #[cfg(test)]
-                                               let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
+                                       let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_error.decode_onion_failure(&self.secp_ctx, &self.logger, &source);
 #[cfg(not(test))]
-                                               let (network_update, short_channel_id, payment_retryable, _, _) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
-
-                                               if self.payment_is_probe(payment_hash, &payment_id) {
-                                                       if !payment_retryable {
-                                                               events::Event::ProbeSuccessful {
-                                                                       payment_id: *payment_id,
-                                                                       payment_hash: payment_hash.clone(),
-                                                                       path: path.clone(),
-                                                               }
-                                                       } else {
-                                                               events::Event::ProbeFailed {
-                                                                       payment_id: *payment_id,
-                                                                       payment_hash: payment_hash.clone(),
-                                                                       path: path.clone(),
-                                                                       short_channel_id,
-                                                               }
-                                                       }
-                                               } else {
-                                                       // TODO: If we decided to blame ourselves (or one of our channels) in
-                                                       // process_onion_failure we should close that channel as it implies our
-                                                       // next-hop is needlessly blaming us!
-                                                       if let Some(scid) = short_channel_id {
-                                                               retry.as_mut().map(|r| r.payment_params.previously_failed_channels.push(scid));
-                                                       }
-                                                       events::Event::PaymentPathFailed {
-                                                               payment_id: Some(*payment_id),
-                                                               payment_hash: payment_hash.clone(),
-                                                               payment_failed_permanently: !payment_retryable,
-                                                               network_update,
-                                                               all_paths_failed,
-                                                               path: path.clone(),
-                                                               short_channel_id,
-                                                               retry,
-                                                               #[cfg(test)]
-                                                               error_code: onion_error_code,
-                                                               #[cfg(test)]
-                                                               error_data: onion_error_data
-                                                       }
-                                               }
-                                       },
-                                       &HTLCFailReason::Reason {
-#[cfg(test)]
-                                                       ref failure_code,
-#[cfg(test)]
-                                                       ref data,
-                                                       .. } => {
-                                               // we get a fail_malformed_htlc from the first hop
-                                               // TODO: We'd like to generate a NetworkUpdate for temporary
-                                               // failures here, but that would be insufficient as find_route
-                                               // generally ignores its view of our own channels as we provide them via
-                                               // ChannelDetails.
-                                               // TODO: For non-temporary failures, we really should be closing the
-                                               // channel here as we apparently can't relay through them anyway.
-                                               let scid = path.first().unwrap().short_channel_id;
-                                               retry.as_mut().map(|r| r.payment_params.previously_failed_channels.push(scid));
-
-                                               if self.payment_is_probe(payment_hash, &payment_id) {
-                                                       events::Event::ProbeFailed {
+                                       let (network_update, short_channel_id, payment_retryable, _, _) = onion_error.decode_onion_failure(&self.secp_ctx, &self.logger, &source);
+
+                                       if self.payment_is_probe(payment_hash, &payment_id) {
+                                               if !payment_retryable {
+                                                       events::Event::ProbeSuccessful {
                                                                payment_id: *payment_id,
                                                                payment_hash: payment_hash.clone(),
                                                                path: path.clone(),
-                                                               short_channel_id: Some(scid),
                                                        }
                                                } else {
-                                                       events::Event::PaymentPathFailed {
-                                                               payment_id: Some(*payment_id),
+                                                       events::Event::ProbeFailed {
+                                                               payment_id: *payment_id,
                                                                payment_hash: payment_hash.clone(),
-                                                               payment_failed_permanently: false,
-                                                               network_update: None,
-                                                               all_paths_failed,
                                                                path: path.clone(),
-                                                               short_channel_id: Some(scid),
-                                                               retry,
-#[cfg(test)]
-                                                               error_code: Some(*failure_code),
-#[cfg(test)]
-                                                               error_data: Some(data.clone()),
+                                                               short_channel_id,
                                                        }
                                                }
+                                       } else {
+                                               // TODO: If we decided to blame ourselves (or one of our channels) in
+                                               // process_onion_failure we should close that channel as it implies our
+                                               // next-hop is needlessly blaming us!
+                                               if let Some(scid) = short_channel_id {
+                                                       retry.as_mut().map(|r| r.payment_params.previously_failed_channels.push(scid));
+                                               }
+                                               events::Event::PaymentPathFailed {
+                                                       payment_id: Some(*payment_id),
+                                                       payment_hash: payment_hash.clone(),
+                                                       payment_failed_permanently: !payment_retryable,
+                                                       network_update,
+                                                       all_paths_failed,
+                                                       path: path.clone(),
+                                                       short_channel_id,
+                                                       retry,
+                                                       #[cfg(test)]
+                                                       error_code: onion_error_code,
+                                                       #[cfg(test)]
+                                                       error_data: onion_error_data
+                                               }
                                        }
                                };
                                let mut pending_events = self.pending_events.lock().unwrap();
@@ -4029,23 +3979,8 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                                if let Some(ev) = full_failure_ev { pending_events.push(ev); }
                        },
                        HTLCSource::PreviousHopData(HTLCPreviousHopData { ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret, ref phantom_shared_secret, ref outpoint }) => {
-                               let err_packet = match onion_error {
-                                       HTLCFailReason::Reason { ref failure_code, ref data } => {
-                                               log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
-                                               if let Some(phantom_ss) = phantom_shared_secret {
-                                                       let phantom_packet = onion_utils::build_failure_packet(phantom_ss, *failure_code, &data[..]).encode();
-                                                       let encrypted_phantom_packet = onion_utils::encrypt_failure_packet(phantom_ss, &phantom_packet);
-                                                       onion_utils::encrypt_failure_packet(incoming_packet_shared_secret, &encrypted_phantom_packet.data[..])
-                                               } else {
-                                                       let packet = onion_utils::build_failure_packet(incoming_packet_shared_secret, *failure_code, &data[..]).encode();
-                                                       onion_utils::encrypt_failure_packet(incoming_packet_shared_secret, &packet)
-                                               }
-                                       },
-                                       HTLCFailReason::LightningError { err } => {
-                                               log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards with pre-built LightningError", log_bytes!(payment_hash.0));
-                                               onion_utils::encrypt_failure_packet(incoming_packet_shared_secret, &err.data)
-                                       }
-                               };
+                               log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with {:?}", log_bytes!(payment_hash.0), onion_error);
+                               let err_packet = onion_error.get_encrypted_failure_packet(incoming_packet_shared_secret, phantom_shared_secret);
 
                                let mut forward_event = None;
                                let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
@@ -4075,7 +4010,7 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                }
        }
 
-       /// Provides a payment preimage in response to [`Event::PaymentReceived`], generating any
+       /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
        /// [`MessageSendEvent`]s needed to claim the payment.
        ///
        /// Note that calling this method does *not* guarantee that the payment has been claimed. You
@@ -4083,11 +4018,11 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
        /// provided to your [`EventHandler`] when [`process_pending_events`] is next called.
        ///
        /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
-       /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentReceived`
+       /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
        /// event matches your expectation. If you fail to do so and call this method, you may provide
        /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
        ///
-       /// [`Event::PaymentReceived`]: crate::util::events::Event::PaymentReceived
+       /// [`Event::PaymentClaimable`]: crate::util::events::Event::PaymentClaimable
        /// [`Event::PaymentClaimed`]: crate::util::events::Event::PaymentClaimed
        /// [`process_pending_events`]: EventsProvider::process_pending_events
        /// [`create_inbound_payment`]: Self::create_inbound_payment
@@ -4195,9 +4130,8 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                        mem::drop(channel_state_lock);
                        if !valid_mpp {
                                for htlc in sources.drain(..) {
-                                       let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
-                                       htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(
-                                               self.best_block.read().unwrap().height()));
+                                       let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
+                                       htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
                                        let source = HTLCSource::PreviousHopData(htlc.prev_hop);
                                        let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
                                        let receiver = HTLCDestination::FailedPayment { payment_hash };
@@ -4705,7 +4639,7 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                                        if chan.get().get_counterparty_node_id() != *counterparty_node_id {
                                                return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
                                        }
-                                       (try_chan_entry!(self, chan.get_mut().funding_created(msg, best_block, &self.logger), chan), chan.remove())
+                                       (try_chan_entry!(self, chan.get_mut().funding_created(msg, best_block, &self.keys_manager, &self.logger), chan), chan.remove())
                                },
                                hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
                        }
@@ -4776,7 +4710,7 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                                        if chan.get().get_counterparty_node_id() != *counterparty_node_id {
                                                return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
                                        }
-                                       let (monitor, funding_tx, channel_ready) = match chan.get_mut().funding_signed(&msg, best_block, &self.logger) {
+                                       let (monitor, funding_tx, channel_ready) = match chan.get_mut().funding_signed(&msg, best_block, &self.keys_manager, &self.logger) {
                                                Ok(update) => update,
                                                Err(e) => try_chan_entry!(self, Err(e), chan),
                                        };
@@ -4973,10 +4907,10 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                                                PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
                                                        let reason = if (error_code & 0x1000) != 0 {
                                                                let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
-                                                               onion_utils::build_first_hop_failure_packet(incoming_shared_secret, real_code, &error_data)
+                                                               HTLCFailReason::reason(real_code, error_data)
                                                        } else {
-                                                               onion_utils::build_first_hop_failure_packet(incoming_shared_secret, error_code, &[])
-                                                       };
+                                                               HTLCFailReason::from_failure_code(error_code)
+                                                       }.get_encrypted_failure_packet(incoming_shared_secret, &None);
                                                        let msg = msgs::UpdateFailHTLC {
                                                                channel_id: msg.channel_id,
                                                                htlc_id: msg.htlc_id,
@@ -5020,7 +4954,7 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                                if chan.get().get_counterparty_node_id() != *counterparty_node_id {
                                        return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
                                }
-                               try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::LightningError { err: msg.reason.clone() }), chan);
+                               try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan);
                        },
                        hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
                }
@@ -5039,7 +4973,7 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                                        let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
                                        try_chan_entry!(self, Err(chan_err), chan);
                                }
-                               try_chan_entry!(self, chan.get_mut().update_fail_malformed_htlc(&msg, HTLCFailReason::from_failure_code(msg.failure_code)), chan);
+                               try_chan_entry!(self, chan.get_mut().update_fail_malformed_htlc(&msg, HTLCFailReason::reason(msg.failure_code, msg.sha256_of_onion.to_vec())), chan);
                                Ok(())
                        },
                        hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
@@ -5632,8 +5566,8 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
        /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
        /// [`PaymentHash`] and [`PaymentPreimage`] for you.
        ///
-       /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentReceived`], which
-       /// will have the [`PaymentReceived::payment_preimage`] field filled in. That should then be
+       /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
+       /// will have the [`PaymentClaimable::payment_preimage`] field filled in. That should then be
        /// passed directly to [`claim_funds`].
        ///
        /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
@@ -5649,8 +5583,8 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
        /// Errors if `min_value_msat` is greater than total bitcoin supply.
        ///
        /// [`claim_funds`]: Self::claim_funds
-       /// [`PaymentReceived`]: events::Event::PaymentReceived
-       /// [`PaymentReceived::payment_preimage`]: events::Event::PaymentReceived::payment_preimage
+       /// [`PaymentClaimable`]: events::Event::PaymentClaimable
+       /// [`PaymentClaimable::payment_preimage`]: events::Event::PaymentClaimable::payment_preimage
        /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
        pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32) -> Result<(PaymentHash, PaymentSecret), ()> {
                inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs, &self.keys_manager, self.highest_seen_timestamp.load(Ordering::Acquire) as u64)
@@ -5676,7 +5610,7 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
        /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
        /// stored external to LDK.
        ///
-       /// A [`PaymentReceived`] event will only be generated if the [`PaymentSecret`] matches a
+       /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
        /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
        /// the `min_value_msat` provided here, if one is provided.
        ///
@@ -5686,7 +5620,7 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
        ///
        /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
        /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
-       /// before a [`PaymentReceived`] event will be generated, ensuring that we do not provide the
+       /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
        /// sender "proof-of-payment" unless they have paid the required amount.
        ///
        /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
@@ -5697,9 +5631,9 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
        ///
        /// Note that we use block header time to time-out pending inbound payments (with some margin
        /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
-       /// accept a payment and generate a [`PaymentReceived`] event for some time after the expiry.
+       /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
        /// If you need exact expiry semantics, you should enforce them upon receipt of
-       /// [`PaymentReceived`].
+       /// [`PaymentClaimable`].
        ///
        /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry`
        /// set to at least [`MIN_FINAL_CLTV_EXPIRY`].
@@ -5715,7 +5649,7 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
        /// Errors if `min_value_msat` is greater than total bitcoin supply.
        ///
        /// [`create_inbound_payment`]: Self::create_inbound_payment
-       /// [`PaymentReceived`]: events::Event::PaymentReceived
+       /// [`PaymentClaimable`]: events::Event::PaymentClaimable
        pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32) -> Result<PaymentSecret, ()> {
                inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash, invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64)
        }
@@ -5793,7 +5727,7 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                let mut inflight_htlcs = InFlightHtlcs::new();
 
                for chan in self.channel_state.lock().unwrap().by_id.values() {
-                       for htlc_source in chan.inflight_htlc_sources() {
+                       for (htlc_source, _) in chan.inflight_htlc_sources() {
                                if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
                                        inflight_htlcs.process_path(path, self.get_our_node_id());
                                }
@@ -5811,6 +5745,12 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
                events.into_inner()
        }
 
+       #[cfg(test)]
+       pub fn pop_pending_event(&self) -> Option<events::Event> {
+               let mut events = self.pending_events.lock().unwrap();
+               if events.is_empty() { None } else { Some(events.remove(0)) }
+       }
+
        #[cfg(test)]
        pub fn has_pending_payments(&self) -> bool {
                !self.pending_outbound_payments.lock().unwrap().is_empty()
@@ -6167,8 +6107,8 @@ where
                                        // number of blocks we generally consider it to take to do a commitment update,
                                        // just give up on it and fail the HTLC.
                                        if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
-                                               let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
-                                               htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(height));
+                                               let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
+                                               htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
 
                                                timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
                                                        HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
@@ -6917,16 +6857,6 @@ impl Writeable for HTLCSource {
        }
 }
 
-impl_writeable_tlv_based_enum!(HTLCFailReason,
-       (0, LightningError) => {
-               (0, err, required),
-       },
-       (1, Reason) => {
-               (0, failure_code, required),
-               (2, data, vec_type),
-       },
-;);
-
 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
        (0, forward_info, required),
        (1, prev_user_channel_id, (default_value, 0)),
@@ -7304,6 +7234,25 @@ impl<'a, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
                                                user_channel_id: channel.get_user_id(),
                                                reason: ClosureReason::OutdatedChannelManager
                                        });
+                                       for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
+                                               let mut found_htlc = false;
+                                               for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
+                                                       if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
+                                               }
+                                               if !found_htlc {
+                                                       // If we have some HTLCs in the channel which are not present in the newer
+                                                       // ChannelMonitor, they have been removed and should be failed back to
+                                                       // ensure we don't forget them entirely. Note that if the missing HTLC(s)
+                                                       // were actually claimed we'd have generated and ensured the previous-hop
+                                                       // claim update ChannelMonitor updates were persisted prior to persising
+                                                       // the ChannelMonitor update for the forward leg, so attempting to fail the
+                                                       // backwards leg of the HTLC will simply be rejected.
+                                                       log_info!(args.logger,
+                                                               "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
+                                                               log_bytes!(channel.channel_id()), log_bytes!(payment_hash.0));
+                                                       failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.get_counterparty_node_id(), channel.channel_id()));
+                                               }
+                                       }
                                } else {
                                        log_info!(args.logger, "Successfully loaded channel {}", log_bytes!(channel.channel_id()));
                                        if let Some(short_channel_id) = channel.get_short_channel_id() {
@@ -7384,16 +7333,6 @@ impl<'a, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
                                None => continue,
                        }
                }
-               if forward_htlcs_count > 0 {
-                       // If we have pending HTLCs to forward, assume we either dropped a
-                       // `PendingHTLCsForwardable` or the user received it but never processed it as they
-                       // shut down before the timer hit. Either way, set the time_forwardable to a small
-                       // constant as enough time has likely passed that we should simply handle the forwards
-                       // now, or at least after the user gets a chance to reconnect to our peers.
-                       pending_events_read.push(events::Event::PendingHTLCsForwardable {
-                               time_forwardable: Duration::from_secs(2),
-                       });
-               }
 
                let background_event_count: u64 = Readable::read(reader)?;
                let mut pending_background_events_read: Vec<BackgroundEvent> = Vec::with_capacity(cmp::min(background_event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<BackgroundEvent>()));
@@ -7504,10 +7443,44 @@ impl<'a, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
                                                        }
                                                }
                                        }
+                                       for (htlc_source, htlc) in monitor.get_all_current_outbound_htlcs() {
+                                               if let HTLCSource::PreviousHopData(prev_hop_data) = htlc_source {
+                                                       // The ChannelMonitor is now responsible for this HTLC's
+                                                       // failure/success and will let us know what its outcome is. If we
+                                                       // still have an entry for this HTLC in `forward_htlcs`, we were
+                                                       // apparently not persisted after the monitor was when forwarding
+                                                       // the payment.
+                                                       forward_htlcs.retain(|_, forwards| {
+                                                               forwards.retain(|forward| {
+                                                                       if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
+                                                                               if htlc_info.prev_short_channel_id == prev_hop_data.short_channel_id &&
+                                                                                       htlc_info.prev_htlc_id == prev_hop_data.htlc_id
+                                                                               {
+                                                                                       log_info!(args.logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
+                                                                                               log_bytes!(htlc.payment_hash.0), log_bytes!(monitor.get_funding_txo().0.to_channel_id()));
+                                                                                       false
+                                                                               } else { true }
+                                                                       } else { true }
+                                                               });
+                                                               !forwards.is_empty()
+                                                       })
+                                               }
+                                       }
                                }
                        }
                }
 
+               if !forward_htlcs.is_empty() {
+                       // If we have pending HTLCs to forward, assume we either dropped a
+                       // `PendingHTLCsForwardable` or the user received it but never processed it as they
+                       // shut down before the timer hit. Either way, set the time_forwardable to a small
+                       // constant as enough time has likely passed that we should simply handle the forwards
+                       // now, or at least after the user gets a chance to reconnect to our peers.
+                       pending_events_read.push(events::Event::PendingHTLCsForwardable {
+                               time_forwardable: Duration::from_secs(2),
+                       });
+               }
+
                let inbound_pmt_key_material = args.keys_manager.get_inbound_payment_key_material();
                let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
 
@@ -8441,7 +8414,7 @@ pub mod bench {
                                $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &get_event_msg!(NodeHolder { node: &$node_a }, MessageSendEvent::SendRevokeAndACK, $node_b.get_our_node_id()));
 
                                expect_pending_htlcs_forwardable!(NodeHolder { node: &$node_b });
-                               expect_payment_received!(NodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
+                               expect_payment_claimable!(NodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
                                $node_b.claim_funds(payment_preimage);
                                expect_payment_claimed!(NodeHolder { node: &$node_b }, payment_hash, 10_000);
 
index 9ca5bbab125701c7dc840bb0ea4b3a55da771813..bdf40f466e7450b476c4678b343751f70f919337 100644 (file)
@@ -1127,7 +1127,7 @@ macro_rules! check_closed_event {
                use $crate::util::events::Event;
 
                let events = $node.node.get_and_clear_pending_events();
-               assert_eq!(events.len(), $events);
+               assert_eq!(events.len(), $events, "{:?}", events);
                let expected_reason = $reason;
                let mut issues_discard_funding = false;
                for event in events {
@@ -1386,7 +1386,7 @@ macro_rules! expect_pending_htlcs_forwardable_conditions {
                let events = $node.node.get_and_clear_pending_events();
                match events[0] {
                        $crate::util::events::Event::PendingHTLCsForwardable { .. } => { },
-                       _ => panic!("Unexpected event"),
+                       _ => panic!("Unexpected event {:?}", events),
                };
 
                let count = expected_failures.len() + 1;
@@ -1471,15 +1471,15 @@ macro_rules! expect_pending_htlcs_forwardable_from_events {
 }
 #[macro_export]
 #[cfg(any(test, feature = "_bench_unstable", feature = "_test_utils"))]
-macro_rules! expect_payment_received {
+macro_rules! expect_payment_claimable {
        ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr) => {
-               expect_payment_received!($node, $expected_payment_hash, $expected_payment_secret, $expected_recv_value, None, $node.node.get_our_node_id())
+               expect_payment_claimable!($node, $expected_payment_hash, $expected_payment_secret, $expected_recv_value, None, $node.node.get_our_node_id())
        };
        ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr, $expected_payment_preimage: expr, $expected_receiver_node_id: expr) => {
                let events = $node.node.get_and_clear_pending_events();
                assert_eq!(events.len(), 1);
                match events[0] {
-                       $crate::util::events::Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id: _, via_user_channel_id: _ } => {
+                       $crate::util::events::Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id: _, via_user_channel_id: _ } => {
                                assert_eq!($expected_payment_hash, *payment_hash);
                                assert_eq!($expected_recv_value, amount_msat);
                                assert_eq!($expected_receiver_node_id, receiver_node_id.unwrap());
@@ -1596,7 +1596,7 @@ macro_rules! expect_payment_forwarded {
                                if !$downstream_force_closed {
                                        assert!($node.node.list_channels().iter().any(|x| x.counterparty.node_id == $next_node.node.get_our_node_id() && x.channel_id == next_channel_id.unwrap()));
                                }
-                               assert_eq!(claim_from_onchain_tx, $upstream_force_closed);
+                               assert_eq!(claim_from_onchain_tx, $downstream_force_closed);
                        },
                        _ => panic!("Unexpected event"),
                }
@@ -1756,7 +1756,7 @@ pub fn send_along_route_with_secret<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>,
        payment_id
 }
 
-pub fn do_pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: Option<PaymentSecret>, ev: MessageSendEvent, payment_received_expected: bool, clear_recipient_events: bool, expected_preimage: Option<PaymentPreimage>) {
+pub fn do_pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: Option<PaymentSecret>, ev: MessageSendEvent, payment_claimable_expected: bool, clear_recipient_events: bool, expected_preimage: Option<PaymentPreimage>) {
        let mut payment_event = SendEvent::from_event(ev);
        let mut prev_node = origin_node;
 
@@ -1771,10 +1771,10 @@ pub fn do_pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_p
 
                if idx == expected_path.len() - 1 && clear_recipient_events {
                        let events_2 = node.node.get_and_clear_pending_events();
-                       if payment_received_expected {
+                       if payment_claimable_expected {
                                assert_eq!(events_2.len(), 1);
                                match events_2[0] {
-                                       Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat, receiver_node_id, ref via_channel_id, ref via_user_channel_id } => {
+                                       Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, ref via_channel_id, ref via_user_channel_id } => {
                                                assert_eq!(our_payment_hash, *payment_hash);
                                                assert_eq!(node.node.get_our_node_id(), receiver_node_id.unwrap());
                                                match &purpose {
@@ -1808,8 +1808,8 @@ pub fn do_pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_p
        }
 }
 
-pub fn pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: Option<PaymentSecret>, ev: MessageSendEvent, payment_received_expected: bool, expected_preimage: Option<PaymentPreimage>) {
-       do_pass_along_path(origin_node, expected_path, recv_value, our_payment_hash, our_payment_secret, ev, payment_received_expected, true, expected_preimage);
+pub fn pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: Option<PaymentSecret>, ev: MessageSendEvent, payment_claimable_expected: bool, expected_preimage: Option<PaymentPreimage>) {
+       do_pass_along_path(origin_node, expected_path, recv_value, our_payment_hash, our_payment_secret, ev, payment_claimable_expected, true, expected_preimage);
 }
 
 pub fn pass_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&[&Node<'a, 'b, 'c>]], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: PaymentSecret) {
@@ -1817,7 +1817,7 @@ pub fn pass_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_rou
        assert_eq!(events.len(), expected_route.len());
        for (path_idx, (ev, expected_path)) in events.drain(..).zip(expected_route.iter()).enumerate() {
                // Once we've gotten through all the HTLCs, the last one should result in a
-               // PaymentReceived (but each previous one should not!), .
+               // PaymentClaimable (but each previous one should not!), .
                let expect_payment = path_idx == expected_route.len() - 1;
                pass_along_path(origin_node, expected_path, recv_value, our_payment_hash.clone(), Some(our_payment_secret), ev, expect_payment, None);
        }
index c0d6eb2cd697379aaf6568641b8dbd523a026e38..79c85e75447d5bb959ef391c5941d0d62db933ff 100644 (file)
@@ -30,7 +30,7 @@ use crate::ln::features::{ChannelFeatures, NodeFeatures};
 use crate::ln::msgs;
 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
 use crate::util::enforcing_trait_impls::EnforcingSigner;
-use crate::util::{byte_utils, test_utils};
+use crate::util::test_utils;
 use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason, HTLCDestination};
 use crate::util::errors::APIError;
 use crate::util::ser::{Writeable, ReadableArgs};
@@ -705,7 +705,7 @@ fn test_update_fee_that_funder_cannot_afford() {
 
        // Assemble the set of keys we can use for signatures for our commitment_signed message.
        let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
-               &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
+               &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
 
        let res = {
                let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
@@ -834,7 +834,7 @@ fn test_update_fee_with_fundee_update_add_htlc() {
        let events = nodes[0].node.get_and_clear_pending_events();
        assert_eq!(events.len(), 1);
        match events[0] {
-               Event::PaymentReceived { .. } => { },
+               Event::PaymentClaimable { .. } => { },
                _ => panic!("Unexpected event"),
        };
 
@@ -1179,7 +1179,7 @@ fn holding_cell_htlc_counting() {
        assert_eq!(events.len(), payments.len());
        for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
                match event {
-                       &Event::PaymentReceived { ref payment_hash, .. } => {
+                       &Event::PaymentClaimable { ref payment_hash, .. } => {
                                assert_eq!(*payment_hash, *hash);
                        },
                        _ => panic!("Unexpected event"),
@@ -1412,7 +1412,7 @@ fn test_fee_spike_violation_fails_htlc() {
 
        // Assemble the set of keys we can use for signatures for our commitment_signed message.
        let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
-               &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
+               &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
 
        // Build the remote commitment transaction so we can sign it, and then later use the
        // signature for the commitment_signed message.
@@ -1936,7 +1936,7 @@ fn test_channel_reserve_holding_cell_htlcs() {
        commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
 
        expect_pending_htlcs_forwardable!(nodes[2]);
-       expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
+       expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
 
        // flush the htlcs in the holding cell
        assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
@@ -1956,7 +1956,7 @@ fn test_channel_reserve_holding_cell_htlcs() {
        let events = nodes[2].node.get_and_clear_pending_events();
        assert_eq!(events.len(), 2);
        match events[0] {
-               Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
+               Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
                        assert_eq!(our_payment_hash_21, *payment_hash);
                        assert_eq!(recv_value_21, amount_msat);
                        assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
@@ -1972,7 +1972,7 @@ fn test_channel_reserve_holding_cell_htlcs() {
                _ => panic!("Unexpected event"),
        }
        match events[1] {
-               Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
+               Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
                        assert_eq!(our_payment_hash_22, *payment_hash);
                        assert_eq!(recv_value_22, amount_msat);
                        assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
@@ -2106,7 +2106,7 @@ fn channel_reserve_in_flight_removes() {
        assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
 
        expect_pending_htlcs_forwardable!(nodes[1]);
-       expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
+       expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
 
        // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
        // resolve the second HTLC from A's point of view.
@@ -2153,7 +2153,7 @@ fn channel_reserve_in_flight_removes() {
        check_added_monitors!(nodes[0], 1);
 
        expect_pending_htlcs_forwardable!(nodes[0]);
-       expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
+       expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
 
        claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
        claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
@@ -3739,7 +3739,7 @@ fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken
        let events_2 = nodes[1].node.get_and_clear_pending_events();
        assert_eq!(events_2.len(), 1);
        match events_2[0] {
-               Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
+               Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
                        assert_eq!(payment_hash_1, *payment_hash);
                        assert_eq!(amount_msat, 1_000_000);
                        assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
@@ -4025,7 +4025,7 @@ fn test_drop_messages_peer_disconnect_dual_htlc() {
        let events_5 = nodes[1].node.get_and_clear_pending_events();
        assert_eq!(events_5.len(), 1);
        match events_5[0] {
-               Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
+               Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
                        assert_eq!(payment_hash_2, *payment_hash);
                        match &purpose {
                                PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
@@ -4068,7 +4068,7 @@ fn do_test_htlc_timeout(send_partial_mpp: bool) {
                let mut events = nodes[0].node.get_and_clear_pending_msg_events();
                assert_eq!(events.len(), 1);
                // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
-               // hop should *not* yet generate any PaymentReceived event(s).
+               // hop should *not* yet generate any PaymentClaimable event(s).
                pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
                our_payment_hash
        } else {
@@ -4100,8 +4100,8 @@ fn do_test_htlc_timeout(send_partial_mpp: bool) {
        nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
        commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
        // 100_000 msat as u64, followed by the height at which we failed back above
-       let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
-       expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
+       let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
+       expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
        expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
 }
 
@@ -4803,7 +4803,7 @@ fn test_duplicate_payment_hash_one_failure_one_success() {
        assert_eq!(htlc_success_txn[2], commitment_txn[0]);
        assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
        assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
-       assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
+       assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
 
        mine_transaction(&nodes[1], &htlc_timeout_tx);
        connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
@@ -4826,7 +4826,7 @@ fn test_duplicate_payment_hash_one_failure_one_success() {
        // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
        // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
        // and nodes[2] fee) is rounded down and then claimed in full.
-       mine_transaction(&nodes[1], &htlc_success_txn[0]);
+       mine_transaction(&nodes[1], &htlc_success_txn[1]);
        expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
        let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
        assert!(updates.update_add_htlcs.is_empty());
@@ -5800,7 +5800,7 @@ fn test_free_and_fail_holding_cell_htlcs() {
        let events = nodes[1].node.get_and_clear_pending_events();
        assert_eq!(events.len(), 1);
        match events[0] {
-               Event::PaymentReceived { .. } => {},
+               Event::PaymentClaimable { .. } => {},
                _ => panic!("Unexpected event"),
        }
        nodes[1].node.claim_funds(payment_preimage_1);
@@ -6059,7 +6059,7 @@ fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment()
                commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
 
                expect_pending_htlcs_forwardable!(nodes[1]);
-               expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
+               expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
        }
        let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
        unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
@@ -6974,8 +6974,8 @@ fn test_check_htlc_underpaying() {
        commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
 
        // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
-       let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
-       expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
+       let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
+       expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
        expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
 }
 
@@ -7954,7 +7954,7 @@ fn test_preimage_storage() {
        let events = nodes[1].node.get_and_clear_pending_events();
        assert_eq!(events.len(), 1);
        match events[0] {
-               Event::PaymentReceived { ref purpose, .. } => {
+               Event::PaymentClaimable { ref purpose, .. } => {
                        match &purpose {
                                PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
                                        claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
@@ -8024,7 +8024,7 @@ fn test_secret_timeout() {
        let events = nodes[1].node.get_and_clear_pending_events();
        assert_eq!(events.len(), 1);
        match events[0] {
-               Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
+               Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
                        assert!(payment_preimage.is_none());
                        assert_eq!(payment_secret, our_payment_secret);
                        // We don't actually have the payment preimage with which to claim this payment!
@@ -8131,7 +8131,7 @@ fn test_update_err_monitor_lockdown() {
                let mut w = test_utils::TestVecWriter(Vec::new());
                monitor.write(&mut w).unwrap();
                let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
-                               &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
+                               &mut io::Cursor::new(&w.0), nodes[0].keys_manager).unwrap().1;
                assert!(new_monitor == *monitor);
                let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
                assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
@@ -8195,7 +8195,7 @@ fn test_concurrent_monitor_claim() {
                let mut w = test_utils::TestVecWriter(Vec::new());
                monitor.write(&mut w).unwrap();
                let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
-                               &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
+                               &mut io::Cursor::new(&w.0), nodes[0].keys_manager).unwrap().1;
                assert!(new_monitor == *monitor);
                let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
                assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
@@ -8224,7 +8224,7 @@ fn test_concurrent_monitor_claim() {
                let mut w = test_utils::TestVecWriter(Vec::new());
                monitor.write(&mut w).unwrap();
                let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
-                               &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
+                               &mut io::Cursor::new(&w.0), nodes[0].keys_manager).unwrap().1;
                assert!(new_monitor == *monitor);
                let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
                assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
@@ -8959,7 +8959,7 @@ fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
                commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
        }
        expect_pending_htlcs_forwardable!(nodes[1]);
-       expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
+       expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
 
        {
                // Note that we use a different PaymentId here to allow us to duplicativly pay
@@ -9021,7 +9021,7 @@ fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
 #[test]
 fn test_dup_htlc_second_fail_panic() {
        // Previously, if we received two HTLCs back-to-back, where the second overran the expected
-       // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
+       // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
        // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
        // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
        do_test_dup_htlc_second_rejected(true);
@@ -9208,9 +9208,9 @@ fn test_keysend_payments_to_private_node() {
 
 #[test]
 fn test_double_partial_claim() {
-       // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
+       // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
        // time out, the sender resends only some of the MPP parts, then the user processes the
-       // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
+       // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
        // amount.
        let chanmon_cfgs = create_chanmon_cfgs(4);
        let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
@@ -9231,7 +9231,7 @@ fn test_double_partial_claim() {
        });
 
        send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
-       // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
+       // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
        // amount of time to respond to.
 
        // Connect some blocks to time out the payment
@@ -9255,7 +9255,7 @@ fn test_double_partial_claim() {
        pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
 
        // At this point nodes[3] has received one half of the payment, and the user goes to handle
-       // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
+       // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
        nodes[3].node.claim_funds(payment_preimage);
        check_added_monitors!(nodes[3], 0);
        assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
index cee75f8c2076b9df36e4bcf824aa887795358387..8726c6a996204b99e0fa653c3240a348c2752fcf 100644 (file)
@@ -616,7 +616,7 @@ fn test_balances_on_local_commitment_htlcs() {
        commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
 
        expect_pending_htlcs_forwardable!(nodes[1]);
-       expect_payment_received!(nodes[1], payment_hash, payment_secret, 10_000_000);
+       expect_payment_claimable!(nodes[1], payment_hash, payment_secret, 10_000_000);
 
        let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 20_000_000);
        nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
@@ -627,7 +627,7 @@ fn test_balances_on_local_commitment_htlcs() {
        commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
 
        expect_pending_htlcs_forwardable!(nodes[1]);
-       expect_payment_received!(nodes[1], payment_hash_2, payment_secret_2, 20_000_000);
+       expect_payment_claimable!(nodes[1], payment_hash_2, payment_secret_2, 20_000_000);
        nodes[1].node.claim_funds(payment_preimage_2);
        get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
        check_added_monitors!(nodes[1], 1);
index 2bf36ffba8997fda27777e016d3bd643c9bc212e..ca2fd76584174a5e1be7b2c405c28a0cf29541d3 100644 (file)
@@ -25,7 +25,7 @@ use crate::ln::msgs::{ChannelMessageHandler, ChannelUpdate};
 use crate::ln::wire::Encode;
 use crate::util::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
 use crate::util::ser::{Writeable, Writer};
-use crate::util::{byte_utils, test_utils};
+use crate::util::test_utils;
 use crate::util::config::{UserConfig, ChannelConfig};
 use crate::util::errors::APIError;
 
@@ -125,7 +125,7 @@ fn run_onion_failure_test_with_fail_intercept<F1,F2,F3>(_name: &str, test_case:
 
                        if test_case == 2 || test_case == 200 {
                                expect_htlc_forward!(&nodes[2]);
-                               expect_event!(&nodes[2], Event::PaymentReceived);
+                               expect_event!(&nodes[2], Event::PaymentClaimable);
                                callback_node();
                                expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
                        }
@@ -548,7 +548,7 @@ fn test_onion_failure() {
                connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
                connect_blocks(&nodes[1], height - nodes[1].best_block_info().1);
                connect_blocks(&nodes[2], height - nodes[2].best_block_info().1);
-       }, || {}, true, Some(17), None, None);
+       }, || {}, false, Some(0x4000 | 15), None, None);
 
        run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, &payment_secret, |_| {}, || {
                for (_, pending_forwards) in nodes[1].node.forward_htlcs.lock().unwrap().iter_mut() {
@@ -1053,8 +1053,8 @@ fn test_phantom_final_incorrect_cltv_expiry() {
        commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
 
        // Ensure the payment fails with the expected error.
-       let expected_cltv = 82;
-       let error_data = byte_utils::be32_to_array(expected_cltv).to_vec();
+       let expected_cltv: u32 = 82;
+       let error_data = expected_cltv.to_be_bytes().to_vec();
        let mut fail_conditions = PaymentFailedConditions::new()
                .blamed_scid(phantom_scid)
                .expected_htlc_error_data(18, &error_data);
@@ -1099,10 +1099,93 @@ fn test_phantom_failure_too_low_cltv() {
        commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
 
        // Ensure the payment fails with the expected error.
-       let error_data = Vec::new();
+       let mut error_data = recv_value_msat.to_be_bytes().to_vec();
+       error_data.extend_from_slice(
+               &nodes[0].node.best_block.read().unwrap().height().to_be_bytes(),
+       );
+       let mut fail_conditions = PaymentFailedConditions::new()
+               .blamed_scid(phantom_scid)
+               .expected_htlc_error_data(0x4000 | 15, &error_data);
+       expect_payment_failed_conditions(&nodes[0], payment_hash, true, fail_conditions);
+}
+
+#[test]
+fn test_phantom_failure_modified_cltv() {
+       // Test that we fail back phantoms if the upstream node fiddled with the CLTV too much with the
+       // correct error code.
+       let chanmon_cfgs = create_chanmon_cfgs(2);
+       let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+       let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
+       let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+
+       let channel = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
+
+       // Get the route.
+       let recv_value_msat = 10_000;
+       let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
+       let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
+
+       // Route the HTLC through to the destination.
+       nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
+       check_added_monitors!(nodes[0], 1);
+       let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
+       let mut update_add = update_0.update_add_htlcs[0].clone();
+
+       // Modify the route to have a too-low cltv.
+       update_add.cltv_expiry -= 10;
+
+       nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
+       commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
+
+       let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
+       assert!(update_1.update_fail_htlcs.len() == 1);
+       let fail_msg = update_1.update_fail_htlcs[0].clone();
+       nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
+       commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
+
+       // Ensure the payment fails with the expected error.
        let mut fail_conditions = PaymentFailedConditions::new()
                .blamed_scid(phantom_scid)
-               .expected_htlc_error_data(17, &error_data);
+               .expected_htlc_error_data(0x2000 | 2, &[]);
+       expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
+}
+
+#[test]
+fn test_phantom_failure_expires_too_soon() {
+       // Test that we fail back phantoms if the HTLC got delayed and we got blocks in between with
+       // the correct error code.
+       let chanmon_cfgs = create_chanmon_cfgs(2);
+       let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+       let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
+       let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+
+       let channel = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
+
+       // Get the route.
+       let recv_value_msat = 10_000;
+       let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1], Some(recv_value_msat));
+       let (mut route, phantom_scid) = get_phantom_route!(nodes, recv_value_msat, channel);
+
+       // Route the HTLC through to the destination.
+       nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
+       check_added_monitors!(nodes[0], 1);
+       let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
+       let mut update_add = update_0.update_add_htlcs[0].clone();
+
+       connect_blocks(&nodes[1], CLTV_FAR_FAR_AWAY);
+       nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
+       commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
+
+       let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
+       assert!(update_1.update_fail_htlcs.len() == 1);
+       let fail_msg = update_1.update_fail_htlcs[0].clone();
+       nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
+       commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
+
+       // Ensure the payment fails with the expected error.
+       let mut fail_conditions = PaymentFailedConditions::new()
+               .blamed_scid(phantom_scid)
+               .expected_htlc_error_data(0x2000 | 2, &[]);
        expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
 }
 
@@ -1144,10 +1227,8 @@ fn test_phantom_failure_too_low_recv_amt() {
        commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
 
        // Ensure the payment fails with the expected error.
-       let mut error_data = byte_utils::be64_to_array(bad_recv_amt_msat).to_vec();
-       error_data.extend_from_slice(
-               &byte_utils::be32_to_array(nodes[1].node.best_block.read().unwrap().height()),
-       );
+       let mut error_data = bad_recv_amt_msat.to_be_bytes().to_vec();
+       error_data.extend_from_slice(&nodes[1].node.best_block.read().unwrap().height().to_be_bytes());
        let mut fail_conditions = PaymentFailedConditions::new()
                .blamed_scid(phantom_scid)
                .expected_htlc_error_data(0x4000 | 15, &error_data);
@@ -1229,7 +1310,7 @@ fn test_phantom_failure_reject_payment() {
        nodes[1].node.process_pending_htlc_forwards();
        expect_pending_htlcs_forwardable_ignore!(nodes[1]);
        nodes[1].node.process_pending_htlc_forwards();
-       expect_payment_received!(nodes[1], payment_hash, payment_secret, recv_amt_msat, None, route.paths[0].last().unwrap().pubkey);
+       expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_amt_msat, None, route.paths[0].last().unwrap().pubkey);
        nodes[1].node.fail_htlc_backwards(&payment_hash);
        expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
        nodes[1].node.process_pending_htlc_forwards();
@@ -1242,10 +1323,8 @@ fn test_phantom_failure_reject_payment() {
        commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
 
        // Ensure the payment fails with the expected error.
-       let mut error_data = byte_utils::be64_to_array(recv_amt_msat).to_vec();
-       error_data.extend_from_slice(
-               &byte_utils::be32_to_array(nodes[1].node.best_block.read().unwrap().height()),
-       );
+       let mut error_data = recv_amt_msat.to_be_bytes().to_vec();
+       error_data.extend_from_slice(&nodes[1].node.best_block.read().unwrap().height().to_be_bytes());
        let mut fail_conditions = PaymentFailedConditions::new()
                .blamed_scid(phantom_scid)
                .expected_htlc_error_data(0x4000 | 15, &error_data);
index 6f85e2db8d60f2684bc867bb5636cfa22b00f168..1abaf5920a51d8476d56b6f65968f725bd1a781a 100644 (file)
@@ -15,7 +15,7 @@ use crate::routing::gossip::NetworkUpdate;
 use crate::routing::router::RouteHop;
 use crate::util::chacha20::{ChaCha20, ChaChaReader};
 use crate::util::errors::{self, APIError};
-use crate::util::ser::{Readable, ReadableArgs, Writeable, LengthCalculatingWriter};
+use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer, LengthCalculatingWriter};
 use crate::util::logger::Logger;
 
 use bitcoin::hashes::{Hash, HashEngine};
@@ -382,7 +382,7 @@ pub(super) fn build_failure_packet(shared_secret: &[u8], failure_type: u16, fail
        packet
 }
 
-#[inline]
+#[cfg(test)]
 pub(super) fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
        let failure_packet = build_failure_packet(shared_secret, failure_type, failure_data);
        encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
@@ -592,6 +592,146 @@ pub(super) fn process_onion_failure<T: secp256k1::Signing, L: Deref>(secp_ctx: &
        } else { unreachable!(); }
 }
 
+#[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
+pub(super) struct HTLCFailReason(HTLCFailReasonRepr);
+
+#[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
+enum HTLCFailReasonRepr {
+       LightningError {
+               err: msgs::OnionErrorPacket,
+       },
+       Reason {
+               failure_code: u16,
+               data: Vec<u8>,
+       }
+}
+
+impl core::fmt::Debug for HTLCFailReason {
+       fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
+               match self.0 {
+                       HTLCFailReasonRepr::Reason { ref failure_code, .. } => {
+                               write!(f, "HTLC error code {}", failure_code)
+                       },
+                       HTLCFailReasonRepr::LightningError { .. } => {
+                               write!(f, "pre-built LightningError")
+                       }
+               }
+       }
+}
+
+impl Writeable for HTLCFailReason {
+       fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
+               self.0.write(writer)
+       }
+}
+impl Readable for HTLCFailReason {
+       fn read<R: Read>(reader: &mut R) -> Result<Self, msgs::DecodeError> {
+               Ok(Self(Readable::read(reader)?))
+       }
+}
+
+impl_writeable_tlv_based_enum!(HTLCFailReasonRepr,
+       (0, LightningError) => {
+               (0, err, required),
+       },
+       (1, Reason) => {
+               (0, failure_code, required),
+               (2, data, vec_type),
+       },
+;);
+
+impl HTLCFailReason {
+       pub(super) fn reason(failure_code: u16, data: Vec<u8>) -> Self {
+               const BADONION: u16 = 0x8000;
+               const PERM: u16 = 0x4000;
+               const NODE: u16 = 0x2000;
+               const UPDATE: u16 = 0x1000;
+
+                    if failure_code == 1  | PERM { debug_assert!(data.is_empty()) }
+               else if failure_code == 2  | NODE { debug_assert!(data.is_empty()) }
+               else if failure_code == 2  | PERM | NODE { debug_assert!(data.is_empty()) }
+               else if failure_code == 3  | PERM | NODE { debug_assert!(data.is_empty()) }
+               else if failure_code == 4  | BADONION | PERM { debug_assert_eq!(data.len(), 32) }
+               else if failure_code == 5  | BADONION | PERM { debug_assert_eq!(data.len(), 32) }
+               else if failure_code == 6  | BADONION | PERM { debug_assert_eq!(data.len(), 32) }
+               else if failure_code == 7  | UPDATE {
+                       debug_assert_eq!(data.len() - 2, u16::from_be_bytes(data[0..2].try_into().unwrap()) as usize) }
+               else if failure_code == 8  | PERM { debug_assert!(data.is_empty()) }
+               else if failure_code == 9  | PERM { debug_assert!(data.is_empty()) }
+               else if failure_code == 10 | PERM { debug_assert!(data.is_empty()) }
+               else if failure_code == 11 | UPDATE {
+                       debug_assert_eq!(data.len() - 2 - 8, u16::from_be_bytes(data[8..10].try_into().unwrap()) as usize) }
+               else if failure_code == 12 | UPDATE {
+                       debug_assert_eq!(data.len() - 2 - 8, u16::from_be_bytes(data[8..10].try_into().unwrap()) as usize) }
+               else if failure_code == 13 | UPDATE {
+                       debug_assert_eq!(data.len() - 2 - 4, u16::from_be_bytes(data[4..6].try_into().unwrap()) as usize) }
+               else if failure_code == 14 | UPDATE {
+                       debug_assert_eq!(data.len() - 2, u16::from_be_bytes(data[0..2].try_into().unwrap()) as usize) }
+               else if failure_code == 15 | PERM { debug_assert_eq!(data.len(), 12) }
+               else if failure_code == 18 { debug_assert_eq!(data.len(), 4) }
+               else if failure_code == 19 { debug_assert_eq!(data.len(), 8) }
+               else if failure_code == 20 | UPDATE {
+                       debug_assert_eq!(data.len() - 2 - 2, u16::from_be_bytes(data[2..4].try_into().unwrap()) as usize) }
+               else if failure_code == 21 { debug_assert!(data.is_empty()) }
+               else if failure_code == 22 | PERM { debug_assert!(data.len() <= 11) }
+               else if failure_code == 23 { debug_assert!(data.is_empty()) }
+               else if failure_code & BADONION != 0 {
+                       // We set some bogus BADONION failure codes in test, so ignore unknown ones.
+               }
+               else { debug_assert!(false, "Unknown failure code: {}", failure_code) }
+
+               Self(HTLCFailReasonRepr::Reason { failure_code, data })
+       }
+
+       pub(super) fn from_failure_code(failure_code: u16) -> Self {
+               Self::reason(failure_code, Vec::new())
+       }
+
+       pub(super) fn from_msg(msg: &msgs::UpdateFailHTLC) -> Self {
+               Self(HTLCFailReasonRepr::LightningError { err: msg.reason.clone() })
+       }
+
+       pub(super) fn get_encrypted_failure_packet(&self, incoming_packet_shared_secret: &[u8; 32], phantom_shared_secret: &Option<[u8; 32]>)
+       -> msgs::OnionErrorPacket {
+               match self.0 {
+                       HTLCFailReasonRepr::Reason { ref failure_code, ref data } => {
+                               if let Some(phantom_ss) = phantom_shared_secret {
+                                       let phantom_packet = build_failure_packet(phantom_ss, *failure_code, &data[..]).encode();
+                                       let encrypted_phantom_packet = encrypt_failure_packet(phantom_ss, &phantom_packet);
+                                       encrypt_failure_packet(incoming_packet_shared_secret, &encrypted_phantom_packet.data[..])
+                               } else {
+                                       let packet = build_failure_packet(incoming_packet_shared_secret, *failure_code, &data[..]).encode();
+                                       encrypt_failure_packet(incoming_packet_shared_secret, &packet)
+                               }
+                       },
+                       HTLCFailReasonRepr::LightningError { ref err } => {
+                               encrypt_failure_packet(incoming_packet_shared_secret, &err.data)
+                       }
+               }
+       }
+
+       pub(super) fn decode_onion_failure<T: secp256k1::Signing, L: Deref>(
+               &self, secp_ctx: &Secp256k1<T>, logger: &L, htlc_source: &HTLCSource
+       ) -> (Option<NetworkUpdate>, Option<u64>, bool, Option<u16>, Option<Vec<u8>>)
+       where L::Target: Logger {
+               match self.0 {
+                       HTLCFailReasonRepr::LightningError { ref err } => {
+                               process_onion_failure(secp_ctx, logger, &htlc_source, err.data.clone())
+                       },
+                       HTLCFailReasonRepr::Reason { ref failure_code, ref data, .. } => {
+                               // we get a fail_malformed_htlc from the first hop
+                               // TODO: We'd like to generate a NetworkUpdate for temporary
+                               // failures here, but that would be insufficient as find_route
+                               // generally ignores its view of our own channels as we provide them via
+                               // ChannelDetails.
+                               if let &HTLCSource::OutboundRoute { ref path, .. } = htlc_source {
+                                       (None, Some(path.first().unwrap().short_channel_id), true, Some(*failure_code), Some(data.clone()))
+                               } else { unreachable!(); }
+                       }
+               }
+       }
+}
+
 /// Allows `decode_next_hop` to return the next hop packet bytes for either payments or onion
 /// message forwards.
 pub(crate) trait NextPacketBytes: AsMut<[u8]> {
index d9d22b6ca6b5bac82ac8c66b26b1e08124c4c878..ff65bac4bc8b9e7e18832ae067ab5bbf1769b57c 100644 (file)
@@ -1516,7 +1516,7 @@ fn do_test_intercepted_payment(test: InterceptTest) {
                expect_pending_htlcs_forwardable!(nodes[2]);
 
                let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
-               expect_payment_received!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
+               expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
                do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
                let events = nodes[0].node.get_and_clear_pending_events();
                assert_eq!(events.len(), 2);
index 42835ed8035637948ae89b067d229c52e9c71efc..f2166246d3c89000ab593970a3b10d5067170519 100644 (file)
@@ -694,7 +694,7 @@ fn test_0conf_channel_with_async_monitor() {
        nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_send.msgs[0]);
        commitment_signed_dance!(nodes[2], nodes[1], bs_send.commitment_msg, false);
        expect_pending_htlcs_forwardable!(nodes[2]);
-       expect_payment_received!(nodes[2], payment_hash, payment_secret, 1_000_000);
+       expect_payment_claimable!(nodes[2], payment_hash, payment_secret, 1_000_000);
        claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
 
        confirm_transaction(&nodes[0], &tx);
index 1056ceebdd9dc963e9255c6be690c1310de8bd6d..2c7e8e72bbee663fd824a7f3aad5a27b1c118792 100644 (file)
 //! Functional tests which test for correct behavior across node restarts.
 
 use crate::chain::{ChannelMonitorUpdateStatus, Watch};
+use crate::chain::chaininterface::LowerBoundedFeeEstimator;
 use crate::chain::channelmonitor::ChannelMonitor;
+use crate::chain::keysinterface::KeysInterface;
 use crate::chain::transaction::OutPoint;
 use crate::ln::channelmanager::{self, ChannelManager, ChannelManagerReadArgs, PaymentId};
 use crate::ln::msgs;
 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
 use crate::util::enforcing_trait_impls::EnforcingSigner;
 use crate::util::test_utils;
-use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
+use crate::util::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
 use crate::util::ser::{Writeable, ReadableArgs};
 use crate::util::config::UserConfig;
 
@@ -635,7 +637,7 @@ fn test_forwardable_regen() {
        assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
 
        expect_pending_htlcs_forwardable!(nodes[1]);
-       expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
+       expect_payment_claimable!(nodes[1], payment_hash, payment_secret, 100_000);
        check_added_monitors!(nodes[1], 1);
 
        let mut events = nodes[1].node.get_and_clear_pending_msg_events();
@@ -644,7 +646,7 @@ fn test_forwardable_regen() {
        nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
        commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
        expect_pending_htlcs_forwardable!(nodes[2]);
-       expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
+       expect_payment_claimable!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
 
        claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
        claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
@@ -654,7 +656,7 @@ fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
        // Test what happens if a node receives an MPP payment, claims it, but crashes before
        // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
        // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
-       // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
+       // have the PaymentClaimable event, (b) have one (or two) channel(s) that goes on chain with the
        // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
        // not have the preimage tied to the still-pending HTLC.
        //
@@ -691,7 +693,7 @@ fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
        nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
        check_added_monitors!(nodes[0], 2);
 
-       // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
+       // Send the payment through to nodes[3] *without* clearing the PaymentClaimable event
        let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
        assert_eq!(send_events.len(), 2);
        do_pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), send_events[0].clone(), true, false, None);
@@ -711,7 +713,7 @@ fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
 
        let original_manager = nodes[3].node.encode();
 
-       expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
+       expect_payment_claimable!(nodes[3], payment_hash, payment_secret, 15_000_000);
 
        nodes[3].node.claim_funds(payment_preimage);
        check_added_monitors!(nodes[3], 2);
@@ -748,11 +750,11 @@ fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
        nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
 
        // During deserialization, we should have closed one channel and broadcast its latest
-       // commitment transaction. We should also still have the original PaymentReceived event we
+       // commitment transaction. We should also still have the original PaymentClaimable event we
        // never finished processing.
        let events = nodes[3].node.get_and_clear_pending_events();
        assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
-       if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
+       if let Event::PaymentClaimable { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
        if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
        if persist_both_monitors {
                if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
@@ -811,3 +813,192 @@ fn test_partial_claim_before_restart() {
        do_test_partial_claim_before_restart(false);
        do_test_partial_claim_before_restart(true);
 }
+
+fn do_forwarded_payment_no_manager_persistence(use_cs_commitment: bool, claim_htlc: bool) {
+       if !use_cs_commitment { assert!(!claim_htlc); }
+       // If we go to forward a payment, and the ChannelMonitor persistence completes, but the
+       // ChannelManager does not, we shouldn't try to forward the payment again, nor should we fail
+       // it back until the ChannelMonitor decides the fate of the HTLC.
+       // This was never an issue, but it may be easy to regress here going forward.
+       let chanmon_cfgs = create_chanmon_cfgs(3);
+       let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
+       let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
+
+       let persister;
+       let new_chain_monitor;
+       let nodes_1_deserialized;
+
+       let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
+
+       let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
+       let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
+
+       let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
+       let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
+       let htlc_expiry = nodes[0].best_block_info().1 + TEST_FINAL_CLTV;
+       nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), payment_id).unwrap();
+       check_added_monitors!(nodes[0], 1);
+
+       let payment_event = SendEvent::from_node(&nodes[0]);
+       nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
+       commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
+
+       let node_encoded = nodes[1].node.encode();
+
+       expect_pending_htlcs_forwardable!(nodes[1]);
+
+       let payment_event = SendEvent::from_node(&nodes[1]);
+       nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
+       nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
+       check_added_monitors!(nodes[2], 1);
+
+       if claim_htlc {
+               get_monitor!(nodes[2], chan_id_2).provide_payment_preimage(&payment_hash, &payment_preimage,
+                       &nodes[2].tx_broadcaster, &LowerBoundedFeeEstimator(nodes[2].fee_estimator), &nodes[2].logger);
+       }
+       assert!(nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
+
+       let _ = nodes[2].node.get_and_clear_pending_msg_events();
+
+       nodes[2].node.force_close_broadcasting_latest_txn(&chan_id_2, &nodes[1].node.get_our_node_id()).unwrap();
+       let cs_commitment_tx = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
+       assert_eq!(cs_commitment_tx.len(), if claim_htlc { 2 } else { 1 });
+
+       check_added_monitors!(nodes[2], 1);
+       check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
+       check_closed_broadcast!(nodes[2], true);
+
+       let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id_1).encode();
+       let chan_1_monitor_serialized = get_monitor!(nodes[1], chan_id_2).encode();
+       reload_node!(nodes[1], node_encoded, &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
+
+       check_closed_event!(nodes[1], 1, ClosureReason::OutdatedChannelManager);
+
+       let bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
+       assert_eq!(bs_commitment_tx.len(), 1);
+
+       nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
+       reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
+
+       if use_cs_commitment {
+               // If we confirm a commitment transaction that has the HTLC on-chain, nodes[1] should wait
+               // for an HTLC-spending transaction before it does anything with the HTLC upstream.
+               confirm_transaction(&nodes[1], &cs_commitment_tx[0]);
+               assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
+               assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
+
+               if claim_htlc {
+                       confirm_transaction(&nodes[1], &cs_commitment_tx[1]);
+               } else {
+                       connect_blocks(&nodes[1], htlc_expiry - nodes[1].best_block_info().1);
+                       let bs_htlc_timeout_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
+                       assert_eq!(bs_htlc_timeout_tx.len(), 1);
+                       confirm_transaction(&nodes[1], &bs_htlc_timeout_tx[0]);
+               }
+       } else {
+               confirm_transaction(&nodes[1], &bs_commitment_tx[0]);
+       }
+
+       if !claim_htlc {
+               expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
+       } else {
+               expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(1000), false, true);
+       }
+       check_added_monitors!(nodes[1], 1);
+
+       let events = nodes[1].node.get_and_clear_pending_msg_events();
+       assert_eq!(events.len(), 1);
+       match &events[0] {
+               MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { update_fulfill_htlcs, update_fail_htlcs, commitment_signed, .. }, .. } => {
+                       if claim_htlc {
+                               nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
+                       } else {
+                               nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
+                       }
+                       commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
+               },
+               _ => panic!("Unexpected event"),
+       }
+
+       if claim_htlc {
+               expect_payment_sent!(nodes[0], payment_preimage);
+       } else {
+               expect_payment_failed!(nodes[0], payment_hash, false);
+       }
+}
+
+#[test]
+fn forwarded_payment_no_manager_persistence() {
+       do_forwarded_payment_no_manager_persistence(true, true);
+       do_forwarded_payment_no_manager_persistence(true, false);
+       do_forwarded_payment_no_manager_persistence(false, false);
+}
+
+#[test]
+fn removed_payment_no_manager_persistence() {
+       // If an HTLC is failed to us on a channel, and the ChannelMonitor persistence completes, but
+       // the corresponding ChannelManager persistence does not, we need to ensure that the HTLC is
+       // still failed back to the previous hop even though the ChannelMonitor now no longer is aware
+       // of the HTLC. This was previously broken as no attempt was made to figure out which HTLCs
+       // were left dangling when a channel was force-closed due to a stale ChannelManager.
+       let chanmon_cfgs = create_chanmon_cfgs(3);
+       let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
+       let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
+
+       let persister;
+       let new_chain_monitor;
+       let nodes_1_deserialized;
+
+       let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
+
+       let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
+       let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
+
+       let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
+
+       let node_encoded = nodes[1].node.encode();
+
+       nodes[2].node.fail_htlc_backwards(&payment_hash);
+       expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
+       check_added_monitors!(nodes[2], 1);
+       let events = nodes[2].node.get_and_clear_pending_msg_events();
+       assert_eq!(events.len(), 1);
+       match &events[0] {
+               MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. }, .. } => {
+                       nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &update_fail_htlcs[0]);
+                       commitment_signed_dance!(nodes[1], nodes[2], commitment_signed, false);
+               },
+               _ => panic!("Unexpected event"),
+       }
+
+       let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id_1).encode();
+       let chan_1_monitor_serialized = get_monitor!(nodes[1], chan_id_2).encode();
+       reload_node!(nodes[1], node_encoded, &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
+
+       match nodes[1].node.pop_pending_event().unwrap() {
+               Event::ChannelClosed { ref reason, .. } => {
+                       assert_eq!(*reason, ClosureReason::OutdatedChannelManager);
+               },
+               _ => panic!("Unexpected event"),
+       }
+
+       // Now that the ChannelManager has force-closed the channel which had the HTLC removed, it is
+       // now forgotten everywhere. The ChannelManager should have, as a side-effect of reload,
+       // learned that the HTLC is gone from the ChannelMonitor and added it to the to-fail-back set.
+       nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
+       reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
+
+       expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
+       check_added_monitors!(nodes[1], 1);
+       let events = nodes[1].node.get_and_clear_pending_msg_events();
+       assert_eq!(events.len(), 1);
+       match &events[0] {
+               MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. }, .. } => {
+                       nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
+                       commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
+               },
+               _ => panic!("Unexpected event"),
+       }
+
+       expect_payment_failed!(nodes[0], payment_hash, false);
+}
index 1ab6384e3b8ebe997b3e4c511ddcaf721946e935..419a6b73a697621bbb825865f440d2a04b26641a 100644 (file)
@@ -17,34 +17,6 @@ pub fn slice_to_be48(v: &[u8]) -> u64 {
        ((v[5] as u64) << 8*0)
 }
 #[inline]
-pub fn slice_to_be64(v: &[u8]) -> u64 {
-       ((v[0] as u64) << 8*7) |
-       ((v[1] as u64) << 8*6) |
-       ((v[2] as u64) << 8*5) |
-       ((v[3] as u64) << 8*4) |
-       ((v[4] as u64) << 8*3) |
-       ((v[5] as u64) << 8*2) |
-       ((v[6] as u64) << 8*1) |
-       ((v[7] as u64) << 8*0)
-}
-
-#[inline]
-pub fn be16_to_array(u: u16) -> [u8; 2] {
-       let mut v = [0; 2];
-       v[0] = ((u >> 8*1) & 0xff) as u8;
-       v[1] = ((u >> 8*0) & 0xff) as u8;
-       v
-}
-#[inline]
-pub fn be32_to_array(u: u32) -> [u8; 4] {
-       let mut v = [0; 4];
-       v[0] = ((u >> 8*3) & 0xff) as u8;
-       v[1] = ((u >> 8*2) & 0xff) as u8;
-       v[2] = ((u >> 8*1) & 0xff) as u8;
-       v[3] = ((u >> 8*0) & 0xff) as u8;
-       v
-}
-#[inline]
 pub fn be48_to_array(u: u64) -> [u8; 6] {
        assert!(u & 0xffff_0000_0000_0000 == 0);
        let mut v = [0; 6];
@@ -56,31 +28,14 @@ pub fn be48_to_array(u: u64) -> [u8; 6] {
        v[5] = ((u >> 8*0) & 0xff) as u8;
        v
 }
-#[inline]
-pub fn be64_to_array(u: u64) -> [u8; 8] {
-       let mut v = [0; 8];
-       v[0] = ((u >> 8*7) & 0xff) as u8;
-       v[1] = ((u >> 8*6) & 0xff) as u8;
-       v[2] = ((u >> 8*5) & 0xff) as u8;
-       v[3] = ((u >> 8*4) & 0xff) as u8;
-       v[4] = ((u >> 8*3) & 0xff) as u8;
-       v[5] = ((u >> 8*2) & 0xff) as u8;
-       v[6] = ((u >> 8*1) & 0xff) as u8;
-       v[7] = ((u >> 8*0) & 0xff) as u8;
-       v
-}
 
 #[cfg(test)]
 mod tests {
        use super::*;
-       
+
        #[test]
        fn test_all() {
                assert_eq!(slice_to_be48(&[0xde, 0xad, 0xbe, 0xef, 0x1b, 0xad]), 0xdeadbeef1bad);
-               assert_eq!(slice_to_be64(&[0xde, 0xad, 0xbe, 0xef, 0x1b, 0xad, 0x1d, 0xea]), 0xdeadbeef1bad1dea);
-               assert_eq!(be16_to_array(0xdead), [0xde, 0xad]);
-               assert_eq!(be32_to_array(0xdeadbeef), [0xde, 0xad, 0xbe, 0xef]);
                assert_eq!(be48_to_array(0xdeadbeef1bad), [0xde, 0xad, 0xbe, 0xef, 0x1b, 0xad]);
-               assert_eq!(be64_to_array(0xdeadbeef1bad1dea), [0xde, 0xad, 0xbe, 0xef, 0x1b, 0xad, 0x1d, 0xea]);
        }
 }
index 55bad7f63f24502bf84b774329fbc1487a5166a9..1a9038a2f5dc1c3c2122e71f8f6a5b0d4e945782 100644 (file)
@@ -23,6 +23,8 @@ use bitcoin::util::sighash;
 use bitcoin::secp256k1;
 use bitcoin::secp256k1::{SecretKey, PublicKey};
 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
+#[cfg(anchors)]
+use crate::util::events::HTLCDescriptor;
 use crate::util::ser::{Writeable, Writer};
 use crate::io::Error;
 
@@ -190,6 +192,17 @@ impl BaseSign for EnforcingSigner {
                Ok(self.inner.sign_justice_revoked_htlc(justice_tx, input, amount, per_commitment_key, htlc, secp_ctx).unwrap())
        }
 
+       #[cfg(anchors)]
+       fn sign_holder_htlc_transaction(
+               &self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
+               secp_ctx: &Secp256k1<secp256k1::All>
+       ) -> Result<Signature, ()> {
+               let per_commitment_point = self.get_per_commitment_point(htlc_descriptor.per_commitment_number, secp_ctx);
+               assert_eq!(htlc_tx.input[input], htlc_descriptor.unsigned_tx_input());
+               assert_eq!(htlc_tx.output[input], htlc_descriptor.tx_output(&per_commitment_point, secp_ctx));
+               Ok(self.inner.sign_holder_htlc_transaction(htlc_tx, input, htlc_descriptor, secp_ctx).unwrap())
+       }
+
        fn sign_counterparty_htlc_transaction(&self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
                Ok(self.inner.sign_counterparty_htlc_transaction(htlc_tx, input, amount, per_commitment_point, htlc, secp_ctx).unwrap())
        }
@@ -215,8 +228,8 @@ impl BaseSign for EnforcingSigner {
                self.inner.sign_channel_announcement(msg, secp_ctx)
        }
 
-       fn ready_channel(&mut self, channel_parameters: &ChannelTransactionParameters) {
-               self.inner.ready_channel(channel_parameters)
+       fn provide_channel_parameters(&mut self, channel_parameters: &ChannelTransactionParameters) {
+               self.inner.provide_channel_parameters(channel_parameters)
        }
 }
 
index 18058bc03a8e10505ce0f966729cb56d66a7d147..2c7e5413dafff9d9f027eab116d0967faae6ed2e 100644 (file)
@@ -16,7 +16,7 @@
 
 use crate::chain::keysinterface::SpendableOutputDescriptor;
 #[cfg(anchors)]
-use crate::ln::chan_utils::HTLCOutputInCommitment;
+use crate::ln::chan_utils::{self, ChannelTransactionParameters, HTLCOutputInCommitment};
 use crate::ln::channelmanager::{InterceptId, PaymentId};
 use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
 use crate::ln::features::ChannelTypeFeatures;
@@ -29,11 +29,15 @@ use crate::routing::router::{RouteHop, RouteParameters};
 
 use bitcoin::{PackedLockTime, Transaction};
 #[cfg(anchors)]
-use bitcoin::OutPoint;
+use bitcoin::{OutPoint, Txid, TxIn, TxOut, Witness};
 use bitcoin::blockdata::script::Script;
 use bitcoin::hashes::Hash;
 use bitcoin::hashes::sha256::Hash as Sha256;
 use bitcoin::secp256k1::PublicKey;
+#[cfg(anchors)]
+use bitcoin::secp256k1::{self, Secp256k1};
+#[cfg(anchors)]
+use bitcoin::secp256k1::ecdsa::Signature;
 use crate::io;
 use crate::prelude::*;
 use core::time::Duration;
@@ -237,6 +241,99 @@ pub struct AnchorDescriptor {
        pub outpoint: OutPoint,
 }
 
+#[cfg(anchors)]
+/// A descriptor used to sign for a commitment transaction's HTLC output.
+#[derive(Clone, Debug)]
+pub struct HTLCDescriptor {
+       /// A unique identifier used along with `channel_value_satoshis` to re-derive the
+       /// [`InMemorySigner`] required to sign `input`.
+       ///
+       /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
+       pub channel_keys_id: [u8; 32],
+       /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
+       /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
+       /// `input`.
+       ///
+       /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
+       pub channel_value_satoshis: u64,
+       /// The necessary channel parameters that need to be provided to the re-derived
+       /// [`InMemorySigner`] through [`BaseSign::ready_channel`].
+       ///
+       /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
+       /// [`BaseSign::ready_channel`]: crate::chain::keysinterface::BaseSign::ready_channel
+       pub channel_parameters: ChannelTransactionParameters,
+       /// The txid of the commitment transaction in which the HTLC output lives.
+       pub commitment_txid: Txid,
+       /// The number of the commitment transaction in which the HTLC output lives.
+       pub per_commitment_number: u64,
+       /// The details of the HTLC as it appears in the commitment transaction.
+       pub htlc: HTLCOutputInCommitment,
+       /// The preimage, if `Some`, to claim the HTLC output with. If `None`, the timeout path must be
+       /// taken.
+       pub preimage: Option<PaymentPreimage>,
+       /// The counterparty's signature required to spend the HTLC output.
+       pub counterparty_sig: Signature
+}
+
+#[cfg(anchors)]
+impl HTLCDescriptor {
+       /// Returns the unsigned transaction input spending the HTLC output in the commitment
+       /// transaction.
+       pub fn unsigned_tx_input(&self) -> TxIn {
+               chan_utils::build_htlc_input(&self.commitment_txid, &self.htlc, true /* opt_anchors */)
+       }
+
+       /// Returns the delayed output created as a result of spending the HTLC output in the commitment
+       /// transaction.
+       pub fn tx_output<C: secp256k1::Signing + secp256k1::Verification>(
+               &self, per_commitment_point: &PublicKey, secp: &Secp256k1<C>
+       ) -> TxOut {
+               let channel_params = self.channel_parameters.as_holder_broadcastable();
+               let broadcaster_keys = channel_params.broadcaster_pubkeys();
+               let counterparty_keys = channel_params.countersignatory_pubkeys();
+               let broadcaster_delayed_key = chan_utils::derive_public_key(
+                       secp, per_commitment_point, &broadcaster_keys.delayed_payment_basepoint
+               );
+               let counterparty_revocation_key = chan_utils::derive_public_revocation_key(
+                       secp, per_commitment_point, &counterparty_keys.revocation_basepoint
+               );
+               chan_utils::build_htlc_output(
+                       0 /* feerate_per_kw */, channel_params.contest_delay(), &self.htlc, true /* opt_anchors */,
+                       false /* use_non_zero_fee_anchors */, &broadcaster_delayed_key, &counterparty_revocation_key
+               )
+       }
+
+       /// Returns the witness script of the HTLC output in the commitment transaction.
+       pub fn witness_script<C: secp256k1::Signing + secp256k1::Verification>(
+               &self, per_commitment_point: &PublicKey, secp: &Secp256k1<C>
+       ) -> Script {
+               let channel_params = self.channel_parameters.as_holder_broadcastable();
+               let broadcaster_keys = channel_params.broadcaster_pubkeys();
+               let counterparty_keys = channel_params.countersignatory_pubkeys();
+               let broadcaster_htlc_key = chan_utils::derive_public_key(
+                       secp, per_commitment_point, &broadcaster_keys.htlc_basepoint
+               );
+               let counterparty_htlc_key = chan_utils::derive_public_key(
+                       secp, per_commitment_point, &counterparty_keys.htlc_basepoint
+               );
+               let counterparty_revocation_key = chan_utils::derive_public_revocation_key(
+                       secp, per_commitment_point, &counterparty_keys.revocation_basepoint
+               );
+               chan_utils::get_htlc_redeemscript_with_explicit_keys(
+                       &self.htlc, true /* opt_anchors */, &broadcaster_htlc_key, &counterparty_htlc_key,
+                       &counterparty_revocation_key,
+               )
+       }
+
+       /// Returns the fully signed witness required to spend the HTLC output in the commitment
+       /// transaction.
+       pub fn tx_input_witness(&self, signature: &Signature, witness_script: &Script) -> Witness {
+               chan_utils::build_htlc_input_witness(
+                       signature, &self.counterparty_sig, &self.preimage, witness_script, true /* opt_anchors */
+               )
+       }
+}
+
 #[cfg(anchors)]
 /// Represents the different types of transactions, originating from LDK, to be bumped.
 #[derive(Clone, Debug)]
@@ -249,14 +346,17 @@ pub enum BumpTransactionEvent {
        /// with additional inputs to meet the target feerate. Failure to meet the target feerate
        /// decreases the confirmation odds of the transaction package (which includes the commitment
        /// and child anchor transactions), possibly resulting in a loss of funds. Once the transaction
-       /// is constructed, it must be fully signed for and broadcasted by the consumer of the event
+       /// is constructed, it must be fully signed for and broadcast by the consumer of the event
        /// along with the `commitment_tx` enclosed. Note that the `commitment_tx` must always be
        /// broadcast first, as the child anchor transaction depends on it.
        ///
        /// The consumer should be able to sign for any of the additional inputs included within the
        /// child anchor transaction. To sign its anchor input, an [`InMemorySigner`] should be
        /// re-derived through [`KeysManager::derive_channel_keys`] with the help of
-       /// [`AnchorDescriptor::channel_keys_id`] and [`AnchorDescriptor::channel_value_satoshis`].
+       /// [`AnchorDescriptor::channel_keys_id`] and [`AnchorDescriptor::channel_value_satoshis`]. The
+       /// anchor input signature can be computed with [`BaseSign::sign_holder_anchor_input`],
+       /// which can then be provided to [`build_anchor_input_witness`] along with the `funding_pubkey`
+       /// to obtain the full witness required to spend.
        ///
        /// It is possible to receive more than one instance of this event if a valid child anchor
        /// transaction is never broadcast or is but not with a sufficient fee to be mined. Care should
@@ -277,6 +377,8 @@ pub enum BumpTransactionEvent {
        ///
        /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
        /// [`KeysManager::derive_channel_keys`]: crate::chain::keysinterface::KeysManager::derive_channel_keys
+       /// [`BaseSign::sign_holder_anchor_input`]: crate::chain::keysinterface::BaseSign::sign_holder_anchor_input
+       /// [`build_anchor_input_witness`]: crate::ln::chan_utils::build_anchor_input_witness
        ChannelClose {
                /// The target feerate that the transaction package, which consists of the commitment
                /// transaction and the to-be-crafted child anchor transaction, must meet.
@@ -295,6 +397,41 @@ pub enum BumpTransactionEvent {
                /// commitment transaction confirms.
                pending_htlcs: Vec<HTLCOutputInCommitment>,
        },
+       /// Indicates that a channel featuring anchor outputs has unilaterally closed on-chain by a
+       /// holder commitment transaction and its HTLC(s) need to be resolved on-chain. With the
+       /// zero-HTLC-transaction-fee variant of anchor outputs, the pre-signed HTLC
+       /// transactions have a zero fee, thus requiring additional inputs and/or outputs to be attached
+       /// for a timely confirmation within the chain. These additional inputs and/or outputs must be
+       /// appended to the resulting HTLC transaction to meet the target feerate. Failure to meet the
+       /// target feerate decreases the confirmation odds of the transaction, possibly resulting in a
+       /// loss of funds. Once the transaction meets the target feerate, it must be signed for and
+       /// broadcast by the consumer of the event.
+       ///
+       /// The consumer should be able to sign for any of the non-HTLC inputs added to the resulting
+       /// HTLC transaction. To sign HTLC inputs, an [`InMemorySigner`] should be re-derived through
+       /// [`KeysManager::derive_channel_keys`] with the help of `channel_keys_id` and
+       /// `channel_value_satoshis`. Each HTLC input's signature can be computed with
+       /// [`BaseSign::sign_holder_htlc_transaction`], which can then be provided to
+       /// [`HTLCDescriptor::tx_input_witness`] to obtain the fully signed witness required to spend.
+       ///
+       /// It is possible to receive more than one instance of this event if a valid HTLC transaction
+       /// is never broadcast or is but not with a sufficient fee to be mined. Care should be taken by
+       /// the consumer of the event to ensure any future iterations of the HTLC transaction adhere to
+       /// the [Replace-By-Fee
+       /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
+       /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
+       /// these events is not user-controlled, users may ignore/drop the event if either they are no
+       /// longer able to commit external confirmed funds to the HTLC transaction or the fee committed
+       /// to the HTLC transaction is greater in value than the HTLCs being claimed.
+       ///
+       /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
+       /// [`KeysManager::derive_channel_keys`]: crate::chain::keysinterface::KeysManager::derive_channel_keys
+       /// [`BaseSign::sign_holder_htlc_transaction`]: crate::chain::keysinterface::BaseSign::sign_holder_htlc_transaction
+       /// [`HTLCDescriptor::tx_input_witness`]: HTLCDescriptor::tx_input_witness
+       HTLCResolution {
+               target_feerate_sat_per_1000_weight: u32,
+               htlc_descriptors: Vec<HTLCDescriptor>,
+       },
 }
 
 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
@@ -350,8 +487,8 @@ pub enum Event {
                /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
                user_channel_id: u128,
        },
-       /// Indicates we've received (an offer of) money! Just gotta dig out that payment preimage and
-       /// feed it to [`ChannelManager::claim_funds`] to get it....
+       /// Indicates that we've been offered a payment and it needs to be claimed via calling
+       /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
        ///
        /// Note that if the preimage is not known, you should call
        /// [`ChannelManager::fail_htlc_backwards`] to free up resources for this HTLC and avoid
@@ -362,17 +499,20 @@ pub enum Event {
        ///
        /// # Note
        /// LDK will not stop an inbound payment from being paid multiple times, so multiple
-       /// `PaymentReceived` events may be generated for the same payment.
+       /// `PaymentClaimable` events may be generated for the same payment.
+       ///
+       /// # Note
+       /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
        ///
        /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
        /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
-       PaymentReceived {
-               /// The node that received the payment.
-               /// This is useful to identify payments which were received via [phantom node payments].
+       PaymentClaimable {
+               /// The node that will receive the payment after it has been claimed.
+               /// This is useful to identify payments received via [phantom nodes].
                /// This field will always be filled in when the event was generated by LDK versions
                /// 0.0.113 and above.
                ///
-               /// [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager
+               /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
                receiver_node_id: Option<PublicKey>,
                /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
                /// not stop you from registering duplicate payment hashes for inbound payments.
@@ -390,31 +530,31 @@ pub enum Event {
        /// Indicates a payment has been claimed and we've received money!
        ///
        /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
-       /// to an [`Event::PaymentReceived`]. However, if we previously crashed during a
+       /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
        /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
-       /// [`Event::PaymentReceived`] event.
+       /// [`Event::PaymentClaimable`] event.
        ///
        /// # Note
        /// LDK will not stop an inbound payment from being paid multiple times, so multiple
-       /// `PaymentReceived` events may be generated for the same payment. If you then call
-       /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentReceived`] you may get
+       /// `PaymentClaimable` events may be generated for the same payment. If you then call
+       /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
        /// multiple `PaymentClaimed` events.
        ///
        /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
        PaymentClaimed {
                /// The node that received the payment.
-               /// This is useful to identify payments which were received via [phantom node payments].
+               /// This is useful to identify payments which were received via [phantom nodes].
                /// This field will always be filled in when the event was generated by LDK versions
                /// 0.0.113 and above.
                ///
-               /// [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager
+               /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
                receiver_node_id: Option<PublicKey>,
                /// The payment hash of the claimed payment. Note that LDK will not stop you from
                /// registering duplicate payment hashes for inbound payments.
                payment_hash: PaymentHash,
                /// The value, in thousandths of a satoshi, that this payment is for.
                amount_msat: u64,
-               /// The purpose of this claimed payment, i.e. whether the payment was for an invoice or a
+               /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
                /// spontaneous payment.
                purpose: PaymentPurpose,
        },
@@ -814,7 +954,7 @@ impl Writeable for Event {
                                // We never write out FundingGenerationReady events as, upon disconnection, peers
                                // drop any channels which have not yet exchanged funding_signed.
                        },
-                       &Event::PaymentReceived { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id } => {
+                       &Event::PaymentClaimable { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id } => {
                                1u8.write(writer)?;
                                let mut payment_secret = None;
                                let payment_preimage;
@@ -980,9 +1120,10 @@ impl Writeable for Event {
                        &Event::BumpTransaction(ref event)=> {
                                27u8.write(writer)?;
                                match event {
-                                       // We never write the ChannelClose events as they'll be replayed upon restarting
-                                       // anyway if the commitment transaction remains unconfirmed.
+                                       // We never write the ChannelClose|HTLCResolution events as they'll be replayed
+                                       // upon restarting anyway if they remain unresolved.
                                        BumpTransactionEvent::ChannelClose { .. } => {}
+                                       BumpTransactionEvent::HTLCResolution { .. } => {}
                                }
                        }
                        &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
@@ -1035,7 +1176,7 @@ impl MaybeReadable for Event {
                                                None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
                                                None => return Err(msgs::DecodeError::InvalidValue),
                                        };
-                                       Ok(Some(Event::PaymentReceived {
+                                       Ok(Some(Event::PaymentClaimable {
                                                receiver_node_id,
                                                payment_hash,
                                                amount_msat,
index 3e1d8a9280d43da344076854739a5a81436f450b..caed542c19b6806cef2b20e849993b2f4e13dc9c 100644 (file)
@@ -679,7 +679,7 @@ macro_rules! impl_writeable_tlv_based_enum {
                                                Ok($st::$tuple_variant_name(Readable::read(reader)?))
                                        }),*
                                        _ => {
-                                               Err(DecodeError::UnknownRequiredFeature)
+                                               Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature)
                                        },
                                }
                        }
index 89bf27de2805ef8c152279cc02855d114d7a4e9b..17bdb06c73f9047368e746edfd07afbbf1d37036 100644 (file)
@@ -80,7 +80,8 @@ impl keysinterface::KeysInterface for OnlyReadsKeysInterface {
        fn get_inbound_payment_key_material(&self) -> KeyMaterial { unreachable!(); }
        fn get_destination_script(&self) -> Script { unreachable!(); }
        fn get_shutdown_scriptpubkey(&self) -> ShutdownScript { unreachable!(); }
-       fn get_channel_signer(&self, _inbound: bool, _channel_value_satoshis: u64) -> EnforcingSigner { unreachable!(); }
+       fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { unreachable!(); }
+       fn derive_channel_signer(&self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32]) -> Self::Signer { unreachable!(); }
        fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }
 
        fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
@@ -629,8 +630,12 @@ impl keysinterface::KeysInterface for TestKeysInterface {
                }
        }
 
-       fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
-               let keys = self.backing.get_channel_signer(inbound, channel_value_satoshis);
+       fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
+               self.backing.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
+       }
+
+       fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> EnforcingSigner {
+               let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id);
                let state = self.make_enforcement_state_cell(keys.commitment_seed);
                EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
        }
diff --git a/pending_changelog/elias-event-renaming.txt b/pending_changelog/elias-event-renaming.txt
new file mode 100644 (file)
index 0000000..c647296
--- /dev/null
@@ -0,0 +1,5 @@
+## API Updates
+
+## Backwards Compatibilty
+- The event formerly known as `PaymentReceived` is now called
+  `PaymentClaimable`.