1 //! The logic to monitor for on-chain transactions and create the relevant claim responses lives
4 //! ChannelMonitor objects are generated by ChannelManager in response to relevant
5 //! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
6 //! be made in responding to certain messages, see ManyChannelMonitor for more.
8 //! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
9 //! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
10 //! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
11 //! security-domain-separated system design, you should consider having multiple paths for
12 //! ChannelMonitors to get out of the HSM and onto monitoring devices.
14 use bitcoin::blockdata::block::BlockHeader;
15 use bitcoin::blockdata::transaction::{TxOut,Transaction};
16 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
17 use bitcoin::blockdata::script::{Script, Builder};
18 use bitcoin::blockdata::opcodes;
19 use bitcoin::consensus::encode;
20 use bitcoin::util::hash::BitcoinHash;
22 use bitcoin_hashes::Hash;
23 use bitcoin_hashes::sha256::Hash as Sha256;
24 use bitcoin_hashes::hash160::Hash as Hash160;
25 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
27 use secp256k1::{Secp256k1,Signature};
28 use secp256k1::key::{SecretKey,PublicKey};
31 use ln::msgs::DecodeError;
33 use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, LocalCommitmentTransaction, HTLCType};
34 use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
35 use ln::onchaintx::OnchainTxHandler;
36 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface, FeeEstimator};
37 use chain::transaction::OutPoint;
38 use chain::keysinterface::{SpendableOutputDescriptor, ChannelKeys};
39 use util::logger::Logger;
40 use util::ser::{ReadableArgs, Readable, MaybeReadable, Writer, Writeable, U48};
41 use util::{byte_utils, events};
43 use std::collections::{HashMap, hash_map};
44 use std::sync::{Arc,Mutex};
45 use std::{hash,cmp, mem};
48 /// An update generated by the underlying Channel itself which contains some new information the
49 /// ChannelMonitor should be made aware of.
50 #[cfg_attr(test, derive(PartialEq))]
53 pub struct ChannelMonitorUpdate {
54 pub(super) updates: Vec<ChannelMonitorUpdateStep>,
55 /// The sequence number of this update. Updates *must* be replayed in-order according to this
56 /// sequence number (and updates may panic if they are not). The update_id values are strictly
57 /// increasing and increase by one for each new update.
59 /// This sequence number is also used to track up to which points updates which returned
60 /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
61 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
65 impl Writeable for ChannelMonitorUpdate {
66 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
67 self.update_id.write(w)?;
68 (self.updates.len() as u64).write(w)?;
69 for update_step in self.updates.iter() {
70 update_step.write(w)?;
75 impl Readable for ChannelMonitorUpdate {
76 fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
77 let update_id: u64 = Readable::read(r)?;
78 let len: u64 = Readable::read(r)?;
79 let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::std::mem::size_of::<ChannelMonitorUpdateStep>()));
81 updates.push(Readable::read(r)?);
83 Ok(Self { update_id, updates })
87 /// An error enum representing a failure to persist a channel monitor update.
89 pub enum ChannelMonitorUpdateErr {
90 /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
91 /// our state failed, but is expected to succeed at some point in the future).
93 /// Such a failure will "freeze" a channel, preventing us from revoking old states or
94 /// submitting new commitment transactions to the remote party. Once the update(s) which failed
95 /// have been successfully applied, ChannelManager::channel_monitor_updated can be used to
96 /// restore the channel to an operational state.
98 /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If
99 /// you return a TemporaryFailure you must ensure that it is written to disk safely before
100 /// writing out the latest ChannelManager state.
102 /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
103 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
104 /// to claim it on this channel) and those updates must be applied wherever they can be. At
105 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
106 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
107 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
110 /// Note that even if updates made after TemporaryFailure succeed you must still call
111 /// channel_monitor_updated to ensure you have the latest monitor and re-enable normal channel
114 /// Note that the update being processed here will not be replayed for you when you call
115 /// ChannelManager::channel_monitor_updated, so you must store the update itself along
116 /// with the persisted ChannelMonitor on your own local disk prior to returning a
117 /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the
118 /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at
121 /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
122 /// remote location (with local copies persisted immediately), it is anticipated that all
123 /// updates will return TemporaryFailure until the remote copies could be updated.
125 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
126 /// different watchtower and cannot update with all watchtowers that were previously informed
127 /// of this channel). This will force-close the channel in question.
129 /// Should also be used to indicate a failure to update the local copy of the channel monitor.
133 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
134 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::update_monitor this
135 /// means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was
137 /// Contains a human-readable error message.
139 pub struct MonitorUpdateError(pub &'static str);
141 /// Simple structure send back by ManyChannelMonitor in case of HTLC detected onchain from a
142 /// forward channel and from which info are needed to update HTLC in a backward channel.
143 #[derive(Clone, PartialEq)]
144 pub struct HTLCUpdate {
145 pub(super) payment_hash: PaymentHash,
146 pub(super) payment_preimage: Option<PaymentPreimage>,
147 pub(super) source: HTLCSource
149 impl_writeable!(HTLCUpdate, 0, { payment_hash, payment_preimage, source });
151 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
152 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
153 /// events to it, while also taking any add/update_monitor events and passing them to some remote
156 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
157 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
158 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
159 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
161 /// User needs to notify implementors of ManyChannelMonitor when a new block is connected or
162 /// disconnected using their `block_connected` and `block_disconnected` methods. However, rather
163 /// than calling these methods directly, the user should register implementors as listeners to the
164 /// BlockNotifier and call the BlockNotifier's `block_(dis)connected` methods, which will notify
165 /// all registered listeners in one go.
166 pub trait ManyChannelMonitor<ChanSigner: ChannelKeys>: Send + Sync {
167 /// Adds a monitor for the given `funding_txo`.
169 /// Implementer must also ensure that the funding_txo txid *and* outpoint are registered with
170 /// any relevant ChainWatchInterfaces such that the provided monitor receives block_connected
171 /// callbacks with the funding transaction, or any spends of it.
173 /// Further, the implementer must also ensure that each output returned in
174 /// monitor.get_outputs_to_watch() is registered to ensure that the provided monitor learns about
175 /// any spends of any of the outputs.
177 /// Any spends of outputs which should have been registered which aren't passed to
178 /// ChannelMonitors via block_connected may result in FUNDS LOSS.
179 fn add_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr>;
181 /// Updates a monitor for the given `funding_txo`.
183 /// Implementer must also ensure that the funding_txo txid *and* outpoint are registered with
184 /// any relevant ChainWatchInterfaces such that the provided monitor receives block_connected
185 /// callbacks with the funding transaction, or any spends of it.
187 /// Further, the implementer must also ensure that each output returned in
188 /// monitor.get_watch_outputs() is registered to ensure that the provided monitor learns about
189 /// any spends of any of the outputs.
191 /// Any spends of outputs which should have been registered which aren't passed to
192 /// ChannelMonitors via block_connected may result in FUNDS LOSS.
193 fn update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr>;
195 /// Used by ChannelManager to get list of HTLC resolved onchain and which needed to be updated
196 /// with success or failure.
198 /// You should probably just call through to
199 /// ChannelMonitor::get_and_clear_pending_htlcs_updated() for each ChannelMonitor and return
201 fn get_and_clear_pending_htlcs_updated(&self) -> Vec<HTLCUpdate>;
204 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
205 /// watchtower or watch our own channels.
207 /// Note that you must provide your own key by which to refer to channels.
209 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
210 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
211 /// index by a PublicKey which is required to sign any updates.
213 /// If you're using this for local monitoring of your own channels, you probably want to use
214 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
215 pub struct SimpleManyChannelMonitor<Key, ChanSigner: ChannelKeys, T: Deref, F: Deref>
216 where T::Target: BroadcasterInterface,
217 F::Target: FeeEstimator
219 #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
220 pub monitors: Mutex<HashMap<Key, ChannelMonitor<ChanSigner>>>,
222 monitors: Mutex<HashMap<Key, ChannelMonitor<ChanSigner>>>,
223 chain_monitor: Arc<ChainWatchInterface>,
229 impl<'a, Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, T: Deref + Sync + Send, F: Deref + Sync + Send>
230 ChainListener for SimpleManyChannelMonitor<Key, ChanSigner, T, F>
231 where T::Target: BroadcasterInterface,
232 F::Target: FeeEstimator
234 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
235 let block_hash = header.bitcoin_hash();
237 let mut monitors = self.monitors.lock().unwrap();
238 for monitor in monitors.values_mut() {
239 let txn_outputs = monitor.block_connected(txn_matched, height, &block_hash, &*self.broadcaster, &*self.fee_estimator);
241 for (ref txid, ref outputs) in txn_outputs {
242 for (idx, output) in outputs.iter().enumerate() {
243 self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey);
250 fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
251 let block_hash = header.bitcoin_hash();
252 let mut monitors = self.monitors.lock().unwrap();
253 for monitor in monitors.values_mut() {
254 monitor.block_disconnected(disconnected_height, &block_hash, &*self.broadcaster, &*self.fee_estimator);
259 impl<Key : Send + cmp::Eq + hash::Hash + 'static, ChanSigner: ChannelKeys, T: Deref, F: Deref> SimpleManyChannelMonitor<Key, ChanSigner, T, F>
260 where T::Target: BroadcasterInterface,
261 F::Target: FeeEstimator
263 /// Creates a new object which can be used to monitor several channels given the chain
264 /// interface with which to register to receive notifications.
265 pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: T, logger: Arc<Logger>, feeest: F) -> SimpleManyChannelMonitor<Key, ChanSigner, T, F> {
266 let res = SimpleManyChannelMonitor {
267 monitors: Mutex::new(HashMap::new()),
271 fee_estimator: feeest,
277 /// Adds or updates the monitor which monitors the channel referred to by the given key.
278 pub fn add_monitor_by_key(&self, key: Key, monitor: ChannelMonitor<ChanSigner>) -> Result<(), MonitorUpdateError> {
279 let mut monitors = self.monitors.lock().unwrap();
280 let entry = match monitors.entry(key) {
281 hash_map::Entry::Occupied(_) => return Err(MonitorUpdateError("Channel monitor for given key is already present")),
282 hash_map::Entry::Vacant(e) => e,
284 match monitor.key_storage {
285 Storage::Local { ref funding_info, .. } => {
288 return Err(MonitorUpdateError("Try to update a useless monitor without funding_txo !"));
290 &Some((ref outpoint, ref script)) => {
291 log_trace!(self, "Got new Channel Monitor for channel {}", log_bytes!(outpoint.to_channel_id()[..]));
292 self.chain_monitor.install_watch_tx(&outpoint.txid, script);
293 self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script);
297 Storage::Watchtower { .. } => {
298 self.chain_monitor.watch_all_txn();
301 for (txid, outputs) in monitor.get_outputs_to_watch().iter() {
302 for (idx, script) in outputs.iter().enumerate() {
303 self.chain_monitor.install_watch_outpoint((*txid, idx as u32), script);
306 entry.insert(monitor);
310 /// Updates the monitor which monitors the channel referred to by the given key.
311 pub fn update_monitor_by_key(&self, key: Key, update: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
312 let mut monitors = self.monitors.lock().unwrap();
313 match monitors.get_mut(&key) {
314 Some(orig_monitor) => {
315 log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_info!(orig_monitor.key_storage));
316 orig_monitor.update_monitor(update)
318 None => Err(MonitorUpdateError("No such monitor registered"))
323 impl<ChanSigner: ChannelKeys, T: Deref + Sync + Send, F: Deref + Sync + Send> ManyChannelMonitor<ChanSigner> for SimpleManyChannelMonitor<OutPoint, ChanSigner, T, F>
324 where T::Target: BroadcasterInterface,
325 F::Target: FeeEstimator
327 fn add_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
328 match self.add_monitor_by_key(funding_txo, monitor) {
330 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
334 fn update_monitor(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> {
335 match self.update_monitor_by_key(funding_txo, update) {
337 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
341 fn get_and_clear_pending_htlcs_updated(&self) -> Vec<HTLCUpdate> {
342 let mut pending_htlcs_updated = Vec::new();
343 for chan in self.monitors.lock().unwrap().values_mut() {
344 pending_htlcs_updated.append(&mut chan.get_and_clear_pending_htlcs_updated());
346 pending_htlcs_updated
350 impl<Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, T: Deref, F: Deref> events::EventsProvider for SimpleManyChannelMonitor<Key, ChanSigner, T, F>
351 where T::Target: BroadcasterInterface,
352 F::Target: FeeEstimator
354 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
355 let mut pending_events = Vec::new();
356 for chan in self.monitors.lock().unwrap().values_mut() {
357 pending_events.append(&mut chan.get_and_clear_pending_events());
363 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
364 /// instead claiming it in its own individual transaction.
365 pub(crate) const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
366 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
367 /// HTLC-Success transaction.
368 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
369 /// transaction confirmed (and we use it in a few more, equivalent, places).
370 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
371 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
372 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
373 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
374 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
375 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
376 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
377 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
378 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
379 /// accurate block height.
380 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
381 /// with at worst this delay, so we are not only using this value as a mercy for them but also
382 /// us as a safeguard to delay with enough time.
383 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
384 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding inbound
385 /// HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us losing money.
386 /// We use also this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
387 /// It may cause spurrious generation of bumped claim txn but that's allright given the outpoint is already
388 /// solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
389 /// keeping bumping another claim tx to solve the outpoint.
390 pub(crate) const ANTI_REORG_DELAY: u32 = 6;
392 enum Storage<ChanSigner: ChannelKeys> {
395 funding_key: SecretKey,
396 revocation_base_key: SecretKey,
397 htlc_base_key: SecretKey,
398 delayed_payment_base_key: SecretKey,
399 payment_base_key: SecretKey,
400 shutdown_pubkey: PublicKey,
401 funding_info: Option<(OutPoint, Script)>,
402 current_remote_commitment_txid: Option<Sha256dHash>,
403 prev_remote_commitment_txid: Option<Sha256dHash>,
406 revocation_base_key: PublicKey,
407 htlc_base_key: PublicKey,
411 #[cfg(any(test, feature = "fuzztarget"))]
412 impl<ChanSigner: ChannelKeys> PartialEq for Storage<ChanSigner> {
413 fn eq(&self, other: &Self) -> bool {
415 Storage::Local { ref keys, .. } => {
418 Storage::Local { ref keys, .. } => keys.pubkeys() == k.pubkeys(),
419 Storage::Watchtower { .. } => false,
422 Storage::Watchtower {ref revocation_base_key, ref htlc_base_key} => {
423 let (rbk, hbk) = (revocation_base_key, htlc_base_key);
425 Storage::Local { .. } => false,
426 Storage::Watchtower {ref revocation_base_key, ref htlc_base_key} =>
427 revocation_base_key == rbk && htlc_base_key == hbk,
434 #[derive(Clone, PartialEq)]
435 struct LocalSignedTx {
436 /// txid of the transaction in tx, just used to make comparison faster
438 tx: LocalCommitmentTransaction,
439 revocation_key: PublicKey,
440 a_htlc_key: PublicKey,
441 b_htlc_key: PublicKey,
442 delayed_payment_key: PublicKey,
443 per_commitment_point: PublicKey,
445 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
448 /// When ChannelMonitor discovers an onchain outpoint being a step of a channel and that it needs
449 /// to generate a tx to push channel state forward, we cache outpoint-solving tx material to build
450 /// a new bumped one in case of lenghty confirmation delay
451 #[derive(Clone, PartialEq)]
452 pub(crate) enum InputMaterial {
454 witness_script: Script,
455 pubkey: Option<PublicKey>,
461 witness_script: Script,
463 preimage: Option<PaymentPreimage>,
468 witness_script: Script,
469 sigs: (Signature, Signature),
470 preimage: Option<PaymentPreimage>,
475 impl Writeable for InputMaterial {
476 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
478 &InputMaterial::Revoked { ref witness_script, ref pubkey, ref key, ref is_htlc, ref amount} => {
479 writer.write_all(&[0; 1])?;
480 witness_script.write(writer)?;
481 pubkey.write(writer)?;
482 writer.write_all(&key[..])?;
483 is_htlc.write(writer)?;
484 writer.write_all(&byte_utils::be64_to_array(*amount))?;
486 &InputMaterial::RemoteHTLC { ref witness_script, ref key, ref preimage, ref amount, ref locktime } => {
487 writer.write_all(&[1; 1])?;
488 witness_script.write(writer)?;
490 preimage.write(writer)?;
491 writer.write_all(&byte_utils::be64_to_array(*amount))?;
492 writer.write_all(&byte_utils::be32_to_array(*locktime))?;
494 &InputMaterial::LocalHTLC { ref witness_script, ref sigs, ref preimage, ref amount } => {
495 writer.write_all(&[2; 1])?;
496 witness_script.write(writer)?;
497 sigs.0.write(writer)?;
498 sigs.1.write(writer)?;
499 preimage.write(writer)?;
500 writer.write_all(&byte_utils::be64_to_array(*amount))?;
507 impl Readable for InputMaterial {
508 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
509 let input_material = match <u8 as Readable>::read(reader)? {
511 let witness_script = Readable::read(reader)?;
512 let pubkey = Readable::read(reader)?;
513 let key = Readable::read(reader)?;
514 let is_htlc = Readable::read(reader)?;
515 let amount = Readable::read(reader)?;
516 InputMaterial::Revoked {
525 let witness_script = Readable::read(reader)?;
526 let key = Readable::read(reader)?;
527 let preimage = Readable::read(reader)?;
528 let amount = Readable::read(reader)?;
529 let locktime = Readable::read(reader)?;
530 InputMaterial::RemoteHTLC {
539 let witness_script = Readable::read(reader)?;
540 let their_sig = Readable::read(reader)?;
541 let our_sig = Readable::read(reader)?;
542 let preimage = Readable::read(reader)?;
543 let amount = Readable::read(reader)?;
544 InputMaterial::LocalHTLC {
546 sigs: (their_sig, our_sig),
551 _ => return Err(DecodeError::InvalidValue),
557 /// ClaimRequest is a descriptor structure to communicate between detection
558 /// and reaction module. They are generated by ChannelMonitor while parsing
559 /// onchain txn leaked from a channel and handed over to OnchainTxHandler which
560 /// is responsible for opportunistic aggregation, selecting and enforcing
561 /// bumping logic, building and signing transactions.
562 pub(crate) struct ClaimRequest {
563 // Block height before which claiming is exclusive to one party,
564 // after reaching it, claiming may be contentious.
565 pub(crate) absolute_timelock: u32,
566 // Timeout tx must have nLocktime set which means aggregating multiple
567 // ones must take the higher nLocktime among them to satisfy all of them.
568 // Sadly it has few pitfalls, a) it takes longuer to get fund back b) CLTV_DELTA
569 // of a sooner-HTLC could be swallowed by the highest nLocktime of the HTLC set.
570 // Do simplify we mark them as non-aggregable.
571 pub(crate) aggregable: bool,
572 // Basic bitcoin outpoint (txid, vout)
573 pub(crate) outpoint: BitcoinOutPoint,
574 // Following outpoint type, set of data needed to generate transaction digest
575 // and satisfy witness program.
576 pub(crate) witness_data: InputMaterial
579 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
580 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
581 #[derive(Clone, PartialEq)]
583 /// HTLC output getting solved by a timeout, at maturation we pass upstream payment source information to solve
584 /// inbound HTLC in backward channel. Note, in case of preimage, we pass info to upstream without delay as we can
585 /// only win from it, so it's never an OnchainEvent
587 htlc_update: (HTLCSource, PaymentHash),
591 const SERIALIZATION_VERSION: u8 = 1;
592 const MIN_SERIALIZATION_VERSION: u8 = 1;
594 #[cfg_attr(test, derive(PartialEq))]
596 pub(super) enum ChannelMonitorUpdateStep {
597 LatestLocalCommitmentTXInfo {
598 // TODO: We really need to not be generating a fully-signed transaction in Channel and
599 // passing it here, we need to hold off so that the ChanSigner can enforce a
600 // only-sign-local-state-for-broadcast once invariant:
601 commitment_tx: LocalCommitmentTransaction,
602 local_keys: chan_utils::TxCreationKeys,
604 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
606 LatestRemoteCommitmentTXInfo {
607 unsigned_commitment_tx: Transaction, // TODO: We should actually only need the txid here
608 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
609 commitment_number: u64,
610 their_revocation_point: PublicKey,
613 payment_preimage: PaymentPreimage,
619 /// Indicates our channel is likely a stale version, we're closing, but this update should
620 /// allow us to spend what is ours if our counterparty broadcasts their latest state.
621 RescueRemoteCommitmentTXInfo {
622 their_current_per_commitment_point: PublicKey,
626 impl Writeable for ChannelMonitorUpdateStep {
627 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
629 &ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { ref commitment_tx, ref local_keys, ref feerate_per_kw, ref htlc_outputs } => {
631 commitment_tx.write(w)?;
632 local_keys.write(w)?;
633 feerate_per_kw.write(w)?;
634 (htlc_outputs.len() as u64).write(w)?;
635 for &(ref output, ref signature, ref source) in htlc_outputs.iter() {
641 &ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo { ref unsigned_commitment_tx, ref htlc_outputs, ref commitment_number, ref their_revocation_point } => {
643 unsigned_commitment_tx.write(w)?;
644 commitment_number.write(w)?;
645 their_revocation_point.write(w)?;
646 (htlc_outputs.len() as u64).write(w)?;
647 for &(ref output, ref source) in htlc_outputs.iter() {
649 source.as_ref().map(|b| b.as_ref()).write(w)?;
652 &ChannelMonitorUpdateStep::PaymentPreimage { ref payment_preimage } => {
654 payment_preimage.write(w)?;
656 &ChannelMonitorUpdateStep::CommitmentSecret { ref idx, ref secret } => {
661 &ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { ref their_current_per_commitment_point } => {
663 their_current_per_commitment_point.write(w)?;
669 impl Readable for ChannelMonitorUpdateStep {
670 fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
671 match Readable::read(r)? {
673 Ok(ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo {
674 commitment_tx: Readable::read(r)?,
675 local_keys: Readable::read(r)?,
676 feerate_per_kw: Readable::read(r)?,
678 let len: u64 = Readable::read(r)?;
679 let mut res = Vec::new();
681 res.push((Readable::read(r)?, Readable::read(r)?, Readable::read(r)?));
688 Ok(ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo {
689 unsigned_commitment_tx: Readable::read(r)?,
690 commitment_number: Readable::read(r)?,
691 their_revocation_point: Readable::read(r)?,
693 let len: u64 = Readable::read(r)?;
694 let mut res = Vec::new();
696 res.push((Readable::read(r)?, <Option<HTLCSource> as Readable>::read(r)?.map(|o| Box::new(o))));
703 Ok(ChannelMonitorUpdateStep::PaymentPreimage {
704 payment_preimage: Readable::read(r)?,
708 Ok(ChannelMonitorUpdateStep::CommitmentSecret {
709 idx: Readable::read(r)?,
710 secret: Readable::read(r)?,
714 Ok(ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo {
715 their_current_per_commitment_point: Readable::read(r)?,
718 _ => Err(DecodeError::InvalidValue),
723 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
724 /// on-chain transactions to ensure no loss of funds occurs.
726 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
727 /// information and are actively monitoring the chain.
729 /// Pending Events or updated HTLCs which have not yet been read out by
730 /// get_and_clear_pending_htlcs_updated or get_and_clear_pending_events are serialized to disk and
731 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
732 /// gotten are fully handled before re-serializing the new state.
733 pub struct ChannelMonitor<ChanSigner: ChannelKeys> {
734 latest_update_id: u64,
735 commitment_transaction_number_obscure_factor: u64,
737 key_storage: Storage<ChanSigner>,
738 their_htlc_base_key: Option<PublicKey>,
739 their_delayed_payment_base_key: Option<PublicKey>,
740 funding_redeemscript: Option<Script>,
741 channel_value_satoshis: Option<u64>,
742 // first is the idx of the first of the two revocation points
743 their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
745 our_to_self_delay: u16,
746 their_to_self_delay: Option<u16>,
748 commitment_secrets: CounterpartyCommitmentSecrets,
749 remote_claimable_outpoints: HashMap<Sha256dHash, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
750 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
751 /// Nor can we figure out their commitment numbers without the commitment transaction they are
752 /// spending. Thus, in order to claim them via revocation key, we track all the remote
753 /// commitment transactions which we find on-chain, mapping them to the commitment number which
754 /// can be used to derive the revocation key and claim the transactions.
755 remote_commitment_txn_on_chain: HashMap<Sha256dHash, (u64, Vec<Script>)>,
756 /// Cache used to make pruning of payment_preimages faster.
757 /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
758 /// remote transactions (ie should remain pretty small).
759 /// Serialized to disk but should generally not be sent to Watchtowers.
760 remote_hash_commitment_number: HashMap<PaymentHash, u64>,
762 // We store two local commitment transactions to avoid any race conditions where we may update
763 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
764 // various monitors for one channel being out of sync, and us broadcasting a local
765 // transaction for which we have deleted claim information on some watchtowers.
766 prev_local_signed_commitment_tx: Option<LocalSignedTx>,
767 current_local_signed_commitment_tx: Option<LocalSignedTx>,
769 // Used just for ChannelManager to make sure it has the latest channel data during
771 current_remote_commitment_number: u64,
773 payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
775 pending_htlcs_updated: Vec<HTLCUpdate>,
776 pending_events: Vec<events::Event>,
778 // Thanks to data loss protection, we may be able to claim our non-htlc funds
779 // back, this is the script we have to spend from but we need to
780 // scan every commitment transaction for that
781 to_remote_rescue: Option<(Script, SecretKey)>,
783 // Used to track onchain events, i.e transactions parts of channels confirmed on chain, on which
784 // we have to take actions once they reach enough confs. Key is a block height timer, i.e we enforce
785 // actions when we receive a block with given height. Actions depend on OnchainEvent type.
786 onchain_events_waiting_threshold_conf: HashMap<u32, Vec<OnchainEvent>>,
788 // If we get serialized out and re-read, we need to make sure that the chain monitoring
789 // interface knows about the TXOs that we want to be notified of spends of. We could probably
790 // be smart and derive them from the above storage fields, but its much simpler and more
791 // Obviously Correct (tm) if we just keep track of them explicitly.
792 outputs_to_watch: HashMap<Sha256dHash, Vec<Script>>,
795 pub onchain_tx_handler: OnchainTxHandler,
797 onchain_tx_handler: OnchainTxHandler,
799 // We simply modify last_block_hash in Channel's block_connected so that serialization is
800 // consistent but hopefully the users' copy handles block_connected in a consistent way.
801 // (we do *not*, however, update them in update_monitor to ensure any local user copies keep
802 // their last_block_hash from its state and not based on updated copies that didn't run through
803 // the full block_connected).
804 pub(crate) last_block_hash: Sha256dHash,
805 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
809 #[cfg(any(test, feature = "fuzztarget"))]
810 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
811 /// underlying object
812 impl<ChanSigner: ChannelKeys> PartialEq for ChannelMonitor<ChanSigner> {
813 fn eq(&self, other: &Self) -> bool {
814 if self.latest_update_id != other.latest_update_id ||
815 self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
816 self.key_storage != other.key_storage ||
817 self.their_htlc_base_key != other.their_htlc_base_key ||
818 self.their_delayed_payment_base_key != other.their_delayed_payment_base_key ||
819 self.funding_redeemscript != other.funding_redeemscript ||
820 self.channel_value_satoshis != other.channel_value_satoshis ||
821 self.their_cur_revocation_points != other.their_cur_revocation_points ||
822 self.our_to_self_delay != other.our_to_self_delay ||
823 self.their_to_self_delay != other.their_to_self_delay ||
824 self.commitment_secrets != other.commitment_secrets ||
825 self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
826 self.remote_commitment_txn_on_chain != other.remote_commitment_txn_on_chain ||
827 self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
828 self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
829 self.current_remote_commitment_number != other.current_remote_commitment_number ||
830 self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
831 self.payment_preimages != other.payment_preimages ||
832 self.pending_htlcs_updated != other.pending_htlcs_updated ||
833 self.pending_events.len() != other.pending_events.len() || // We trust events to round-trip properly
834 self.to_remote_rescue != other.to_remote_rescue ||
835 self.onchain_events_waiting_threshold_conf != other.onchain_events_waiting_threshold_conf ||
836 self.outputs_to_watch != other.outputs_to_watch
845 impl<ChanSigner: ChannelKeys + Writeable> ChannelMonitor<ChanSigner> {
846 /// Serializes into a vec, with various modes for the exposed pub fns
847 fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
848 //TODO: We still write out all the serialization here manually instead of using the fancy
849 //serialization framework we have, we should migrate things over to it.
850 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
851 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
853 self.latest_update_id.write(writer)?;
855 // Set in initial Channel-object creation, so should always be set by now:
856 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
858 match self.key_storage {
859 Storage::Local { ref keys, ref funding_key, ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, ref payment_base_key, ref shutdown_pubkey, ref funding_info, ref current_remote_commitment_txid, ref prev_remote_commitment_txid } => {
860 writer.write_all(&[0; 1])?;
862 writer.write_all(&funding_key[..])?;
863 writer.write_all(&revocation_base_key[..])?;
864 writer.write_all(&htlc_base_key[..])?;
865 writer.write_all(&delayed_payment_base_key[..])?;
866 writer.write_all(&payment_base_key[..])?;
867 writer.write_all(&shutdown_pubkey.serialize())?;
869 &Some((ref outpoint, ref script)) => {
870 writer.write_all(&outpoint.txid[..])?;
871 writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
872 script.write(writer)?;
875 debug_assert!(false, "Try to serialize a useless Local monitor !");
878 current_remote_commitment_txid.write(writer)?;
879 prev_remote_commitment_txid.write(writer)?;
881 Storage::Watchtower { .. } => unimplemented!(),
884 writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
885 writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
886 self.funding_redeemscript.as_ref().unwrap().write(writer)?;
887 self.channel_value_satoshis.unwrap().write(writer)?;
889 match self.their_cur_revocation_points {
890 Some((idx, pubkey, second_option)) => {
891 writer.write_all(&byte_utils::be48_to_array(idx))?;
892 writer.write_all(&pubkey.serialize())?;
893 match second_option {
894 Some(second_pubkey) => {
895 writer.write_all(&second_pubkey.serialize())?;
898 writer.write_all(&[0; 33])?;
903 writer.write_all(&byte_utils::be48_to_array(0))?;
907 writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
908 writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
910 self.commitment_secrets.write(writer)?;
912 macro_rules! serialize_htlc_in_commitment {
913 ($htlc_output: expr) => {
914 writer.write_all(&[$htlc_output.offered as u8; 1])?;
915 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
916 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
917 writer.write_all(&$htlc_output.payment_hash.0[..])?;
918 $htlc_output.transaction_output_index.write(writer)?;
922 writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
923 for (ref txid, ref htlc_infos) in self.remote_claimable_outpoints.iter() {
924 writer.write_all(&txid[..])?;
925 writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
926 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
927 serialize_htlc_in_commitment!(htlc_output);
928 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
932 writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
933 for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
934 writer.write_all(&txid[..])?;
935 writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
936 (txouts.len() as u64).write(writer)?;
937 for script in txouts.iter() {
938 script.write(writer)?;
942 if for_local_storage {
943 writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
944 for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
945 writer.write_all(&payment_hash.0[..])?;
946 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
949 writer.write_all(&byte_utils::be64_to_array(0))?;
952 macro_rules! serialize_local_tx {
953 ($local_tx: expr) => {
954 $local_tx.tx.write(writer)?;
955 writer.write_all(&$local_tx.revocation_key.serialize())?;
956 writer.write_all(&$local_tx.a_htlc_key.serialize())?;
957 writer.write_all(&$local_tx.b_htlc_key.serialize())?;
958 writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
959 writer.write_all(&$local_tx.per_commitment_point.serialize())?;
961 writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
962 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
963 for &(ref htlc_output, ref sig, ref htlc_source) in $local_tx.htlc_outputs.iter() {
964 serialize_htlc_in_commitment!(htlc_output);
965 if let &Some(ref their_sig) = sig {
967 writer.write_all(&their_sig.serialize_compact())?;
971 htlc_source.write(writer)?;
976 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
977 writer.write_all(&[1; 1])?;
978 serialize_local_tx!(prev_local_tx);
980 writer.write_all(&[0; 1])?;
983 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
984 writer.write_all(&[1; 1])?;
985 serialize_local_tx!(cur_local_tx);
987 writer.write_all(&[0; 1])?;
990 if for_local_storage {
991 writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
993 writer.write_all(&byte_utils::be48_to_array(0))?;
996 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
997 for payment_preimage in self.payment_preimages.values() {
998 writer.write_all(&payment_preimage.0[..])?;
1001 writer.write_all(&byte_utils::be64_to_array(self.pending_htlcs_updated.len() as u64))?;
1002 for data in self.pending_htlcs_updated.iter() {
1003 data.write(writer)?;
1006 writer.write_all(&byte_utils::be64_to_array(self.pending_events.len() as u64))?;
1007 for event in self.pending_events.iter() {
1008 event.write(writer)?;
1011 self.last_block_hash.write(writer)?;
1012 if let Some((ref to_remote_script, ref local_key)) = self.to_remote_rescue {
1013 writer.write_all(&[1; 1])?;
1014 to_remote_script.write(writer)?;
1015 local_key.write(writer)?;
1017 writer.write_all(&[0; 1])?;
1020 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
1021 for (ref target, ref events) in self.onchain_events_waiting_threshold_conf.iter() {
1022 writer.write_all(&byte_utils::be32_to_array(**target))?;
1023 writer.write_all(&byte_utils::be64_to_array(events.len() as u64))?;
1024 for ev in events.iter() {
1026 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1028 htlc_update.0.write(writer)?;
1029 htlc_update.1.write(writer)?;
1035 (self.outputs_to_watch.len() as u64).write(writer)?;
1036 for (txid, output_scripts) in self.outputs_to_watch.iter() {
1037 txid.write(writer)?;
1038 (output_scripts.len() as u64).write(writer)?;
1039 for script in output_scripts.iter() {
1040 script.write(writer)?;
1043 self.onchain_tx_handler.write(writer)?;
1048 /// Writes this monitor into the given writer, suitable for writing to disk.
1050 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
1051 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
1052 /// the "reorg path" (ie not just starting at the same height but starting at the highest
1053 /// common block that appears on your best chain as well as on the chain which contains the
1054 /// last block hash returned) upon deserializing the object!
1055 pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
1056 self.write(writer, true)
1059 /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
1061 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
1062 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
1063 /// the "reorg path" (ie not just starting at the same height but starting at the highest
1064 /// common block that appears on your best chain as well as on the chain which contains the
1065 /// last block hash returned) upon deserializing the object!
1066 pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
1067 self.write(writer, false)
1071 impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
1072 pub(super) fn new(keys: ChanSigner, shutdown_pubkey: &PublicKey,
1073 our_to_self_delay: u16, destination_script: &Script, funding_info: (OutPoint, Script),
1074 their_htlc_base_key: &PublicKey, their_delayed_payment_base_key: &PublicKey,
1075 their_to_self_delay: u16, funding_redeemscript: Script, channel_value_satoshis: u64,
1076 commitment_transaction_number_obscure_factor: u64,
1077 logger: Arc<Logger>) -> ChannelMonitor<ChanSigner> {
1079 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
1080 let funding_key = keys.funding_key().clone();
1081 let revocation_base_key = keys.revocation_base_key().clone();
1082 let htlc_base_key = keys.htlc_base_key().clone();
1083 let delayed_payment_base_key = keys.delayed_payment_base_key().clone();
1084 let payment_base_key = keys.payment_base_key().clone();
1086 latest_update_id: 0,
1087 commitment_transaction_number_obscure_factor,
1089 key_storage: Storage::Local {
1092 revocation_base_key,
1094 delayed_payment_base_key,
1096 shutdown_pubkey: shutdown_pubkey.clone(),
1097 funding_info: Some(funding_info),
1098 current_remote_commitment_txid: None,
1099 prev_remote_commitment_txid: None,
1101 their_htlc_base_key: Some(their_htlc_base_key.clone()),
1102 their_delayed_payment_base_key: Some(their_delayed_payment_base_key.clone()),
1103 funding_redeemscript: Some(funding_redeemscript),
1104 channel_value_satoshis: Some(channel_value_satoshis),
1105 their_cur_revocation_points: None,
1107 our_to_self_delay: our_to_self_delay,
1108 their_to_self_delay: Some(their_to_self_delay),
1110 commitment_secrets: CounterpartyCommitmentSecrets::new(),
1111 remote_claimable_outpoints: HashMap::new(),
1112 remote_commitment_txn_on_chain: HashMap::new(),
1113 remote_hash_commitment_number: HashMap::new(),
1115 prev_local_signed_commitment_tx: None,
1116 current_local_signed_commitment_tx: None,
1117 current_remote_commitment_number: 1 << 48,
1119 payment_preimages: HashMap::new(),
1120 pending_htlcs_updated: Vec::new(),
1121 pending_events: Vec::new(),
1123 to_remote_rescue: None,
1125 onchain_events_waiting_threshold_conf: HashMap::new(),
1126 outputs_to_watch: HashMap::new(),
1128 onchain_tx_handler: OnchainTxHandler::new(destination_script.clone(), logger.clone()),
1130 last_block_hash: Default::default(),
1131 secp_ctx: Secp256k1::new(),
1136 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1137 /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
1138 /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
1139 pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
1140 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1141 return Err(MonitorUpdateError("Previous secret did not match new one"));
1144 // Prune HTLCs from the previous remote commitment tx so we don't generate failure/fulfill
1145 // events for now-revoked/fulfilled HTLCs.
1146 if let Storage::Local { ref mut prev_remote_commitment_txid, .. } = self.key_storage {
1147 if let Some(txid) = prev_remote_commitment_txid.take() {
1148 for &mut (_, ref mut source) in self.remote_claimable_outpoints.get_mut(&txid).unwrap() {
1154 if !self.payment_preimages.is_empty() {
1155 let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
1156 let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
1157 let min_idx = self.get_min_seen_secret();
1158 let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
1160 self.payment_preimages.retain(|&k, _| {
1161 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
1162 if k == htlc.payment_hash {
1166 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
1167 for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
1168 if k == htlc.payment_hash {
1173 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
1180 remote_hash_commitment_number.remove(&k);
1189 /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
1190 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1191 /// possibly future revocation/preimage information) to claim outputs where possible.
1192 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1193 pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>, commitment_number: u64, their_revocation_point: PublicKey) {
1194 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
1195 // so that a remote monitor doesn't learn anything unless there is a malicious close.
1196 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
1198 for &(ref htlc, _) in &htlc_outputs {
1199 self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
1202 let new_txid = unsigned_commitment_tx.txid();
1203 log_trace!(self, "Tracking new remote commitment transaction with txid {} at commitment number {} with {} HTLC outputs", new_txid, commitment_number, htlc_outputs.len());
1204 log_trace!(self, "New potential remote commitment transaction: {}", encode::serialize_hex(unsigned_commitment_tx));
1205 if let Storage::Local { ref mut current_remote_commitment_txid, ref mut prev_remote_commitment_txid, .. } = self.key_storage {
1206 *prev_remote_commitment_txid = current_remote_commitment_txid.take();
1207 *current_remote_commitment_txid = Some(new_txid);
1209 self.remote_claimable_outpoints.insert(new_txid, htlc_outputs);
1210 self.current_remote_commitment_number = commitment_number;
1211 //TODO: Merge this into the other per-remote-transaction output storage stuff
1212 match self.their_cur_revocation_points {
1213 Some(old_points) => {
1214 if old_points.0 == commitment_number + 1 {
1215 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
1216 } else if old_points.0 == commitment_number + 2 {
1217 if let Some(old_second_point) = old_points.2 {
1218 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
1220 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1223 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1227 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1232 pub(super) fn provide_rescue_remote_commitment_tx_info(&mut self, their_revocation_point: PublicKey) {
1233 match self.key_storage {
1234 Storage::Local { ref payment_base_key, ref keys, .. } => {
1235 if let Ok(payment_key) = chan_utils::derive_public_key(&self.secp_ctx, &their_revocation_point, &keys.pubkeys().payment_basepoint) {
1236 let to_remote_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1237 .push_slice(&Hash160::hash(&payment_key.serialize())[..])
1239 if let Ok(to_remote_key) = chan_utils::derive_private_key(&self.secp_ctx, &their_revocation_point, &payment_base_key) {
1240 self.to_remote_rescue = Some((to_remote_script, to_remote_key));
1244 Storage::Watchtower { .. } => {}
1248 /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
1249 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
1250 /// is important that any clones of this channel monitor (including remote clones) by kept
1251 /// up-to-date as our local commitment transaction is updated.
1252 /// Panics if set_their_to_self_delay has never been called.
1253 pub(super) fn provide_latest_local_commitment_tx_info(&mut self, commitment_tx: LocalCommitmentTransaction, local_keys: chan_utils::TxCreationKeys, feerate_per_kw: u64, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), MonitorUpdateError> {
1254 if self.their_to_self_delay.is_none() {
1255 return Err(MonitorUpdateError("Got a local commitment tx info update before we'd set basic information about the channel"));
1257 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
1258 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
1259 txid: commitment_tx.txid(),
1261 revocation_key: local_keys.revocation_key,
1262 a_htlc_key: local_keys.a_htlc_key,
1263 b_htlc_key: local_keys.b_htlc_key,
1264 delayed_payment_key: local_keys.a_delayed_payment_key,
1265 per_commitment_point: local_keys.per_commitment_point,
1272 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
1273 /// commitment_tx_infos which contain the payment hash have been revoked.
1274 pub(super) fn provide_payment_preimage(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage) {
1275 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
1278 /// Used in Channel to cheat wrt the update_ids since it plays games, will be removed soon!
1279 pub(super) fn update_monitor_ooo(&mut self, mut updates: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
1280 for update in updates.updates.drain(..) {
1282 ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { commitment_tx, local_keys, feerate_per_kw, htlc_outputs } =>
1283 self.provide_latest_local_commitment_tx_info(commitment_tx, local_keys, feerate_per_kw, htlc_outputs)?,
1284 ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo { unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point } =>
1285 self.provide_latest_remote_commitment_tx_info(&unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point),
1286 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } =>
1287 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage),
1288 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } =>
1289 self.provide_secret(idx, secret)?,
1290 ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { their_current_per_commitment_point } =>
1291 self.provide_rescue_remote_commitment_tx_info(their_current_per_commitment_point),
1294 self.latest_update_id = updates.update_id;
1298 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1301 /// panics if the given update is not the next update by update_id.
1302 pub fn update_monitor(&mut self, mut updates: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
1303 if self.latest_update_id + 1 != updates.update_id {
1304 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
1306 for update in updates.updates.drain(..) {
1308 ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { commitment_tx, local_keys, feerate_per_kw, htlc_outputs } =>
1309 self.provide_latest_local_commitment_tx_info(commitment_tx, local_keys, feerate_per_kw, htlc_outputs)?,
1310 ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo { unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point } =>
1311 self.provide_latest_remote_commitment_tx_info(&unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point),
1312 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } =>
1313 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage),
1314 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } =>
1315 self.provide_secret(idx, secret)?,
1316 ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { their_current_per_commitment_point } =>
1317 self.provide_rescue_remote_commitment_tx_info(their_current_per_commitment_point),
1320 self.latest_update_id = updates.update_id;
1324 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1326 pub fn get_latest_update_id(&self) -> u64 {
1327 self.latest_update_id
1330 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1331 pub fn get_funding_txo(&self) -> Option<OutPoint> {
1332 match self.key_storage {
1333 Storage::Local { ref funding_info, .. } => {
1334 match funding_info {
1335 &Some((outpoint, _)) => Some(outpoint),
1339 Storage::Watchtower { .. } => {
1345 /// Gets a list of txids, with their output scripts (in the order they appear in the
1346 /// transaction), which we must learn about spends of via block_connected().
1347 pub fn get_outputs_to_watch(&self) -> &HashMap<Sha256dHash, Vec<Script>> {
1348 &self.outputs_to_watch
1351 /// Gets the sets of all outpoints which this ChannelMonitor expects to hear about spends of.
1352 /// Generally useful when deserializing as during normal operation the return values of
1353 /// block_connected are sufficient to ensure all relevant outpoints are being monitored (note
1354 /// that the get_funding_txo outpoint and transaction must also be monitored for!).
1355 pub fn get_monitored_outpoints(&self) -> Vec<(Sha256dHash, u32, &Script)> {
1356 let mut res = Vec::with_capacity(self.remote_commitment_txn_on_chain.len() * 2);
1357 for (ref txid, &(_, ref outputs)) in self.remote_commitment_txn_on_chain.iter() {
1358 for (idx, output) in outputs.iter().enumerate() {
1359 res.push(((*txid).clone(), idx as u32, output));
1365 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1366 /// ChannelManager via ManyChannelMonitor::get_and_clear_pending_htlcs_updated().
1367 pub fn get_and_clear_pending_htlcs_updated(&mut self) -> Vec<HTLCUpdate> {
1368 let mut ret = Vec::new();
1369 mem::swap(&mut ret, &mut self.pending_htlcs_updated);
1373 /// Gets the list of pending events which were generated by previous actions, clearing the list
1376 /// This is called by ManyChannelMonitor::get_and_clear_pending_events() and is equivalent to
1377 /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
1378 /// no internal locking in ChannelMonitors.
1379 pub fn get_and_clear_pending_events(&mut self) -> Vec<events::Event> {
1380 let mut ret = Vec::new();
1381 mem::swap(&mut ret, &mut self.pending_events);
1385 /// Can only fail if idx is < get_min_seen_secret
1386 pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
1387 self.commitment_secrets.get_secret(idx)
1390 pub(super) fn get_min_seen_secret(&self) -> u64 {
1391 self.commitment_secrets.get_min_seen_secret()
1394 pub(super) fn get_cur_remote_commitment_number(&self) -> u64 {
1395 self.current_remote_commitment_number
1398 pub(super) fn get_cur_local_commitment_number(&self) -> u64 {
1399 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1400 0xffff_ffff_ffff - ((((local_tx.tx.without_valid_witness().input[0].sequence as u64 & 0xffffff) << 3*8) | (local_tx.tx.without_valid_witness().lock_time as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor)
1401 } else { 0xffff_ffff_ffff }
1404 /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
1405 /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1406 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1407 /// HTLC-Success/HTLC-Timeout transactions.
1408 /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1409 /// revoked remote commitment tx
1410 fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<ClaimRequest>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>) {
1411 // Most secp and related errors trying to create keys means we have no hope of constructing
1412 // a spend transaction...so we return no transactions to broadcast
1413 let mut claimable_outpoints = Vec::new();
1414 let mut watch_outputs = Vec::new();
1415 let mut spendable_outputs = Vec::new();
1417 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1418 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
1420 macro_rules! ignore_error {
1421 ( $thing : expr ) => {
1424 Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs), spendable_outputs)
1429 let commitment_number = 0xffffffffffff - ((((tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (tx.lock_time as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
1430 if commitment_number >= self.get_min_seen_secret() {
1431 let secret = self.get_secret(commitment_number).unwrap();
1432 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1433 let (revocation_pubkey, revocation_key, b_htlc_key, local_payment_key) = match self.key_storage {
1434 Storage::Local { ref keys, ref revocation_base_key, ref payment_base_key, .. } => {
1435 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1436 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().revocation_basepoint)),
1437 ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key)),
1438 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().htlc_basepoint)),
1439 Some(ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &payment_base_key))))
1441 Storage::Watchtower { .. } => {
1445 let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.their_delayed_payment_base_key.unwrap()));
1446 let a_htlc_key = match self.their_htlc_base_key {
1447 None => return (claimable_outpoints, (commitment_txid, watch_outputs), spendable_outputs),
1448 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &their_htlc_base_key)),
1451 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
1452 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1454 let local_payment_p2wpkh = if let Some(payment_key) = local_payment_key {
1455 // Note that the Network here is ignored as we immediately drop the address for the
1456 // script_pubkey version.
1457 let payment_hash160 = Hash160::hash(&PublicKey::from_secret_key(&self.secp_ctx, &payment_key).serialize());
1458 Some(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_hash160[..]).into_script())
1461 // First, process non-htlc outputs (to_local & to_remote)
1462 for (idx, outp) in tx.output.iter().enumerate() {
1463 if outp.script_pubkey == revokeable_p2wsh {
1464 let witness_data = InputMaterial::Revoked { witness_script: revokeable_redeemscript.clone(), pubkey: Some(revocation_pubkey), key: revocation_key, is_htlc: false, amount: outp.value };
1465 claimable_outpoints.push(ClaimRequest { absolute_timelock: height + self.our_to_self_delay as u32, aggregable: true, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 }, witness_data});
1466 } else if Some(&outp.script_pubkey) == local_payment_p2wpkh.as_ref() {
1467 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1468 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1469 key: local_payment_key.unwrap(),
1470 output: outp.clone(),
1475 // Then, try to find revoked htlc outputs
1476 if let Some(ref per_commitment_data) = per_commitment_option {
1477 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1478 if let Some(transaction_output_index) = htlc.transaction_output_index {
1479 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1480 if transaction_output_index as usize >= tx.output.len() ||
1481 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1482 tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1483 return (claimable_outpoints, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
1485 let witness_data = InputMaterial::Revoked { witness_script: expected_script, pubkey: Some(revocation_pubkey), key: revocation_key, is_htlc: true, amount: tx.output[transaction_output_index as usize].value };
1486 claimable_outpoints.push(ClaimRequest { absolute_timelock: htlc.cltv_expiry, aggregable: true, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, witness_data });
1491 // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
1492 if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
1493 // We're definitely a remote commitment transaction!
1494 log_trace!(self, "Got broadcast of revoked remote commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
1495 watch_outputs.append(&mut tx.output.clone());
1496 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1498 macro_rules! check_htlc_fails {
1499 ($txid: expr, $commitment_tx: expr) => {
1500 if let Some(ref outpoints) = self.remote_claimable_outpoints.get($txid) {
1501 for &(ref htlc, ref source_option) in outpoints.iter() {
1502 if let &Some(ref source) = source_option {
1503 log_info!(self, "Failing HTLC with payment_hash {} from {} remote commitment tx due to broadcast of revoked remote commitment transaction, waiting for confirmation (at height {})", log_bytes!(htlc.payment_hash.0), $commitment_tx, height + ANTI_REORG_DELAY - 1);
1504 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1505 hash_map::Entry::Occupied(mut entry) => {
1506 let e = entry.get_mut();
1507 e.retain(|ref event| {
1509 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1510 return htlc_update.0 != **source
1514 e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1516 hash_map::Entry::Vacant(entry) => {
1517 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1525 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1526 if let &Some(ref txid) = current_remote_commitment_txid {
1527 check_htlc_fails!(txid, "current");
1529 if let &Some(ref txid) = prev_remote_commitment_txid {
1530 check_htlc_fails!(txid, "remote");
1533 // No need to check local commitment txn, symmetric HTLCSource must be present as per-htlc data on remote commitment tx
1535 } else if let Some(per_commitment_data) = per_commitment_option {
1536 // While this isn't useful yet, there is a potential race where if a counterparty
1537 // revokes a state at the same time as the commitment transaction for that state is
1538 // confirmed, and the watchtower receives the block before the user, the user could
1539 // upload a new ChannelMonitor with the revocation secret but the watchtower has
1540 // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1541 // not being generated by the above conditional. Thus, to be safe, we go ahead and
1543 watch_outputs.append(&mut tx.output.clone());
1544 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1546 log_trace!(self, "Got broadcast of non-revoked remote commitment transaction {}", commitment_txid);
1548 macro_rules! check_htlc_fails {
1549 ($txid: expr, $commitment_tx: expr, $id: tt) => {
1550 if let Some(ref latest_outpoints) = self.remote_claimable_outpoints.get($txid) {
1551 $id: for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1552 if let &Some(ref source) = source_option {
1553 // Check if the HTLC is present in the commitment transaction that was
1554 // broadcast, but not if it was below the dust limit, which we should
1555 // fail backwards immediately as there is no way for us to learn the
1556 // payment_preimage.
1557 // Note that if the dust limit were allowed to change between
1558 // commitment transactions we'd want to be check whether *any*
1559 // broadcastable commitment transaction has the HTLC in it, but it
1560 // cannot currently change after channel initialization, so we don't
1562 for &(ref broadcast_htlc, ref broadcast_source) in per_commitment_data.iter() {
1563 if broadcast_htlc.transaction_output_index.is_some() && Some(source) == broadcast_source.as_ref() {
1567 log_trace!(self, "Failing HTLC with payment_hash {} from {} remote commitment tx due to broadcast of remote commitment transaction", log_bytes!(htlc.payment_hash.0), $commitment_tx);
1568 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1569 hash_map::Entry::Occupied(mut entry) => {
1570 let e = entry.get_mut();
1571 e.retain(|ref event| {
1573 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1574 return htlc_update.0 != **source
1578 e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1580 hash_map::Entry::Vacant(entry) => {
1581 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1589 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1590 if let &Some(ref txid) = current_remote_commitment_txid {
1591 check_htlc_fails!(txid, "current", 'current_loop);
1593 if let &Some(ref txid) = prev_remote_commitment_txid {
1594 check_htlc_fails!(txid, "previous", 'prev_loop);
1598 if let Some(revocation_points) = self.their_cur_revocation_points {
1599 let revocation_point_option =
1600 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1601 else if let Some(point) = revocation_points.2.as_ref() {
1602 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1604 if let Some(revocation_point) = revocation_point_option {
1605 let (revocation_pubkey, b_htlc_key, htlc_privkey) = match self.key_storage {
1606 Storage::Local { ref keys, ref htlc_base_key, .. } => {
1607 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &keys.pubkeys().revocation_basepoint)),
1608 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &keys.pubkeys().htlc_basepoint)),
1609 ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1611 Storage::Watchtower { .. } => { unimplemented!() }
1613 let a_htlc_key = match self.their_htlc_base_key {
1614 None => return (claimable_outpoints, (commitment_txid, watch_outputs), spendable_outputs),
1615 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
1618 // First, mark as spendable our to_remote output
1619 for (idx, outp) in tx.output.iter().enumerate() {
1620 if outp.script_pubkey.is_v0_p2wpkh() {
1621 match self.key_storage {
1622 Storage::Local { ref payment_base_key, .. } => {
1623 if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &revocation_point, &payment_base_key) {
1624 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1625 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1627 output: outp.clone(),
1631 Storage::Watchtower { .. } => {}
1633 break; // Only to_remote ouput is claimable
1637 // Then, try to find htlc outputs
1638 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1639 if let Some(transaction_output_index) = htlc.transaction_output_index {
1640 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1641 if transaction_output_index as usize >= tx.output.len() ||
1642 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1643 tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1644 return (claimable_outpoints, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
1646 let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
1647 let aggregable = if !htlc.offered { false } else { true };
1648 if preimage.is_some() || !htlc.offered {
1649 let witness_data = InputMaterial::RemoteHTLC { witness_script: expected_script, key: htlc_privkey, preimage, amount: htlc.amount_msat / 1000, locktime: htlc.cltv_expiry };
1650 claimable_outpoints.push(ClaimRequest { absolute_timelock: htlc.cltv_expiry, aggregable, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, witness_data });
1656 } else if let Some((ref to_remote_rescue, ref local_key)) = self.to_remote_rescue {
1657 for (idx, outp) in tx.output.iter().enumerate() {
1658 if to_remote_rescue == &outp.script_pubkey {
1659 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1660 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1661 key: local_key.clone(),
1662 output: outp.clone(),
1667 (claimable_outpoints, (commitment_txid, watch_outputs), spendable_outputs)
1670 /// Attempts to claim a remote HTLC-Success/HTLC-Timeout's outputs using the revocation key
1671 fn check_spend_remote_htlc(&mut self, tx: &Transaction, commitment_number: u64, height: u32) -> (Vec<ClaimRequest>, Option<(Sha256dHash, Vec<TxOut>)>) {
1672 let htlc_txid = tx.txid();
1673 if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
1674 return (Vec::new(), None)
1677 macro_rules! ignore_error {
1678 ( $thing : expr ) => {
1681 Err(_) => return (Vec::new(), None)
1686 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
1687 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1688 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1689 let (revocation_pubkey, revocation_key) = match self.key_storage {
1690 Storage::Local { ref keys, ref revocation_base_key, .. } => {
1691 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().revocation_basepoint)),
1692 ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, revocation_base_key)))
1694 Storage::Watchtower { .. } => { unimplemented!() }
1696 let delayed_key = match self.their_delayed_payment_base_key {
1697 None => return (Vec::new(), None),
1698 Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
1700 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
1702 log_trace!(self, "Remote HTLC broadcast {}:{}", htlc_txid, 0);
1703 let witness_data = InputMaterial::Revoked { witness_script: redeemscript, pubkey: Some(revocation_pubkey), key: revocation_key, is_htlc: false, amount: tx.output[0].value };
1704 let claimable_outpoints = vec!(ClaimRequest { absolute_timelock: height + self.our_to_self_delay as u32, aggregable: true, outpoint: BitcoinOutPoint { txid: htlc_txid, vout: 0}, witness_data });
1705 (claimable_outpoints, Some((htlc_txid, tx.output.clone())))
1708 fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx, delayed_payment_base_key: &SecretKey) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, Vec<TxOut>) {
1709 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
1710 let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1711 let mut watch_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
1713 macro_rules! add_dynamic_output {
1714 ($father_tx: expr, $vout: expr) => {
1715 if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, &local_tx.per_commitment_point, delayed_payment_base_key) {
1716 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WSH {
1717 outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
1718 key: local_delayedkey,
1719 witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
1720 to_self_delay: self.our_to_self_delay,
1721 output: $father_tx.output[$vout as usize].clone(),
1727 let redeemscript = chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.their_to_self_delay.unwrap(), &local_tx.delayed_payment_key);
1728 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
1729 for (idx, output) in local_tx.tx.without_valid_witness().output.iter().enumerate() {
1730 if output.script_pubkey == revokeable_p2wsh {
1731 add_dynamic_output!(local_tx.tx.without_valid_witness(), idx as u32);
1736 if let &Storage::Local { ref htlc_base_key, .. } = &self.key_storage {
1737 for &(ref htlc, ref sigs, _) in local_tx.htlc_outputs.iter() {
1738 if let Some(transaction_output_index) = htlc.transaction_output_index {
1739 if let &Some(ref their_sig) = sigs {
1741 log_trace!(self, "Broadcasting HTLC-Timeout transaction against local commitment transactions");
1742 let mut htlc_timeout_tx = chan_utils::build_htlc_transaction(&local_tx.txid, local_tx.feerate_per_kw, self.their_to_self_delay.unwrap(), htlc, &local_tx.delayed_payment_key, &local_tx.revocation_key);
1743 let (our_sig, htlc_script) = match
1744 chan_utils::sign_htlc_transaction(&mut htlc_timeout_tx, their_sig, &None, htlc, &local_tx.a_htlc_key, &local_tx.b_htlc_key, &local_tx.revocation_key, &local_tx.per_commitment_point, htlc_base_key, &self.secp_ctx) {
1749 add_dynamic_output!(htlc_timeout_tx, 0);
1750 let mut per_input_material = HashMap::with_capacity(1);
1751 per_input_material.insert(htlc_timeout_tx.input[0].previous_output, InputMaterial::LocalHTLC { witness_script: htlc_script, sigs: (*their_sig, our_sig), preimage: None, amount: htlc.amount_msat / 1000});
1752 //TODO: with option_simplified_commitment track outpoint too
1753 log_trace!(self, "Outpoint {}:{} is being being claimed", htlc_timeout_tx.input[0].previous_output.vout, htlc_timeout_tx.input[0].previous_output.txid);
1754 res.push(htlc_timeout_tx);
1756 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1757 log_trace!(self, "Broadcasting HTLC-Success transaction against local commitment transactions");
1758 let mut htlc_success_tx = chan_utils::build_htlc_transaction(&local_tx.txid, local_tx.feerate_per_kw, self.their_to_self_delay.unwrap(), htlc, &local_tx.delayed_payment_key, &local_tx.revocation_key);
1759 let (our_sig, htlc_script) = match
1760 chan_utils::sign_htlc_transaction(&mut htlc_success_tx, their_sig, &Some(*payment_preimage), htlc, &local_tx.a_htlc_key, &local_tx.b_htlc_key, &local_tx.revocation_key, &local_tx.per_commitment_point, htlc_base_key, &self.secp_ctx) {
1765 add_dynamic_output!(htlc_success_tx, 0);
1766 let mut per_input_material = HashMap::with_capacity(1);
1767 per_input_material.insert(htlc_success_tx.input[0].previous_output, InputMaterial::LocalHTLC { witness_script: htlc_script, sigs: (*their_sig, our_sig), preimage: Some(*payment_preimage), amount: htlc.amount_msat / 1000});
1768 //TODO: with option_simplified_commitment track outpoint too
1769 log_trace!(self, "Outpoint {}:{} is being being claimed", htlc_success_tx.input[0].previous_output.vout, htlc_success_tx.input[0].previous_output.txid);
1770 res.push(htlc_success_tx);
1773 watch_outputs.push(local_tx.tx.without_valid_witness().output[transaction_output_index as usize].clone());
1774 } else { panic!("Should have sigs for non-dust local tx outputs!") }
1779 (res, spendable_outputs, watch_outputs)
1782 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1783 /// revoked using data in local_claimable_outpoints.
1784 /// Should not be used if check_spend_revoked_transaction succeeds.
1785 fn check_spend_local_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, (Sha256dHash, Vec<TxOut>)) {
1786 let commitment_txid = tx.txid();
1787 let mut local_txn = Vec::new();
1788 let mut spendable_outputs = Vec::new();
1789 let mut watch_outputs = Vec::new();
1791 macro_rules! wait_threshold_conf {
1792 ($height: expr, $source: expr, $commitment_tx: expr, $payment_hash: expr) => {
1793 log_trace!(self, "Failing HTLC with payment_hash {} from {} local commitment tx due to broadcast of transaction, waiting confirmation (at height{})", log_bytes!($payment_hash.0), $commitment_tx, height + ANTI_REORG_DELAY - 1);
1794 match self.onchain_events_waiting_threshold_conf.entry($height + ANTI_REORG_DELAY - 1) {
1795 hash_map::Entry::Occupied(mut entry) => {
1796 let e = entry.get_mut();
1797 e.retain(|ref event| {
1799 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1800 return htlc_update.0 != $source
1804 e.push(OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)});
1806 hash_map::Entry::Vacant(entry) => {
1807 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)}]);
1813 macro_rules! append_onchain_update {
1814 ($updates: expr) => {
1815 local_txn.append(&mut $updates.0);
1816 spendable_outputs.append(&mut $updates.1);
1817 watch_outputs.append(&mut $updates.2);
1821 // HTLCs set may differ between last and previous local commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
1822 let mut is_local_tx = false;
1824 if let &mut Some(ref mut local_tx) = &mut self.current_local_signed_commitment_tx {
1825 if local_tx.txid == commitment_txid {
1826 match self.key_storage {
1827 Storage::Local { ref funding_key, .. } => {
1828 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
1834 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1835 if local_tx.txid == commitment_txid {
1837 log_trace!(self, "Got latest local commitment tx broadcast, searching for available HTLCs to claim");
1838 assert!(local_tx.tx.has_local_sig());
1839 match self.key_storage {
1840 Storage::Local { ref delayed_payment_base_key, .. } => {
1841 let mut res = self.broadcast_by_local_state(local_tx, delayed_payment_base_key);
1842 append_onchain_update!(res);
1844 Storage::Watchtower { .. } => { }
1848 if let &mut Some(ref mut local_tx) = &mut self.prev_local_signed_commitment_tx {
1849 if local_tx.txid == commitment_txid {
1850 match self.key_storage {
1851 Storage::Local { ref funding_key, .. } => {
1852 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
1858 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1859 if local_tx.txid == commitment_txid {
1861 log_trace!(self, "Got previous local commitment tx broadcast, searching for available HTLCs to claim");
1862 assert!(local_tx.tx.has_local_sig());
1863 match self.key_storage {
1864 Storage::Local { ref delayed_payment_base_key, .. } => {
1865 let mut res = self.broadcast_by_local_state(local_tx, delayed_payment_base_key);
1866 append_onchain_update!(res);
1868 Storage::Watchtower { .. } => { }
1873 macro_rules! fail_dust_htlcs_after_threshold_conf {
1874 ($local_tx: expr) => {
1875 for &(ref htlc, _, ref source) in &$local_tx.htlc_outputs {
1876 if htlc.transaction_output_index.is_none() {
1877 if let &Some(ref source) = source {
1878 wait_threshold_conf!(height, source.clone(), "lastest", htlc.payment_hash.clone());
1886 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1887 fail_dust_htlcs_after_threshold_conf!(local_tx);
1889 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
1890 fail_dust_htlcs_after_threshold_conf!(local_tx);
1894 (local_txn, spendable_outputs, (commitment_txid, watch_outputs))
1897 /// Generate a spendable output event when closing_transaction get registered onchain.
1898 fn check_spend_closing_transaction(&self, tx: &Transaction) -> Option<SpendableOutputDescriptor> {
1899 if tx.input[0].sequence == 0xFFFFFFFF && !tx.input[0].witness.is_empty() && tx.input[0].witness.last().unwrap().len() == 71 {
1900 match self.key_storage {
1901 Storage::Local { ref shutdown_pubkey, .. } => {
1902 let our_channel_close_key_hash = Hash160::hash(&shutdown_pubkey.serialize());
1903 let shutdown_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
1904 for (idx, output) in tx.output.iter().enumerate() {
1905 if shutdown_script == output.script_pubkey {
1906 return Some(SpendableOutputDescriptor::StaticOutput {
1907 outpoint: BitcoinOutPoint { txid: tx.txid(), vout: idx as u32 },
1908 output: output.clone(),
1913 Storage::Watchtower { .. } => {
1914 //TODO: we need to ensure an offline client will generate the event when it
1915 // comes back online after only the watchtower saw the transaction
1922 /// Used by ChannelManager deserialization to broadcast the latest local state if its copy of
1923 /// the Channel was out-of-date. You may use it to get a broadcastable local toxic tx in case of
1924 /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our remote side knows
1925 /// a higher revocation secret than the local commitment number we are aware of. Broadcasting these
1926 /// transactions are UNSAFE, as they allow remote side to punish you. Nevertheless you may want to
1927 /// broadcast them if remote don't close channel with his higher commitment transaction after a
1928 /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
1929 /// out-of-band the other node operator to coordinate with him if option is available to you.
1930 /// In any-case, choice is up to the user.
1931 pub fn get_latest_local_commitment_txn(&mut self) -> Vec<Transaction> {
1932 log_trace!(self, "Getting signed latest local commitment transaction!");
1933 if let &mut Some(ref mut local_tx) = &mut self.current_local_signed_commitment_tx {
1934 match self.key_storage {
1935 Storage::Local { ref funding_key, .. } => {
1936 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
1941 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1942 let mut res = vec![local_tx.tx.with_valid_witness().clone()];
1943 match self.key_storage {
1944 Storage::Local { ref delayed_payment_base_key, .. } => {
1945 res.append(&mut self.broadcast_by_local_state(local_tx, delayed_payment_base_key).0);
1946 // We throw away the generated waiting_first_conf data as we aren't (yet) confirmed and we don't actually know what the caller wants to do.
1947 // The data will be re-generated and tracked in check_spend_local_transaction if we get a confirmation.
1949 _ => panic!("Can only broadcast by local channelmonitor"),
1957 /// Called by SimpleManyChannelMonitor::block_connected, which implements
1958 /// ChainListener::block_connected.
1959 /// Eventually this should be pub and, roughly, implement ChainListener, however this requires
1960 /// &mut self, as well as returns new spendable outputs and outpoints to watch for spending of
1962 fn block_connected<B: Deref, F: Deref>(&mut self, txn_matched: &[&Transaction], height: u32, block_hash: &Sha256dHash, broadcaster: B, fee_estimator: F)-> Vec<(Sha256dHash, Vec<TxOut>)>
1963 where B::Target: BroadcasterInterface,
1964 F::Target: FeeEstimator
1966 for tx in txn_matched {
1967 let mut output_val = 0;
1968 for out in tx.output.iter() {
1969 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
1970 output_val += out.value;
1971 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
1975 log_trace!(self, "Block {} at height {} connected with {} txn matched", block_hash, height, txn_matched.len());
1976 let mut watch_outputs = Vec::new();
1977 let mut spendable_outputs = Vec::new();
1978 let mut claimable_outpoints = Vec::new();
1979 for tx in txn_matched {
1980 if tx.input.len() == 1 {
1981 // Assuming our keys were not leaked (in which case we're screwed no matter what),
1982 // commitment transactions and HTLC transactions will all only ever have one input,
1983 // which is an easy way to filter out any potential non-matching txn for lazy
1985 let prevout = &tx.input[0].previous_output;
1986 let funding_txo = match self.key_storage {
1987 Storage::Local { ref funding_info, .. } => {
1988 funding_info.clone()
1990 Storage::Watchtower { .. } => {
1994 if funding_txo.is_none() || (prevout.txid == funding_txo.as_ref().unwrap().0.txid && prevout.vout == funding_txo.as_ref().unwrap().0.index as u32) {
1995 if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
1996 let (mut new_outpoints, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(&tx, height);
1997 spendable_outputs.append(&mut spendable_output);
1998 if !new_outputs.1.is_empty() {
1999 watch_outputs.push(new_outputs);
2001 if new_outpoints.is_empty() {
2002 let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(&tx, height);
2003 spendable_outputs.append(&mut spendable_output);
2004 for tx in local_txn.iter() {
2005 log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
2006 broadcaster.broadcast_transaction(tx);
2008 if !new_outputs.1.is_empty() {
2009 watch_outputs.push(new_outputs);
2012 claimable_outpoints.append(&mut new_outpoints);
2014 if !funding_txo.is_none() && claimable_outpoints.is_empty() {
2015 if let Some(spendable_output) = self.check_spend_closing_transaction(&tx) {
2016 spendable_outputs.push(spendable_output);
2020 if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
2021 let (mut new_outpoints, new_outputs_option) = self.check_spend_remote_htlc(&tx, commitment_number, height);
2022 claimable_outpoints.append(&mut new_outpoints);
2023 if let Some(new_outputs) = new_outputs_option {
2024 watch_outputs.push(new_outputs);
2029 // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2030 // can also be resolved in a few other ways which can have more than one output. Thus,
2031 // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2032 self.is_resolving_htlc_output(&tx, height);
2034 let should_broadcast = if let Some(_) = self.current_local_signed_commitment_tx {
2035 self.would_broadcast_at_height(height)
2037 if let Some(ref mut cur_local_tx) = self.current_local_signed_commitment_tx {
2038 if should_broadcast {
2039 match self.key_storage {
2040 Storage::Local { ref funding_key, .. } => {
2041 cur_local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2047 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
2048 if should_broadcast {
2049 log_trace!(self, "Broadcast onchain {}", log_tx!(cur_local_tx.tx.with_valid_witness()));
2050 broadcaster.broadcast_transaction(&cur_local_tx.tx.with_valid_witness());
2051 match self.key_storage {
2052 Storage::Local { ref delayed_payment_base_key, .. } => {
2053 let (txs, mut spendable_output, new_outputs) = self.broadcast_by_local_state(&cur_local_tx, delayed_payment_base_key);
2054 spendable_outputs.append(&mut spendable_output);
2055 if !new_outputs.is_empty() {
2056 watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
2059 log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
2060 broadcaster.broadcast_transaction(&tx);
2063 Storage::Watchtower { .. } => { },
2067 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&height) {
2070 OnchainEvent::HTLCUpdate { htlc_update } => {
2071 log_trace!(self, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!((htlc_update.1).0));
2072 self.pending_htlcs_updated.push(HTLCUpdate {
2073 payment_hash: htlc_update.1,
2074 payment_preimage: None,
2075 source: htlc_update.0,
2081 let mut spendable_output = self.onchain_tx_handler.block_connected(txn_matched, claimable_outpoints, height, &*broadcaster, &*fee_estimator);
2082 spendable_outputs.append(&mut spendable_output);
2084 self.last_block_hash = block_hash.clone();
2085 for &(ref txid, ref output_scripts) in watch_outputs.iter() {
2086 self.outputs_to_watch.insert(txid.clone(), output_scripts.iter().map(|o| o.script_pubkey.clone()).collect());
2089 if spendable_outputs.len() > 0 {
2090 self.pending_events.push(events::Event::SpendableOutputs {
2091 outputs: spendable_outputs,
2098 fn block_disconnected<B: Deref, F: Deref>(&mut self, height: u32, block_hash: &Sha256dHash, broadcaster: B, fee_estimator: F)
2099 where B::Target: BroadcasterInterface,
2100 F::Target: FeeEstimator
2102 log_trace!(self, "Block {} at height {} disconnected", block_hash, height);
2103 if let Some(_) = self.onchain_events_waiting_threshold_conf.remove(&(height + ANTI_REORG_DELAY - 1)) {
2105 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2108 self.onchain_tx_handler.block_disconnected(height, broadcaster, fee_estimator);
2110 self.last_block_hash = block_hash.clone();
2113 pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
2114 // We need to consider all HTLCs which are:
2115 // * in any unrevoked remote commitment transaction, as they could broadcast said
2116 // transactions and we'd end up in a race, or
2117 // * are in our latest local commitment transaction, as this is the thing we will
2118 // broadcast if we go on-chain.
2119 // Note that we consider HTLCs which were below dust threshold here - while they don't
2120 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2121 // to the source, and if we don't fail the channel we will have to ensure that the next
2122 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2123 // easier to just fail the channel as this case should be rare enough anyway.
2124 macro_rules! scan_commitment {
2125 ($htlcs: expr, $local_tx: expr) => {
2126 for ref htlc in $htlcs {
2127 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2128 // chain with enough room to claim the HTLC without our counterparty being able to
2129 // time out the HTLC first.
2130 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2131 // concern is being able to claim the corresponding inbound HTLC (on another
2132 // channel) before it expires. In fact, we don't even really care if our
2133 // counterparty here claims such an outbound HTLC after it expired as long as we
2134 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2135 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2136 // we give ourselves a few blocks of headroom after expiration before going
2137 // on-chain for an expired HTLC.
2138 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2139 // from us until we've reached the point where we go on-chain with the
2140 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2141 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2142 // aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2143 // inbound_cltv == height + CLTV_CLAIM_BUFFER
2144 // outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2145 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2146 // CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2147 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2148 // The final, above, condition is checked for statically in channelmanager
2149 // with CHECK_CLTV_EXPIRY_SANITY_2.
2150 let htlc_outbound = $local_tx == htlc.offered;
2151 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2152 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2153 log_info!(self, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2160 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
2161 scan_commitment!(cur_local_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2164 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
2165 if let &Some(ref txid) = current_remote_commitment_txid {
2166 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2167 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2170 if let &Some(ref txid) = prev_remote_commitment_txid {
2171 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2172 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2180 /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a local
2181 /// or remote commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2182 fn is_resolving_htlc_output(&mut self, tx: &Transaction, height: u32) {
2183 'outer_loop: for input in &tx.input {
2184 let mut payment_data = None;
2185 let revocation_sig_claim = (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && input.witness[1].len() == 33)
2186 || (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && input.witness[1].len() == 33);
2187 let accepted_preimage_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::AcceptedHTLC);
2188 let offered_preimage_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC);
2190 macro_rules! log_claim {
2191 ($tx_info: expr, $local_tx: expr, $htlc: expr, $source_avail: expr) => {
2192 // We found the output in question, but aren't failing it backwards
2193 // as we have no corresponding source and no valid remote commitment txid
2194 // to try a weak source binding with same-hash, same-value still-valid offered HTLC.
2195 // This implies either it is an inbound HTLC or an outbound HTLC on a revoked transaction.
2196 let outbound_htlc = $local_tx == $htlc.offered;
2197 if ($local_tx && revocation_sig_claim) ||
2198 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2199 log_error!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2200 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2201 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2202 if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2204 log_info!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2205 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2206 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2207 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2212 macro_rules! check_htlc_valid_remote {
2213 ($remote_txid: expr, $htlc_output: expr) => {
2214 if let &Some(txid) = $remote_txid {
2215 for &(ref pending_htlc, ref pending_source) in self.remote_claimable_outpoints.get(&txid).unwrap() {
2216 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2217 if let &Some(ref source) = pending_source {
2218 log_claim!("revoked remote commitment tx", false, pending_htlc, true);
2219 payment_data = Some(((**source).clone(), $htlc_output.payment_hash));
2228 macro_rules! scan_commitment {
2229 ($htlcs: expr, $tx_info: expr, $local_tx: expr) => {
2230 for (ref htlc_output, source_option) in $htlcs {
2231 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2232 if let Some(ref source) = source_option {
2233 log_claim!($tx_info, $local_tx, htlc_output, true);
2234 // We have a resolution of an HTLC either from one of our latest
2235 // local commitment transactions or an unrevoked remote commitment
2236 // transaction. This implies we either learned a preimage, the HTLC
2237 // has timed out, or we screwed up. In any case, we should now
2238 // resolve the source HTLC with the original sender.
2239 payment_data = Some(((*source).clone(), htlc_output.payment_hash));
2240 } else if !$local_tx {
2241 if let Storage::Local { ref current_remote_commitment_txid, .. } = self.key_storage {
2242 check_htlc_valid_remote!(current_remote_commitment_txid, htlc_output);
2244 if payment_data.is_none() {
2245 if let Storage::Local { ref prev_remote_commitment_txid, .. } = self.key_storage {
2246 check_htlc_valid_remote!(prev_remote_commitment_txid, htlc_output);
2250 if payment_data.is_none() {
2251 log_claim!($tx_info, $local_tx, htlc_output, false);
2252 continue 'outer_loop;
2259 if let Some(ref current_local_signed_commitment_tx) = self.current_local_signed_commitment_tx {
2260 if input.previous_output.txid == current_local_signed_commitment_tx.txid {
2261 scan_commitment!(current_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2262 "our latest local commitment tx", true);
2265 if let Some(ref prev_local_signed_commitment_tx) = self.prev_local_signed_commitment_tx {
2266 if input.previous_output.txid == prev_local_signed_commitment_tx.txid {
2267 scan_commitment!(prev_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2268 "our previous local commitment tx", true);
2271 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(&input.previous_output.txid) {
2272 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
2273 "remote commitment tx", false);
2276 // Check that scan_commitment, above, decided there is some source worth relaying an
2277 // HTLC resolution backwards to and figure out whether we learned a preimage from it.
2278 if let Some((source, payment_hash)) = payment_data {
2279 let mut payment_preimage = PaymentPreimage([0; 32]);
2280 if accepted_preimage_claim {
2281 if !self.pending_htlcs_updated.iter().any(|update| update.source == source) {
2282 payment_preimage.0.copy_from_slice(&input.witness[3]);
2283 self.pending_htlcs_updated.push(HTLCUpdate {
2285 payment_preimage: Some(payment_preimage),
2289 } else if offered_preimage_claim {
2290 if !self.pending_htlcs_updated.iter().any(|update| update.source == source) {
2291 payment_preimage.0.copy_from_slice(&input.witness[1]);
2292 self.pending_htlcs_updated.push(HTLCUpdate {
2294 payment_preimage: Some(payment_preimage),
2299 log_info!(self, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height{})", log_bytes!(payment_hash.0), height + ANTI_REORG_DELAY - 1);
2300 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2301 hash_map::Entry::Occupied(mut entry) => {
2302 let e = entry.get_mut();
2303 e.retain(|ref event| {
2305 OnchainEvent::HTLCUpdate { ref htlc_update } => {
2306 return htlc_update.0 != source
2310 e.push(OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)});
2312 hash_map::Entry::Vacant(entry) => {
2313 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)}]);
2322 const MAX_ALLOC_SIZE: usize = 64*1024;
2324 impl<ChanSigner: ChannelKeys + Readable> ReadableArgs<Arc<Logger>> for (Sha256dHash, ChannelMonitor<ChanSigner>) {
2325 fn read<R: ::std::io::Read>(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
2326 macro_rules! unwrap_obj {
2330 Err(_) => return Err(DecodeError::InvalidValue),
2335 let _ver: u8 = Readable::read(reader)?;
2336 let min_ver: u8 = Readable::read(reader)?;
2337 if min_ver > SERIALIZATION_VERSION {
2338 return Err(DecodeError::UnknownVersion);
2341 let latest_update_id: u64 = Readable::read(reader)?;
2342 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
2344 let key_storage = match <u8 as Readable>::read(reader)? {
2346 let keys = Readable::read(reader)?;
2347 let funding_key = Readable::read(reader)?;
2348 let revocation_base_key = Readable::read(reader)?;
2349 let htlc_base_key = Readable::read(reader)?;
2350 let delayed_payment_base_key = Readable::read(reader)?;
2351 let payment_base_key = Readable::read(reader)?;
2352 let shutdown_pubkey = Readable::read(reader)?;
2353 // Technically this can fail and serialize fail a round-trip, but only for serialization of
2354 // barely-init'd ChannelMonitors that we can't do anything with.
2355 let outpoint = OutPoint {
2356 txid: Readable::read(reader)?,
2357 index: Readable::read(reader)?,
2359 let funding_info = Some((outpoint, Readable::read(reader)?));
2360 let current_remote_commitment_txid = Readable::read(reader)?;
2361 let prev_remote_commitment_txid = Readable::read(reader)?;
2365 revocation_base_key,
2367 delayed_payment_base_key,
2371 current_remote_commitment_txid,
2372 prev_remote_commitment_txid,
2375 _ => return Err(DecodeError::InvalidValue),
2378 let their_htlc_base_key = Some(Readable::read(reader)?);
2379 let their_delayed_payment_base_key = Some(Readable::read(reader)?);
2380 let funding_redeemscript = Some(Readable::read(reader)?);
2381 let channel_value_satoshis = Some(Readable::read(reader)?);
2383 let their_cur_revocation_points = {
2384 let first_idx = <U48 as Readable>::read(reader)?.0;
2388 let first_point = Readable::read(reader)?;
2389 let second_point_slice: [u8; 33] = Readable::read(reader)?;
2390 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
2391 Some((first_idx, first_point, None))
2393 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
2398 let our_to_self_delay: u16 = Readable::read(reader)?;
2399 let their_to_self_delay: Option<u16> = Some(Readable::read(reader)?);
2401 let commitment_secrets = Readable::read(reader)?;
2403 macro_rules! read_htlc_in_commitment {
2406 let offered: bool = Readable::read(reader)?;
2407 let amount_msat: u64 = Readable::read(reader)?;
2408 let cltv_expiry: u32 = Readable::read(reader)?;
2409 let payment_hash: PaymentHash = Readable::read(reader)?;
2410 let transaction_output_index: Option<u32> = Readable::read(reader)?;
2412 HTLCOutputInCommitment {
2413 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
2419 let remote_claimable_outpoints_len: u64 = Readable::read(reader)?;
2420 let mut remote_claimable_outpoints = HashMap::with_capacity(cmp::min(remote_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
2421 for _ in 0..remote_claimable_outpoints_len {
2422 let txid: Sha256dHash = Readable::read(reader)?;
2423 let htlcs_count: u64 = Readable::read(reader)?;
2424 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
2425 for _ in 0..htlcs_count {
2426 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
2428 if let Some(_) = remote_claimable_outpoints.insert(txid, htlcs) {
2429 return Err(DecodeError::InvalidValue);
2433 let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
2434 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
2435 for _ in 0..remote_commitment_txn_on_chain_len {
2436 let txid: Sha256dHash = Readable::read(reader)?;
2437 let commitment_number = <U48 as Readable>::read(reader)?.0;
2438 let outputs_count = <u64 as Readable>::read(reader)?;
2439 let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
2440 for _ in 0..outputs_count {
2441 outputs.push(Readable::read(reader)?);
2443 if let Some(_) = remote_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
2444 return Err(DecodeError::InvalidValue);
2448 let remote_hash_commitment_number_len: u64 = Readable::read(reader)?;
2449 let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
2450 for _ in 0..remote_hash_commitment_number_len {
2451 let payment_hash: PaymentHash = Readable::read(reader)?;
2452 let commitment_number = <U48 as Readable>::read(reader)?.0;
2453 if let Some(_) = remote_hash_commitment_number.insert(payment_hash, commitment_number) {
2454 return Err(DecodeError::InvalidValue);
2458 macro_rules! read_local_tx {
2461 let tx = <LocalCommitmentTransaction as Readable>::read(reader)?;
2462 let revocation_key = Readable::read(reader)?;
2463 let a_htlc_key = Readable::read(reader)?;
2464 let b_htlc_key = Readable::read(reader)?;
2465 let delayed_payment_key = Readable::read(reader)?;
2466 let per_commitment_point = Readable::read(reader)?;
2467 let feerate_per_kw: u64 = Readable::read(reader)?;
2469 let htlcs_len: u64 = Readable::read(reader)?;
2470 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_len as usize, MAX_ALLOC_SIZE / 128));
2471 for _ in 0..htlcs_len {
2472 let htlc = read_htlc_in_commitment!();
2473 let sigs = match <u8 as Readable>::read(reader)? {
2475 1 => Some(Readable::read(reader)?),
2476 _ => return Err(DecodeError::InvalidValue),
2478 htlcs.push((htlc, sigs, Readable::read(reader)?));
2483 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, per_commitment_point, feerate_per_kw,
2490 let prev_local_signed_commitment_tx = match <u8 as Readable>::read(reader)? {
2493 Some(read_local_tx!())
2495 _ => return Err(DecodeError::InvalidValue),
2498 let current_local_signed_commitment_tx = match <u8 as Readable>::read(reader)? {
2501 Some(read_local_tx!())
2503 _ => return Err(DecodeError::InvalidValue),
2506 let current_remote_commitment_number = <U48 as Readable>::read(reader)?.0;
2508 let payment_preimages_len: u64 = Readable::read(reader)?;
2509 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
2510 for _ in 0..payment_preimages_len {
2511 let preimage: PaymentPreimage = Readable::read(reader)?;
2512 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2513 if let Some(_) = payment_preimages.insert(hash, preimage) {
2514 return Err(DecodeError::InvalidValue);
2518 let pending_htlcs_updated_len: u64 = Readable::read(reader)?;
2519 let mut pending_htlcs_updated = Vec::with_capacity(cmp::min(pending_htlcs_updated_len as usize, MAX_ALLOC_SIZE / (32 + 8*3)));
2520 for _ in 0..pending_htlcs_updated_len {
2521 pending_htlcs_updated.push(Readable::read(reader)?);
2524 let pending_events_len: u64 = Readable::read(reader)?;
2525 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<events::Event>()));
2526 for _ in 0..pending_events_len {
2527 if let Some(event) = MaybeReadable::read(reader)? {
2528 pending_events.push(event);
2532 let last_block_hash: Sha256dHash = Readable::read(reader)?;
2533 let to_remote_rescue = match <u8 as Readable>::read(reader)? {
2536 let to_remote_script = Readable::read(reader)?;
2537 let local_key = Readable::read(reader)?;
2538 Some((to_remote_script, local_key))
2540 _ => return Err(DecodeError::InvalidValue),
2543 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
2544 let mut onchain_events_waiting_threshold_conf = HashMap::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
2545 for _ in 0..waiting_threshold_conf_len {
2546 let height_target = Readable::read(reader)?;
2547 let events_len: u64 = Readable::read(reader)?;
2548 let mut events = Vec::with_capacity(cmp::min(events_len as usize, MAX_ALLOC_SIZE / 128));
2549 for _ in 0..events_len {
2550 let ev = match <u8 as Readable>::read(reader)? {
2552 let htlc_source = Readable::read(reader)?;
2553 let hash = Readable::read(reader)?;
2554 OnchainEvent::HTLCUpdate {
2555 htlc_update: (htlc_source, hash)
2558 _ => return Err(DecodeError::InvalidValue),
2562 onchain_events_waiting_threshold_conf.insert(height_target, events);
2565 let outputs_to_watch_len: u64 = Readable::read(reader)?;
2566 let mut outputs_to_watch = HashMap::with_capacity(cmp::min(outputs_to_watch_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<Sha256dHash>() + mem::size_of::<Vec<Script>>())));
2567 for _ in 0..outputs_to_watch_len {
2568 let txid = Readable::read(reader)?;
2569 let outputs_len: u64 = Readable::read(reader)?;
2570 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Script>()));
2571 for _ in 0..outputs_len {
2572 outputs.push(Readable::read(reader)?);
2574 if let Some(_) = outputs_to_watch.insert(txid, outputs) {
2575 return Err(DecodeError::InvalidValue);
2578 let onchain_tx_handler = ReadableArgs::read(reader, logger.clone())?;
2580 Ok((last_block_hash.clone(), ChannelMonitor {
2582 commitment_transaction_number_obscure_factor,
2585 their_htlc_base_key,
2586 their_delayed_payment_base_key,
2587 funding_redeemscript,
2588 channel_value_satoshis,
2589 their_cur_revocation_points,
2592 their_to_self_delay,
2595 remote_claimable_outpoints,
2596 remote_commitment_txn_on_chain,
2597 remote_hash_commitment_number,
2599 prev_local_signed_commitment_tx,
2600 current_local_signed_commitment_tx,
2601 current_remote_commitment_number,
2604 pending_htlcs_updated,
2609 onchain_events_waiting_threshold_conf,
2615 secp_ctx: Secp256k1::new(),
2623 use bitcoin::blockdata::script::{Script, Builder};
2624 use bitcoin::blockdata::opcodes;
2625 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
2626 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
2627 use bitcoin::util::bip143;
2628 use bitcoin_hashes::Hash;
2629 use bitcoin_hashes::sha256::Hash as Sha256;
2630 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
2631 use bitcoin_hashes::hex::FromHex;
2633 use chain::transaction::OutPoint;
2634 use ln::channelmanager::{PaymentPreimage, PaymentHash};
2635 use ln::channelmonitor::ChannelMonitor;
2636 use ln::onchaintx::{OnchainTxHandler, InputDescriptors};
2638 use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys, LocalCommitmentTransaction};
2639 use util::test_utils::TestLogger;
2640 use secp256k1::key::{SecretKey,PublicKey};
2641 use secp256k1::Secp256k1;
2642 use rand::{thread_rng,Rng};
2644 use chain::keysinterface::InMemoryChannelKeys;
2647 fn test_prune_preimages() {
2648 let secp_ctx = Secp256k1::new();
2649 let logger = Arc::new(TestLogger::new());
2651 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2652 macro_rules! dummy_keys {
2656 per_commitment_point: dummy_key.clone(),
2657 revocation_key: dummy_key.clone(),
2658 a_htlc_key: dummy_key.clone(),
2659 b_htlc_key: dummy_key.clone(),
2660 a_delayed_payment_key: dummy_key.clone(),
2661 b_payment_key: dummy_key.clone(),
2666 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2668 let mut preimages = Vec::new();
2670 let mut rng = thread_rng();
2672 let mut preimage = PaymentPreimage([0; 32]);
2673 rng.fill_bytes(&mut preimage.0[..]);
2674 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2675 preimages.push((preimage, hash));
2679 macro_rules! preimages_slice_to_htlc_outputs {
2680 ($preimages_slice: expr) => {
2682 let mut res = Vec::new();
2683 for (idx, preimage) in $preimages_slice.iter().enumerate() {
2684 res.push((HTLCOutputInCommitment {
2688 payment_hash: preimage.1.clone(),
2689 transaction_output_index: Some(idx as u32),
2696 macro_rules! preimages_to_local_htlcs {
2697 ($preimages_slice: expr) => {
2699 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
2700 let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
2706 macro_rules! test_preimages_exist {
2707 ($preimages_slice: expr, $monitor: expr) => {
2708 for preimage in $preimages_slice {
2709 assert!($monitor.payment_preimages.contains_key(&preimage.1));
2714 let keys = InMemoryChannelKeys::new(
2716 SecretKey::from_slice(&[41; 32]).unwrap(),
2717 SecretKey::from_slice(&[41; 32]).unwrap(),
2718 SecretKey::from_slice(&[41; 32]).unwrap(),
2719 SecretKey::from_slice(&[41; 32]).unwrap(),
2720 SecretKey::from_slice(&[41; 32]).unwrap(),
2725 // Prune with one old state and a local commitment tx holding a few overlaps with the
2727 let mut monitor = ChannelMonitor::new(keys,
2728 &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0, &Script::new(),
2729 (OutPoint { txid: Sha256dHash::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
2730 &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
2731 &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
2732 0, Script::new(), 46, 0, logger.clone());
2734 monitor.their_to_self_delay = Some(10);
2736 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10])).unwrap();
2737 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
2738 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
2739 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
2740 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key);
2741 for &(ref preimage, ref hash) in preimages.iter() {
2742 monitor.provide_payment_preimage(hash, preimage);
2745 // Now provide a secret, pruning preimages 10-15
2746 let mut secret = [0; 32];
2747 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2748 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
2749 assert_eq!(monitor.payment_preimages.len(), 15);
2750 test_preimages_exist!(&preimages[0..10], monitor);
2751 test_preimages_exist!(&preimages[15..20], monitor);
2753 // Now provide a further secret, pruning preimages 15-17
2754 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2755 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
2756 assert_eq!(monitor.payment_preimages.len(), 13);
2757 test_preimages_exist!(&preimages[0..10], monitor);
2758 test_preimages_exist!(&preimages[17..20], monitor);
2760 // Now update local commitment tx info, pruning only element 18 as we still care about the
2761 // previous commitment tx's preimages too
2762 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5])).unwrap();
2763 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2764 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
2765 assert_eq!(monitor.payment_preimages.len(), 12);
2766 test_preimages_exist!(&preimages[0..10], monitor);
2767 test_preimages_exist!(&preimages[18..20], monitor);
2769 // But if we do it again, we'll prune 5-10
2770 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3])).unwrap();
2771 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2772 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
2773 assert_eq!(monitor.payment_preimages.len(), 5);
2774 test_preimages_exist!(&preimages[0..5], monitor);
2778 fn test_claim_txn_weight_computation() {
2779 // We test Claim txn weight, knowing that we want expected weigth and
2780 // not actual case to avoid sigs and time-lock delays hell variances.
2782 let secp_ctx = Secp256k1::new();
2783 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
2784 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
2785 let mut sum_actual_sigs = 0;
2787 macro_rules! sign_input {
2788 ($sighash_parts: expr, $input: expr, $idx: expr, $amount: expr, $input_type: expr, $sum_actual_sigs: expr) => {
2789 let htlc = HTLCOutputInCommitment {
2790 offered: if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::OfferedHTLC { true } else { false },
2792 cltv_expiry: 2 << 16,
2793 payment_hash: PaymentHash([1; 32]),
2794 transaction_output_index: Some($idx),
2796 let redeem_script = if *$input_type == InputDescriptors::RevokedOutput { chan_utils::get_revokeable_redeemscript(&pubkey, 256, &pubkey) } else { chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &pubkey, &pubkey, &pubkey) };
2797 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeem_script, $amount)[..]);
2798 let sig = secp_ctx.sign(&sighash, &privkey);
2799 $input.witness.push(sig.serialize_der().to_vec());
2800 $input.witness[0].push(SigHashType::All as u8);
2801 sum_actual_sigs += $input.witness[0].len();
2802 if *$input_type == InputDescriptors::RevokedOutput {
2803 $input.witness.push(vec!(1));
2804 } else if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::RevokedReceivedHTLC {
2805 $input.witness.push(pubkey.clone().serialize().to_vec());
2806 } else if *$input_type == InputDescriptors::ReceivedHTLC {
2807 $input.witness.push(vec![0]);
2809 $input.witness.push(PaymentPreimage([1; 32]).0.to_vec());
2811 $input.witness.push(redeem_script.into_bytes());
2812 println!("witness[0] {}", $input.witness[0].len());
2813 println!("witness[1] {}", $input.witness[1].len());
2814 println!("witness[2] {}", $input.witness[2].len());
2818 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
2819 let txid = Sha256dHash::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
2821 // Justice tx with 1 to_local, 2 revoked offered HTLCs, 1 revoked received HTLCs
2822 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2824 claim_tx.input.push(TxIn {
2825 previous_output: BitcoinOutPoint {
2829 script_sig: Script::new(),
2830 sequence: 0xfffffffd,
2831 witness: Vec::new(),
2834 claim_tx.output.push(TxOut {
2835 script_pubkey: script_pubkey.clone(),
2838 let base_weight = claim_tx.get_weight();
2839 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
2840 let inputs_des = vec![InputDescriptors::RevokedOutput, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedReceivedHTLC];
2841 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
2842 sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
2844 assert_eq!(base_weight + OnchainTxHandler::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
2846 // Claim tx with 1 offered HTLCs, 3 received HTLCs
2847 claim_tx.input.clear();
2848 sum_actual_sigs = 0;
2850 claim_tx.input.push(TxIn {
2851 previous_output: BitcoinOutPoint {
2855 script_sig: Script::new(),
2856 sequence: 0xfffffffd,
2857 witness: Vec::new(),
2860 let base_weight = claim_tx.get_weight();
2861 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
2862 let inputs_des = vec![InputDescriptors::OfferedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC];
2863 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
2864 sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
2866 assert_eq!(base_weight + OnchainTxHandler::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
2868 // Justice tx with 1 revoked HTLC-Success tx output
2869 claim_tx.input.clear();
2870 sum_actual_sigs = 0;
2871 claim_tx.input.push(TxIn {
2872 previous_output: BitcoinOutPoint {
2876 script_sig: Script::new(),
2877 sequence: 0xfffffffd,
2878 witness: Vec::new(),
2880 let base_weight = claim_tx.get_weight();
2881 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
2882 let inputs_des = vec![InputDescriptors::RevokedOutput];
2883 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
2884 sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
2886 assert_eq!(base_weight + OnchainTxHandler::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs));
2889 // Further testing is done in the ChannelManager integration tests.