1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The logic to monitor for on-chain transactions and create the relevant claim responses lives
13 //! ChannelMonitor objects are generated by ChannelManager in response to relevant
14 //! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
15 //! be made in responding to certain messages, see [`chain::Watch`] for more.
17 //! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
18 //! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
19 //! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
20 //! security-domain-separated system design, you should consider having multiple paths for
21 //! ChannelMonitors to get out of the HSM and onto monitoring devices.
23 use bitcoin::blockdata::block::{Block, BlockHeader};
24 use bitcoin::blockdata::transaction::{TxOut,Transaction};
25 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
26 use bitcoin::blockdata::script::{Script, Builder};
27 use bitcoin::blockdata::opcodes;
29 use bitcoin::hashes::Hash;
30 use bitcoin::hashes::sha256::Hash as Sha256;
31 use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
33 use bitcoin::secp256k1::{Secp256k1,Signature};
34 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
35 use bitcoin::secp256k1;
37 use ln::msgs::DecodeError;
39 use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCType, ChannelTransactionParameters, HolderCommitmentTransaction};
40 use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
41 use ln::onchaintx::{OnchainTxHandler, InputDescriptors};
43 use chain::WatchedOutput;
44 use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
45 use chain::transaction::{OutPoint, TransactionData};
46 use chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, Sign, KeysInterface};
48 use util::logger::Logger;
49 use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, U48};
51 use util::events::Event;
53 use std::collections::{HashMap, HashSet};
59 /// An update generated by the underlying Channel itself which contains some new information the
60 /// ChannelMonitor should be made aware of.
61 #[cfg_attr(any(test, feature = "fuzztarget", feature = "_test_utils"), derive(PartialEq))]
64 pub struct ChannelMonitorUpdate {
65 pub(crate) updates: Vec<ChannelMonitorUpdateStep>,
66 /// The sequence number of this update. Updates *must* be replayed in-order according to this
67 /// sequence number (and updates may panic if they are not). The update_id values are strictly
68 /// increasing and increase by one for each new update, with one exception specified below.
70 /// This sequence number is also used to track up to which points updates which returned
71 /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
72 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
74 /// The only instance where update_id values are not strictly increasing is the case where we
75 /// allow post-force-close updates with a special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. See
76 /// its docs for more details.
81 /// (1) a channel has been force closed and
82 /// (2) we receive a preimage from a forward link that allows us to spend an HTLC output on
83 /// this channel's (the backward link's) broadcasted commitment transaction
84 /// then we allow the `ChannelManager` to send a `ChannelMonitorUpdate` with this update ID,
85 /// with the update providing said payment preimage. No other update types are allowed after
87 pub const CLOSED_CHANNEL_UPDATE_ID: u64 = std::u64::MAX;
89 impl Writeable for ChannelMonitorUpdate {
90 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
91 self.update_id.write(w)?;
92 (self.updates.len() as u64).write(w)?;
93 for update_step in self.updates.iter() {
94 update_step.write(w)?;
99 impl Readable for ChannelMonitorUpdate {
100 fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
101 let update_id: u64 = Readable::read(r)?;
102 let len: u64 = Readable::read(r)?;
103 let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::std::mem::size_of::<ChannelMonitorUpdateStep>()));
105 updates.push(Readable::read(r)?);
107 Ok(Self { update_id, updates })
111 /// An error enum representing a failure to persist a channel monitor update.
112 #[derive(Clone, Debug)]
113 pub enum ChannelMonitorUpdateErr {
114 /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
115 /// our state failed, but is expected to succeed at some point in the future).
117 /// Such a failure will "freeze" a channel, preventing us from revoking old states or
118 /// submitting new commitment transactions to the counterparty. Once the update(s) which failed
119 /// have been successfully applied, ChannelManager::channel_monitor_updated can be used to
120 /// restore the channel to an operational state.
122 /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If
123 /// you return a TemporaryFailure you must ensure that it is written to disk safely before
124 /// writing out the latest ChannelManager state.
126 /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
127 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
128 /// to claim it on this channel) and those updates must be applied wherever they can be. At
129 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
130 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
131 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
134 /// Note that even if updates made after TemporaryFailure succeed you must still call
135 /// channel_monitor_updated to ensure you have the latest monitor and re-enable normal channel
138 /// Note that the update being processed here will not be replayed for you when you call
139 /// ChannelManager::channel_monitor_updated, so you must store the update itself along
140 /// with the persisted ChannelMonitor on your own local disk prior to returning a
141 /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the
142 /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at
145 /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
146 /// remote location (with local copies persisted immediately), it is anticipated that all
147 /// updates will return TemporaryFailure until the remote copies could be updated.
149 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
150 /// different watchtower and cannot update with all watchtowers that were previously informed
151 /// of this channel).
153 /// At reception of this error, ChannelManager will force-close the channel and return at
154 /// least a final ChannelMonitorUpdate::ChannelForceClosed which must be delivered to at
155 /// least one ChannelMonitor copy. Revocation secret MUST NOT be released and offchain channel
156 /// update must be rejected.
158 /// This failure may also signal a failure to update the local persisted copy of one of
159 /// the channel monitor instance.
161 /// Note that even when you fail a holder commitment transaction update, you must store the
162 /// update to ensure you can claim from it in case of a duplicate copy of this ChannelMonitor
163 /// broadcasts it (e.g distributed channel-monitor deployment)
165 /// In case of distributed watchtowers deployment, the new version must be written to disk, as
166 /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
167 /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
168 /// lagging behind on block processing.
172 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
173 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::update_monitor this
174 /// means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was
176 /// Contains a developer-readable error message.
177 #[derive(Clone, Debug)]
178 pub struct MonitorUpdateError(pub &'static str);
180 /// An event to be processed by the ChannelManager.
181 #[derive(Clone, PartialEq)]
182 pub enum MonitorEvent {
183 /// A monitor event containing an HTLCUpdate.
184 HTLCEvent(HTLCUpdate),
186 /// A monitor event that the Channel's commitment transaction was broadcasted.
187 CommitmentTxBroadcasted(OutPoint),
190 /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
191 /// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
192 /// preimage claim backward will lead to loss of funds.
193 #[derive(Clone, PartialEq)]
194 pub struct HTLCUpdate {
195 pub(crate) payment_hash: PaymentHash,
196 pub(crate) payment_preimage: Option<PaymentPreimage>,
197 pub(crate) source: HTLCSource
199 impl_writeable!(HTLCUpdate, 0, { payment_hash, payment_preimage, source });
201 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
202 /// instead claiming it in its own individual transaction.
203 pub(crate) const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
204 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
205 /// HTLC-Success transaction.
206 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
207 /// transaction confirmed (and we use it in a few more, equivalent, places).
208 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
209 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
210 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
211 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
212 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
213 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
214 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
215 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
216 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
217 /// accurate block height.
218 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
219 /// with at worst this delay, so we are not only using this value as a mercy for them but also
220 /// us as a safeguard to delay with enough time.
221 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
222 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding inbound
223 /// HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us losing money.
224 /// We use also this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
225 /// It may cause spurrious generation of bumped claim txn but that's allright given the outpoint is already
226 /// solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
227 /// keeping bumping another claim tx to solve the outpoint.
228 pub(crate) const ANTI_REORG_DELAY: u32 = 6;
229 /// Number of blocks before confirmation at which we fail back an un-relayed HTLC or at which we
230 /// refuse to accept a new HTLC.
232 /// This is used for a few separate purposes:
233 /// 1) if we've received an MPP HTLC to us and it expires within this many blocks and we are
234 /// waiting on additional parts (or waiting on the preimage for any HTLC from the user), we will
236 /// 2) if we receive an HTLC within this many blocks of its expiry (plus one to avoid a race
237 /// condition with the above), we will fail this HTLC without telling the user we received it,
238 /// 3) if we are waiting on a connection or a channel state update to send an HTLC to a peer, and
239 /// that HTLC expires within this many blocks, we will simply fail the HTLC instead.
241 /// (1) is all about protecting us - we need enough time to update the channel state before we hit
242 /// CLTV_CLAIM_BUFFER, at which point we'd go on chain to claim the HTLC with the preimage.
244 /// (2) is the same, but with an additional buffer to avoid accepting an HTLC which is immediately
245 /// in a race condition between the user connecting a block (which would fail it) and the user
246 /// providing us the preimage (which would claim it).
248 /// (3) is about our counterparty - we don't want to relay an HTLC to a counterparty when they may
249 /// end up force-closing the channel on us to claim it.
250 pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS;
252 // TODO(devrandom) replace this with HolderCommitmentTransaction
253 #[derive(Clone, PartialEq)]
254 struct HolderSignedTx {
255 /// txid of the transaction in tx, just used to make comparison faster
257 revocation_key: PublicKey,
258 a_htlc_key: PublicKey,
259 b_htlc_key: PublicKey,
260 delayed_payment_key: PublicKey,
261 per_commitment_point: PublicKey,
263 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
266 /// We use this to track counterparty commitment transactions and htlcs outputs and
267 /// use it to generate any justice or 2nd-stage preimage/timeout transactions.
269 struct CounterpartyCommitmentTransaction {
270 counterparty_delayed_payment_base_key: PublicKey,
271 counterparty_htlc_base_key: PublicKey,
272 on_counterparty_tx_csv: u16,
273 per_htlc: HashMap<Txid, Vec<HTLCOutputInCommitment>>
276 impl Writeable for CounterpartyCommitmentTransaction {
277 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
278 self.counterparty_delayed_payment_base_key.write(w)?;
279 self.counterparty_htlc_base_key.write(w)?;
280 w.write_all(&byte_utils::be16_to_array(self.on_counterparty_tx_csv))?;
281 w.write_all(&byte_utils::be64_to_array(self.per_htlc.len() as u64))?;
282 for (ref txid, ref htlcs) in self.per_htlc.iter() {
283 w.write_all(&txid[..])?;
284 w.write_all(&byte_utils::be64_to_array(htlcs.len() as u64))?;
285 for &ref htlc in htlcs.iter() {
292 impl Readable for CounterpartyCommitmentTransaction {
293 fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
294 let counterparty_commitment_transaction = {
295 let counterparty_delayed_payment_base_key = Readable::read(r)?;
296 let counterparty_htlc_base_key = Readable::read(r)?;
297 let on_counterparty_tx_csv: u16 = Readable::read(r)?;
298 let per_htlc_len: u64 = Readable::read(r)?;
299 let mut per_htlc = HashMap::with_capacity(cmp::min(per_htlc_len as usize, MAX_ALLOC_SIZE / 64));
300 for _ in 0..per_htlc_len {
301 let txid: Txid = Readable::read(r)?;
302 let htlcs_count: u64 = Readable::read(r)?;
303 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
304 for _ in 0..htlcs_count {
305 let htlc = Readable::read(r)?;
308 if let Some(_) = per_htlc.insert(txid, htlcs) {
309 return Err(DecodeError::InvalidValue);
312 CounterpartyCommitmentTransaction {
313 counterparty_delayed_payment_base_key,
314 counterparty_htlc_base_key,
315 on_counterparty_tx_csv,
319 Ok(counterparty_commitment_transaction)
323 /// When ChannelMonitor discovers an onchain outpoint being a step of a channel and that it needs
324 /// to generate a tx to push channel state forward, we cache outpoint-solving tx material to build
325 /// a new bumped one in case of lenghty confirmation delay
326 #[derive(Clone, PartialEq)]
327 pub(crate) enum InputMaterial {
329 per_commitment_point: PublicKey,
330 counterparty_delayed_payment_base_key: PublicKey,
331 counterparty_htlc_base_key: PublicKey,
332 per_commitment_key: SecretKey,
333 input_descriptor: InputDescriptors,
335 htlc: Option<HTLCOutputInCommitment>,
336 on_counterparty_tx_csv: u16,
339 per_commitment_point: PublicKey,
340 counterparty_delayed_payment_base_key: PublicKey,
341 counterparty_htlc_base_key: PublicKey,
342 preimage: Option<PaymentPreimage>,
343 htlc: HTLCOutputInCommitment
346 preimage: Option<PaymentPreimage>,
350 funding_redeemscript: Script,
354 impl Writeable for InputMaterial {
355 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
357 &InputMaterial::Revoked { ref per_commitment_point, ref counterparty_delayed_payment_base_key, ref counterparty_htlc_base_key, ref per_commitment_key, ref input_descriptor, ref amount, ref htlc, ref on_counterparty_tx_csv} => {
358 writer.write_all(&[0; 1])?;
359 per_commitment_point.write(writer)?;
360 counterparty_delayed_payment_base_key.write(writer)?;
361 counterparty_htlc_base_key.write(writer)?;
362 writer.write_all(&per_commitment_key[..])?;
363 input_descriptor.write(writer)?;
364 writer.write_all(&byte_utils::be64_to_array(*amount))?;
366 on_counterparty_tx_csv.write(writer)?;
368 &InputMaterial::CounterpartyHTLC { ref per_commitment_point, ref counterparty_delayed_payment_base_key, ref counterparty_htlc_base_key, ref preimage, ref htlc} => {
369 writer.write_all(&[1; 1])?;
370 per_commitment_point.write(writer)?;
371 counterparty_delayed_payment_base_key.write(writer)?;
372 counterparty_htlc_base_key.write(writer)?;
373 preimage.write(writer)?;
376 &InputMaterial::HolderHTLC { ref preimage, ref amount } => {
377 writer.write_all(&[2; 1])?;
378 preimage.write(writer)?;
379 writer.write_all(&byte_utils::be64_to_array(*amount))?;
381 &InputMaterial::Funding { ref funding_redeemscript } => {
382 writer.write_all(&[3; 1])?;
383 funding_redeemscript.write(writer)?;
390 impl Readable for InputMaterial {
391 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
392 let input_material = match <u8 as Readable>::read(reader)? {
394 let per_commitment_point = Readable::read(reader)?;
395 let counterparty_delayed_payment_base_key = Readable::read(reader)?;
396 let counterparty_htlc_base_key = Readable::read(reader)?;
397 let per_commitment_key = Readable::read(reader)?;
398 let input_descriptor = Readable::read(reader)?;
399 let amount = Readable::read(reader)?;
400 let htlc = Readable::read(reader)?;
401 let on_counterparty_tx_csv = Readable::read(reader)?;
402 InputMaterial::Revoked {
403 per_commitment_point,
404 counterparty_delayed_payment_base_key,
405 counterparty_htlc_base_key,
410 on_counterparty_tx_csv
414 let per_commitment_point = Readable::read(reader)?;
415 let counterparty_delayed_payment_base_key = Readable::read(reader)?;
416 let counterparty_htlc_base_key = Readable::read(reader)?;
417 let preimage = Readable::read(reader)?;
418 let htlc = Readable::read(reader)?;
419 InputMaterial::CounterpartyHTLC {
420 per_commitment_point,
421 counterparty_delayed_payment_base_key,
422 counterparty_htlc_base_key,
428 let preimage = Readable::read(reader)?;
429 let amount = Readable::read(reader)?;
430 InputMaterial::HolderHTLC {
436 InputMaterial::Funding {
437 funding_redeemscript: Readable::read(reader)?,
440 _ => return Err(DecodeError::InvalidValue),
446 /// ClaimRequest is a descriptor structure to communicate between detection
447 /// and reaction module. They are generated by ChannelMonitor while parsing
448 /// onchain txn leaked from a channel and handed over to OnchainTxHandler which
449 /// is responsible for opportunistic aggregation, selecting and enforcing
450 /// bumping logic, building and signing transactions.
451 pub(crate) struct ClaimRequest {
452 // Block height before which claiming is exclusive to one party,
453 // after reaching it, claiming may be contentious.
454 pub(crate) absolute_timelock: u32,
455 // Timeout tx must have nLocktime set which means aggregating multiple
456 // ones must take the higher nLocktime among them to satisfy all of them.
457 // Sadly it has few pitfalls, a) it takes longuer to get fund back b) CLTV_DELTA
458 // of a sooner-HTLC could be swallowed by the highest nLocktime of the HTLC set.
459 // Do simplify we mark them as non-aggregable.
460 pub(crate) aggregable: bool,
461 // Basic bitcoin outpoint (txid, vout)
462 pub(crate) outpoint: BitcoinOutPoint,
463 // Following outpoint type, set of data needed to generate transaction digest
464 // and satisfy witness program.
465 pub(crate) witness_data: InputMaterial
468 /// An entry for an [`OnchainEvent`], stating the block height when the event was observed.
470 /// Used to determine when the on-chain event can be considered safe from a chain reorganization.
472 struct OnchainEventEntry {
477 impl OnchainEventEntry {
478 fn confirmation_threshold(&self) -> u32 {
479 self.height + ANTI_REORG_DELAY - 1
482 fn has_reached_confirmation_threshold(&self, height: u32) -> bool {
483 height >= self.confirmation_threshold()
487 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
488 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
491 /// HTLC output getting solved by a timeout, at maturation we pass upstream payment source information to solve
492 /// inbound HTLC in backward channel. Note, in case of preimage, we pass info to upstream without delay as we can
493 /// only win from it, so it's never an OnchainEvent
495 htlc_update: (HTLCSource, PaymentHash),
498 descriptor: SpendableOutputDescriptor,
502 const SERIALIZATION_VERSION: u8 = 1;
503 const MIN_SERIALIZATION_VERSION: u8 = 1;
505 #[cfg_attr(any(test, feature = "fuzztarget", feature = "_test_utils"), derive(PartialEq))]
507 pub(crate) enum ChannelMonitorUpdateStep {
508 LatestHolderCommitmentTXInfo {
509 commitment_tx: HolderCommitmentTransaction,
510 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
512 LatestCounterpartyCommitmentTXInfo {
513 commitment_txid: Txid,
514 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
515 commitment_number: u64,
516 their_revocation_point: PublicKey,
519 payment_preimage: PaymentPreimage,
525 /// Used to indicate that the no future updates will occur, and likely that the latest holder
526 /// commitment transaction(s) should be broadcast, as the channel has been force-closed.
528 /// If set to false, we shouldn't broadcast the latest holder commitment transaction as we
529 /// think we've fallen behind!
530 should_broadcast: bool,
534 impl Writeable for ChannelMonitorUpdateStep {
535 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
537 &ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { ref commitment_tx, ref htlc_outputs } => {
539 commitment_tx.write(w)?;
540 (htlc_outputs.len() as u64).write(w)?;
541 for &(ref output, ref signature, ref source) in htlc_outputs.iter() {
547 &ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, ref htlc_outputs, ref commitment_number, ref their_revocation_point } => {
549 commitment_txid.write(w)?;
550 commitment_number.write(w)?;
551 their_revocation_point.write(w)?;
552 (htlc_outputs.len() as u64).write(w)?;
553 for &(ref output, ref source) in htlc_outputs.iter() {
555 source.as_ref().map(|b| b.as_ref()).write(w)?;
558 &ChannelMonitorUpdateStep::PaymentPreimage { ref payment_preimage } => {
560 payment_preimage.write(w)?;
562 &ChannelMonitorUpdateStep::CommitmentSecret { ref idx, ref secret } => {
567 &ChannelMonitorUpdateStep::ChannelForceClosed { ref should_broadcast } => {
569 should_broadcast.write(w)?;
575 impl Readable for ChannelMonitorUpdateStep {
576 fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
577 match Readable::read(r)? {
579 Ok(ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo {
580 commitment_tx: Readable::read(r)?,
582 let len: u64 = Readable::read(r)?;
583 let mut res = Vec::new();
585 res.push((Readable::read(r)?, Readable::read(r)?, Readable::read(r)?));
592 Ok(ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo {
593 commitment_txid: Readable::read(r)?,
594 commitment_number: Readable::read(r)?,
595 their_revocation_point: Readable::read(r)?,
597 let len: u64 = Readable::read(r)?;
598 let mut res = Vec::new();
600 res.push((Readable::read(r)?, <Option<HTLCSource> as Readable>::read(r)?.map(|o| Box::new(o))));
607 Ok(ChannelMonitorUpdateStep::PaymentPreimage {
608 payment_preimage: Readable::read(r)?,
612 Ok(ChannelMonitorUpdateStep::CommitmentSecret {
613 idx: Readable::read(r)?,
614 secret: Readable::read(r)?,
618 Ok(ChannelMonitorUpdateStep::ChannelForceClosed {
619 should_broadcast: Readable::read(r)?
622 _ => Err(DecodeError::InvalidValue),
627 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
628 /// on-chain transactions to ensure no loss of funds occurs.
630 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
631 /// information and are actively monitoring the chain.
633 /// Pending Events or updated HTLCs which have not yet been read out by
634 /// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
635 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
636 /// gotten are fully handled before re-serializing the new state.
638 /// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
639 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
640 /// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
641 /// returned block hash and the the current chain and then reconnecting blocks to get to the
642 /// best chain) upon deserializing the object!
643 pub struct ChannelMonitor<Signer: Sign> {
645 pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
647 inner: Mutex<ChannelMonitorImpl<Signer>>,
650 pub(crate) struct ChannelMonitorImpl<Signer: Sign> {
651 latest_update_id: u64,
652 commitment_transaction_number_obscure_factor: u64,
654 destination_script: Script,
655 broadcasted_holder_revokable_script: Option<(Script, PublicKey, PublicKey)>,
656 counterparty_payment_script: Script,
657 shutdown_script: Script,
659 channel_keys_id: [u8; 32],
660 holder_revocation_basepoint: PublicKey,
661 funding_info: (OutPoint, Script),
662 current_counterparty_commitment_txid: Option<Txid>,
663 prev_counterparty_commitment_txid: Option<Txid>,
665 counterparty_tx_cache: CounterpartyCommitmentTransaction,
666 funding_redeemscript: Script,
667 channel_value_satoshis: u64,
668 // first is the idx of the first of the two revocation points
669 their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
671 on_holder_tx_csv: u16,
673 commitment_secrets: CounterpartyCommitmentSecrets,
674 counterparty_claimable_outpoints: HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
675 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
676 /// Nor can we figure out their commitment numbers without the commitment transaction they are
677 /// spending. Thus, in order to claim them via revocation key, we track all the counterparty
678 /// commitment transactions which we find on-chain, mapping them to the commitment number which
679 /// can be used to derive the revocation key and claim the transactions.
680 counterparty_commitment_txn_on_chain: HashMap<Txid, u64>,
681 /// Cache used to make pruning of payment_preimages faster.
682 /// Maps payment_hash values to commitment numbers for counterparty transactions for non-revoked
683 /// counterparty transactions (ie should remain pretty small).
684 /// Serialized to disk but should generally not be sent to Watchtowers.
685 counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
687 // We store two holder commitment transactions to avoid any race conditions where we may update
688 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
689 // various monitors for one channel being out of sync, and us broadcasting a holder
690 // transaction for which we have deleted claim information on some watchtowers.
691 prev_holder_signed_commitment_tx: Option<HolderSignedTx>,
692 current_holder_commitment_tx: HolderSignedTx,
694 // Used just for ChannelManager to make sure it has the latest channel data during
696 current_counterparty_commitment_number: u64,
697 // Used just for ChannelManager to make sure it has the latest channel data during
699 current_holder_commitment_number: u64,
701 payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
703 pending_monitor_events: Vec<MonitorEvent>,
704 pending_events: Vec<Event>,
706 // Used to track on-chain events (i.e., transactions part of channels confirmed on chain) on
707 // which to take actions once they reach enough confirmations. Each entry includes the
708 // transaction's id and the height when the transaction was confirmed on chain.
709 onchain_events_waiting_threshold_conf: Vec<OnchainEventEntry>,
711 // If we get serialized out and re-read, we need to make sure that the chain monitoring
712 // interface knows about the TXOs that we want to be notified of spends of. We could probably
713 // be smart and derive them from the above storage fields, but its much simpler and more
714 // Obviously Correct (tm) if we just keep track of them explicitly.
715 outputs_to_watch: HashMap<Txid, Vec<(u32, Script)>>,
718 pub onchain_tx_handler: OnchainTxHandler<Signer>,
720 onchain_tx_handler: OnchainTxHandler<Signer>,
722 // This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the
723 // channel has been force-closed. After this is set, no further holder commitment transaction
724 // updates may occur, and we panic!() if one is provided.
725 lockdown_from_offchain: bool,
727 // Set once we've signed a holder commitment transaction and handed it over to our
728 // OnchainTxHandler. After this is set, no future updates to our holder commitment transactions
729 // may occur, and we fail any such monitor updates.
731 // In case of update rejection due to a locally already signed commitment transaction, we
732 // nevertheless store update content to track in case of concurrent broadcast by another
733 // remote monitor out-of-order with regards to the block view.
734 holder_tx_signed: bool,
736 // We simply modify last_block_hash in Channel's block_connected so that serialization is
737 // consistent but hopefully the users' copy handles block_connected in a consistent way.
738 // (we do *not*, however, update them in update_monitor to ensure any local user copies keep
739 // their last_block_hash from its state and not based on updated copies that didn't run through
740 // the full block_connected).
741 last_block_hash: BlockHash,
742 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
745 #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
746 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
747 /// underlying object
748 impl<Signer: Sign> PartialEq for ChannelMonitor<Signer> {
749 fn eq(&self, other: &Self) -> bool {
750 let inner = self.inner.lock().unwrap();
751 let other = other.inner.lock().unwrap();
756 #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
757 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
758 /// underlying object
759 impl<Signer: Sign> PartialEq for ChannelMonitorImpl<Signer> {
760 fn eq(&self, other: &Self) -> bool {
761 if self.latest_update_id != other.latest_update_id ||
762 self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
763 self.destination_script != other.destination_script ||
764 self.broadcasted_holder_revokable_script != other.broadcasted_holder_revokable_script ||
765 self.counterparty_payment_script != other.counterparty_payment_script ||
766 self.channel_keys_id != other.channel_keys_id ||
767 self.holder_revocation_basepoint != other.holder_revocation_basepoint ||
768 self.funding_info != other.funding_info ||
769 self.current_counterparty_commitment_txid != other.current_counterparty_commitment_txid ||
770 self.prev_counterparty_commitment_txid != other.prev_counterparty_commitment_txid ||
771 self.counterparty_tx_cache != other.counterparty_tx_cache ||
772 self.funding_redeemscript != other.funding_redeemscript ||
773 self.channel_value_satoshis != other.channel_value_satoshis ||
774 self.their_cur_revocation_points != other.their_cur_revocation_points ||
775 self.on_holder_tx_csv != other.on_holder_tx_csv ||
776 self.commitment_secrets != other.commitment_secrets ||
777 self.counterparty_claimable_outpoints != other.counterparty_claimable_outpoints ||
778 self.counterparty_commitment_txn_on_chain != other.counterparty_commitment_txn_on_chain ||
779 self.counterparty_hash_commitment_number != other.counterparty_hash_commitment_number ||
780 self.prev_holder_signed_commitment_tx != other.prev_holder_signed_commitment_tx ||
781 self.current_counterparty_commitment_number != other.current_counterparty_commitment_number ||
782 self.current_holder_commitment_number != other.current_holder_commitment_number ||
783 self.current_holder_commitment_tx != other.current_holder_commitment_tx ||
784 self.payment_preimages != other.payment_preimages ||
785 self.pending_monitor_events != other.pending_monitor_events ||
786 self.pending_events.len() != other.pending_events.len() || // We trust events to round-trip properly
787 self.onchain_events_waiting_threshold_conf != other.onchain_events_waiting_threshold_conf ||
788 self.outputs_to_watch != other.outputs_to_watch ||
789 self.lockdown_from_offchain != other.lockdown_from_offchain ||
790 self.holder_tx_signed != other.holder_tx_signed
799 impl<Signer: Sign> Writeable for ChannelMonitor<Signer> {
800 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
801 //TODO: We still write out all the serialization here manually instead of using the fancy
802 //serialization framework we have, we should migrate things over to it.
803 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
804 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
806 self.inner.lock().unwrap().write(writer)
810 impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
811 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
812 self.latest_update_id.write(writer)?;
814 // Set in initial Channel-object creation, so should always be set by now:
815 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
817 self.destination_script.write(writer)?;
818 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
819 writer.write_all(&[0; 1])?;
820 broadcasted_holder_revokable_script.0.write(writer)?;
821 broadcasted_holder_revokable_script.1.write(writer)?;
822 broadcasted_holder_revokable_script.2.write(writer)?;
824 writer.write_all(&[1; 1])?;
827 self.counterparty_payment_script.write(writer)?;
828 self.shutdown_script.write(writer)?;
830 self.channel_keys_id.write(writer)?;
831 self.holder_revocation_basepoint.write(writer)?;
832 writer.write_all(&self.funding_info.0.txid[..])?;
833 writer.write_all(&byte_utils::be16_to_array(self.funding_info.0.index))?;
834 self.funding_info.1.write(writer)?;
835 self.current_counterparty_commitment_txid.write(writer)?;
836 self.prev_counterparty_commitment_txid.write(writer)?;
838 self.counterparty_tx_cache.write(writer)?;
839 self.funding_redeemscript.write(writer)?;
840 self.channel_value_satoshis.write(writer)?;
842 match self.their_cur_revocation_points {
843 Some((idx, pubkey, second_option)) => {
844 writer.write_all(&byte_utils::be48_to_array(idx))?;
845 writer.write_all(&pubkey.serialize())?;
846 match second_option {
847 Some(second_pubkey) => {
848 writer.write_all(&second_pubkey.serialize())?;
851 writer.write_all(&[0; 33])?;
856 writer.write_all(&byte_utils::be48_to_array(0))?;
860 writer.write_all(&byte_utils::be16_to_array(self.on_holder_tx_csv))?;
862 self.commitment_secrets.write(writer)?;
864 macro_rules! serialize_htlc_in_commitment {
865 ($htlc_output: expr) => {
866 writer.write_all(&[$htlc_output.offered as u8; 1])?;
867 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
868 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
869 writer.write_all(&$htlc_output.payment_hash.0[..])?;
870 $htlc_output.transaction_output_index.write(writer)?;
874 writer.write_all(&byte_utils::be64_to_array(self.counterparty_claimable_outpoints.len() as u64))?;
875 for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() {
876 writer.write_all(&txid[..])?;
877 writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
878 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
879 serialize_htlc_in_commitment!(htlc_output);
880 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
884 writer.write_all(&byte_utils::be64_to_array(self.counterparty_commitment_txn_on_chain.len() as u64))?;
885 for (ref txid, commitment_number) in self.counterparty_commitment_txn_on_chain.iter() {
886 writer.write_all(&txid[..])?;
887 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
890 writer.write_all(&byte_utils::be64_to_array(self.counterparty_hash_commitment_number.len() as u64))?;
891 for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() {
892 writer.write_all(&payment_hash.0[..])?;
893 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
896 macro_rules! serialize_holder_tx {
897 ($holder_tx: expr) => {
898 $holder_tx.txid.write(writer)?;
899 writer.write_all(&$holder_tx.revocation_key.serialize())?;
900 writer.write_all(&$holder_tx.a_htlc_key.serialize())?;
901 writer.write_all(&$holder_tx.b_htlc_key.serialize())?;
902 writer.write_all(&$holder_tx.delayed_payment_key.serialize())?;
903 writer.write_all(&$holder_tx.per_commitment_point.serialize())?;
905 writer.write_all(&byte_utils::be32_to_array($holder_tx.feerate_per_kw))?;
906 writer.write_all(&byte_utils::be64_to_array($holder_tx.htlc_outputs.len() as u64))?;
907 for &(ref htlc_output, ref sig, ref htlc_source) in $holder_tx.htlc_outputs.iter() {
908 serialize_htlc_in_commitment!(htlc_output);
909 if let &Some(ref their_sig) = sig {
911 writer.write_all(&their_sig.serialize_compact())?;
915 htlc_source.write(writer)?;
920 if let Some(ref prev_holder_tx) = self.prev_holder_signed_commitment_tx {
921 writer.write_all(&[1; 1])?;
922 serialize_holder_tx!(prev_holder_tx);
924 writer.write_all(&[0; 1])?;
927 serialize_holder_tx!(self.current_holder_commitment_tx);
929 writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?;
930 writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?;
932 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
933 for payment_preimage in self.payment_preimages.values() {
934 writer.write_all(&payment_preimage.0[..])?;
937 writer.write_all(&byte_utils::be64_to_array(self.pending_monitor_events.len() as u64))?;
938 for event in self.pending_monitor_events.iter() {
940 MonitorEvent::HTLCEvent(upd) => {
944 MonitorEvent::CommitmentTxBroadcasted(_) => 1u8.write(writer)?
948 writer.write_all(&byte_utils::be64_to_array(self.pending_events.len() as u64))?;
949 for event in self.pending_events.iter() {
950 event.write(writer)?;
953 self.last_block_hash.write(writer)?;
955 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
956 for ref entry in self.onchain_events_waiting_threshold_conf.iter() {
957 writer.write_all(&byte_utils::be32_to_array(entry.height))?;
959 OnchainEvent::HTLCUpdate { ref htlc_update } => {
961 htlc_update.0.write(writer)?;
962 htlc_update.1.write(writer)?;
964 OnchainEvent::MaturingOutput { ref descriptor } => {
966 descriptor.write(writer)?;
971 (self.outputs_to_watch.len() as u64).write(writer)?;
972 for (txid, idx_scripts) in self.outputs_to_watch.iter() {
974 (idx_scripts.len() as u64).write(writer)?;
975 for (idx, script) in idx_scripts.iter() {
977 script.write(writer)?;
980 self.onchain_tx_handler.write(writer)?;
982 self.lockdown_from_offchain.write(writer)?;
983 self.holder_tx_signed.write(writer)?;
989 impl<Signer: Sign> ChannelMonitor<Signer> {
990 pub(crate) fn new(secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_pubkey: &PublicKey,
991 on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script),
992 channel_parameters: &ChannelTransactionParameters,
993 funding_redeemscript: Script, channel_value_satoshis: u64,
994 commitment_transaction_number_obscure_factor: u64,
995 initial_holder_commitment_tx: HolderCommitmentTransaction,
996 last_block_hash: BlockHash) -> ChannelMonitor<Signer> {
998 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
999 let our_channel_close_key_hash = WPubkeyHash::hash(&shutdown_pubkey.serialize());
1000 let shutdown_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
1001 let payment_key_hash = WPubkeyHash::hash(&keys.pubkeys().payment_point.serialize());
1002 let counterparty_payment_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_key_hash[..]).into_script();
1004 let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
1005 let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
1006 let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
1007 let counterparty_tx_cache = CounterpartyCommitmentTransaction { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv, per_htlc: HashMap::new() };
1009 let channel_keys_id = keys.channel_keys_id();
1010 let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
1012 // block for Rust 1.34 compat
1013 let (holder_commitment_tx, current_holder_commitment_number) = {
1014 let trusted_tx = initial_holder_commitment_tx.trust();
1015 let txid = trusted_tx.txid();
1017 let tx_keys = trusted_tx.keys();
1018 let holder_commitment_tx = HolderSignedTx {
1020 revocation_key: tx_keys.revocation_key,
1021 a_htlc_key: tx_keys.broadcaster_htlc_key,
1022 b_htlc_key: tx_keys.countersignatory_htlc_key,
1023 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
1024 per_commitment_point: tx_keys.per_commitment_point,
1025 feerate_per_kw: trusted_tx.feerate_per_kw(),
1026 htlc_outputs: Vec::new(), // There are never any HTLCs in the initial commitment transactions
1028 (holder_commitment_tx, trusted_tx.commitment_number())
1031 let onchain_tx_handler =
1032 OnchainTxHandler::new(destination_script.clone(), keys,
1033 channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx.clone());
1035 let mut outputs_to_watch = HashMap::new();
1036 outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
1039 inner: Mutex::new(ChannelMonitorImpl {
1040 latest_update_id: 0,
1041 commitment_transaction_number_obscure_factor,
1043 destination_script: destination_script.clone(),
1044 broadcasted_holder_revokable_script: None,
1045 counterparty_payment_script,
1049 holder_revocation_basepoint,
1051 current_counterparty_commitment_txid: None,
1052 prev_counterparty_commitment_txid: None,
1054 counterparty_tx_cache,
1055 funding_redeemscript,
1056 channel_value_satoshis,
1057 their_cur_revocation_points: None,
1059 on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
1061 commitment_secrets: CounterpartyCommitmentSecrets::new(),
1062 counterparty_claimable_outpoints: HashMap::new(),
1063 counterparty_commitment_txn_on_chain: HashMap::new(),
1064 counterparty_hash_commitment_number: HashMap::new(),
1066 prev_holder_signed_commitment_tx: None,
1067 current_holder_commitment_tx: holder_commitment_tx,
1068 current_counterparty_commitment_number: 1 << 48,
1069 current_holder_commitment_number,
1071 payment_preimages: HashMap::new(),
1072 pending_monitor_events: Vec::new(),
1073 pending_events: Vec::new(),
1075 onchain_events_waiting_threshold_conf: Vec::new(),
1080 lockdown_from_offchain: false,
1081 holder_tx_signed: false,
1090 fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
1091 self.inner.lock().unwrap().provide_secret(idx, secret)
1094 /// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction.
1095 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1096 /// possibly future revocation/preimage information) to claim outputs where possible.
1097 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1098 pub(crate) fn provide_latest_counterparty_commitment_tx<L: Deref>(
1101 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
1102 commitment_number: u64,
1103 their_revocation_point: PublicKey,
1105 ) where L::Target: Logger {
1106 self.inner.lock().unwrap().provide_latest_counterparty_commitment_tx(
1107 txid, htlc_outputs, commitment_number, their_revocation_point, logger)
1111 fn provide_latest_holder_commitment_tx(
1113 holder_commitment_tx: HolderCommitmentTransaction,
1114 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
1115 ) -> Result<(), MonitorUpdateError> {
1116 self.inner.lock().unwrap().provide_latest_holder_commitment_tx(
1117 holder_commitment_tx, htlc_outputs)
1121 pub(crate) fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
1123 payment_hash: &PaymentHash,
1124 payment_preimage: &PaymentPreimage,
1129 B::Target: BroadcasterInterface,
1130 F::Target: FeeEstimator,
1133 self.inner.lock().unwrap().provide_payment_preimage(
1134 payment_hash, payment_preimage, broadcaster, fee_estimator, logger)
1137 pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(
1142 B::Target: BroadcasterInterface,
1145 self.inner.lock().unwrap().broadcast_latest_holder_commitment_txn(broadcaster, logger)
1148 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1151 /// panics if the given update is not the next update by update_id.
1152 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(
1154 updates: &ChannelMonitorUpdate,
1158 ) -> Result<(), MonitorUpdateError>
1160 B::Target: BroadcasterInterface,
1161 F::Target: FeeEstimator,
1164 self.inner.lock().unwrap().update_monitor(updates, broadcaster, fee_estimator, logger)
1167 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1169 pub fn get_latest_update_id(&self) -> u64 {
1170 self.inner.lock().unwrap().get_latest_update_id()
1173 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1174 pub fn get_funding_txo(&self) -> (OutPoint, Script) {
1175 self.inner.lock().unwrap().get_funding_txo().clone()
1178 /// Gets a list of txids, with their output scripts (in the order they appear in the
1179 /// transaction), which we must learn about spends of via block_connected().
1180 pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, Script)>)> {
1181 self.inner.lock().unwrap().get_outputs_to_watch()
1182 .iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect()
1185 /// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly
1186 /// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs
1187 /// have been registered.
1188 pub fn load_outputs_to_watch<F: Deref>(&self, filter: &F) where F::Target: chain::Filter {
1189 let lock = self.inner.lock().unwrap();
1190 filter.register_tx(&lock.get_funding_txo().0.txid, &lock.get_funding_txo().1);
1191 for (txid, outputs) in lock.get_outputs_to_watch().iter() {
1192 for (index, script_pubkey) in outputs.iter() {
1193 assert!(*index <= u16::max_value() as u32);
1194 filter.register_output(WatchedOutput {
1196 outpoint: OutPoint { txid: *txid, index: *index as u16 },
1197 script_pubkey: script_pubkey.clone(),
1203 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1204 /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
1205 pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
1206 self.inner.lock().unwrap().get_and_clear_pending_monitor_events()
1209 /// Gets the list of pending events which were generated by previous actions, clearing the list
1212 /// This is called by ChainMonitor::get_and_clear_pending_events() and is equivalent to
1213 /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
1214 /// no internal locking in ChannelMonitors.
1215 pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
1216 self.inner.lock().unwrap().get_and_clear_pending_events()
1219 pub(crate) fn get_min_seen_secret(&self) -> u64 {
1220 self.inner.lock().unwrap().get_min_seen_secret()
1223 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1224 self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
1227 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1228 self.inner.lock().unwrap().get_cur_holder_commitment_number()
1231 /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
1232 /// the Channel was out-of-date. You may use it to get a broadcastable holder toxic tx in case of
1233 /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our counterparty side knows
1234 /// a higher revocation secret than the holder commitment number we are aware of. Broadcasting these
1235 /// transactions are UNSAFE, as they allow counterparty side to punish you. Nevertheless you may want to
1236 /// broadcast them if counterparty don't close channel with his higher commitment transaction after a
1237 /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
1238 /// out-of-band the other node operator to coordinate with him if option is available to you.
1239 /// In any-case, choice is up to the user.
1240 pub fn get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1241 where L::Target: Logger {
1242 self.inner.lock().unwrap().get_latest_holder_commitment_txn(logger)
1245 /// Unsafe test-only version of get_latest_holder_commitment_txn used by our test framework
1246 /// to bypass HolderCommitmentTransaction state update lockdown after signature and generate
1247 /// revoked commitment transaction.
1248 #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
1249 pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1250 where L::Target: Logger {
1251 self.inner.lock().unwrap().unsafe_get_latest_holder_commitment_txn(logger)
1254 /// Processes transactions in a newly connected block, which may result in any of the following:
1255 /// - update the monitor's state against resolved HTLCs
1256 /// - punish the counterparty in the case of seeing a revoked commitment transaction
1257 /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
1258 /// - detect settled outputs for later spending
1259 /// - schedule and bump any in-flight claims
1261 /// Returns any new outputs to watch from `txdata`; after called, these are also included in
1262 /// [`get_outputs_to_watch`].
1264 /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
1265 pub fn block_connected<B: Deref, F: Deref, L: Deref>(
1267 header: &BlockHeader,
1268 txdata: &TransactionData,
1273 ) -> Vec<(Txid, Vec<(u32, TxOut)>)>
1275 B::Target: BroadcasterInterface,
1276 F::Target: FeeEstimator,
1279 self.inner.lock().unwrap().block_connected(
1280 header, txdata, height, broadcaster, fee_estimator, logger)
1283 /// Determines if the disconnected block contained any transactions of interest and updates
1285 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(
1287 header: &BlockHeader,
1293 B::Target: BroadcasterInterface,
1294 F::Target: FeeEstimator,
1297 self.inner.lock().unwrap().block_disconnected(
1298 header, height, broadcaster, fee_estimator, logger)
1302 impl<Signer: Sign> ChannelMonitorImpl<Signer> {
1303 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1304 /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
1305 /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
1306 fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
1307 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1308 return Err(MonitorUpdateError("Previous secret did not match new one"));
1311 // Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
1312 // events for now-revoked/fulfilled HTLCs.
1313 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
1314 for &mut (_, ref mut source) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
1319 if !self.payment_preimages.is_empty() {
1320 let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
1321 let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
1322 let min_idx = self.get_min_seen_secret();
1323 let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
1325 self.payment_preimages.retain(|&k, _| {
1326 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
1327 if k == htlc.payment_hash {
1331 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
1332 for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
1333 if k == htlc.payment_hash {
1338 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
1345 counterparty_hash_commitment_number.remove(&k);
1354 pub(crate) fn provide_latest_counterparty_commitment_tx<L: Deref>(&mut self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>, commitment_number: u64, their_revocation_point: PublicKey, logger: &L) where L::Target: Logger {
1355 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
1356 // so that a remote monitor doesn't learn anything unless there is a malicious close.
1357 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
1359 for &(ref htlc, _) in &htlc_outputs {
1360 self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
1363 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", txid, commitment_number, htlc_outputs.len());
1364 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
1365 self.current_counterparty_commitment_txid = Some(txid);
1366 self.counterparty_claimable_outpoints.insert(txid, htlc_outputs.clone());
1367 self.current_counterparty_commitment_number = commitment_number;
1368 //TODO: Merge this into the other per-counterparty-transaction output storage stuff
1369 match self.their_cur_revocation_points {
1370 Some(old_points) => {
1371 if old_points.0 == commitment_number + 1 {
1372 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
1373 } else if old_points.0 == commitment_number + 2 {
1374 if let Some(old_second_point) = old_points.2 {
1375 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
1377 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1380 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1384 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1387 let mut htlcs = Vec::with_capacity(htlc_outputs.len());
1388 for htlc in htlc_outputs {
1389 if htlc.0.transaction_output_index.is_some() {
1393 self.counterparty_tx_cache.per_htlc.insert(txid, htlcs);
1396 /// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
1397 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
1398 /// is important that any clones of this channel monitor (including remote clones) by kept
1399 /// up-to-date as our holder commitment transaction is updated.
1400 /// Panics if set_on_holder_tx_csv has never been called.
1401 fn provide_latest_holder_commitment_tx(&mut self, holder_commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), MonitorUpdateError> {
1402 // block for Rust 1.34 compat
1403 let mut new_holder_commitment_tx = {
1404 let trusted_tx = holder_commitment_tx.trust();
1405 let txid = trusted_tx.txid();
1406 let tx_keys = trusted_tx.keys();
1407 self.current_holder_commitment_number = trusted_tx.commitment_number();
1410 revocation_key: tx_keys.revocation_key,
1411 a_htlc_key: tx_keys.broadcaster_htlc_key,
1412 b_htlc_key: tx_keys.countersignatory_htlc_key,
1413 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
1414 per_commitment_point: tx_keys.per_commitment_point,
1415 feerate_per_kw: trusted_tx.feerate_per_kw(),
1419 self.onchain_tx_handler.provide_latest_holder_tx(holder_commitment_tx);
1420 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
1421 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
1422 if self.holder_tx_signed {
1423 return Err(MonitorUpdateError("Latest holder commitment signed has already been signed, update is rejected"));
1428 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
1429 /// commitment_tx_infos which contain the payment hash have been revoked.
1430 fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, broadcaster: &B, fee_estimator: &F, logger: &L)
1431 where B::Target: BroadcasterInterface,
1432 F::Target: FeeEstimator,
1435 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
1437 // If the channel is force closed, try to claim the output from this preimage.
1438 // First check if a counterparty commitment transaction has been broadcasted:
1439 macro_rules! claim_htlcs {
1440 ($commitment_number: expr, $txid: expr) => {
1441 let htlc_claim_reqs = self.get_counterparty_htlc_output_claim_reqs($commitment_number, $txid, None);
1442 self.onchain_tx_handler.update_claims_view(&Vec::new(), htlc_claim_reqs, None, broadcaster, fee_estimator, logger);
1445 if let Some(txid) = self.current_counterparty_commitment_txid {
1446 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
1447 claim_htlcs!(*commitment_number, txid);
1451 if let Some(txid) = self.prev_counterparty_commitment_txid {
1452 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
1453 claim_htlcs!(*commitment_number, txid);
1458 // Then if a holder commitment transaction has been seen on-chain, broadcast transactions
1459 // claiming the HTLC output from each of the holder commitment transactions.
1460 // Note that we can't just use `self.holder_tx_signed`, because that only covers the case where
1461 // *we* sign a holder commitment transaction, not when e.g. a watchtower broadcasts one of our
1462 // holder commitment transactions.
1463 if self.broadcasted_holder_revokable_script.is_some() {
1464 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx);
1465 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, None, broadcaster, fee_estimator, logger);
1466 if let Some(ref tx) = self.prev_holder_signed_commitment_tx {
1467 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&tx);
1468 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, None, broadcaster, fee_estimator, logger);
1473 pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(&mut self, broadcaster: &B, logger: &L)
1474 where B::Target: BroadcasterInterface,
1477 for tx in self.get_latest_holder_commitment_txn(logger).iter() {
1478 broadcaster.broadcast_transaction(tx);
1480 self.pending_monitor_events.push(MonitorEvent::CommitmentTxBroadcasted(self.funding_info.0));
1483 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &L) -> Result<(), MonitorUpdateError>
1484 where B::Target: BroadcasterInterface,
1485 F::Target: FeeEstimator,
1488 // ChannelMonitor updates may be applied after force close if we receive a
1489 // preimage for a broadcasted commitment transaction HTLC output that we'd
1490 // like to claim on-chain. If this is the case, we no longer have guaranteed
1491 // access to the monitor's update ID, so we use a sentinel value instead.
1492 if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
1493 match updates.updates[0] {
1494 ChannelMonitorUpdateStep::PaymentPreimage { .. } => {},
1495 _ => panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage"),
1497 assert_eq!(updates.updates.len(), 1);
1498 } else if self.latest_update_id + 1 != updates.update_id {
1499 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
1501 for update in updates.updates.iter() {
1503 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs } => {
1504 log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
1505 if self.lockdown_from_offchain { panic!(); }
1506 self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone())?
1508 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_revocation_point } => {
1509 log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
1510 self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_revocation_point, logger)
1512 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } => {
1513 log_trace!(logger, "Updating ChannelMonitor with payment preimage");
1514 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage, broadcaster, fee_estimator, logger)
1516 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
1517 log_trace!(logger, "Updating ChannelMonitor with commitment secret");
1518 self.provide_secret(*idx, *secret)?
1520 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
1521 log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
1522 self.lockdown_from_offchain = true;
1523 if *should_broadcast {
1524 self.broadcast_latest_holder_commitment_txn(broadcaster, logger);
1525 } else if !self.holder_tx_signed {
1526 log_error!(logger, "You have a toxic holder commitment transaction avaible in channel monitor, read comment in ChannelMonitor::get_latest_holder_commitment_txn to be informed of manual action to take");
1528 // If we generated a MonitorEvent::CommitmentTxBroadcasted, the ChannelManager
1529 // will still give us a ChannelForceClosed event with !should_broadcast, but we
1530 // shouldn't print the scary warning above.
1531 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
1536 self.latest_update_id = updates.update_id;
1540 pub fn get_latest_update_id(&self) -> u64 {
1541 self.latest_update_id
1544 pub fn get_funding_txo(&self) -> &(OutPoint, Script) {
1548 pub fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, Script)>> {
1549 // If we've detected a counterparty commitment tx on chain, we must include it in the set
1550 // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
1551 // its trivial to do, double-check that here.
1552 for (txid, _) in self.counterparty_commitment_txn_on_chain.iter() {
1553 self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
1555 &self.outputs_to_watch
1558 pub fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
1559 let mut ret = Vec::new();
1560 mem::swap(&mut ret, &mut self.pending_monitor_events);
1564 pub fn get_and_clear_pending_events(&mut self) -> Vec<Event> {
1565 let mut ret = Vec::new();
1566 mem::swap(&mut ret, &mut self.pending_events);
1570 /// Can only fail if idx is < get_min_seen_secret
1571 fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
1572 self.commitment_secrets.get_secret(idx)
1575 pub(crate) fn get_min_seen_secret(&self) -> u64 {
1576 self.commitment_secrets.get_min_seen_secret()
1579 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1580 self.current_counterparty_commitment_number
1583 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1584 self.current_holder_commitment_number
1587 /// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
1588 /// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1589 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1590 /// HTLC-Success/HTLC-Timeout transactions.
1591 /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1592 /// revoked counterparty commitment tx
1593 fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> (Vec<ClaimRequest>, (Txid, Vec<(u32, TxOut)>)) where L::Target: Logger {
1594 // Most secp and related errors trying to create keys means we have no hope of constructing
1595 // a spend transaction...so we return no transactions to broadcast
1596 let mut claimable_outpoints = Vec::new();
1597 let mut watch_outputs = Vec::new();
1599 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1600 let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
1602 macro_rules! ignore_error {
1603 ( $thing : expr ) => {
1606 Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs))
1611 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);
1612 if commitment_number >= self.get_min_seen_secret() {
1613 let secret = self.get_secret(commitment_number).unwrap();
1614 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1615 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1616 let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint));
1617 let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.counterparty_tx_cache.counterparty_delayed_payment_base_key));
1619 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_tx_cache.on_counterparty_tx_csv, &delayed_key);
1620 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1622 // First, process non-htlc outputs (to_holder & to_counterparty)
1623 for (idx, outp) in tx.output.iter().enumerate() {
1624 if outp.script_pubkey == revokeable_p2wsh {
1625 let witness_data = InputMaterial::Revoked { per_commitment_point, counterparty_delayed_payment_base_key: self.counterparty_tx_cache.counterparty_delayed_payment_base_key, counterparty_htlc_base_key: self.counterparty_tx_cache.counterparty_htlc_base_key, per_commitment_key, input_descriptor: InputDescriptors::RevokedOutput, amount: outp.value, htlc: None, on_counterparty_tx_csv: self.counterparty_tx_cache.on_counterparty_tx_csv};
1626 claimable_outpoints.push(ClaimRequest { absolute_timelock: height + self.counterparty_tx_cache.on_counterparty_tx_csv as u32, aggregable: true, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 }, witness_data});
1630 // Then, try to find revoked htlc outputs
1631 if let Some(ref per_commitment_data) = per_commitment_option {
1632 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1633 if let Some(transaction_output_index) = htlc.transaction_output_index {
1634 if transaction_output_index as usize >= tx.output.len() ||
1635 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
1636 return (claimable_outpoints, (commitment_txid, watch_outputs)); // Corrupted per_commitment_data, fuck this user
1638 let witness_data = InputMaterial::Revoked { per_commitment_point, counterparty_delayed_payment_base_key: self.counterparty_tx_cache.counterparty_delayed_payment_base_key, counterparty_htlc_base_key: self.counterparty_tx_cache.counterparty_htlc_base_key, per_commitment_key, input_descriptor: if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC }, amount: tx.output[transaction_output_index as usize].value, htlc: Some(htlc.clone()), on_counterparty_tx_csv: self.counterparty_tx_cache.on_counterparty_tx_csv};
1639 claimable_outpoints.push(ClaimRequest { absolute_timelock: htlc.cltv_expiry, aggregable: true, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, witness_data });
1644 // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
1645 if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
1646 // We're definitely a counterparty commitment transaction!
1647 log_trace!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
1648 for (idx, outp) in tx.output.iter().enumerate() {
1649 watch_outputs.push((idx as u32, outp.clone()));
1651 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
1653 macro_rules! check_htlc_fails {
1654 ($txid: expr, $commitment_tx: expr) => {
1655 if let Some(ref outpoints) = self.counterparty_claimable_outpoints.get($txid) {
1656 for &(ref htlc, ref source_option) in outpoints.iter() {
1657 if let &Some(ref source) = source_option {
1658 self.onchain_events_waiting_threshold_conf.retain(|ref entry| {
1659 if entry.height != height { return true; }
1661 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1662 htlc_update.0 != **source
1667 let entry = OnchainEventEntry {
1669 event: OnchainEvent::HTLCUpdate {
1670 htlc_update: ((**source).clone(), htlc.payment_hash.clone())
1673 log_info!(logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of revoked counterparty commitment transaction, waiting for confirmation (at height {})", log_bytes!(htlc.payment_hash.0), $commitment_tx, entry.confirmation_threshold());
1674 self.onchain_events_waiting_threshold_conf.push(entry);
1680 if let Some(ref txid) = self.current_counterparty_commitment_txid {
1681 check_htlc_fails!(txid, "current");
1683 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
1684 check_htlc_fails!(txid, "counterparty");
1686 // No need to check holder commitment txn, symmetric HTLCSource must be present as per-htlc data on counterparty commitment tx
1688 } else if let Some(per_commitment_data) = per_commitment_option {
1689 // While this isn't useful yet, there is a potential race where if a counterparty
1690 // revokes a state at the same time as the commitment transaction for that state is
1691 // confirmed, and the watchtower receives the block before the user, the user could
1692 // upload a new ChannelMonitor with the revocation secret but the watchtower has
1693 // already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
1694 // not being generated by the above conditional. Thus, to be safe, we go ahead and
1696 for (idx, outp) in tx.output.iter().enumerate() {
1697 watch_outputs.push((idx as u32, outp.clone()));
1699 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
1701 log_trace!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
1703 macro_rules! check_htlc_fails {
1704 ($txid: expr, $commitment_tx: expr, $id: tt) => {
1705 if let Some(ref latest_outpoints) = self.counterparty_claimable_outpoints.get($txid) {
1706 $id: for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1707 if let &Some(ref source) = source_option {
1708 // Check if the HTLC is present in the commitment transaction that was
1709 // broadcast, but not if it was below the dust limit, which we should
1710 // fail backwards immediately as there is no way for us to learn the
1711 // payment_preimage.
1712 // Note that if the dust limit were allowed to change between
1713 // commitment transactions we'd want to be check whether *any*
1714 // broadcastable commitment transaction has the HTLC in it, but it
1715 // cannot currently change after channel initialization, so we don't
1717 for &(ref broadcast_htlc, ref broadcast_source) in per_commitment_data.iter() {
1718 if broadcast_htlc.transaction_output_index.is_some() && Some(source) == broadcast_source.as_ref() {
1722 log_trace!(logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of counterparty commitment transaction", log_bytes!(htlc.payment_hash.0), $commitment_tx);
1723 self.onchain_events_waiting_threshold_conf.retain(|ref entry| {
1724 if entry.height != height { return true; }
1726 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1727 htlc_update.0 != **source
1732 self.onchain_events_waiting_threshold_conf.push(OnchainEventEntry {
1734 event: OnchainEvent::HTLCUpdate {
1735 htlc_update: ((**source).clone(), htlc.payment_hash.clone())
1743 if let Some(ref txid) = self.current_counterparty_commitment_txid {
1744 check_htlc_fails!(txid, "current", 'current_loop);
1746 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
1747 check_htlc_fails!(txid, "previous", 'prev_loop);
1750 let htlc_claim_reqs = self.get_counterparty_htlc_output_claim_reqs(commitment_number, commitment_txid, Some(tx));
1751 for req in htlc_claim_reqs {
1752 claimable_outpoints.push(req);
1756 (claimable_outpoints, (commitment_txid, watch_outputs))
1759 fn get_counterparty_htlc_output_claim_reqs(&self, commitment_number: u64, commitment_txid: Txid, tx: Option<&Transaction>) -> Vec<ClaimRequest> {
1760 let mut claims = Vec::new();
1761 if let Some(htlc_outputs) = self.counterparty_claimable_outpoints.get(&commitment_txid) {
1762 if let Some(revocation_points) = self.their_cur_revocation_points {
1763 let revocation_point_option =
1764 // If the counterparty commitment tx is the latest valid state, use their latest
1765 // per-commitment point
1766 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1767 else if let Some(point) = revocation_points.2.as_ref() {
1768 // If counterparty commitment tx is the state previous to the latest valid state, use
1769 // their previous per-commitment point (non-atomicity of revocation means it's valid for
1770 // them to temporarily have two valid commitment txns from our viewpoint)
1771 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1773 if let Some(revocation_point) = revocation_point_option {
1774 for (_, &(ref htlc, _)) in htlc_outputs.iter().enumerate() {
1775 if let Some(transaction_output_index) = htlc.transaction_output_index {
1776 if let Some(transaction) = tx {
1777 if transaction_output_index as usize >= transaction.output.len() ||
1778 transaction.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
1779 return claims; // Corrupted per_commitment_data, fuck this user
1784 if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) {
1788 let aggregable = if !htlc.offered { false } else { true };
1789 if preimage.is_some() || !htlc.offered {
1790 let witness_data = InputMaterial::CounterpartyHTLC { per_commitment_point: *revocation_point, counterparty_delayed_payment_base_key: self.counterparty_tx_cache.counterparty_delayed_payment_base_key, counterparty_htlc_base_key: self.counterparty_tx_cache.counterparty_htlc_base_key, preimage, htlc: htlc.clone() };
1791 claims.push(ClaimRequest { absolute_timelock: htlc.cltv_expiry, aggregable, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, witness_data });
1801 /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
1802 fn check_spend_counterparty_htlc<L: Deref>(&mut self, tx: &Transaction, commitment_number: u64, height: u32, logger: &L) -> (Vec<ClaimRequest>, Option<(Txid, Vec<(u32, TxOut)>)>) where L::Target: Logger {
1803 let htlc_txid = tx.txid();
1804 if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
1805 return (Vec::new(), None)
1808 macro_rules! ignore_error {
1809 ( $thing : expr ) => {
1812 Err(_) => return (Vec::new(), None)
1817 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
1818 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1819 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1821 log_trace!(logger, "Counterparty HTLC broadcast {}:{}", htlc_txid, 0);
1822 let witness_data = InputMaterial::Revoked { per_commitment_point, counterparty_delayed_payment_base_key: self.counterparty_tx_cache.counterparty_delayed_payment_base_key, counterparty_htlc_base_key: self.counterparty_tx_cache.counterparty_htlc_base_key, per_commitment_key, input_descriptor: InputDescriptors::RevokedOutput, amount: tx.output[0].value, htlc: None, on_counterparty_tx_csv: self.counterparty_tx_cache.on_counterparty_tx_csv };
1823 let claimable_outpoints = vec!(ClaimRequest { absolute_timelock: height + self.counterparty_tx_cache.on_counterparty_tx_csv as u32, aggregable: true, outpoint: BitcoinOutPoint { txid: htlc_txid, vout: 0}, witness_data });
1824 let outputs = vec![(0, tx.output[0].clone())];
1825 (claimable_outpoints, Some((htlc_txid, outputs)))
1828 // Returns (1) `ClaimRequest`s that can be given to the OnChainTxHandler, so that the handler can
1829 // broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable
1830 // script so we can detect whether a holder transaction has been seen on-chain.
1831 fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx) -> (Vec<ClaimRequest>, Option<(Script, PublicKey, PublicKey)>) {
1832 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
1834 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
1835 let broadcasted_holder_revokable_script = Some((redeemscript.to_v0_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
1837 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
1838 if let Some(transaction_output_index) = htlc.transaction_output_index {
1839 claim_requests.push(ClaimRequest { absolute_timelock: ::std::u32::MAX, aggregable: false, outpoint: BitcoinOutPoint { txid: holder_tx.txid, vout: transaction_output_index as u32 },
1840 witness_data: InputMaterial::HolderHTLC {
1841 preimage: if !htlc.offered {
1842 if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1843 Some(preimage.clone())
1845 // We can't build an HTLC-Success transaction without the preimage
1849 amount: htlc.amount_msat,
1854 (claim_requests, broadcasted_holder_revokable_script)
1857 // Returns holder HTLC outputs to watch and react to in case of spending.
1858 fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
1859 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
1860 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
1861 if let Some(transaction_output_index) = htlc.transaction_output_index {
1862 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
1868 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
1869 /// revoked using data in holder_claimable_outpoints.
1870 /// Should not be used if check_spend_revoked_transaction succeeds.
1871 fn check_spend_holder_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> (Vec<ClaimRequest>, (Txid, Vec<(u32, TxOut)>)) where L::Target: Logger {
1872 let commitment_txid = tx.txid();
1873 let mut claim_requests = Vec::new();
1874 let mut watch_outputs = Vec::new();
1876 macro_rules! wait_threshold_conf {
1877 ($source: expr, $commitment_tx: expr, $payment_hash: expr) => {
1878 self.onchain_events_waiting_threshold_conf.retain(|ref entry| {
1879 if entry.height != height { return true; }
1881 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1882 htlc_update.0 != $source
1887 let entry = OnchainEventEntry {
1889 event: OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash) },
1891 log_trace!(logger, "Failing HTLC with payment_hash {} from {} holder commitment tx due to broadcast of transaction, waiting confirmation (at height{})", log_bytes!($payment_hash.0), $commitment_tx, entry.confirmation_threshold());
1892 self.onchain_events_waiting_threshold_conf.push(entry);
1896 macro_rules! append_onchain_update {
1897 ($updates: expr, $to_watch: expr) => {
1898 claim_requests = $updates.0;
1899 self.broadcasted_holder_revokable_script = $updates.1;
1900 watch_outputs.append(&mut $to_watch);
1904 // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
1905 let mut is_holder_tx = false;
1907 if self.current_holder_commitment_tx.txid == commitment_txid {
1908 is_holder_tx = true;
1909 log_trace!(logger, "Got latest holder commitment tx broadcast, searching for available HTLCs to claim");
1910 let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx);
1911 let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
1912 append_onchain_update!(res, to_watch);
1913 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
1914 if holder_tx.txid == commitment_txid {
1915 is_holder_tx = true;
1916 log_trace!(logger, "Got previous holder commitment tx broadcast, searching for available HTLCs to claim");
1917 let res = self.get_broadcasted_holder_claims(holder_tx);
1918 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
1919 append_onchain_update!(res, to_watch);
1923 macro_rules! fail_dust_htlcs_after_threshold_conf {
1924 ($holder_tx: expr) => {
1925 for &(ref htlc, _, ref source) in &$holder_tx.htlc_outputs {
1926 if htlc.transaction_output_index.is_none() {
1927 if let &Some(ref source) = source {
1928 wait_threshold_conf!(source.clone(), "lastest", htlc.payment_hash.clone());
1936 fail_dust_htlcs_after_threshold_conf!(self.current_holder_commitment_tx);
1937 if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
1938 fail_dust_htlcs_after_threshold_conf!(holder_tx);
1942 (claim_requests, (commitment_txid, watch_outputs))
1945 pub fn get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
1946 log_trace!(logger, "Getting signed latest holder commitment transaction!");
1947 self.holder_tx_signed = true;
1948 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
1949 let txid = commitment_tx.txid();
1950 let mut res = vec![commitment_tx];
1951 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
1952 if let Some(vout) = htlc.0.transaction_output_index {
1953 let preimage = if !htlc.0.offered {
1954 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
1955 // We can't build an HTLC-Success transaction without the preimage
1959 if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
1960 &::bitcoin::OutPoint { txid, vout }, &preimage) {
1965 // 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.
1966 // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
1970 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
1971 fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
1972 log_trace!(logger, "Getting signed copy of latest holder commitment transaction!");
1973 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
1974 let txid = commitment_tx.txid();
1975 let mut res = vec![commitment_tx];
1976 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
1977 if let Some(vout) = htlc.0.transaction_output_index {
1978 let preimage = if !htlc.0.offered {
1979 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
1980 // We can't build an HTLC-Success transaction without the preimage
1984 if let Some(htlc_tx) = self.onchain_tx_handler.unsafe_get_fully_signed_htlc_tx(
1985 &::bitcoin::OutPoint { txid, vout }, &preimage) {
1993 pub fn block_connected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, txdata: &TransactionData, height: u32, broadcaster: B, fee_estimator: F, logger: L)-> Vec<(Txid, Vec<(u32, TxOut)>)>
1994 where B::Target: BroadcasterInterface,
1995 F::Target: FeeEstimator,
1998 let txn_matched = self.filter_block(txdata);
1999 for tx in &txn_matched {
2000 let mut output_val = 0;
2001 for out in tx.output.iter() {
2002 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2003 output_val += out.value;
2004 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2008 let block_hash = header.block_hash();
2009 log_trace!(logger, "Block {} at height {} connected with {} txn matched", block_hash, height, txn_matched.len());
2011 let mut watch_outputs = Vec::new();
2012 let mut claimable_outpoints = Vec::new();
2013 for tx in &txn_matched {
2014 if tx.input.len() == 1 {
2015 // Assuming our keys were not leaked (in which case we're screwed no matter what),
2016 // commitment transactions and HTLC transactions will all only ever have one input,
2017 // which is an easy way to filter out any potential non-matching txn for lazy
2019 let prevout = &tx.input[0].previous_output;
2020 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
2021 if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
2022 let (mut new_outpoints, new_outputs) = self.check_spend_counterparty_transaction(&tx, height, &logger);
2023 if !new_outputs.1.is_empty() {
2024 watch_outputs.push(new_outputs);
2026 if new_outpoints.is_empty() {
2027 let (mut new_outpoints, new_outputs) = self.check_spend_holder_transaction(&tx, height, &logger);
2028 if !new_outputs.1.is_empty() {
2029 watch_outputs.push(new_outputs);
2031 claimable_outpoints.append(&mut new_outpoints);
2033 claimable_outpoints.append(&mut new_outpoints);
2036 if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&prevout.txid) {
2037 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(&tx, commitment_number, height, &logger);
2038 claimable_outpoints.append(&mut new_outpoints);
2039 if let Some(new_outputs) = new_outputs_option {
2040 watch_outputs.push(new_outputs);
2045 // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2046 // can also be resolved in a few other ways which can have more than one output. Thus,
2047 // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2048 self.is_resolving_htlc_output(&tx, height, &logger);
2050 self.is_paying_spendable_output(&tx, height, &logger);
2052 let should_broadcast = self.would_broadcast_at_height(height, &logger);
2053 if should_broadcast {
2054 claimable_outpoints.push(ClaimRequest { absolute_timelock: height, aggregable: false, outpoint: BitcoinOutPoint { txid: self.funding_info.0.txid.clone(), vout: self.funding_info.0.index as u32 }, witness_data: InputMaterial::Funding { funding_redeemscript: self.funding_redeemscript.clone() }});
2056 if should_broadcast {
2057 self.pending_monitor_events.push(MonitorEvent::CommitmentTxBroadcasted(self.funding_info.0));
2058 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2059 self.holder_tx_signed = true;
2060 let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx);
2061 let new_outputs = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, &commitment_tx);
2062 if !new_outputs.is_empty() {
2063 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
2065 claimable_outpoints.append(&mut new_outpoints);
2068 // Find which on-chain events have reached their confirmation threshold.
2069 let onchain_events_waiting_threshold_conf =
2070 self.onchain_events_waiting_threshold_conf.drain(..).collect::<Vec<_>>();
2071 let mut onchain_events_reaching_threshold_conf = Vec::new();
2072 for entry in onchain_events_waiting_threshold_conf {
2073 if entry.has_reached_confirmation_threshold(height) {
2074 onchain_events_reaching_threshold_conf.push(entry);
2076 self.onchain_events_waiting_threshold_conf.push(entry);
2080 // Used to check for duplicate HTLC resolutions.
2081 #[cfg(debug_assertions)]
2082 let unmatured_htlcs: Vec<_> = self.onchain_events_waiting_threshold_conf
2084 .filter_map(|entry| match &entry.event {
2085 OnchainEvent::HTLCUpdate { htlc_update } => Some(htlc_update.0.clone()),
2086 OnchainEvent::MaturingOutput { .. } => None,
2089 #[cfg(debug_assertions)]
2090 let mut matured_htlcs = Vec::new();
2092 // Produce actionable events from on-chain events having reached their threshold.
2093 for entry in onchain_events_reaching_threshold_conf.drain(..) {
2095 OnchainEvent::HTLCUpdate { htlc_update } => {
2096 // Check for duplicate HTLC resolutions.
2097 #[cfg(debug_assertions)]
2100 unmatured_htlcs.iter().find(|&htlc| htlc == &htlc_update.0).is_none(),
2101 "An unmature HTLC transaction conflicts with a maturing one; failed to \
2102 call block_disconnected for a block containing the conflicting \
2105 matured_htlcs.iter().find(|&htlc| htlc == &htlc_update.0).is_none(),
2106 "A matured HTLC transaction conflicts with a maturing one; failed to \
2107 call block_disconnected for a block containing the conflicting \
2109 matured_htlcs.push(htlc_update.0.clone());
2112 log_trace!(logger, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!((htlc_update.1).0));
2113 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2114 payment_hash: htlc_update.1,
2115 payment_preimage: None,
2116 source: htlc_update.0,
2119 OnchainEvent::MaturingOutput { descriptor } => {
2120 log_trace!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
2121 self.pending_events.push(Event::SpendableOutputs {
2122 outputs: vec![descriptor]
2128 self.onchain_tx_handler.update_claims_view(&txn_matched, claimable_outpoints, Some(height), &&*broadcaster, &&*fee_estimator, &&*logger);
2129 self.last_block_hash = block_hash;
2131 // Determine new outputs to watch by comparing against previously known outputs to watch,
2132 // updating the latter in the process.
2133 watch_outputs.retain(|&(ref txid, ref txouts)| {
2134 let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
2135 self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
2139 // If we see a transaction for which we registered outputs previously,
2140 // make sure the registered scriptpubkey at the expected index match
2141 // the actual transaction output one. We failed this case before #653.
2142 for tx in &txn_matched {
2143 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.txid()) {
2144 for idx_and_script in outputs.iter() {
2145 assert!((idx_and_script.0 as usize) < tx.output.len());
2146 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
2154 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, height: u32, broadcaster: B, fee_estimator: F, logger: L)
2155 where B::Target: BroadcasterInterface,
2156 F::Target: FeeEstimator,
2159 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
2162 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2163 //- maturing spendable output has transaction paying us has been disconnected
2164 self.onchain_events_waiting_threshold_conf.retain(|ref entry| entry.height != height);
2166 self.onchain_tx_handler.block_disconnected(height, broadcaster, fee_estimator, logger);
2168 self.last_block_hash = header.prev_blockhash;
2171 /// Filters a block's `txdata` for transactions spending watched outputs or for any child
2172 /// transactions thereof.
2173 fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
2174 let mut matched_txn = HashSet::new();
2175 txdata.iter().filter(|&&(_, tx)| {
2176 let mut matches = self.spends_watched_output(tx);
2177 for input in tx.input.iter() {
2178 if matches { break; }
2179 if matched_txn.contains(&input.previous_output.txid) {
2184 matched_txn.insert(tx.txid());
2187 }).map(|(_, tx)| *tx).collect()
2190 /// Checks if a given transaction spends any watched outputs.
2191 fn spends_watched_output(&self, tx: &Transaction) -> bool {
2192 for input in tx.input.iter() {
2193 if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
2194 for (idx, _script_pubkey) in outputs.iter() {
2195 if *idx == input.previous_output.vout {
2198 // If the expected script is a known type, check that the witness
2199 // appears to be spending the correct type (ie that the match would
2200 // actually succeed in BIP 158/159-style filters).
2201 if _script_pubkey.is_v0_p2wsh() {
2202 assert_eq!(&bitcoin::Address::p2wsh(&Script::from(input.witness.last().unwrap().clone()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
2203 } else if _script_pubkey.is_v0_p2wpkh() {
2204 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap(), bitcoin::Network::Bitcoin).unwrap().script_pubkey(), _script_pubkey);
2205 } else { panic!(); }
2216 fn would_broadcast_at_height<L: Deref>(&self, height: u32, logger: &L) -> bool where L::Target: Logger {
2217 // We need to consider all HTLCs which are:
2218 // * in any unrevoked counterparty commitment transaction, as they could broadcast said
2219 // transactions and we'd end up in a race, or
2220 // * are in our latest holder commitment transaction, as this is the thing we will
2221 // broadcast if we go on-chain.
2222 // Note that we consider HTLCs which were below dust threshold here - while they don't
2223 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2224 // to the source, and if we don't fail the channel we will have to ensure that the next
2225 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2226 // easier to just fail the channel as this case should be rare enough anyway.
2227 macro_rules! scan_commitment {
2228 ($htlcs: expr, $holder_tx: expr) => {
2229 for ref htlc in $htlcs {
2230 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2231 // chain with enough room to claim the HTLC without our counterparty being able to
2232 // time out the HTLC first.
2233 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2234 // concern is being able to claim the corresponding inbound HTLC (on another
2235 // channel) before it expires. In fact, we don't even really care if our
2236 // counterparty here claims such an outbound HTLC after it expired as long as we
2237 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2238 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2239 // we give ourselves a few blocks of headroom after expiration before going
2240 // on-chain for an expired HTLC.
2241 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2242 // from us until we've reached the point where we go on-chain with the
2243 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2244 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2245 // aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2246 // inbound_cltv == height + CLTV_CLAIM_BUFFER
2247 // outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2248 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2249 // CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2250 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2251 // The final, above, condition is checked for statically in channelmanager
2252 // with CHECK_CLTV_EXPIRY_SANITY_2.
2253 let htlc_outbound = $holder_tx == htlc.offered;
2254 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2255 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2256 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2263 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2265 if let Some(ref txid) = self.current_counterparty_commitment_txid {
2266 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2267 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2270 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
2271 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
2272 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2279 /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
2280 /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2281 fn is_resolving_htlc_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2282 'outer_loop: for input in &tx.input {
2283 let mut payment_data = None;
2284 let revocation_sig_claim = (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && input.witness[1].len() == 33)
2285 || (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && input.witness[1].len() == 33);
2286 let accepted_preimage_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::AcceptedHTLC);
2287 let offered_preimage_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC);
2289 macro_rules! log_claim {
2290 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
2291 // We found the output in question, but aren't failing it backwards
2292 // as we have no corresponding source and no valid counterparty commitment txid
2293 // to try a weak source binding with same-hash, same-value still-valid offered HTLC.
2294 // This implies either it is an inbound HTLC or an outbound HTLC on a revoked transaction.
2295 let outbound_htlc = $holder_tx == $htlc.offered;
2296 if ($holder_tx && revocation_sig_claim) ||
2297 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2298 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2299 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2300 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2301 if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2303 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2304 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2305 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2306 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2311 macro_rules! check_htlc_valid_counterparty {
2312 ($counterparty_txid: expr, $htlc_output: expr) => {
2313 if let Some(txid) = $counterparty_txid {
2314 for &(ref pending_htlc, ref pending_source) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
2315 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2316 if let &Some(ref source) = pending_source {
2317 log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
2318 payment_data = Some(((**source).clone(), $htlc_output.payment_hash));
2327 macro_rules! scan_commitment {
2328 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
2329 for (ref htlc_output, source_option) in $htlcs {
2330 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2331 if let Some(ref source) = source_option {
2332 log_claim!($tx_info, $holder_tx, htlc_output, true);
2333 // We have a resolution of an HTLC either from one of our latest
2334 // holder commitment transactions or an unrevoked counterparty commitment
2335 // transaction. This implies we either learned a preimage, the HTLC
2336 // has timed out, or we screwed up. In any case, we should now
2337 // resolve the source HTLC with the original sender.
2338 payment_data = Some(((*source).clone(), htlc_output.payment_hash));
2339 } else if !$holder_tx {
2340 check_htlc_valid_counterparty!(self.current_counterparty_commitment_txid, htlc_output);
2341 if payment_data.is_none() {
2342 check_htlc_valid_counterparty!(self.prev_counterparty_commitment_txid, htlc_output);
2345 if payment_data.is_none() {
2346 log_claim!($tx_info, $holder_tx, htlc_output, false);
2347 continue 'outer_loop;
2354 if input.previous_output.txid == self.current_holder_commitment_tx.txid {
2355 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2356 "our latest holder commitment tx", true);
2358 if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
2359 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
2360 scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2361 "our previous holder commitment tx", true);
2364 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
2365 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
2366 "counterparty commitment tx", false);
2369 // Check that scan_commitment, above, decided there is some source worth relaying an
2370 // HTLC resolution backwards to and figure out whether we learned a preimage from it.
2371 if let Some((source, payment_hash)) = payment_data {
2372 let mut payment_preimage = PaymentPreimage([0; 32]);
2373 if accepted_preimage_claim {
2374 if !self.pending_monitor_events.iter().any(
2375 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
2376 payment_preimage.0.copy_from_slice(&input.witness[3]);
2377 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2379 payment_preimage: Some(payment_preimage),
2383 } else if offered_preimage_claim {
2384 if !self.pending_monitor_events.iter().any(
2385 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
2386 upd.source == source
2388 payment_preimage.0.copy_from_slice(&input.witness[1]);
2389 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2391 payment_preimage: Some(payment_preimage),
2396 self.onchain_events_waiting_threshold_conf.retain(|ref entry| {
2397 if entry.height != height { return true; }
2399 OnchainEvent::HTLCUpdate { ref htlc_update } => {
2400 htlc_update.0 != source
2405 let entry = OnchainEventEntry {
2407 event: OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash) },
2409 log_info!(logger, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height{})", log_bytes!(payment_hash.0), entry.confirmation_threshold());
2410 self.onchain_events_waiting_threshold_conf.push(entry);
2416 /// Check if any transaction broadcasted is paying fund back to some address we can assume to own
2417 fn is_paying_spendable_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
2418 let mut spendable_output = None;
2419 for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us
2420 if i > ::std::u16::MAX as usize {
2421 // While it is possible that an output exists on chain which is greater than the
2422 // 2^16th output in a given transaction, this is only possible if the output is not
2423 // in a lightning transaction and was instead placed there by some third party who
2424 // wishes to give us money for no reason.
2425 // Namely, any lightning transactions which we pre-sign will never have anywhere
2426 // near 2^16 outputs both because such transactions must have ~2^16 outputs who's
2427 // scripts are not longer than one byte in length and because they are inherently
2428 // non-standard due to their size.
2429 // Thus, it is completely safe to ignore such outputs, and while it may result in
2430 // us ignoring non-lightning fund to us, that is only possible if someone fills
2431 // nearly a full block with garbage just to hit this case.
2434 if outp.script_pubkey == self.destination_script {
2435 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
2436 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2437 output: outp.clone(),
2440 } else if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
2441 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
2442 spendable_output = Some(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
2443 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2444 per_commitment_point: broadcasted_holder_revokable_script.1,
2445 to_self_delay: self.on_holder_tx_csv,
2446 output: outp.clone(),
2447 revocation_pubkey: broadcasted_holder_revokable_script.2.clone(),
2448 channel_keys_id: self.channel_keys_id,
2449 channel_value_satoshis: self.channel_value_satoshis,
2453 } else if self.counterparty_payment_script == outp.script_pubkey {
2454 spendable_output = Some(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
2455 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2456 output: outp.clone(),
2457 channel_keys_id: self.channel_keys_id,
2458 channel_value_satoshis: self.channel_value_satoshis,
2461 } else if outp.script_pubkey == self.shutdown_script {
2462 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
2463 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
2464 output: outp.clone(),
2468 if let Some(spendable_output) = spendable_output {
2469 let entry = OnchainEventEntry {
2471 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
2473 log_trace!(logger, "Maturing {} until {}", log_spendable!(spendable_output), entry.confirmation_threshold());
2474 self.onchain_events_waiting_threshold_conf.push(entry);
2479 /// `Persist` defines behavior for persisting channel monitors: this could mean
2480 /// writing once to disk, and/or uploading to one or more backup services.
2482 /// Note that for every new monitor, you **must** persist the new `ChannelMonitor`
2483 /// to disk/backups. And, on every update, you **must** persist either the
2484 /// `ChannelMonitorUpdate` or the updated monitor itself. Otherwise, there is risk
2485 /// of situations such as revoking a transaction, then crashing before this
2486 /// revocation can be persisted, then unintentionally broadcasting a revoked
2487 /// transaction and losing money. This is a risk because previous channel states
2488 /// are toxic, so it's important that whatever channel state is persisted is
2489 /// kept up-to-date.
2490 pub trait Persist<ChannelSigner: Sign>: Send + Sync {
2491 /// Persist a new channel's data. The data can be stored any way you want, but
2492 /// the identifier provided by Rust-Lightning is the channel's outpoint (and
2493 /// it is up to you to maintain a correct mapping between the outpoint and the
2494 /// stored channel data). Note that you **must** persist every new monitor to
2495 /// disk. See the `Persist` trait documentation for more details.
2497 /// See [`ChannelMonitor::write`] for writing out a `ChannelMonitor`,
2498 /// and [`ChannelMonitorUpdateErr`] for requirements when returning errors.
2499 fn persist_new_channel(&self, id: OutPoint, data: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
2501 /// Update one channel's data. The provided `ChannelMonitor` has already
2502 /// applied the given update.
2504 /// Note that on every update, you **must** persist either the
2505 /// `ChannelMonitorUpdate` or the updated monitor itself to disk/backups. See
2506 /// the `Persist` trait documentation for more details.
2508 /// If an implementer chooses to persist the updates only, they need to make
2509 /// sure that all the updates are applied to the `ChannelMonitors` *before*
2510 /// the set of channel monitors is given to the `ChannelManager`
2511 /// deserialization routine. See [`ChannelMonitor::update_monitor`] for
2512 /// applying a monitor update to a monitor. If full `ChannelMonitors` are
2513 /// persisted, then there is no need to persist individual updates.
2515 /// Note that there could be a performance tradeoff between persisting complete
2516 /// channel monitors on every update vs. persisting only updates and applying
2517 /// them in batches. The size of each monitor grows `O(number of state updates)`
2518 /// whereas updates are small and `O(1)`.
2520 /// See [`ChannelMonitor::write`] for writing out a `ChannelMonitor`,
2521 /// [`ChannelMonitorUpdate::write`] for writing out an update, and
2522 /// [`ChannelMonitorUpdateErr`] for requirements when returning errors.
2523 fn update_persisted_channel(&self, id: OutPoint, update: &ChannelMonitorUpdate, data: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
2526 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
2528 T::Target: BroadcasterInterface,
2529 F::Target: FeeEstimator,
2532 fn block_connected(&self, block: &Block, height: u32) {
2533 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
2534 self.0.block_connected(&block.header, &txdata, height, &*self.1, &*self.2, &*self.3);
2537 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
2538 self.0.block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
2542 const MAX_ALLOC_SIZE: usize = 64*1024;
2544 impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
2545 for (BlockHash, ChannelMonitor<Signer>) {
2546 fn read<R: ::std::io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
2547 macro_rules! unwrap_obj {
2551 Err(_) => return Err(DecodeError::InvalidValue),
2556 let _ver: u8 = Readable::read(reader)?;
2557 let min_ver: u8 = Readable::read(reader)?;
2558 if min_ver > SERIALIZATION_VERSION {
2559 return Err(DecodeError::UnknownVersion);
2562 let latest_update_id: u64 = Readable::read(reader)?;
2563 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
2565 let destination_script = Readable::read(reader)?;
2566 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
2568 let revokable_address = Readable::read(reader)?;
2569 let per_commitment_point = Readable::read(reader)?;
2570 let revokable_script = Readable::read(reader)?;
2571 Some((revokable_address, per_commitment_point, revokable_script))
2574 _ => return Err(DecodeError::InvalidValue),
2576 let counterparty_payment_script = Readable::read(reader)?;
2577 let shutdown_script = Readable::read(reader)?;
2579 let channel_keys_id = Readable::read(reader)?;
2580 let holder_revocation_basepoint = Readable::read(reader)?;
2581 // Technically this can fail and serialize fail a round-trip, but only for serialization of
2582 // barely-init'd ChannelMonitors that we can't do anything with.
2583 let outpoint = OutPoint {
2584 txid: Readable::read(reader)?,
2585 index: Readable::read(reader)?,
2587 let funding_info = (outpoint, Readable::read(reader)?);
2588 let current_counterparty_commitment_txid = Readable::read(reader)?;
2589 let prev_counterparty_commitment_txid = Readable::read(reader)?;
2591 let counterparty_tx_cache = Readable::read(reader)?;
2592 let funding_redeemscript = Readable::read(reader)?;
2593 let channel_value_satoshis = Readable::read(reader)?;
2595 let their_cur_revocation_points = {
2596 let first_idx = <U48 as Readable>::read(reader)?.0;
2600 let first_point = Readable::read(reader)?;
2601 let second_point_slice: [u8; 33] = Readable::read(reader)?;
2602 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
2603 Some((first_idx, first_point, None))
2605 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
2610 let on_holder_tx_csv: u16 = Readable::read(reader)?;
2612 let commitment_secrets = Readable::read(reader)?;
2614 macro_rules! read_htlc_in_commitment {
2617 let offered: bool = Readable::read(reader)?;
2618 let amount_msat: u64 = Readable::read(reader)?;
2619 let cltv_expiry: u32 = Readable::read(reader)?;
2620 let payment_hash: PaymentHash = Readable::read(reader)?;
2621 let transaction_output_index: Option<u32> = Readable::read(reader)?;
2623 HTLCOutputInCommitment {
2624 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
2630 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
2631 let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
2632 for _ in 0..counterparty_claimable_outpoints_len {
2633 let txid: Txid = Readable::read(reader)?;
2634 let htlcs_count: u64 = Readable::read(reader)?;
2635 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
2636 for _ in 0..htlcs_count {
2637 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
2639 if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
2640 return Err(DecodeError::InvalidValue);
2644 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
2645 let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
2646 for _ in 0..counterparty_commitment_txn_on_chain_len {
2647 let txid: Txid = Readable::read(reader)?;
2648 let commitment_number = <U48 as Readable>::read(reader)?.0;
2649 if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, commitment_number) {
2650 return Err(DecodeError::InvalidValue);
2654 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
2655 let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
2656 for _ in 0..counterparty_hash_commitment_number_len {
2657 let payment_hash: PaymentHash = Readable::read(reader)?;
2658 let commitment_number = <U48 as Readable>::read(reader)?.0;
2659 if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
2660 return Err(DecodeError::InvalidValue);
2664 macro_rules! read_holder_tx {
2667 let txid = Readable::read(reader)?;
2668 let revocation_key = Readable::read(reader)?;
2669 let a_htlc_key = Readable::read(reader)?;
2670 let b_htlc_key = Readable::read(reader)?;
2671 let delayed_payment_key = Readable::read(reader)?;
2672 let per_commitment_point = Readable::read(reader)?;
2673 let feerate_per_kw: u32 = Readable::read(reader)?;
2675 let htlcs_len: u64 = Readable::read(reader)?;
2676 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_len as usize, MAX_ALLOC_SIZE / 128));
2677 for _ in 0..htlcs_len {
2678 let htlc = read_htlc_in_commitment!();
2679 let sigs = match <u8 as Readable>::read(reader)? {
2681 1 => Some(Readable::read(reader)?),
2682 _ => return Err(DecodeError::InvalidValue),
2684 htlcs.push((htlc, sigs, Readable::read(reader)?));
2689 revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, per_commitment_point, feerate_per_kw,
2696 let prev_holder_signed_commitment_tx = match <u8 as Readable>::read(reader)? {
2699 Some(read_holder_tx!())
2701 _ => return Err(DecodeError::InvalidValue),
2703 let current_holder_commitment_tx = read_holder_tx!();
2705 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
2706 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
2708 let payment_preimages_len: u64 = Readable::read(reader)?;
2709 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
2710 for _ in 0..payment_preimages_len {
2711 let preimage: PaymentPreimage = Readable::read(reader)?;
2712 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2713 if let Some(_) = payment_preimages.insert(hash, preimage) {
2714 return Err(DecodeError::InvalidValue);
2718 let pending_monitor_events_len: u64 = Readable::read(reader)?;
2719 let mut pending_monitor_events = Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3)));
2720 for _ in 0..pending_monitor_events_len {
2721 let ev = match <u8 as Readable>::read(reader)? {
2722 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
2723 1 => MonitorEvent::CommitmentTxBroadcasted(funding_info.0),
2724 _ => return Err(DecodeError::InvalidValue)
2726 pending_monitor_events.push(ev);
2729 let pending_events_len: u64 = Readable::read(reader)?;
2730 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
2731 for _ in 0..pending_events_len {
2732 if let Some(event) = MaybeReadable::read(reader)? {
2733 pending_events.push(event);
2737 let last_block_hash: BlockHash = Readable::read(reader)?;
2739 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
2740 let mut onchain_events_waiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
2741 for _ in 0..waiting_threshold_conf_len {
2742 let height = Readable::read(reader)?;
2743 let event = match <u8 as Readable>::read(reader)? {
2745 let htlc_source = Readable::read(reader)?;
2746 let hash = Readable::read(reader)?;
2747 OnchainEvent::HTLCUpdate {
2748 htlc_update: (htlc_source, hash)
2752 let descriptor = Readable::read(reader)?;
2753 OnchainEvent::MaturingOutput {
2757 _ => return Err(DecodeError::InvalidValue),
2759 onchain_events_waiting_threshold_conf.push(OnchainEventEntry { height, event });
2762 let outputs_to_watch_len: u64 = Readable::read(reader)?;
2763 let mut outputs_to_watch = HashMap::with_capacity(cmp::min(outputs_to_watch_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<Txid>() + mem::size_of::<u32>() + mem::size_of::<Vec<Script>>())));
2764 for _ in 0..outputs_to_watch_len {
2765 let txid = Readable::read(reader)?;
2766 let outputs_len: u64 = Readable::read(reader)?;
2767 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<Script>())));
2768 for _ in 0..outputs_len {
2769 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
2771 if let Some(_) = outputs_to_watch.insert(txid, outputs) {
2772 return Err(DecodeError::InvalidValue);
2775 let onchain_tx_handler = ReadableArgs::read(reader, keys_manager)?;
2777 let lockdown_from_offchain = Readable::read(reader)?;
2778 let holder_tx_signed = Readable::read(reader)?;
2780 let mut secp_ctx = Secp256k1::new();
2781 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
2783 Ok((last_block_hash.clone(), ChannelMonitor {
2784 inner: Mutex::new(ChannelMonitorImpl {
2786 commitment_transaction_number_obscure_factor,
2789 broadcasted_holder_revokable_script,
2790 counterparty_payment_script,
2794 holder_revocation_basepoint,
2796 current_counterparty_commitment_txid,
2797 prev_counterparty_commitment_txid,
2799 counterparty_tx_cache,
2800 funding_redeemscript,
2801 channel_value_satoshis,
2802 their_cur_revocation_points,
2807 counterparty_claimable_outpoints,
2808 counterparty_commitment_txn_on_chain,
2809 counterparty_hash_commitment_number,
2811 prev_holder_signed_commitment_tx,
2812 current_holder_commitment_tx,
2813 current_counterparty_commitment_number,
2814 current_holder_commitment_number,
2817 pending_monitor_events,
2820 onchain_events_waiting_threshold_conf,
2825 lockdown_from_offchain,
2837 use bitcoin::blockdata::constants::genesis_block;
2838 use bitcoin::blockdata::script::{Script, Builder};
2839 use bitcoin::blockdata::opcodes;
2840 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
2841 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
2842 use bitcoin::util::bip143;
2843 use bitcoin::hashes::Hash;
2844 use bitcoin::hashes::sha256::Hash as Sha256;
2845 use bitcoin::hashes::hex::FromHex;
2846 use bitcoin::hash_types::Txid;
2847 use bitcoin::network::constants::Network;
2849 use chain::channelmonitor::ChannelMonitor;
2850 use chain::transaction::OutPoint;
2851 use ln::channelmanager::{PaymentPreimage, PaymentHash};
2852 use ln::onchaintx::{OnchainTxHandler, InputDescriptors};
2854 use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
2855 use util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
2856 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
2857 use bitcoin::secp256k1::Secp256k1;
2858 use std::sync::{Arc, Mutex};
2859 use chain::keysinterface::InMemorySigner;
2862 fn test_prune_preimages() {
2863 let secp_ctx = Secp256k1::new();
2864 let logger = Arc::new(TestLogger::new());
2865 let broadcaster = Arc::new(TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
2866 let fee_estimator = Arc::new(TestFeeEstimator { sat_per_kw: 253 });
2868 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2869 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
2871 let mut preimages = Vec::new();
2874 let preimage = PaymentPreimage([i; 32]);
2875 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
2876 preimages.push((preimage, hash));
2880 macro_rules! preimages_slice_to_htlc_outputs {
2881 ($preimages_slice: expr) => {
2883 let mut res = Vec::new();
2884 for (idx, preimage) in $preimages_slice.iter().enumerate() {
2885 res.push((HTLCOutputInCommitment {
2889 payment_hash: preimage.1.clone(),
2890 transaction_output_index: Some(idx as u32),
2897 macro_rules! preimages_to_holder_htlcs {
2898 ($preimages_slice: expr) => {
2900 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
2901 let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
2907 macro_rules! test_preimages_exist {
2908 ($preimages_slice: expr, $monitor: expr) => {
2909 for preimage in $preimages_slice {
2910 assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
2915 let keys = InMemorySigner::new(
2917 SecretKey::from_slice(&[41; 32]).unwrap(),
2918 SecretKey::from_slice(&[41; 32]).unwrap(),
2919 SecretKey::from_slice(&[41; 32]).unwrap(),
2920 SecretKey::from_slice(&[41; 32]).unwrap(),
2921 SecretKey::from_slice(&[41; 32]).unwrap(),
2927 let counterparty_pubkeys = ChannelPublicKeys {
2928 funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
2929 revocation_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
2930 payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
2931 delayed_payment_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap()),
2932 htlc_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())
2934 let funding_outpoint = OutPoint { txid: Default::default(), index: u16::max_value() };
2935 let channel_parameters = ChannelTransactionParameters {
2936 holder_pubkeys: keys.holder_channel_pubkeys.clone(),
2937 holder_selected_contest_delay: 66,
2938 is_outbound_from_holder: true,
2939 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
2940 pubkeys: counterparty_pubkeys,
2941 selected_contest_delay: 67,
2943 funding_outpoint: Some(funding_outpoint),
2945 // Prune with one old state and a holder commitment tx holding a few overlaps with the
2947 let last_block_hash = genesis_block(Network::Testnet).block_hash();
2948 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
2949 &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0, &Script::new(),
2950 (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
2951 &channel_parameters,
2952 Script::new(), 46, 0,
2953 HolderCommitmentTransaction::dummy(), last_block_hash);
2955 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
2956 let dummy_txid = dummy_tx.txid();
2957 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
2958 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
2959 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
2960 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
2961 for &(ref preimage, ref hash) in preimages.iter() {
2962 monitor.provide_payment_preimage(hash, preimage, &broadcaster, &fee_estimator, &logger);
2965 // Now provide a secret, pruning preimages 10-15
2966 let mut secret = [0; 32];
2967 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2968 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
2969 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
2970 test_preimages_exist!(&preimages[0..10], monitor);
2971 test_preimages_exist!(&preimages[15..20], monitor);
2973 // Now provide a further secret, pruning preimages 15-17
2974 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2975 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
2976 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
2977 test_preimages_exist!(&preimages[0..10], monitor);
2978 test_preimages_exist!(&preimages[17..20], monitor);
2980 // Now update holder commitment tx info, pruning only element 18 as we still care about the
2981 // previous commitment tx's preimages too
2982 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..5])).unwrap();
2983 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2984 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
2985 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
2986 test_preimages_exist!(&preimages[0..10], monitor);
2987 test_preimages_exist!(&preimages[18..20], monitor);
2989 // But if we do it again, we'll prune 5-10
2990 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..3])).unwrap();
2991 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2992 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
2993 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
2994 test_preimages_exist!(&preimages[0..5], monitor);
2998 fn test_claim_txn_weight_computation() {
2999 // We test Claim txn weight, knowing that we want expected weigth and
3000 // not actual case to avoid sigs and time-lock delays hell variances.
3002 let secp_ctx = Secp256k1::new();
3003 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3004 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3005 let mut sum_actual_sigs = 0;
3007 macro_rules! sign_input {
3008 ($sighash_parts: expr, $idx: expr, $amount: expr, $input_type: expr, $sum_actual_sigs: expr) => {
3009 let htlc = HTLCOutputInCommitment {
3010 offered: if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::OfferedHTLC { true } else { false },
3012 cltv_expiry: 2 << 16,
3013 payment_hash: PaymentHash([1; 32]),
3014 transaction_output_index: Some($idx as u32),
3016 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) };
3017 let sighash = hash_to_message!(&$sighash_parts.signature_hash($idx, &redeem_script, $amount, SigHashType::All)[..]);
3018 let sig = secp_ctx.sign(&sighash, &privkey);
3019 $sighash_parts.access_witness($idx).push(sig.serialize_der().to_vec());
3020 $sighash_parts.access_witness($idx)[0].push(SigHashType::All as u8);
3021 sum_actual_sigs += $sighash_parts.access_witness($idx)[0].len();
3022 if *$input_type == InputDescriptors::RevokedOutput {
3023 $sighash_parts.access_witness($idx).push(vec!(1));
3024 } else if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::RevokedReceivedHTLC {
3025 $sighash_parts.access_witness($idx).push(pubkey.clone().serialize().to_vec());
3026 } else if *$input_type == InputDescriptors::ReceivedHTLC {
3027 $sighash_parts.access_witness($idx).push(vec![0]);
3029 $sighash_parts.access_witness($idx).push(PaymentPreimage([1; 32]).0.to_vec());
3031 $sighash_parts.access_witness($idx).push(redeem_script.into_bytes());
3032 println!("witness[0] {}", $sighash_parts.access_witness($idx)[0].len());
3033 println!("witness[1] {}", $sighash_parts.access_witness($idx)[1].len());
3034 println!("witness[2] {}", $sighash_parts.access_witness($idx)[2].len());
3038 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3039 let txid = Txid::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3041 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
3042 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3044 claim_tx.input.push(TxIn {
3045 previous_output: BitcoinOutPoint {
3049 script_sig: Script::new(),
3050 sequence: 0xfffffffd,
3051 witness: Vec::new(),
3054 claim_tx.output.push(TxOut {
3055 script_pubkey: script_pubkey.clone(),
3058 let base_weight = claim_tx.get_weight();
3059 let inputs_des = vec![InputDescriptors::RevokedOutput, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedReceivedHTLC];
3061 let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3062 for (idx, inp) in inputs_des.iter().enumerate() {
3063 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3066 assert_eq!(base_weight + OnchainTxHandler::<InMemorySigner>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
3068 // Claim tx with 1 offered HTLCs, 3 received HTLCs
3069 claim_tx.input.clear();
3070 sum_actual_sigs = 0;
3072 claim_tx.input.push(TxIn {
3073 previous_output: BitcoinOutPoint {
3077 script_sig: Script::new(),
3078 sequence: 0xfffffffd,
3079 witness: Vec::new(),
3082 let base_weight = claim_tx.get_weight();
3083 let inputs_des = vec![InputDescriptors::OfferedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC];
3085 let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3086 for (idx, inp) in inputs_des.iter().enumerate() {
3087 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3090 assert_eq!(base_weight + OnchainTxHandler::<InMemorySigner>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
3092 // Justice tx with 1 revoked HTLC-Success tx output
3093 claim_tx.input.clear();
3094 sum_actual_sigs = 0;
3095 claim_tx.input.push(TxIn {
3096 previous_output: BitcoinOutPoint {
3100 script_sig: Script::new(),
3101 sequence: 0xfffffffd,
3102 witness: Vec::new(),
3104 let base_weight = claim_tx.get_weight();
3105 let inputs_des = vec![InputDescriptors::RevokedOutput];
3107 let mut sighash_parts = bip143::SigHashCache::new(&mut claim_tx);
3108 for (idx, inp) in inputs_des.iter().enumerate() {
3109 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
3112 assert_eq!(base_weight + OnchainTxHandler::<InMemorySigner>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs));
3115 // Further testing is done in the ChannelManager integration tests.