1 //! The logic to monitor for on-chain transactions and create the relevant claim responses lives
4 //! ChannelMonitor objects are generated by ChannelManager in response to relevant
5 //! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
6 //! be made in responding to certain messages, see ManyChannelMonitor for more.
8 //! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
9 //! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
10 //! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
11 //! security-domain-separated system design, you should consider having multiple paths for
12 //! ChannelMonitors to get out of the HSM and onto monitoring devices.
14 use bitcoin::blockdata::block::BlockHeader;
15 use bitcoin::blockdata::transaction::{TxIn,TxOut,SigHashType,Transaction};
16 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
17 use bitcoin::blockdata::script::{Script, Builder};
18 use bitcoin::blockdata::opcodes;
19 use bitcoin::consensus::encode;
20 use bitcoin::util::hash::BitcoinHash;
21 use bitcoin::util::bip143;
23 use bitcoin_hashes::Hash;
24 use bitcoin_hashes::sha256::Hash as Sha256;
25 use bitcoin_hashes::hash160::Hash as Hash160;
26 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
28 use secp256k1::{Secp256k1,Signature};
29 use secp256k1::key::{SecretKey,PublicKey};
32 use ln::msgs::DecodeError;
34 use ln::chan_utils::{HTLCOutputInCommitment, LocalCommitmentTransaction, HTLCType};
35 use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
36 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface, FeeEstimator, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT};
37 use chain::transaction::OutPoint;
38 use chain::keysinterface::SpendableOutputDescriptor;
39 use util::logger::Logger;
40 use util::ser::{ReadableArgs, Readable, Writer, Writeable, U48};
41 use util::{byte_utils, events};
43 use std::collections::{HashMap, hash_map, HashSet};
44 use std::sync::{Arc,Mutex};
45 use std::{hash,cmp, mem};
47 /// An error enum representing a failure to persist a channel monitor update.
49 pub enum ChannelMonitorUpdateErr {
50 /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
51 /// our state failed, but is expected to succeed at some point in the future).
53 /// Such a failure will "freeze" a channel, preventing us from revoking old states or
54 /// submitting new commitment transactions to the remote party.
55 /// ChannelManager::test_restore_channel_monitor can be used to retry the update(s) and restore
56 /// the channel to an operational state.
58 /// Note that continuing to operate when no copy of the updated ChannelMonitor could be
59 /// persisted is unsafe - if you failed to store the update on your own local disk you should
60 /// instead return PermanentFailure to force closure of the channel ASAP.
62 /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
63 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
64 /// to claim it on this channel) and those updates must be applied wherever they can be. At
65 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
66 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
67 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
70 /// Note that even if updates made after TemporaryFailure succeed you must still call
71 /// test_restore_channel_monitor to ensure you have the latest monitor and re-enable normal
72 /// channel operation.
74 /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
75 /// remote location (with local copies persisted immediately), it is anticipated that all
76 /// updates will return TemporaryFailure until the remote copies could be updated.
78 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
79 /// different watchtower and cannot update with all watchtowers that were previously informed
80 /// of this channel). This will force-close the channel in question.
82 /// Should also be used to indicate a failure to update the local copy of the channel monitor.
86 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
87 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::insert_combine this
88 /// means you tried to merge two monitors for different channels or for a channel which was
89 /// restored from a backup and then generated new commitment updates.
90 /// Contains a human-readable error message.
92 pub struct MonitorUpdateError(pub &'static str);
94 /// Simple structure send back by ManyChannelMonitor in case of HTLC detected onchain from a
95 /// forward channel and from which info are needed to update HTLC in a backward channel.
96 pub struct HTLCUpdate {
97 pub(super) payment_hash: PaymentHash,
98 pub(super) payment_preimage: Option<PaymentPreimage>,
99 pub(super) source: HTLCSource
102 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
103 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
104 /// events to it, while also taking any add_update_monitor events and passing them to some remote
107 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
108 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
109 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
110 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
112 /// User needs to notify implementors of ManyChannelMonitor when a new block is connected or
113 /// disconnected using their `block_connected` and `block_disconnected` methods. However, rather
114 /// than calling these methods directly, the user should register implementors as listeners to the
115 /// BlockNotifier and call the BlockNotifier's `block_(dis)connected` methods, which will notify
116 /// all registered listeners in one go.
117 pub trait ManyChannelMonitor: Send + Sync {
118 /// Adds or updates a monitor for the given `funding_txo`.
120 /// Implementor must also ensure that the funding_txo outpoint is registered with any relevant
121 /// ChainWatchInterfaces such that the provided monitor receives block_connected callbacks with
122 /// any spends of it.
123 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>;
125 /// Used by ChannelManager to get list of HTLC resolved onchain and which needed to be updated
126 /// with success or failure backward
127 fn fetch_pending_htlc_updated(&self) -> Vec<HTLCUpdate>;
130 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
131 /// watchtower or watch our own channels.
133 /// Note that you must provide your own key by which to refer to channels.
135 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
136 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
137 /// index by a PublicKey which is required to sign any updates.
139 /// If you're using this for local monitoring of your own channels, you probably want to use
140 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
141 pub struct SimpleManyChannelMonitor<Key> {
142 #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
143 pub monitors: Mutex<HashMap<Key, ChannelMonitor>>,
145 monitors: Mutex<HashMap<Key, ChannelMonitor>>,
146 chain_monitor: Arc<ChainWatchInterface>,
147 broadcaster: Arc<BroadcasterInterface>,
148 pending_events: Mutex<Vec<events::Event>>,
149 pending_htlc_updated: Mutex<HashMap<PaymentHash, Vec<(HTLCSource, Option<PaymentPreimage>)>>>,
151 fee_estimator: Arc<FeeEstimator>
154 impl<'a, Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
156 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
157 let block_hash = header.bitcoin_hash();
158 let mut new_events: Vec<events::Event> = Vec::with_capacity(0);
159 let mut htlc_updated_infos = Vec::new();
161 let mut monitors = self.monitors.lock().unwrap();
162 for monitor in monitors.values_mut() {
163 let (txn_outputs, spendable_outputs, mut htlc_updated) = monitor.block_connected(txn_matched, height, &block_hash, &*self.broadcaster, &*self.fee_estimator);
164 if spendable_outputs.len() > 0 {
165 new_events.push(events::Event::SpendableOutputs {
166 outputs: spendable_outputs,
170 for (ref txid, ref outputs) in txn_outputs {
171 for (idx, output) in outputs.iter().enumerate() {
172 self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey);
175 htlc_updated_infos.append(&mut htlc_updated);
179 // ChannelManager will just need to fetch pending_htlc_updated and pass state backward
180 let mut pending_htlc_updated = self.pending_htlc_updated.lock().unwrap();
181 for htlc in htlc_updated_infos.drain(..) {
182 match pending_htlc_updated.entry(htlc.2) {
183 hash_map::Entry::Occupied(mut e) => {
184 // In case of reorg we may have htlc outputs solved in a different way so
185 // we prefer to keep claims but don't store duplicate updates for a given
186 // (payment_hash, HTLCSource) pair.
187 let mut existing_claim = false;
188 e.get_mut().retain(|htlc_data| {
189 if htlc.0 == htlc_data.0 {
190 if htlc_data.1.is_some() {
191 existing_claim = true;
197 e.get_mut().push((htlc.0, htlc.1));
200 hash_map::Entry::Vacant(e) => {
201 e.insert(vec![(htlc.0, htlc.1)]);
206 let mut pending_events = self.pending_events.lock().unwrap();
207 pending_events.append(&mut new_events);
210 fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
211 let block_hash = header.bitcoin_hash();
212 let mut monitors = self.monitors.lock().unwrap();
213 for monitor in monitors.values_mut() {
214 monitor.block_disconnected(disconnected_height, &block_hash, &*self.broadcaster, &*self.fee_estimator);
219 impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
220 /// Creates a new object which can be used to monitor several channels given the chain
221 /// interface with which to register to receive notifications.
222 pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>, feeest: Arc<FeeEstimator>) -> Arc<SimpleManyChannelMonitor<Key>> {
223 let res = Arc::new(SimpleManyChannelMonitor {
224 monitors: Mutex::new(HashMap::new()),
227 pending_events: Mutex::new(Vec::new()),
228 pending_htlc_updated: Mutex::new(HashMap::new()),
230 fee_estimator: feeest,
236 /// Adds or updates the monitor which monitors the channel referred to by the given key.
237 pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), MonitorUpdateError> {
238 let mut monitors = self.monitors.lock().unwrap();
239 match monitors.get_mut(&key) {
240 Some(orig_monitor) => {
241 log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_info!(monitor.key_storage));
242 return orig_monitor.insert_combine(monitor);
246 match monitor.key_storage {
247 Storage::Local { ref funding_info, .. } => {
250 return Err(MonitorUpdateError("Try to update a useless monitor without funding_txo !"));
252 &Some((ref outpoint, ref script)) => {
253 log_trace!(self, "Got new Channel Monitor for channel {}", log_bytes!(outpoint.to_channel_id()[..]));
254 self.chain_monitor.install_watch_tx(&outpoint.txid, script);
255 self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script);
259 Storage::Watchtower { .. } => {
260 self.chain_monitor.watch_all_txn();
263 monitors.insert(key, monitor);
268 impl ManyChannelMonitor for SimpleManyChannelMonitor<OutPoint> {
269 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr> {
270 match self.add_update_monitor_by_key(funding_txo, monitor) {
272 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
276 fn fetch_pending_htlc_updated(&self) -> Vec<HTLCUpdate> {
277 let mut updated = self.pending_htlc_updated.lock().unwrap();
278 let mut pending_htlcs_updated = Vec::with_capacity(updated.len());
279 for (k, v) in updated.drain() {
281 pending_htlcs_updated.push(HTLCUpdate {
283 payment_preimage: htlc_data.1,
288 pending_htlcs_updated
292 impl<Key : Send + cmp::Eq + hash::Hash> events::EventsProvider for SimpleManyChannelMonitor<Key> {
293 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
294 let mut pending_events = self.pending_events.lock().unwrap();
295 let mut ret = Vec::new();
296 mem::swap(&mut ret, &mut *pending_events);
301 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
302 /// instead claiming it in its own individual transaction.
303 const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
304 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
305 /// HTLC-Success transaction.
306 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
307 /// transaction confirmed (and we use it in a few more, equivalent, places).
308 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
309 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
310 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
311 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
312 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
313 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
314 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
315 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
316 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
317 /// accurate block height.
318 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
319 /// with at worst this delay, so we are not only using this value as a mercy for them but also
320 /// us as a safeguard to delay with enough time.
321 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
322 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding inbound
323 /// HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us losing money.
324 /// We use also this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
325 /// It may cause spurrious generation of bumped claim txn but that's allright given the outpoint is already
326 /// solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
327 /// keeping bumping another claim tx to solve the outpoint.
328 pub(crate) const ANTI_REORG_DELAY: u32 = 6;
330 #[derive(Clone, PartialEq)]
333 funding_key: SecretKey,
334 revocation_base_key: SecretKey,
335 htlc_base_key: SecretKey,
336 delayed_payment_base_key: SecretKey,
337 payment_base_key: SecretKey,
338 shutdown_pubkey: PublicKey,
339 funding_info: Option<(OutPoint, Script)>,
340 current_remote_commitment_txid: Option<Sha256dHash>,
341 prev_remote_commitment_txid: Option<Sha256dHash>,
344 revocation_base_key: PublicKey,
345 htlc_base_key: PublicKey,
349 #[derive(Clone, PartialEq)]
350 struct LocalSignedTx {
351 /// txid of the transaction in tx, just used to make comparison faster
353 tx: LocalCommitmentTransaction,
354 revocation_key: PublicKey,
355 a_htlc_key: PublicKey,
356 b_htlc_key: PublicKey,
357 delayed_payment_key: PublicKey,
358 per_commitment_point: PublicKey,
360 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
364 enum InputDescriptors {
369 RevokedOutput, // either a revoked to_local output on commitment tx, a revoked HTLC-Timeout output or a revoked HTLC-Success output
372 /// When ChannelMonitor discovers an onchain outpoint being a step of a channel and that it needs
373 /// to generate a tx to push channel state forward, we cache outpoint-solving tx material to build
374 /// a new bumped one in case of lenghty confirmation delay
375 #[derive(Clone, PartialEq)]
379 pubkey: Option<PublicKey>,
387 preimage: Option<PaymentPreimage>,
393 sigs: (Signature, Signature),
394 preimage: Option<PaymentPreimage>,
399 impl Writeable for InputMaterial {
400 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
402 &InputMaterial::Revoked { ref script, ref pubkey, ref key, ref is_htlc, ref amount} => {
403 writer.write_all(&[0; 1])?;
404 script.write(writer)?;
405 pubkey.write(writer)?;
406 writer.write_all(&key[..])?;
408 writer.write_all(&[0; 1])?;
410 writer.write_all(&[1; 1])?;
412 writer.write_all(&byte_utils::be64_to_array(*amount))?;
414 &InputMaterial::RemoteHTLC { ref script, ref key, ref preimage, ref amount, ref locktime } => {
415 writer.write_all(&[1; 1])?;
416 script.write(writer)?;
418 preimage.write(writer)?;
419 writer.write_all(&byte_utils::be64_to_array(*amount))?;
420 writer.write_all(&byte_utils::be32_to_array(*locktime))?;
422 &InputMaterial::LocalHTLC { ref script, ref sigs, ref preimage, ref amount } => {
423 writer.write_all(&[2; 1])?;
424 script.write(writer)?;
425 sigs.0.write(writer)?;
426 sigs.1.write(writer)?;
427 preimage.write(writer)?;
428 writer.write_all(&byte_utils::be64_to_array(*amount))?;
435 impl<R: ::std::io::Read> Readable<R> for InputMaterial {
436 fn read(reader: &mut R) -> Result<Self, DecodeError> {
437 let input_material = match <u8 as Readable<R>>::read(reader)? {
439 let script = Readable::read(reader)?;
440 let pubkey = Readable::read(reader)?;
441 let key = Readable::read(reader)?;
442 let is_htlc = match <u8 as Readable<R>>::read(reader)? {
445 _ => return Err(DecodeError::InvalidValue),
447 let amount = Readable::read(reader)?;
448 InputMaterial::Revoked {
457 let script = Readable::read(reader)?;
458 let key = Readable::read(reader)?;
459 let preimage = Readable::read(reader)?;
460 let amount = Readable::read(reader)?;
461 let locktime = Readable::read(reader)?;
462 InputMaterial::RemoteHTLC {
471 let script = Readable::read(reader)?;
472 let their_sig = Readable::read(reader)?;
473 let our_sig = Readable::read(reader)?;
474 let preimage = Readable::read(reader)?;
475 let amount = Readable::read(reader)?;
476 InputMaterial::LocalHTLC {
478 sigs: (their_sig, our_sig),
483 _ => return Err(DecodeError::InvalidValue),
489 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
490 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
491 #[derive(Clone, PartialEq)]
493 /// Outpoint under claim process by our own tx, once this one get enough confirmations, we remove it from
494 /// bump-txn candidate buffer.
496 claim_request: Sha256dHash,
498 /// HTLC output getting solved by a timeout, at maturation we pass upstream payment source information to solve
499 /// inbound HTLC in backward channel. Note, in case of preimage, we pass info to upstream without delay as we can
500 /// only win from it, so it's never an OnchainEvent
502 htlc_update: (HTLCSource, PaymentHash),
504 /// Claim tx aggregate multiple claimable outpoints. One of the outpoint may be claimed by a remote party tx.
505 /// In this case, we need to drop the outpoint and regenerate a new claim tx. By safety, we keep tracking
506 /// the outpoint to be sure to resurect it back to the claim tx if reorgs happen.
507 ContentiousOutpoint {
508 outpoint: BitcoinOutPoint,
509 input_material: InputMaterial,
513 /// Higher-level cache structure needed to re-generate bumped claim txn if needed
514 #[derive(Clone, PartialEq)]
515 pub struct ClaimTxBumpMaterial {
516 // At every block tick, used to check if pending claiming tx is taking too
517 // much time for confirmation and we need to bump it.
519 // Tracked in case of reorg to wipe out now-superflous bump material
520 feerate_previous: u64,
521 // Soonest timelocks among set of outpoints claimed, used to compute
522 // a priority of not feerate
523 soonest_timelock: u32,
524 // Cache of script, pubkey, sig or key to solve claimable outputs scriptpubkey.
525 per_input_material: HashMap<BitcoinOutPoint, InputMaterial>,
528 impl Writeable for ClaimTxBumpMaterial {
529 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
530 writer.write_all(&byte_utils::be32_to_array(self.height_timer))?;
531 writer.write_all(&byte_utils::be64_to_array(self.feerate_previous))?;
532 writer.write_all(&byte_utils::be32_to_array(self.soonest_timelock))?;
533 writer.write_all(&byte_utils::be64_to_array(self.per_input_material.len() as u64))?;
534 for (outp, tx_material) in self.per_input_material.iter() {
536 tx_material.write(writer)?;
542 impl<R: ::std::io::Read> Readable<R> for ClaimTxBumpMaterial {
543 fn read(reader: &mut R) -> Result<Self, DecodeError> {
544 let height_timer = Readable::read(reader)?;
545 let feerate_previous = Readable::read(reader)?;
546 let soonest_timelock = Readable::read(reader)?;
547 let per_input_material_len: u64 = Readable::read(reader)?;
548 let mut per_input_material = HashMap::with_capacity(cmp::min(per_input_material_len as usize, MAX_ALLOC_SIZE / 128));
549 for _ in 0 ..per_input_material_len {
550 let outpoint = Readable::read(reader)?;
551 let input_material = Readable::read(reader)?;
552 per_input_material.insert(outpoint, input_material);
554 Ok(Self { height_timer, feerate_previous, soonest_timelock, per_input_material })
558 const SERIALIZATION_VERSION: u8 = 1;
559 const MIN_SERIALIZATION_VERSION: u8 = 1;
561 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
562 /// on-chain transactions to ensure no loss of funds occurs.
564 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
565 /// information and are actively monitoring the chain.
567 pub struct ChannelMonitor {
568 commitment_transaction_number_obscure_factor: u64,
570 key_storage: Storage,
571 their_htlc_base_key: Option<PublicKey>,
572 their_delayed_payment_base_key: Option<PublicKey>,
573 funding_redeemscript: Option<Script>,
574 channel_value_satoshis: Option<u64>,
575 // first is the idx of the first of the two revocation points
576 their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
578 our_to_self_delay: u16,
579 their_to_self_delay: Option<u16>,
581 old_secrets: [([u8; 32], u64); 49],
582 remote_claimable_outpoints: HashMap<Sha256dHash, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
583 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
584 /// Nor can we figure out their commitment numbers without the commitment transaction they are
585 /// spending. Thus, in order to claim them via revocation key, we track all the remote
586 /// commitment transactions which we find on-chain, mapping them to the commitment number which
587 /// can be used to derive the revocation key and claim the transactions.
588 remote_commitment_txn_on_chain: HashMap<Sha256dHash, (u64, Vec<Script>)>,
589 /// Cache used to make pruning of payment_preimages faster.
590 /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
591 /// remote transactions (ie should remain pretty small).
592 /// Serialized to disk but should generally not be sent to Watchtowers.
593 remote_hash_commitment_number: HashMap<PaymentHash, u64>,
595 // We store two local commitment transactions to avoid any race conditions where we may update
596 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
597 // various monitors for one channel being out of sync, and us broadcasting a local
598 // transaction for which we have deleted claim information on some watchtowers.
599 prev_local_signed_commitment_tx: Option<LocalSignedTx>,
600 current_local_signed_commitment_tx: Option<LocalSignedTx>,
602 // Used just for ChannelManager to make sure it has the latest channel data during
604 current_remote_commitment_number: u64,
606 payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
608 destination_script: Script,
609 // Thanks to data loss protection, we may be able to claim our non-htlc funds
610 // back, this is the script we have to spend from but we need to
611 // scan every commitment transaction for that
612 to_remote_rescue: Option<(Script, SecretKey)>,
614 // Used to track claiming requests. If claim tx doesn't confirm before height timer expiration we need to bump
615 // it (RBF or CPFP). If an input has been part of an aggregate tx at first claim try, we need to keep it within
616 // another bumped aggregate tx to comply with RBF rules. We may have multiple claiming txn in the flight for the
617 // same set of outpoints. One of the outpoints may be spent by a transaction not issued by us. That's why at
618 // block connection we scan all inputs and if any of them is among a set of a claiming request we test for set
619 // equality between spending transaction and claim request. If true, it means transaction was one our claiming one
620 // after a security delay of 6 blocks we remove pending claim request. If false, it means transaction wasn't and
621 // we need to regenerate new claim request we reduced set of stil-claimable outpoints.
622 // Key is identifier of the pending claim request, i.e the txid of the initial claiming transaction generated by
623 // us and is immutable until all outpoint of the claimable set are post-anti-reorg-delay solved.
624 // Entry is cache of elements need to generate a bumped claiming transaction (see ClaimTxBumpMaterial)
625 #[cfg(test)] // Used in functional_test to verify sanitization
626 pub pending_claim_requests: HashMap<Sha256dHash, ClaimTxBumpMaterial>,
628 pending_claim_requests: HashMap<Sha256dHash, ClaimTxBumpMaterial>,
630 // Used to link outpoints claimed in a connected block to a pending claim request.
631 // Key is outpoint than monitor parsing has detected we have keys/scripts to claim
632 // Value is (pending claim request identifier, confirmation_block), identifier
633 // is txid of the initial claiming transaction and is immutable until outpoint is
634 // post-anti-reorg-delay solved, confirmaiton_block is used to erase entry if
635 // block with output gets disconnected.
636 #[cfg(test)] // Used in functional_test to verify sanitization
637 pub claimable_outpoints: HashMap<BitcoinOutPoint, (Sha256dHash, u32)>,
639 claimable_outpoints: HashMap<BitcoinOutPoint, (Sha256dHash, u32)>,
641 // Used to track onchain events, i.e transactions parts of channels confirmed on chain, on which
642 // we have to take actions once they reach enough confs. Key is a block height timer, i.e we enforce
643 // actions when we receive a block with given height. Actions depend on OnchainEvent type.
644 onchain_events_waiting_threshold_conf: HashMap<u32, Vec<OnchainEvent>>,
646 // We simply modify last_block_hash in Channel's block_connected so that serialization is
647 // consistent but hopefully the users' copy handles block_connected in a consistent way.
648 // (we do *not*, however, update them in insert_combine to ensure any local user copies keep
649 // their last_block_hash from its state and not based on updated copies that didn't run through
650 // the full block_connected).
651 pub(crate) last_block_hash: Sha256dHash,
652 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
656 macro_rules! subtract_high_prio_fee {
657 ($self: ident, $fee_estimator: expr, $value: expr, $predicted_weight: expr, $used_feerate: expr) => {
659 $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority);
660 let mut fee = $used_feerate * ($predicted_weight as u64) / 1000;
662 $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
663 fee = $used_feerate * ($predicted_weight as u64) / 1000;
665 $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background);
666 fee = $used_feerate * ($predicted_weight as u64) / 1000;
668 log_error!($self, "Failed to generate an on-chain punishment tx as even low priority fee ({} sat) was more than the entire claim balance ({} sat)",
672 log_warn!($self, "Used low priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
678 log_warn!($self, "Used medium priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
691 #[cfg(any(test, feature = "fuzztarget"))]
692 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
693 /// underlying object
694 impl PartialEq for ChannelMonitor {
695 fn eq(&self, other: &Self) -> bool {
696 if self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
697 self.key_storage != other.key_storage ||
698 self.their_htlc_base_key != other.their_htlc_base_key ||
699 self.their_delayed_payment_base_key != other.their_delayed_payment_base_key ||
700 self.funding_redeemscript != other.funding_redeemscript ||
701 self.channel_value_satoshis != other.channel_value_satoshis ||
702 self.their_cur_revocation_points != other.their_cur_revocation_points ||
703 self.our_to_self_delay != other.our_to_self_delay ||
704 self.their_to_self_delay != other.their_to_self_delay ||
705 self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
706 self.remote_commitment_txn_on_chain != other.remote_commitment_txn_on_chain ||
707 self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
708 self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
709 self.current_remote_commitment_number != other.current_remote_commitment_number ||
710 self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
711 self.payment_preimages != other.payment_preimages ||
712 self.destination_script != other.destination_script ||
713 self.to_remote_rescue != other.to_remote_rescue ||
714 self.pending_claim_requests != other.pending_claim_requests ||
715 self.claimable_outpoints != other.claimable_outpoints ||
716 self.onchain_events_waiting_threshold_conf != other.onchain_events_waiting_threshold_conf
720 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
721 if secret != o_secret || idx != o_idx {
730 impl ChannelMonitor {
731 pub(super) fn new(funding_key: &SecretKey, revocation_base_key: &SecretKey, delayed_payment_base_key: &SecretKey, htlc_base_key: &SecretKey, payment_base_key: &SecretKey, shutdown_pubkey: &PublicKey, our_to_self_delay: u16, destination_script: Script, logger: Arc<Logger>) -> ChannelMonitor {
733 commitment_transaction_number_obscure_factor: 0,
735 key_storage: Storage::Local {
736 funding_key: funding_key.clone(),
737 revocation_base_key: revocation_base_key.clone(),
738 htlc_base_key: htlc_base_key.clone(),
739 delayed_payment_base_key: delayed_payment_base_key.clone(),
740 payment_base_key: payment_base_key.clone(),
741 shutdown_pubkey: shutdown_pubkey.clone(),
743 current_remote_commitment_txid: None,
744 prev_remote_commitment_txid: None,
746 their_htlc_base_key: None,
747 their_delayed_payment_base_key: None,
748 funding_redeemscript: None,
749 channel_value_satoshis: None,
750 their_cur_revocation_points: None,
752 our_to_self_delay: our_to_self_delay,
753 their_to_self_delay: None,
755 old_secrets: [([0; 32], 1 << 48); 49],
756 remote_claimable_outpoints: HashMap::new(),
757 remote_commitment_txn_on_chain: HashMap::new(),
758 remote_hash_commitment_number: HashMap::new(),
760 prev_local_signed_commitment_tx: None,
761 current_local_signed_commitment_tx: None,
762 current_remote_commitment_number: 1 << 48,
764 payment_preimages: HashMap::new(),
765 destination_script: destination_script,
766 to_remote_rescue: None,
768 pending_claim_requests: HashMap::new(),
770 claimable_outpoints: HashMap::new(),
772 onchain_events_waiting_threshold_conf: HashMap::new(),
774 last_block_hash: Default::default(),
775 secp_ctx: Secp256k1::new(),
780 fn get_witnesses_weight(inputs: &[InputDescriptors]) -> usize {
781 let mut tx_weight = 2; // count segwit flags
783 // We use expected weight (and not actual) as signatures and time lock delays may vary
784 tx_weight += match inp {
785 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
786 &InputDescriptors::RevokedOfferedHTLC => {
787 1 + 1 + 73 + 1 + 33 + 1 + 133
789 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
790 &InputDescriptors::RevokedReceivedHTLC => {
791 1 + 1 + 73 + 1 + 33 + 1 + 139
793 // number_of_witness_elements + sig_length + remotehtlc_sig + preimage_length + preimage + witness_script_length + witness_script
794 &InputDescriptors::OfferedHTLC => {
795 1 + 1 + 73 + 1 + 32 + 1 + 133
797 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
798 &InputDescriptors::ReceivedHTLC => {
799 1 + 1 + 73 + 1 + 1 + 1 + 139
801 // number_of_witness_elements + sig_length + revocation_sig + true_length + op_true + witness_script_length + witness_script
802 &InputDescriptors::RevokedOutput => {
803 1 + 1 + 73 + 1 + 1 + 1 + 77
810 fn get_height_timer(current_height: u32, timelock_expiration: u32) -> u32 {
811 if timelock_expiration <= current_height || timelock_expiration - current_height <= 3 {
812 return current_height + 1
813 } else if timelock_expiration - current_height <= 15 {
814 return current_height + 3
820 fn place_secret(idx: u64) -> u8 {
822 if idx & (1 << i) == (1 << i) {
830 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
831 let mut res: [u8; 32] = secret;
833 let bitpos = bits - 1 - i;
834 if idx & (1 << bitpos) == (1 << bitpos) {
835 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
836 res = Sha256::hash(&res).into_inner();
842 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
843 /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
844 /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
845 pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
846 let pos = ChannelMonitor::place_secret(idx);
848 let (old_secret, old_idx) = self.old_secrets[i as usize];
849 if ChannelMonitor::derive_secret(secret, pos, old_idx) != old_secret {
850 return Err(MonitorUpdateError("Previous secret did not match new one"));
853 if self.get_min_seen_secret() <= idx {
856 self.old_secrets[pos as usize] = (secret, idx);
858 // Prune HTLCs from the previous remote commitment tx so we don't generate failure/fulfill
859 // events for now-revoked/fulfilled HTLCs.
860 // TODO: We should probably consider whether we're really getting the next secret here.
861 if let Storage::Local { ref mut prev_remote_commitment_txid, .. } = self.key_storage {
862 if let Some(txid) = prev_remote_commitment_txid.take() {
863 for &mut (_, ref mut source) in self.remote_claimable_outpoints.get_mut(&txid).unwrap() {
869 if !self.payment_preimages.is_empty() {
870 let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
871 let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
872 let min_idx = self.get_min_seen_secret();
873 let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
875 self.payment_preimages.retain(|&k, _| {
876 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
877 if k == htlc.payment_hash {
881 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
882 for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
883 if k == htlc.payment_hash {
888 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
895 remote_hash_commitment_number.remove(&k);
904 /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
905 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
906 /// possibly future revocation/preimage information) to claim outputs where possible.
907 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
908 pub(super) fn provide_latest_remote_commitment_tx_info(&mut self, unsigned_commitment_tx: &Transaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>, commitment_number: u64, their_revocation_point: PublicKey) {
909 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
910 // so that a remote monitor doesn't learn anything unless there is a malicious close.
911 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
913 for &(ref htlc, _) in &htlc_outputs {
914 self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
917 let new_txid = unsigned_commitment_tx.txid();
918 log_trace!(self, "Tracking new remote commitment transaction with txid {} at commitment number {} with {} HTLC outputs", new_txid, commitment_number, htlc_outputs.len());
919 log_trace!(self, "New potential remote commitment transaction: {}", encode::serialize_hex(unsigned_commitment_tx));
920 if let Storage::Local { ref mut current_remote_commitment_txid, ref mut prev_remote_commitment_txid, .. } = self.key_storage {
921 *prev_remote_commitment_txid = current_remote_commitment_txid.take();
922 *current_remote_commitment_txid = Some(new_txid);
924 self.remote_claimable_outpoints.insert(new_txid, htlc_outputs);
925 self.current_remote_commitment_number = commitment_number;
926 //TODO: Merge this into the other per-remote-transaction output storage stuff
927 match self.their_cur_revocation_points {
928 Some(old_points) => {
929 if old_points.0 == commitment_number + 1 {
930 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
931 } else if old_points.0 == commitment_number + 2 {
932 if let Some(old_second_point) = old_points.2 {
933 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
935 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
938 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
942 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
947 pub(super) fn provide_rescue_remote_commitment_tx_info(&mut self, their_revocation_point: PublicKey) {
948 match self.key_storage {
949 Storage::Local { ref payment_base_key, .. } => {
950 if let Ok(payment_key) = chan_utils::derive_public_key(&self.secp_ctx, &their_revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &payment_base_key)) {
951 let to_remote_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
952 .push_slice(&Hash160::hash(&payment_key.serialize())[..])
954 if let Ok(to_remote_key) = chan_utils::derive_private_key(&self.secp_ctx, &their_revocation_point, &payment_base_key) {
955 self.to_remote_rescue = Some((to_remote_script, to_remote_key));
959 Storage::Watchtower { .. } => {}
963 /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
964 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
965 /// is important that any clones of this channel monitor (including remote clones) by kept
966 /// up-to-date as our local commitment transaction is updated.
967 /// Panics if set_their_to_self_delay has never been called.
968 pub(super) fn provide_latest_local_commitment_tx_info(&mut self, commitment_tx: LocalCommitmentTransaction, local_keys: chan_utils::TxCreationKeys, feerate_per_kw: u64, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) {
969 assert!(self.their_to_self_delay.is_some());
970 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
971 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
972 txid: commitment_tx.txid(),
974 revocation_key: local_keys.revocation_key,
975 a_htlc_key: local_keys.a_htlc_key,
976 b_htlc_key: local_keys.b_htlc_key,
977 delayed_payment_key: local_keys.a_delayed_payment_key,
978 per_commitment_point: local_keys.per_commitment_point,
984 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
985 /// commitment_tx_infos which contain the payment hash have been revoked.
986 pub(super) fn provide_payment_preimage(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage) {
987 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
990 /// Combines this ChannelMonitor with the information contained in the other ChannelMonitor.
991 /// After a successful call this ChannelMonitor is up-to-date and is safe to use to monitor the
992 /// chain for new blocks/transactions.
993 pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), MonitorUpdateError> {
994 match self.key_storage {
995 Storage::Local { ref funding_info, .. } => {
996 if funding_info.is_none() { return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); }
997 let our_funding_info = funding_info;
998 if let Storage::Local { ref funding_info, .. } = other.key_storage {
999 if funding_info.is_none() { return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); }
1000 // We should be able to compare the entire funding_txo, but in fuzztarget it's trivially
1001 // easy to collide the funding_txo hash and have a different scriptPubKey.
1002 if funding_info.as_ref().unwrap().0 != our_funding_info.as_ref().unwrap().0 {
1003 return Err(MonitorUpdateError("Funding transaction outputs are not identical!"));
1006 return Err(MonitorUpdateError("Try to combine a Local monitor with a Watchtower one !"));
1009 Storage::Watchtower { .. } => {
1010 if let Storage::Watchtower { .. } = other.key_storage {
1013 return Err(MonitorUpdateError("Try to combine a Watchtower monitor with a Local one !"));
1017 let other_min_secret = other.get_min_seen_secret();
1018 let our_min_secret = self.get_min_seen_secret();
1019 if our_min_secret > other_min_secret {
1020 self.provide_secret(other_min_secret, other.get_secret(other_min_secret).unwrap())?;
1022 if let Some(ref local_tx) = self.current_local_signed_commitment_tx {
1023 if let Some(ref other_local_tx) = other.current_local_signed_commitment_tx {
1024 let our_commitment_number = 0xffffffffffff - ((((local_tx.tx.without_valid_witness().input[0].sequence as u64 & 0xffffff) << 3*8) | (local_tx.tx.without_valid_witness().lock_time as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
1025 let other_commitment_number = 0xffffffffffff - ((((other_local_tx.tx.without_valid_witness().input[0].sequence as u64 & 0xffffff) << 3*8) | (other_local_tx.tx.without_valid_witness().lock_time as u64 & 0xffffff)) ^ other.commitment_transaction_number_obscure_factor);
1026 if our_commitment_number >= other_commitment_number {
1027 self.key_storage = other.key_storage;
1031 // TODO: We should use current_remote_commitment_number and the commitment number out of
1032 // local transactions to decide how to merge
1033 if our_min_secret >= other_min_secret {
1034 self.their_cur_revocation_points = other.their_cur_revocation_points;
1035 for (txid, htlcs) in other.remote_claimable_outpoints.drain() {
1036 self.remote_claimable_outpoints.insert(txid, htlcs);
1038 if let Some(local_tx) = other.prev_local_signed_commitment_tx {
1039 self.prev_local_signed_commitment_tx = Some(local_tx);
1041 if let Some(local_tx) = other.current_local_signed_commitment_tx {
1042 self.current_local_signed_commitment_tx = Some(local_tx);
1044 self.payment_preimages = other.payment_preimages;
1045 self.to_remote_rescue = other.to_remote_rescue;
1048 self.current_remote_commitment_number = cmp::min(self.current_remote_commitment_number, other.current_remote_commitment_number);
1052 /// Allows this monitor to scan only for transactions which are applicable. Note that this is
1053 /// optional, without it this monitor cannot be used in an SPV client, but you may wish to
1054 /// avoid this (or call unset_funding_info) on a monitor you wish to send to a watchtower as it
1055 /// provides slightly better privacy.
1056 /// It's the responsibility of the caller to register outpoint and script with passing the former
1057 /// value as key to add_update_monitor.
1058 pub(super) fn set_funding_info(&mut self, new_funding_info: (OutPoint, Script)) {
1059 match self.key_storage {
1060 Storage::Local { ref mut funding_info, .. } => {
1061 *funding_info = Some(new_funding_info);
1063 Storage::Watchtower { .. } => {
1064 panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
1069 /// We log these base keys at channel opening to being able to rebuild redeemscript in case of leaked revoked commit tx
1070 /// Panics if commitment_transaction_number_obscure_factor doesn't fit in 48 bits
1071 pub(super) fn set_basic_channel_info(&mut self, their_htlc_base_key: &PublicKey, their_delayed_payment_base_key: &PublicKey, their_to_self_delay: u16, funding_redeemscript: Script, channel_value_satoshis: u64, commitment_transaction_number_obscure_factor: u64) {
1072 self.their_htlc_base_key = Some(their_htlc_base_key.clone());
1073 self.their_delayed_payment_base_key = Some(their_delayed_payment_base_key.clone());
1074 self.their_to_self_delay = Some(their_to_self_delay);
1075 self.funding_redeemscript = Some(funding_redeemscript);
1076 self.channel_value_satoshis = Some(channel_value_satoshis);
1077 assert!(commitment_transaction_number_obscure_factor < (1 << 48));
1078 self.commitment_transaction_number_obscure_factor = commitment_transaction_number_obscure_factor;
1081 pub(super) fn unset_funding_info(&mut self) {
1082 match self.key_storage {
1083 Storage::Local { ref mut funding_info, .. } => {
1084 *funding_info = None;
1086 Storage::Watchtower { .. } => {
1087 panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
1092 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1093 pub fn get_funding_txo(&self) -> Option<OutPoint> {
1094 match self.key_storage {
1095 Storage::Local { ref funding_info, .. } => {
1096 match funding_info {
1097 &Some((outpoint, _)) => Some(outpoint),
1101 Storage::Watchtower { .. } => {
1107 /// Gets the sets of all outpoints which this ChannelMonitor expects to hear about spends of.
1108 /// Generally useful when deserializing as during normal operation the return values of
1109 /// block_connected are sufficient to ensure all relevant outpoints are being monitored (note
1110 /// that the get_funding_txo outpoint and transaction must also be monitored for!).
1111 pub fn get_monitored_outpoints(&self) -> Vec<(Sha256dHash, u32, &Script)> {
1112 let mut res = Vec::with_capacity(self.remote_commitment_txn_on_chain.len() * 2);
1113 for (ref txid, &(_, ref outputs)) in self.remote_commitment_txn_on_chain.iter() {
1114 for (idx, output) in outputs.iter().enumerate() {
1115 res.push(((*txid).clone(), idx as u32, output));
1121 /// Serializes into a vec, with various modes for the exposed pub fns
1122 fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
1123 //TODO: We still write out all the serialization here manually instead of using the fancy
1124 //serialization framework we have, we should migrate things over to it.
1125 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
1126 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
1128 // Set in initial Channel-object creation, so should always be set by now:
1129 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
1131 macro_rules! write_option {
1138 &None => 0u8.write(writer)?,
1143 match self.key_storage {
1144 Storage::Local { ref funding_key, ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, ref payment_base_key, ref shutdown_pubkey, ref funding_info, ref current_remote_commitment_txid, ref prev_remote_commitment_txid } => {
1145 writer.write_all(&[0; 1])?;
1146 writer.write_all(&funding_key[..])?;
1147 writer.write_all(&revocation_base_key[..])?;
1148 writer.write_all(&htlc_base_key[..])?;
1149 writer.write_all(&delayed_payment_base_key[..])?;
1150 writer.write_all(&payment_base_key[..])?;
1151 writer.write_all(&shutdown_pubkey.serialize())?;
1152 match funding_info {
1153 &Some((ref outpoint, ref script)) => {
1154 writer.write_all(&outpoint.txid[..])?;
1155 writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
1156 script.write(writer)?;
1159 debug_assert!(false, "Try to serialize a useless Local monitor !");
1162 current_remote_commitment_txid.write(writer)?;
1163 prev_remote_commitment_txid.write(writer)?;
1165 Storage::Watchtower { .. } => unimplemented!(),
1168 writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
1169 writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
1170 self.funding_redeemscript.as_ref().unwrap().write(writer)?;
1171 self.channel_value_satoshis.unwrap().write(writer)?;
1173 match self.their_cur_revocation_points {
1174 Some((idx, pubkey, second_option)) => {
1175 writer.write_all(&byte_utils::be48_to_array(idx))?;
1176 writer.write_all(&pubkey.serialize())?;
1177 match second_option {
1178 Some(second_pubkey) => {
1179 writer.write_all(&second_pubkey.serialize())?;
1182 writer.write_all(&[0; 33])?;
1187 writer.write_all(&byte_utils::be48_to_array(0))?;
1191 writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
1192 writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
1194 for &(ref secret, ref idx) in self.old_secrets.iter() {
1195 writer.write_all(secret)?;
1196 writer.write_all(&byte_utils::be64_to_array(*idx))?;
1199 macro_rules! serialize_htlc_in_commitment {
1200 ($htlc_output: expr) => {
1201 writer.write_all(&[$htlc_output.offered as u8; 1])?;
1202 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
1203 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
1204 writer.write_all(&$htlc_output.payment_hash.0[..])?;
1205 $htlc_output.transaction_output_index.write(writer)?;
1209 writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
1210 for (ref txid, ref htlc_infos) in self.remote_claimable_outpoints.iter() {
1211 writer.write_all(&txid[..])?;
1212 writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
1213 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
1214 serialize_htlc_in_commitment!(htlc_output);
1215 write_option!(htlc_source);
1219 writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
1220 for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
1221 writer.write_all(&txid[..])?;
1222 writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
1223 (txouts.len() as u64).write(writer)?;
1224 for script in txouts.iter() {
1225 script.write(writer)?;
1229 if for_local_storage {
1230 writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
1231 for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
1232 writer.write_all(&payment_hash.0[..])?;
1233 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1236 writer.write_all(&byte_utils::be64_to_array(0))?;
1239 macro_rules! serialize_local_tx {
1240 ($local_tx: expr) => {
1241 $local_tx.tx.write(writer)?;
1242 writer.write_all(&$local_tx.revocation_key.serialize())?;
1243 writer.write_all(&$local_tx.a_htlc_key.serialize())?;
1244 writer.write_all(&$local_tx.b_htlc_key.serialize())?;
1245 writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
1246 writer.write_all(&$local_tx.per_commitment_point.serialize())?;
1248 writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
1249 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
1250 for &(ref htlc_output, ref sig, ref htlc_source) in $local_tx.htlc_outputs.iter() {
1251 serialize_htlc_in_commitment!(htlc_output);
1252 if let &Some(ref their_sig) = sig {
1254 writer.write_all(&their_sig.serialize_compact())?;
1258 write_option!(htlc_source);
1263 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
1264 writer.write_all(&[1; 1])?;
1265 serialize_local_tx!(prev_local_tx);
1267 writer.write_all(&[0; 1])?;
1270 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1271 writer.write_all(&[1; 1])?;
1272 serialize_local_tx!(cur_local_tx);
1274 writer.write_all(&[0; 1])?;
1277 if for_local_storage {
1278 writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
1280 writer.write_all(&byte_utils::be48_to_array(0))?;
1283 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
1284 for payment_preimage in self.payment_preimages.values() {
1285 writer.write_all(&payment_preimage.0[..])?;
1288 self.last_block_hash.write(writer)?;
1289 self.destination_script.write(writer)?;
1290 if let Some((ref to_remote_script, ref local_key)) = self.to_remote_rescue {
1291 writer.write_all(&[1; 1])?;
1292 to_remote_script.write(writer)?;
1293 local_key.write(writer)?;
1295 writer.write_all(&[0; 1])?;
1298 writer.write_all(&byte_utils::be64_to_array(self.pending_claim_requests.len() as u64))?;
1299 for (ref ancestor_claim_txid, claim_tx_data) in self.pending_claim_requests.iter() {
1300 ancestor_claim_txid.write(writer)?;
1301 claim_tx_data.write(writer)?;
1304 writer.write_all(&byte_utils::be64_to_array(self.claimable_outpoints.len() as u64))?;
1305 for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
1306 outp.write(writer)?;
1307 claim_and_height.0.write(writer)?;
1308 claim_and_height.1.write(writer)?;
1311 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
1312 for (ref target, ref events) in self.onchain_events_waiting_threshold_conf.iter() {
1313 writer.write_all(&byte_utils::be32_to_array(**target))?;
1314 writer.write_all(&byte_utils::be64_to_array(events.len() as u64))?;
1315 for ev in events.iter() {
1317 OnchainEvent::Claim { ref claim_request } => {
1318 writer.write_all(&[0; 1])?;
1319 claim_request.write(writer)?;
1321 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1322 writer.write_all(&[1; 1])?;
1323 htlc_update.0.write(writer)?;
1324 htlc_update.1.write(writer)?;
1326 OnchainEvent::ContentiousOutpoint { ref outpoint, ref input_material } => {
1327 writer.write_all(&[2; 1])?;
1328 outpoint.write(writer)?;
1329 input_material.write(writer)?;
1338 /// Writes this monitor into the given writer, suitable for writing to disk.
1340 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
1341 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
1342 /// the "reorg path" (ie not just starting at the same height but starting at the highest
1343 /// common block that appears on your best chain as well as on the chain which contains the
1344 /// last block hash returned) upon deserializing the object!
1345 pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
1346 self.write(writer, true)
1349 /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
1351 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
1352 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
1353 /// the "reorg path" (ie not just starting at the same height but starting at the highest
1354 /// common block that appears on your best chain as well as on the chain which contains the
1355 /// last block hash returned) upon deserializing the object!
1356 pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
1357 self.write(writer, false)
1360 /// Can only fail if idx is < get_min_seen_secret
1361 pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
1362 for i in 0..self.old_secrets.len() {
1363 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
1364 return Some(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
1367 assert!(idx < self.get_min_seen_secret());
1371 pub(super) fn get_min_seen_secret(&self) -> u64 {
1372 //TODO This can be optimized?
1373 let mut min = 1 << 48;
1374 for &(_, idx) in self.old_secrets.iter() {
1382 pub(super) fn get_cur_remote_commitment_number(&self) -> u64 {
1383 self.current_remote_commitment_number
1386 pub(super) fn get_cur_local_commitment_number(&self) -> u64 {
1387 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1388 0xffff_ffff_ffff - ((((local_tx.tx.without_valid_witness().input[0].sequence as u64 & 0xffffff) << 3*8) | (local_tx.tx.without_valid_witness().lock_time as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor)
1389 } else { 0xffff_ffff_ffff }
1392 /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
1393 /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1394 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1395 /// HTLC-Success/HTLC-Timeout transactions.
1396 /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1397 /// revoked remote commitment tx
1398 fn check_spend_remote_transaction(&mut self, tx: &Transaction, height: u32, fee_estimator: &FeeEstimator) -> (Vec<Transaction>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>) {
1399 // Most secp and related errors trying to create keys means we have no hope of constructing
1400 // a spend transaction...so we return no transactions to broadcast
1401 let mut txn_to_broadcast = Vec::new();
1402 let mut watch_outputs = Vec::new();
1403 let mut spendable_outputs = Vec::new();
1405 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1406 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
1408 macro_rules! ignore_error {
1409 ( $thing : expr ) => {
1412 Err(_) => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
1417 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);
1418 if commitment_number >= self.get_min_seen_secret() {
1419 let secret = self.get_secret(commitment_number).unwrap();
1420 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1421 let (revocation_pubkey, b_htlc_key, local_payment_key) = match self.key_storage {
1422 Storage::Local { ref revocation_base_key, ref htlc_base_key, ref payment_base_key, .. } => {
1423 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1424 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1425 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))),
1426 Some(ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &payment_base_key))))
1428 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1429 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1430 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
1431 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)),
1435 let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.their_delayed_payment_base_key.unwrap()));
1436 let a_htlc_key = match self.their_htlc_base_key {
1437 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
1438 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &their_htlc_base_key)),
1441 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
1442 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1444 let local_payment_p2wpkh = if let Some(payment_key) = local_payment_key {
1445 // Note that the Network here is ignored as we immediately drop the address for the
1446 // script_pubkey version.
1447 let payment_hash160 = Hash160::hash(&PublicKey::from_secret_key(&self.secp_ctx, &payment_key).serialize());
1448 Some(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_hash160[..]).into_script())
1451 let mut total_value = 0;
1452 let mut inputs = Vec::new();
1453 let mut inputs_info = Vec::new();
1454 let mut inputs_desc = Vec::new();
1456 for (idx, outp) in tx.output.iter().enumerate() {
1457 if outp.script_pubkey == revokeable_p2wsh {
1459 previous_output: BitcoinOutPoint {
1460 txid: commitment_txid,
1463 script_sig: Script::new(),
1464 sequence: 0xfffffffd,
1465 witness: Vec::new(),
1467 inputs_desc.push(InputDescriptors::RevokedOutput);
1468 inputs_info.push((None, outp.value, self.our_to_self_delay as u32));
1469 total_value += outp.value;
1470 } else if Some(&outp.script_pubkey) == local_payment_p2wpkh.as_ref() {
1471 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1472 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1473 key: local_payment_key.unwrap(),
1474 output: outp.clone(),
1479 macro_rules! sign_input {
1480 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
1482 let (sig, redeemscript, revocation_key) = match self.key_storage {
1483 Storage::Local { ref revocation_base_key, .. } => {
1484 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
1485 let htlc = &per_commitment_option.unwrap()[$htlc_idx.unwrap()].0;
1486 chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
1488 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]);
1489 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1490 (self.secp_ctx.sign(&sighash, &revocation_key), redeemscript, revocation_key)
1492 Storage::Watchtower { .. } => {
1496 $input.witness.push(sig.serialize_der().to_vec());
1497 $input.witness[0].push(SigHashType::All as u8);
1498 if $htlc_idx.is_none() {
1499 $input.witness.push(vec!(1));
1501 $input.witness.push(revocation_pubkey.serialize().to_vec());
1503 $input.witness.push(redeemscript.clone().into_bytes());
1504 (redeemscript, revocation_key)
1509 if let Some(ref per_commitment_data) = per_commitment_option {
1510 inputs.reserve_exact(per_commitment_data.len());
1512 for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1513 if let Some(transaction_output_index) = htlc.transaction_output_index {
1514 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1515 if transaction_output_index as usize >= tx.output.len() ||
1516 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1517 tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1518 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
1521 previous_output: BitcoinOutPoint {
1522 txid: commitment_txid,
1523 vout: transaction_output_index,
1525 script_sig: Script::new(),
1526 sequence: 0xfffffffd,
1527 witness: Vec::new(),
1529 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1531 inputs_desc.push(if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC });
1532 inputs_info.push((Some(idx), tx.output[transaction_output_index as usize].value, htlc.cltv_expiry));
1533 total_value += tx.output[transaction_output_index as usize].value;
1535 let mut single_htlc_tx = Transaction {
1539 output: vec!(TxOut {
1540 script_pubkey: self.destination_script.clone(),
1541 value: htlc.amount_msat / 1000,
1544 let predicted_weight = single_htlc_tx.get_weight() + Self::get_witnesses_weight(&[if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC }]);
1545 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
1546 let mut used_feerate;
1547 if subtract_high_prio_fee!(self, fee_estimator, single_htlc_tx.output[0].value, predicted_weight, used_feerate) {
1548 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1549 let (redeemscript, revocation_key) = sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
1550 assert!(predicted_weight >= single_htlc_tx.get_weight());
1551 log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", single_htlc_tx.input[0].previous_output.txid, single_htlc_tx.input[0].previous_output.vout, height_timer);
1552 let mut per_input_material = HashMap::with_capacity(1);
1553 per_input_material.insert(single_htlc_tx.input[0].previous_output, InputMaterial::Revoked { script: redeemscript, pubkey: Some(revocation_pubkey), key: revocation_key, is_htlc: true, amount: htlc.amount_msat / 1000 });
1554 match self.claimable_outpoints.entry(single_htlc_tx.input[0].previous_output) {
1555 hash_map::Entry::Occupied(_) => {},
1556 hash_map::Entry::Vacant(entry) => { entry.insert((single_htlc_tx.txid(), height)); }
1558 match self.pending_claim_requests.entry(single_htlc_tx.txid()) {
1559 hash_map::Entry::Occupied(_) => {},
1560 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock: htlc.cltv_expiry, per_input_material }); }
1562 txn_to_broadcast.push(single_htlc_tx);
1569 if !inputs.is_empty() || !txn_to_broadcast.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
1570 // We're definitely a remote commitment transaction!
1571 log_trace!(self, "Got broadcast of revoked remote commitment transaction, generating general spend tx with {} inputs and {} other txn to broadcast", inputs.len(), txn_to_broadcast.len());
1572 watch_outputs.append(&mut tx.output.clone());
1573 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1575 macro_rules! check_htlc_fails {
1576 ($txid: expr, $commitment_tx: expr) => {
1577 if let Some(ref outpoints) = self.remote_claimable_outpoints.get($txid) {
1578 for &(ref htlc, ref source_option) in outpoints.iter() {
1579 if let &Some(ref source) = source_option {
1580 log_info!(self, "Failing HTLC with payment_hash {} from {} remote commitment tx due to broadcast of revoked remote commitment transaction, waiting for confirmation (at height {})", log_bytes!(htlc.payment_hash.0), $commitment_tx, height + ANTI_REORG_DELAY - 1);
1581 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1582 hash_map::Entry::Occupied(mut entry) => {
1583 let e = entry.get_mut();
1584 e.retain(|ref event| {
1586 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1587 return htlc_update.0 != **source
1592 e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1594 hash_map::Entry::Vacant(entry) => {
1595 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1603 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1604 if let &Some(ref txid) = current_remote_commitment_txid {
1605 check_htlc_fails!(txid, "current");
1607 if let &Some(ref txid) = prev_remote_commitment_txid {
1608 check_htlc_fails!(txid, "remote");
1611 // No need to check local commitment txn, symmetric HTLCSource must be present as per-htlc data on remote commitment tx
1613 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
1615 let outputs = vec!(TxOut {
1616 script_pubkey: self.destination_script.clone(),
1619 let mut spend_tx = Transaction {
1626 let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&inputs_desc[..]);
1628 let mut used_feerate;
1629 if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, used_feerate) {
1630 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs);
1633 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1635 let mut per_input_material = HashMap::with_capacity(spend_tx.input.len());
1636 let mut soonest_timelock = ::std::u32::MAX;
1637 for info in inputs_info.iter() {
1638 if info.2 <= soonest_timelock {
1639 soonest_timelock = info.2;
1642 let height_timer = Self::get_height_timer(height, soonest_timelock);
1643 let spend_txid = spend_tx.txid();
1644 for (input, info) in spend_tx.input.iter_mut().zip(inputs_info.iter()) {
1645 let (redeemscript, revocation_key) = sign_input!(sighash_parts, input, info.0, info.1);
1646 log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", input.previous_output.txid, input.previous_output.vout, height_timer);
1647 per_input_material.insert(input.previous_output, InputMaterial::Revoked { script: redeemscript, pubkey: if info.0.is_some() { Some(revocation_pubkey) } else { None }, key: revocation_key, is_htlc: if info.0.is_some() { true } else { false }, amount: info.1 });
1648 match self.claimable_outpoints.entry(input.previous_output) {
1649 hash_map::Entry::Occupied(_) => {},
1650 hash_map::Entry::Vacant(entry) => { entry.insert((spend_txid, height)); }
1653 match self.pending_claim_requests.entry(spend_txid) {
1654 hash_map::Entry::Occupied(_) => {},
1655 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock, per_input_material }); }
1658 assert!(predicted_weight >= spend_tx.get_weight());
1660 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1661 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1662 output: spend_tx.output[0].clone(),
1664 txn_to_broadcast.push(spend_tx);
1665 } else if let Some(per_commitment_data) = per_commitment_option {
1666 // While this isn't useful yet, there is a potential race where if a counterparty
1667 // revokes a state at the same time as the commitment transaction for that state is
1668 // confirmed, and the watchtower receives the block before the user, the user could
1669 // upload a new ChannelMonitor with the revocation secret but the watchtower has
1670 // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1671 // not being generated by the above conditional. Thus, to be safe, we go ahead and
1673 watch_outputs.append(&mut tx.output.clone());
1674 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1676 log_trace!(self, "Got broadcast of non-revoked remote commitment transaction {}", commitment_txid);
1678 macro_rules! check_htlc_fails {
1679 ($txid: expr, $commitment_tx: expr, $id: tt) => {
1680 if let Some(ref latest_outpoints) = self.remote_claimable_outpoints.get($txid) {
1681 $id: for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1682 if let &Some(ref source) = source_option {
1683 // Check if the HTLC is present in the commitment transaction that was
1684 // broadcast, but not if it was below the dust limit, which we should
1685 // fail backwards immediately as there is no way for us to learn the
1686 // payment_preimage.
1687 // Note that if the dust limit were allowed to change between
1688 // commitment transactions we'd want to be check whether *any*
1689 // broadcastable commitment transaction has the HTLC in it, but it
1690 // cannot currently change after channel initialization, so we don't
1692 for &(ref broadcast_htlc, ref broadcast_source) in per_commitment_data.iter() {
1693 if broadcast_htlc.transaction_output_index.is_some() && Some(source) == broadcast_source.as_ref() {
1697 log_trace!(self, "Failing HTLC with payment_hash {} from {} remote commitment tx due to broadcast of remote commitment transaction", log_bytes!(htlc.payment_hash.0), $commitment_tx);
1698 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1699 hash_map::Entry::Occupied(mut entry) => {
1700 let e = entry.get_mut();
1701 e.retain(|ref event| {
1703 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1704 return htlc_update.0 != **source
1709 e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1711 hash_map::Entry::Vacant(entry) => {
1712 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1720 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1721 if let &Some(ref txid) = current_remote_commitment_txid {
1722 check_htlc_fails!(txid, "current", 'current_loop);
1724 if let &Some(ref txid) = prev_remote_commitment_txid {
1725 check_htlc_fails!(txid, "previous", 'prev_loop);
1729 if let Some(revocation_points) = self.their_cur_revocation_points {
1730 let revocation_point_option =
1731 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1732 else if let Some(point) = revocation_points.2.as_ref() {
1733 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1735 if let Some(revocation_point) = revocation_point_option {
1736 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
1737 Storage::Local { ref revocation_base_key, ref htlc_base_key, .. } => {
1738 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
1739 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
1741 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1742 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
1743 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1746 let a_htlc_key = match self.their_htlc_base_key {
1747 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
1748 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
1751 for (idx, outp) in tx.output.iter().enumerate() {
1752 if outp.script_pubkey.is_v0_p2wpkh() {
1753 match self.key_storage {
1754 Storage::Local { ref payment_base_key, .. } => {
1755 if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &revocation_point, &payment_base_key) {
1756 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1757 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1759 output: outp.clone(),
1763 Storage::Watchtower { .. } => {}
1765 break; // Only to_remote ouput is claimable
1769 let mut total_value = 0;
1770 let mut inputs = Vec::new();
1771 let mut inputs_desc = Vec::new();
1772 let mut inputs_info = Vec::new();
1774 macro_rules! sign_input {
1775 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr) => {
1777 let (sig, redeemscript, htlc_key) = match self.key_storage {
1778 Storage::Local { ref htlc_base_key, .. } => {
1779 let htlc = &per_commitment_option.unwrap()[$input.sequence as usize].0;
1780 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1781 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]);
1782 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
1783 (self.secp_ctx.sign(&sighash, &htlc_key), redeemscript, htlc_key)
1785 Storage::Watchtower { .. } => {
1789 $input.witness.push(sig.serialize_der().to_vec());
1790 $input.witness[0].push(SigHashType::All as u8);
1791 $input.witness.push($preimage);
1792 $input.witness.push(redeemscript.clone().into_bytes());
1793 (redeemscript, htlc_key)
1798 for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1799 if let Some(transaction_output_index) = htlc.transaction_output_index {
1800 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1801 if transaction_output_index as usize >= tx.output.len() ||
1802 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1803 tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1804 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
1806 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
1809 previous_output: BitcoinOutPoint {
1810 txid: commitment_txid,
1811 vout: transaction_output_index,
1813 script_sig: Script::new(),
1814 sequence: idx as u32, // reset to 0xfffffffd in sign_input
1815 witness: Vec::new(),
1817 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1819 inputs_desc.push(if htlc.offered { InputDescriptors::OfferedHTLC } else { InputDescriptors::ReceivedHTLC });
1820 inputs_info.push((payment_preimage, tx.output[transaction_output_index as usize].value, htlc.cltv_expiry));
1821 total_value += tx.output[transaction_output_index as usize].value;
1823 let mut single_htlc_tx = Transaction {
1827 output: vec!(TxOut {
1828 script_pubkey: self.destination_script.clone(),
1829 value: htlc.amount_msat / 1000,
1832 let predicted_weight = single_htlc_tx.get_weight() + Self::get_witnesses_weight(&[if htlc.offered { InputDescriptors::OfferedHTLC } else { InputDescriptors::ReceivedHTLC }]);
1833 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
1834 let mut used_feerate;
1835 if subtract_high_prio_fee!(self, fee_estimator, single_htlc_tx.output[0].value, predicted_weight, used_feerate) {
1836 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1837 let (redeemscript, htlc_key) = sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.0.to_vec());
1838 assert!(predicted_weight >= single_htlc_tx.get_weight());
1839 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1840 outpoint: BitcoinOutPoint { txid: single_htlc_tx.txid(), vout: 0 },
1841 output: single_htlc_tx.output[0].clone(),
1843 log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", single_htlc_tx.input[0].previous_output.txid, single_htlc_tx.input[0].previous_output.vout, height_timer);
1844 let mut per_input_material = HashMap::with_capacity(1);
1845 per_input_material.insert(single_htlc_tx.input[0].previous_output, InputMaterial::RemoteHTLC { script: redeemscript, key: htlc_key, preimage: Some(*payment_preimage), amount: htlc.amount_msat / 1000, locktime: 0 });
1846 match self.claimable_outpoints.entry(single_htlc_tx.input[0].previous_output) {
1847 hash_map::Entry::Occupied(_) => {},
1848 hash_map::Entry::Vacant(entry) => { entry.insert((single_htlc_tx.txid(), height)); }
1850 match self.pending_claim_requests.entry(single_htlc_tx.txid()) {
1851 hash_map::Entry::Occupied(_) => {},
1852 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock: htlc.cltv_expiry, per_input_material}); }
1854 txn_to_broadcast.push(single_htlc_tx);
1860 // TODO: If the HTLC has already expired, potentially merge it with the
1861 // rest of the claim transaction, as above.
1863 previous_output: BitcoinOutPoint {
1864 txid: commitment_txid,
1865 vout: transaction_output_index,
1867 script_sig: Script::new(),
1868 sequence: idx as u32,
1869 witness: Vec::new(),
1871 let mut timeout_tx = Transaction {
1873 lock_time: htlc.cltv_expiry,
1875 output: vec!(TxOut {
1876 script_pubkey: self.destination_script.clone(),
1877 value: htlc.amount_msat / 1000,
1880 let predicted_weight = timeout_tx.get_weight() + Self::get_witnesses_weight(&[InputDescriptors::ReceivedHTLC]);
1881 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
1882 let mut used_feerate;
1883 if subtract_high_prio_fee!(self, fee_estimator, timeout_tx.output[0].value, predicted_weight, used_feerate) {
1884 let sighash_parts = bip143::SighashComponents::new(&timeout_tx);
1885 let (redeemscript, htlc_key) = sign_input!(sighash_parts, timeout_tx.input[0], htlc.amount_msat / 1000, vec![0]);
1886 assert!(predicted_weight >= timeout_tx.get_weight());
1887 //TODO: track SpendableOutputDescriptor
1888 log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", timeout_tx.input[0].previous_output.txid, timeout_tx.input[0].previous_output.vout, height_timer);
1889 let mut per_input_material = HashMap::with_capacity(1);
1890 per_input_material.insert(timeout_tx.input[0].previous_output, InputMaterial::RemoteHTLC { script : redeemscript, key: htlc_key, preimage: None, amount: htlc.amount_msat / 1000, locktime: htlc.cltv_expiry });
1891 match self.claimable_outpoints.entry(timeout_tx.input[0].previous_output) {
1892 hash_map::Entry::Occupied(_) => {},
1893 hash_map::Entry::Vacant(entry) => { entry.insert((timeout_tx.txid(), height)); }
1895 match self.pending_claim_requests.entry(timeout_tx.txid()) {
1896 hash_map::Entry::Occupied(_) => {},
1897 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock: htlc.cltv_expiry, per_input_material }); }
1900 txn_to_broadcast.push(timeout_tx);
1905 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
1907 let outputs = vec!(TxOut {
1908 script_pubkey: self.destination_script.clone(),
1911 let mut spend_tx = Transaction {
1918 let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&inputs_desc[..]);
1920 let mut used_feerate;
1921 if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, used_feerate) {
1922 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs);
1925 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1927 let mut per_input_material = HashMap::with_capacity(spend_tx.input.len());
1928 let mut soonest_timelock = ::std::u32::MAX;
1929 for info in inputs_info.iter() {
1930 if info.2 <= soonest_timelock {
1931 soonest_timelock = info.2;
1934 let height_timer = Self::get_height_timer(height, soonest_timelock);
1935 let spend_txid = spend_tx.txid();
1936 for (input, info) in spend_tx.input.iter_mut().zip(inputs_info.iter()) {
1937 let (redeemscript, htlc_key) = sign_input!(sighash_parts, input, info.1, (info.0).0.to_vec());
1938 log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", input.previous_output.txid, input.previous_output.vout, height_timer);
1939 per_input_material.insert(input.previous_output, InputMaterial::RemoteHTLC { script: redeemscript, key: htlc_key, preimage: Some(*(info.0)), amount: info.1, locktime: 0});
1940 match self.claimable_outpoints.entry(input.previous_output) {
1941 hash_map::Entry::Occupied(_) => {},
1942 hash_map::Entry::Vacant(entry) => { entry.insert((spend_txid, height)); }
1945 match self.pending_claim_requests.entry(spend_txid) {
1946 hash_map::Entry::Occupied(_) => {},
1947 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock, per_input_material }); }
1949 assert!(predicted_weight >= spend_tx.get_weight());
1950 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1951 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1952 output: spend_tx.output[0].clone(),
1954 txn_to_broadcast.push(spend_tx);
1957 } else if let Some((ref to_remote_rescue, ref local_key)) = self.to_remote_rescue {
1958 for (idx, outp) in tx.output.iter().enumerate() {
1959 if to_remote_rescue == &outp.script_pubkey {
1960 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1961 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1962 key: local_key.clone(),
1963 output: outp.clone(),
1969 (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
1972 /// Attempts to claim a remote HTLC-Success/HTLC-Timeout's outputs using the revocation key
1973 fn check_spend_remote_htlc(&mut self, tx: &Transaction, commitment_number: u64, height: u32, fee_estimator: &FeeEstimator) -> (Option<Transaction>, Option<SpendableOutputDescriptor>) {
1974 //TODO: send back new outputs to guarantee pending_claim_request consistency
1975 if tx.input.len() != 1 || tx.output.len() != 1 {
1979 macro_rules! ignore_error {
1980 ( $thing : expr ) => {
1983 Err(_) => return (None, None)
1988 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (None, None); };
1989 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1990 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1991 let revocation_pubkey = match self.key_storage {
1992 Storage::Local { ref revocation_base_key, .. } => {
1993 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key)))
1995 Storage::Watchtower { ref revocation_base_key, .. } => {
1996 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key))
1999 let delayed_key = match self.their_delayed_payment_base_key {
2000 None => return (None, None),
2001 Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
2003 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
2004 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
2005 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
2007 let mut inputs = Vec::new();
2010 if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout
2012 previous_output: BitcoinOutPoint {
2016 script_sig: Script::new(),
2017 sequence: 0xfffffffd,
2018 witness: Vec::new(),
2020 amount = tx.output[0].value;
2023 if !inputs.is_empty() {
2024 let outputs = vec!(TxOut {
2025 script_pubkey: self.destination_script.clone(),
2029 let mut spend_tx = Transaction {
2035 let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&[InputDescriptors::RevokedOutput]);
2036 let mut used_feerate;
2037 if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, used_feerate) {
2038 return (None, None);
2041 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
2043 let (sig, revocation_key) = match self.key_storage {
2044 Storage::Local { ref revocation_base_key, .. } => {
2045 let sighash = hash_to_message!(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]);
2046 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
2047 (self.secp_ctx.sign(&sighash, &revocation_key), revocation_key)
2049 Storage::Watchtower { .. } => {
2053 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
2054 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
2055 spend_tx.input[0].witness.push(vec!(1));
2056 spend_tx.input[0].witness.push(redeemscript.clone().into_bytes());
2058 assert!(predicted_weight >= spend_tx.get_weight());
2059 let outpoint = BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 };
2060 let output = spend_tx.output[0].clone();
2061 let height_timer = Self::get_height_timer(height, self.their_to_self_delay.unwrap() as u32); // We can safely unwrap given we are past channel opening
2062 log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", spend_tx.input[0].previous_output.txid, spend_tx.input[0].previous_output.vout, height_timer);
2063 let mut per_input_material = HashMap::with_capacity(1);
2064 per_input_material.insert(spend_tx.input[0].previous_output, InputMaterial::Revoked { script: redeemscript, pubkey: None, key: revocation_key, is_htlc: false, amount: tx.output[0].value });
2065 match self.claimable_outpoints.entry(spend_tx.input[0].previous_output) {
2066 hash_map::Entry::Occupied(_) => {},
2067 hash_map::Entry::Vacant(entry) => { entry.insert((spend_tx.txid(), height)); }
2069 match self.pending_claim_requests.entry(spend_tx.txid()) {
2070 hash_map::Entry::Occupied(_) => {},
2071 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock: height + self.our_to_self_delay as u32, per_input_material }); }
2073 (Some(spend_tx), Some(SpendableOutputDescriptor::StaticOutput { outpoint, output }))
2074 } else { (None, None) }
2077 fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx, delayed_payment_base_key: &SecretKey, height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, Vec<TxOut>, Vec<(Sha256dHash, ClaimTxBumpMaterial)>) {
2078 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
2079 let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
2080 let mut watch_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
2081 let mut pending_claims = Vec::with_capacity(local_tx.htlc_outputs.len());
2083 macro_rules! add_dynamic_output {
2084 ($father_tx: expr, $vout: expr) => {
2085 if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, &local_tx.per_commitment_point, delayed_payment_base_key) {
2086 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WSH {
2087 outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
2088 key: local_delayedkey,
2089 witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
2090 to_self_delay: self.our_to_self_delay,
2091 output: $father_tx.output[$vout as usize].clone(),
2097 let redeemscript = chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.their_to_self_delay.unwrap(), &local_tx.delayed_payment_key);
2098 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
2099 for (idx, output) in local_tx.tx.without_valid_witness().output.iter().enumerate() {
2100 if output.script_pubkey == revokeable_p2wsh {
2101 add_dynamic_output!(local_tx.tx.without_valid_witness(), idx as u32);
2106 if let &Storage::Local { ref htlc_base_key, .. } = &self.key_storage {
2107 for &(ref htlc, ref sigs, _) in local_tx.htlc_outputs.iter() {
2108 if let Some(transaction_output_index) = htlc.transaction_output_index {
2109 if let &Some(ref their_sig) = sigs {
2111 log_trace!(self, "Broadcasting HTLC-Timeout transaction against local commitment transactions");
2112 let mut htlc_timeout_tx = chan_utils::build_htlc_transaction(&local_tx.txid, local_tx.feerate_per_kw, self.their_to_self_delay.unwrap(), htlc, &local_tx.delayed_payment_key, &local_tx.revocation_key);
2113 let (our_sig, htlc_script) = match
2114 chan_utils::sign_htlc_transaction(&mut htlc_timeout_tx, their_sig, &None, htlc, &local_tx.a_htlc_key, &local_tx.b_htlc_key, &local_tx.revocation_key, &local_tx.per_commitment_point, htlc_base_key, &self.secp_ctx) {
2119 add_dynamic_output!(htlc_timeout_tx, 0);
2120 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
2121 let mut per_input_material = HashMap::with_capacity(1);
2122 per_input_material.insert(htlc_timeout_tx.input[0].previous_output, InputMaterial::LocalHTLC { script: htlc_script, sigs: (*their_sig, our_sig), preimage: None, amount: htlc.amount_msat / 1000});
2123 //TODO: with option_simplified_commitment track outpoint too
2124 log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", htlc_timeout_tx.input[0].previous_output.vout, htlc_timeout_tx.input[0].previous_output.txid, height_timer);
2125 pending_claims.push((htlc_timeout_tx.txid(), ClaimTxBumpMaterial { height_timer, feerate_previous: 0, soonest_timelock: htlc.cltv_expiry, per_input_material }));
2126 res.push(htlc_timeout_tx);
2128 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2129 log_trace!(self, "Broadcasting HTLC-Success transaction against local commitment transactions");
2130 let mut htlc_success_tx = chan_utils::build_htlc_transaction(&local_tx.txid, local_tx.feerate_per_kw, self.their_to_self_delay.unwrap(), htlc, &local_tx.delayed_payment_key, &local_tx.revocation_key);
2131 let (our_sig, htlc_script) = match
2132 chan_utils::sign_htlc_transaction(&mut htlc_success_tx, their_sig, &Some(*payment_preimage), htlc, &local_tx.a_htlc_key, &local_tx.b_htlc_key, &local_tx.revocation_key, &local_tx.per_commitment_point, htlc_base_key, &self.secp_ctx) {
2137 add_dynamic_output!(htlc_success_tx, 0);
2138 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
2139 let mut per_input_material = HashMap::with_capacity(1);
2140 per_input_material.insert(htlc_success_tx.input[0].previous_output, InputMaterial::LocalHTLC { script: htlc_script, sigs: (*their_sig, our_sig), preimage: Some(*payment_preimage), amount: htlc.amount_msat / 1000});
2141 //TODO: with option_simplified_commitment track outpoint too
2142 log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", htlc_success_tx.input[0].previous_output.vout, htlc_success_tx.input[0].previous_output.txid, height_timer);
2143 pending_claims.push((htlc_success_tx.txid(), ClaimTxBumpMaterial { height_timer, feerate_previous: 0, soonest_timelock: htlc.cltv_expiry, per_input_material }));
2144 res.push(htlc_success_tx);
2147 watch_outputs.push(local_tx.tx.without_valid_witness().output[transaction_output_index as usize].clone());
2148 } else { panic!("Should have sigs for non-dust local tx outputs!") }
2153 (res, spendable_outputs, watch_outputs, pending_claims)
2156 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
2157 /// revoked using data in local_claimable_outpoints.
2158 /// Should not be used if check_spend_revoked_transaction succeeds.
2159 fn check_spend_local_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, (Sha256dHash, Vec<TxOut>)) {
2160 let commitment_txid = tx.txid();
2161 let mut local_txn = Vec::new();
2162 let mut spendable_outputs = Vec::new();
2163 let mut watch_outputs = Vec::new();
2165 macro_rules! wait_threshold_conf {
2166 ($height: expr, $source: expr, $commitment_tx: expr, $payment_hash: expr) => {
2167 log_trace!(self, "Failing HTLC with payment_hash {} from {} local commitment tx due to broadcast of transaction, waiting confirmation (at height{})", log_bytes!($payment_hash.0), $commitment_tx, height + ANTI_REORG_DELAY - 1);
2168 match self.onchain_events_waiting_threshold_conf.entry($height + ANTI_REORG_DELAY - 1) {
2169 hash_map::Entry::Occupied(mut entry) => {
2170 let e = entry.get_mut();
2171 e.retain(|ref event| {
2173 OnchainEvent::HTLCUpdate { ref htlc_update } => {
2174 return htlc_update.0 != $source
2179 e.push(OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)});
2181 hash_map::Entry::Vacant(entry) => {
2182 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)}]);
2188 macro_rules! append_onchain_update {
2189 ($updates: expr) => {
2190 local_txn.append(&mut $updates.0);
2191 spendable_outputs.append(&mut $updates.1);
2192 watch_outputs.append(&mut $updates.2);
2193 for claim in $updates.3 {
2194 match self.pending_claim_requests.entry(claim.0) {
2195 hash_map::Entry::Occupied(_) => {},
2196 hash_map::Entry::Vacant(entry) => { entry.insert(claim.1); }
2202 // HTLCs set may differ between last and previous local commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
2203 let mut is_local_tx = false;
2205 if let &mut Some(ref mut local_tx) = &mut self.current_local_signed_commitment_tx {
2206 if local_tx.txid == commitment_txid {
2207 match self.key_storage {
2208 Storage::Local { ref funding_key, .. } => {
2209 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2215 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
2216 if local_tx.txid == commitment_txid {
2218 log_trace!(self, "Got latest local commitment tx broadcast, searching for available HTLCs to claim");
2219 assert!(local_tx.tx.has_local_sig());
2220 match self.key_storage {
2221 Storage::Local { ref delayed_payment_base_key, .. } => {
2222 append_onchain_update!(self.broadcast_by_local_state(local_tx, delayed_payment_base_key, height));
2224 Storage::Watchtower { .. } => { }
2228 if let &mut Some(ref mut local_tx) = &mut self.prev_local_signed_commitment_tx {
2229 if local_tx.txid == commitment_txid {
2230 match self.key_storage {
2231 Storage::Local { ref funding_key, .. } => {
2232 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2238 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
2239 if local_tx.txid == commitment_txid {
2241 log_trace!(self, "Got previous local commitment tx broadcast, searching for available HTLCs to claim");
2242 assert!(local_tx.tx.has_local_sig());
2243 match self.key_storage {
2244 Storage::Local { ref delayed_payment_base_key, .. } => {
2245 append_onchain_update!(self.broadcast_by_local_state(local_tx, delayed_payment_base_key, height));
2247 Storage::Watchtower { .. } => { }
2252 macro_rules! fail_dust_htlcs_after_threshold_conf {
2253 ($local_tx: expr) => {
2254 for &(ref htlc, _, ref source) in &$local_tx.htlc_outputs {
2255 if htlc.transaction_output_index.is_none() {
2256 if let &Some(ref source) = source {
2257 wait_threshold_conf!(height, source.clone(), "lastest", htlc.payment_hash.clone());
2265 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
2266 fail_dust_htlcs_after_threshold_conf!(local_tx);
2268 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
2269 fail_dust_htlcs_after_threshold_conf!(local_tx);
2273 (local_txn, spendable_outputs, (commitment_txid, watch_outputs))
2276 /// Generate a spendable output event when closing_transaction get registered onchain.
2277 fn check_spend_closing_transaction(&self, tx: &Transaction) -> Option<SpendableOutputDescriptor> {
2278 if tx.input[0].sequence == 0xFFFFFFFF && !tx.input[0].witness.is_empty() && tx.input[0].witness.last().unwrap().len() == 71 {
2279 match self.key_storage {
2280 Storage::Local { ref shutdown_pubkey, .. } => {
2281 let our_channel_close_key_hash = Hash160::hash(&shutdown_pubkey.serialize());
2282 let shutdown_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
2283 for (idx, output) in tx.output.iter().enumerate() {
2284 if shutdown_script == output.script_pubkey {
2285 return Some(SpendableOutputDescriptor::StaticOutput {
2286 outpoint: BitcoinOutPoint { txid: tx.txid(), vout: idx as u32 },
2287 output: output.clone(),
2292 Storage::Watchtower { .. } => {
2293 //TODO: we need to ensure an offline client will generate the event when it
2294 // comes back online after only the watchtower saw the transaction
2301 /// Used by ChannelManager deserialization to broadcast the latest local state if its copy of
2302 /// the Channel was out-of-date. You may use it to get a broadcastable local toxic tx in case of
2303 /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our remote side knows
2304 /// a higher revocation secret than the local commitment number we are aware of. Broadcasting these
2305 /// transactions are UNSAFE, as they allow remote side to punish you. Nevertheless you may want to
2306 /// broadcast them if remote don't close channel with his higher commitment transaction after a
2307 /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
2308 /// out-of-band the other node operator to coordinate with him if option is available to you.
2309 /// In any-case, choice is up to the user.
2310 pub fn get_latest_local_commitment_txn(&mut self) -> Vec<Transaction> {
2311 log_trace!(self, "Getting signed latest local commitment transaction!");
2312 if let &mut Some(ref mut local_tx) = &mut self.current_local_signed_commitment_tx {
2313 match self.key_storage {
2314 Storage::Local { ref funding_key, .. } => {
2315 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2320 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
2321 let mut res = vec![local_tx.tx.with_valid_witness().clone()];
2322 match self.key_storage {
2323 Storage::Local { ref delayed_payment_base_key, .. } => {
2324 res.append(&mut self.broadcast_by_local_state(local_tx, delayed_payment_base_key, 0).0);
2325 // 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.
2326 // The data will be re-generated and tracked in check_spend_local_transaction if we get a confirmation.
2328 _ => panic!("Can only broadcast by local channelmonitor"),
2336 fn block_connected(&mut self, txn_matched: &[&Transaction], height: u32, block_hash: &Sha256dHash, broadcaster: &BroadcasterInterface, fee_estimator: &FeeEstimator)-> (Vec<(Sha256dHash, Vec<TxOut>)>, Vec<SpendableOutputDescriptor>, Vec<(HTLCSource, Option<PaymentPreimage>, PaymentHash)>) {
2337 log_trace!(self, "Block {} at height {} connected with {} txn matched", block_hash, height, txn_matched.len());
2338 let mut watch_outputs = Vec::new();
2339 let mut spendable_outputs = Vec::new();
2340 let mut htlc_updated = Vec::new();
2341 let mut bump_candidates = HashSet::new();
2342 for tx in txn_matched {
2343 if tx.input.len() == 1 {
2344 // Assuming our keys were not leaked (in which case we're screwed no matter what),
2345 // commitment transactions and HTLC transactions will all only ever have one input,
2346 // which is an easy way to filter out any potential non-matching txn for lazy
2348 let prevout = &tx.input[0].previous_output;
2349 let mut txn: Vec<Transaction> = Vec::new();
2350 let funding_txo = match self.key_storage {
2351 Storage::Local { ref funding_info, .. } => {
2352 funding_info.clone()
2354 Storage::Watchtower { .. } => {
2358 if funding_txo.is_none() || (prevout.txid == funding_txo.as_ref().unwrap().0.txid && prevout.vout == funding_txo.as_ref().unwrap().0.index as u32) {
2359 if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
2360 let (remote_txn, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(&tx, height, fee_estimator);
2362 spendable_outputs.append(&mut spendable_output);
2363 if !new_outputs.1.is_empty() {
2364 watch_outputs.push(new_outputs);
2367 let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(&tx, height);
2368 spendable_outputs.append(&mut spendable_output);
2370 if !new_outputs.1.is_empty() {
2371 watch_outputs.push(new_outputs);
2375 if !funding_txo.is_none() && txn.is_empty() {
2376 if let Some(spendable_output) = self.check_spend_closing_transaction(&tx) {
2377 spendable_outputs.push(spendable_output);
2381 if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
2382 let (tx, spendable_output) = self.check_spend_remote_htlc(&tx, commitment_number, height, fee_estimator);
2383 if let Some(tx) = tx {
2386 if let Some(spendable_output) = spendable_output {
2387 spendable_outputs.push(spendable_output);
2391 for tx in txn.iter() {
2392 log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
2393 broadcaster.broadcast_transaction(tx);
2396 // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2397 // can also be resolved in a few other ways which can have more than one output. Thus,
2398 // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2399 let mut updated = self.is_resolving_htlc_output(&tx, height);
2400 if updated.len() > 0 {
2401 htlc_updated.append(&mut updated);
2404 // Scan all input to verify is one of the outpoint spent is of interest for us
2405 let mut claimed_outputs_material = Vec::new();
2406 for inp in &tx.input {
2407 if let Some(first_claim_txid_height) = self.claimable_outpoints.get(&inp.previous_output) {
2408 // If outpoint has claim request pending on it...
2409 if let Some(claim_material) = self.pending_claim_requests.get_mut(&first_claim_txid_height.0) {
2410 //... we need to verify equality between transaction outpoints and claim request
2411 // outpoints to know if transaction is the original claim or a bumped one issued
2413 let mut set_equality = true;
2414 if claim_material.per_input_material.len() != tx.input.len() {
2415 set_equality = false;
2417 for (claim_inp, tx_inp) in claim_material.per_input_material.keys().zip(tx.input.iter()) {
2418 if *claim_inp != tx_inp.previous_output {
2419 set_equality = false;
2424 macro_rules! clean_claim_request_after_safety_delay {
2426 let new_event = OnchainEvent::Claim { claim_request: first_claim_txid_height.0.clone() };
2427 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2428 hash_map::Entry::Occupied(mut entry) => {
2429 if !entry.get().contains(&new_event) {
2430 entry.get_mut().push(new_event);
2433 hash_map::Entry::Vacant(entry) => {
2434 entry.insert(vec![new_event]);
2440 // If this is our transaction (or our counterparty spent all the outputs
2441 // before we could anyway with same inputs order than us), wait for
2442 // ANTI_REORG_DELAY and clean the RBF tracking map.
2444 clean_claim_request_after_safety_delay!();
2445 } else { // If false, generate new claim request with update outpoint set
2446 for input in tx.input.iter() {
2447 if let Some(input_material) = claim_material.per_input_material.remove(&input.previous_output) {
2448 claimed_outputs_material.push((input.previous_output, input_material));
2450 // If there are no outpoints left to claim in this request, drop it entirely after ANTI_REORG_DELAY.
2451 if claim_material.per_input_material.is_empty() {
2452 clean_claim_request_after_safety_delay!();
2455 //TODO: recompute soonest_timelock to avoid wasting a bit on fees
2456 bump_candidates.insert(first_claim_txid_height.0.clone());
2458 break; //No need to iterate further, either tx is our or their
2460 panic!("Inconsistencies between pending_claim_requests map and claimable_outpoints map");
2464 for (outpoint, input_material) in claimed_outputs_material.drain(..) {
2465 let new_event = OnchainEvent::ContentiousOutpoint { outpoint, input_material };
2466 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2467 hash_map::Entry::Occupied(mut entry) => {
2468 if !entry.get().contains(&new_event) {
2469 entry.get_mut().push(new_event);
2472 hash_map::Entry::Vacant(entry) => {
2473 entry.insert(vec![new_event]);
2478 let should_broadcast = if let Some(_) = self.current_local_signed_commitment_tx {
2479 self.would_broadcast_at_height(height)
2481 if let Some(ref mut cur_local_tx) = self.current_local_signed_commitment_tx {
2482 if should_broadcast {
2483 match self.key_storage {
2484 Storage::Local { ref funding_key, .. } => {
2485 cur_local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2491 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
2492 if should_broadcast {
2493 log_trace!(self, "Broadcast onchain {}", log_tx!(cur_local_tx.tx.with_valid_witness()));
2494 broadcaster.broadcast_transaction(&cur_local_tx.tx.with_valid_witness());
2495 match self.key_storage {
2496 Storage::Local { ref delayed_payment_base_key, .. } => {
2497 let (txs, mut spendable_output, new_outputs, _) = self.broadcast_by_local_state(&cur_local_tx, delayed_payment_base_key, height);
2498 spendable_outputs.append(&mut spendable_output);
2499 if !new_outputs.is_empty() {
2500 watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
2503 log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
2504 broadcaster.broadcast_transaction(&tx);
2507 Storage::Watchtower { .. } => { },
2511 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&height) {
2514 OnchainEvent::Claim { claim_request } => {
2515 // We may remove a whole set of claim outpoints here, as these one may have
2516 // been aggregated in a single tx and claimed so atomically
2517 if let Some(bump_material) = self.pending_claim_requests.remove(&claim_request) {
2518 for outpoint in bump_material.per_input_material.keys() {
2519 self.claimable_outpoints.remove(&outpoint);
2523 OnchainEvent::HTLCUpdate { htlc_update } => {
2524 log_trace!(self, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!((htlc_update.1).0));
2525 htlc_updated.push((htlc_update.0, None, htlc_update.1));
2527 OnchainEvent::ContentiousOutpoint { outpoint, .. } => {
2528 self.claimable_outpoints.remove(&outpoint);
2533 for (first_claim_txid, ref mut cached_claim_datas) in self.pending_claim_requests.iter_mut() {
2534 if cached_claim_datas.height_timer == height {
2535 bump_candidates.insert(first_claim_txid.clone());
2538 for first_claim_txid in bump_candidates.iter() {
2539 if let Some((new_timer, new_feerate)) = {
2540 if let Some(claim_material) = self.pending_claim_requests.get(first_claim_txid) {
2541 if let Some((new_timer, new_feerate, bump_tx)) = self.bump_claim_tx(height, &claim_material, fee_estimator) {
2542 broadcaster.broadcast_transaction(&bump_tx);
2543 Some((new_timer, new_feerate))
2545 } else { unreachable!(); }
2547 if let Some(claim_material) = self.pending_claim_requests.get_mut(first_claim_txid) {
2548 claim_material.height_timer = new_timer;
2549 claim_material.feerate_previous = new_feerate;
2550 } else { unreachable!(); }
2553 self.last_block_hash = block_hash.clone();
2554 (watch_outputs, spendable_outputs, htlc_updated)
2557 fn block_disconnected(&mut self, height: u32, block_hash: &Sha256dHash, broadcaster: &BroadcasterInterface, fee_estimator: &FeeEstimator) {
2558 log_trace!(self, "Block {} at height {} disconnected", block_hash, height);
2559 let mut bump_candidates = HashMap::new();
2560 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&(height + ANTI_REORG_DELAY - 1)) {
2562 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2563 //- our claim tx on a commitment tx output
2564 //- resurect outpoint back in its claimable set and regenerate tx
2567 OnchainEvent::ContentiousOutpoint { outpoint, input_material } => {
2568 if let Some(ancestor_claimable_txid) = self.claimable_outpoints.get(&outpoint) {
2569 if let Some(claim_material) = self.pending_claim_requests.get_mut(&ancestor_claimable_txid.0) {
2570 claim_material.per_input_material.insert(outpoint, input_material);
2571 // Using a HashMap guarantee us than if we have multiple outpoints getting
2572 // resurrected only one bump claim tx is going to be broadcast
2573 bump_candidates.insert(ancestor_claimable_txid.clone(), claim_material.clone());
2581 for (_, claim_material) in bump_candidates.iter_mut() {
2582 if let Some((new_timer, new_feerate, bump_tx)) = self.bump_claim_tx(height, &claim_material, fee_estimator) {
2583 claim_material.height_timer = new_timer;
2584 claim_material.feerate_previous = new_feerate;
2585 broadcaster.broadcast_transaction(&bump_tx);
2588 for (ancestor_claim_txid, claim_material) in bump_candidates.drain() {
2589 self.pending_claim_requests.insert(ancestor_claim_txid.0, claim_material);
2591 //TODO: if we implement cross-block aggregated claim transaction we need to refresh set of outpoints and regenerate tx but
2592 // right now if one of the outpoint get disconnected, just erase whole pending claim request.
2593 let mut remove_request = Vec::new();
2594 self.claimable_outpoints.retain(|_, ref v|
2596 remove_request.push(v.0.clone());
2599 for req in remove_request {
2600 self.pending_claim_requests.remove(&req);
2602 self.last_block_hash = block_hash.clone();
2605 pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
2606 // We need to consider all HTLCs which are:
2607 // * in any unrevoked remote commitment transaction, as they could broadcast said
2608 // transactions and we'd end up in a race, or
2609 // * are in our latest local commitment transaction, as this is the thing we will
2610 // broadcast if we go on-chain.
2611 // Note that we consider HTLCs which were below dust threshold here - while they don't
2612 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2613 // to the source, and if we don't fail the channel we will have to ensure that the next
2614 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2615 // easier to just fail the channel as this case should be rare enough anyway.
2616 macro_rules! scan_commitment {
2617 ($htlcs: expr, $local_tx: expr) => {
2618 for ref htlc in $htlcs {
2619 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2620 // chain with enough room to claim the HTLC without our counterparty being able to
2621 // time out the HTLC first.
2622 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2623 // concern is being able to claim the corresponding inbound HTLC (on another
2624 // channel) before it expires. In fact, we don't even really care if our
2625 // counterparty here claims such an outbound HTLC after it expired as long as we
2626 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2627 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2628 // we give ourselves a few blocks of headroom after expiration before going
2629 // on-chain for an expired HTLC.
2630 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2631 // from us until we've reached the point where we go on-chain with the
2632 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2633 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2634 // aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2635 // inbound_cltv == height + CLTV_CLAIM_BUFFER
2636 // outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2637 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2638 // CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2639 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2640 // The final, above, condition is checked for statically in channelmanager
2641 // with CHECK_CLTV_EXPIRY_SANITY_2.
2642 let htlc_outbound = $local_tx == htlc.offered;
2643 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2644 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2645 log_info!(self, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2652 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
2653 scan_commitment!(cur_local_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2656 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
2657 if let &Some(ref txid) = current_remote_commitment_txid {
2658 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2659 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2662 if let &Some(ref txid) = prev_remote_commitment_txid {
2663 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2664 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2672 /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a local
2673 /// or remote commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2674 fn is_resolving_htlc_output(&mut self, tx: &Transaction, height: u32) -> Vec<(HTLCSource, Option<PaymentPreimage>, PaymentHash)> {
2675 let mut htlc_updated = Vec::new();
2677 'outer_loop: for input in &tx.input {
2678 let mut payment_data = None;
2679 let revocation_sig_claim = (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && input.witness[1].len() == 33)
2680 || (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && input.witness[1].len() == 33);
2681 let accepted_preimage_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::AcceptedHTLC);
2682 let offered_preimage_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC);
2684 macro_rules! log_claim {
2685 ($tx_info: expr, $local_tx: expr, $htlc: expr, $source_avail: expr) => {
2686 // We found the output in question, but aren't failing it backwards
2687 // as we have no corresponding source and no valid remote commitment txid
2688 // to try a weak source binding with same-hash, same-value still-valid offered HTLC.
2689 // This implies either it is an inbound HTLC or an outbound HTLC on a revoked transaction.
2690 let outbound_htlc = $local_tx == $htlc.offered;
2691 if ($local_tx && revocation_sig_claim) ||
2692 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2693 log_error!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2694 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2695 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2696 if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2698 log_info!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2699 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2700 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2701 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2706 macro_rules! check_htlc_valid_remote {
2707 ($remote_txid: expr, $htlc_output: expr) => {
2708 if let &Some(txid) = $remote_txid {
2709 for &(ref pending_htlc, ref pending_source) in self.remote_claimable_outpoints.get(&txid).unwrap() {
2710 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2711 if let &Some(ref source) = pending_source {
2712 log_claim!("revoked remote commitment tx", false, pending_htlc, true);
2713 payment_data = Some(((**source).clone(), $htlc_output.payment_hash));
2722 macro_rules! scan_commitment {
2723 ($htlcs: expr, $tx_info: expr, $local_tx: expr) => {
2724 for (ref htlc_output, source_option) in $htlcs {
2725 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2726 if let Some(ref source) = source_option {
2727 log_claim!($tx_info, $local_tx, htlc_output, true);
2728 // We have a resolution of an HTLC either from one of our latest
2729 // local commitment transactions or an unrevoked remote commitment
2730 // transaction. This implies we either learned a preimage, the HTLC
2731 // has timed out, or we screwed up. In any case, we should now
2732 // resolve the source HTLC with the original sender.
2733 payment_data = Some(((*source).clone(), htlc_output.payment_hash));
2734 } else if !$local_tx {
2735 if let Storage::Local { ref current_remote_commitment_txid, .. } = self.key_storage {
2736 check_htlc_valid_remote!(current_remote_commitment_txid, htlc_output);
2738 if payment_data.is_none() {
2739 if let Storage::Local { ref prev_remote_commitment_txid, .. } = self.key_storage {
2740 check_htlc_valid_remote!(prev_remote_commitment_txid, htlc_output);
2744 if payment_data.is_none() {
2745 log_claim!($tx_info, $local_tx, htlc_output, false);
2746 continue 'outer_loop;
2753 if let Some(ref current_local_signed_commitment_tx) = self.current_local_signed_commitment_tx {
2754 if input.previous_output.txid == current_local_signed_commitment_tx.txid {
2755 scan_commitment!(current_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2756 "our latest local commitment tx", true);
2759 if let Some(ref prev_local_signed_commitment_tx) = self.prev_local_signed_commitment_tx {
2760 if input.previous_output.txid == prev_local_signed_commitment_tx.txid {
2761 scan_commitment!(prev_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2762 "our previous local commitment tx", true);
2765 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(&input.previous_output.txid) {
2766 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
2767 "remote commitment tx", false);
2770 // Check that scan_commitment, above, decided there is some source worth relaying an
2771 // HTLC resolution backwards to and figure out whether we learned a preimage from it.
2772 if let Some((source, payment_hash)) = payment_data {
2773 let mut payment_preimage = PaymentPreimage([0; 32]);
2774 if accepted_preimage_claim {
2775 payment_preimage.0.copy_from_slice(&input.witness[3]);
2776 htlc_updated.push((source, Some(payment_preimage), payment_hash));
2777 } else if offered_preimage_claim {
2778 payment_preimage.0.copy_from_slice(&input.witness[1]);
2779 htlc_updated.push((source, Some(payment_preimage), payment_hash));
2781 log_info!(self, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height{})", log_bytes!(payment_hash.0), height + ANTI_REORG_DELAY - 1);
2782 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2783 hash_map::Entry::Occupied(mut entry) => {
2784 let e = entry.get_mut();
2785 e.retain(|ref event| {
2787 OnchainEvent::HTLCUpdate { ref htlc_update } => {
2788 return htlc_update.0 != source
2793 e.push(OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)});
2795 hash_map::Entry::Vacant(entry) => {
2796 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)}]);
2805 /// Lightning security model (i.e being able to redeem/timeout HTLC or penalize coutnerparty onchain) lays on the assumption of claim transactions getting confirmed before timelock expiration
2806 /// (CSV or CLTV following cases). In case of high-fee spikes, claim tx may stuck in the mempool, so you need to bump its feerate quickly using Replace-By-Fee or Child-Pay-For-Parent.
2807 fn bump_claim_tx(&self, height: u32, cached_claim_datas: &ClaimTxBumpMaterial, fee_estimator: &FeeEstimator) -> Option<(u32, u64, Transaction)> {
2808 if cached_claim_datas.per_input_material.len() == 0 { return None } // But don't prune pending claiming request yet, we may have to resurrect HTLCs
2809 let mut inputs = Vec::new();
2810 for outp in cached_claim_datas.per_input_material.keys() {
2812 previous_output: *outp,
2813 script_sig: Script::new(),
2814 sequence: 0xfffffffd,
2815 witness: Vec::new(),
2818 let mut bumped_tx = Transaction {
2822 output: vec![TxOut {
2823 script_pubkey: self.destination_script.clone(),
2828 macro_rules! RBF_bump {
2829 ($amount: expr, $old_feerate: expr, $fee_estimator: expr, $predicted_weight: expr) => {
2831 let mut used_feerate;
2832 // If old feerate inferior to actual one given back by Fee Estimator, use it to compute new fee...
2833 let new_fee = if $old_feerate < $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority) {
2834 let mut value = $amount;
2835 if subtract_high_prio_fee!(self, $fee_estimator, value, $predicted_weight, used_feerate) {
2836 // Overflow check is done in subtract_high_prio_fee
2839 log_trace!(self, "Can't new-estimation bump new claiming tx, amount {} is too small", $amount);
2842 // ...else just increase the previous feerate by 25% (because that's a nice number)
2844 let fee = $old_feerate * $predicted_weight / 750;
2846 log_trace!(self, "Can't 25% bump new claiming tx, amount {} is too small", $amount);
2852 let previous_fee = $old_feerate * $predicted_weight / 1000;
2853 let min_relay_fee = MIN_RELAY_FEE_SAT_PER_1000_WEIGHT * $predicted_weight / 1000;
2854 // BIP 125 Opt-in Full Replace-by-Fee Signaling
2855 // * 3. The replacement transaction pays an absolute fee of at least the sum paid by the original transactions.
2856 // * 4. The replacement transaction must also pay for its own bandwidth at or above the rate set by the node's minimum relay fee setting.
2857 let new_fee = if new_fee < previous_fee + min_relay_fee {
2858 new_fee + previous_fee + min_relay_fee - new_fee
2862 Some((new_fee, new_fee * 1000 / $predicted_weight))
2867 let new_timer = Self::get_height_timer(height, cached_claim_datas.soonest_timelock);
2868 let mut inputs_witnesses_weight = 0;
2870 for per_outp_material in cached_claim_datas.per_input_material.values() {
2871 match per_outp_material {
2872 &InputMaterial::Revoked { ref script, ref is_htlc, ref amount, .. } => {
2873 log_trace!(self, "Is HLTC ? {}", is_htlc);
2874 inputs_witnesses_weight += Self::get_witnesses_weight(if !is_htlc { &[InputDescriptors::RevokedOutput] } else if HTLCType::scriptlen_to_htlctype(script.len()) == Some(HTLCType::OfferedHTLC) { &[InputDescriptors::RevokedOfferedHTLC] } else if HTLCType::scriptlen_to_htlctype(script.len()) == Some(HTLCType::AcceptedHTLC) { &[InputDescriptors::RevokedReceivedHTLC] } else { unreachable!() });
2877 &InputMaterial::RemoteHTLC { ref preimage, ref amount, .. } => {
2878 inputs_witnesses_weight += Self::get_witnesses_weight(if preimage.is_some() { &[InputDescriptors::OfferedHTLC] } else { &[InputDescriptors::ReceivedHTLC] });
2881 &InputMaterial::LocalHTLC { .. } => { return None; }
2885 let predicted_weight = bumped_tx.get_weight() + inputs_witnesses_weight;
2887 if let Some((new_fee, feerate)) = RBF_bump!(amt, cached_claim_datas.feerate_previous, fee_estimator, predicted_weight as u64) {
2888 // If new computed fee is superior at the whole claimable amount burn all in fees
2890 bumped_tx.output[0].value = 0;
2892 bumped_tx.output[0].value = amt - new_fee;
2894 new_feerate = feerate;
2898 assert!(new_feerate != 0);
2900 for (i, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() {
2901 match per_outp_material {
2902 &InputMaterial::Revoked { ref script, ref pubkey, ref key, ref is_htlc, ref amount } => {
2903 let sighash_parts = bip143::SighashComponents::new(&bumped_tx);
2904 let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &script, *amount)[..]);
2905 let sig = self.secp_ctx.sign(&sighash, &key);
2906 bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
2907 bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
2909 bumped_tx.input[i].witness.push(pubkey.unwrap().clone().serialize().to_vec());
2911 bumped_tx.input[i].witness.push(vec!(1));
2913 bumped_tx.input[i].witness.push(script.clone().into_bytes());
2914 log_trace!(self, "Going to broadcast bumped Penalty Transaction {} claiming revoked {} output {} from {} with new feerate {}", bumped_tx.txid(), if !is_htlc { "to_local" } else if HTLCType::scriptlen_to_htlctype(script.len()) == Some(HTLCType::OfferedHTLC) { "offered" } else if HTLCType::scriptlen_to_htlctype(script.len()) == Some(HTLCType::AcceptedHTLC) { "received" } else { "" }, outp.vout, outp.txid, new_feerate);
2916 &InputMaterial::RemoteHTLC { ref script, ref key, ref preimage, ref amount, ref locktime } => {
2917 if !preimage.is_some() { bumped_tx.lock_time = *locktime };
2918 let sighash_parts = bip143::SighashComponents::new(&bumped_tx);
2919 let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &script, *amount)[..]);
2920 let sig = self.secp_ctx.sign(&sighash, &key);
2921 bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
2922 bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
2923 if let &Some(preimage) = preimage {
2924 bumped_tx.input[i].witness.push(preimage.clone().0.to_vec());
2926 bumped_tx.input[i].witness.push(vec![0]);
2928 bumped_tx.input[i].witness.push(script.clone().into_bytes());
2929 log_trace!(self, "Going to broadcast bumped Claim Transaction {} claiming remote {} htlc output {} from {} with new feerate {}", bumped_tx.txid(), if preimage.is_some() { "offered" } else { "received" }, outp.vout, outp.txid, new_feerate);
2931 &InputMaterial::LocalHTLC { .. } => {
2932 //TODO : Given that Local Commitment Transaction and HTLC-Timeout/HTLC-Success are counter-signed by peer, we can't
2933 // RBF them. Need a Lightning specs change and package relay modification :
2934 // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-November/016518.html
2939 assert!(predicted_weight >= bumped_tx.get_weight());
2940 Some((new_timer, new_feerate, bumped_tx))
2944 const MAX_ALLOC_SIZE: usize = 64*1024;
2946 impl<R: ::std::io::Read> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelMonitor) {
2947 fn read(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
2948 let secp_ctx = Secp256k1::new();
2949 macro_rules! unwrap_obj {
2953 Err(_) => return Err(DecodeError::InvalidValue),
2958 let _ver: u8 = Readable::read(reader)?;
2959 let min_ver: u8 = Readable::read(reader)?;
2960 if min_ver > SERIALIZATION_VERSION {
2961 return Err(DecodeError::UnknownVersion);
2964 let commitment_transaction_number_obscure_factor = <U48 as Readable<R>>::read(reader)?.0;
2966 let key_storage = match <u8 as Readable<R>>::read(reader)? {
2968 let funding_key = Readable::read(reader)?;
2969 let revocation_base_key = Readable::read(reader)?;
2970 let htlc_base_key = Readable::read(reader)?;
2971 let delayed_payment_base_key = Readable::read(reader)?;
2972 let payment_base_key = Readable::read(reader)?;
2973 let shutdown_pubkey = Readable::read(reader)?;
2974 // Technically this can fail and serialize fail a round-trip, but only for serialization of
2975 // barely-init'd ChannelMonitors that we can't do anything with.
2976 let outpoint = OutPoint {
2977 txid: Readable::read(reader)?,
2978 index: Readable::read(reader)?,
2980 let funding_info = Some((outpoint, Readable::read(reader)?));
2981 let current_remote_commitment_txid = Readable::read(reader)?;
2982 let prev_remote_commitment_txid = Readable::read(reader)?;
2985 revocation_base_key,
2987 delayed_payment_base_key,
2991 current_remote_commitment_txid,
2992 prev_remote_commitment_txid,
2995 _ => return Err(DecodeError::InvalidValue),
2998 let their_htlc_base_key = Some(Readable::read(reader)?);
2999 let their_delayed_payment_base_key = Some(Readable::read(reader)?);
3000 let funding_redeemscript = Some(Readable::read(reader)?);
3001 let channel_value_satoshis = Some(Readable::read(reader)?);
3003 let their_cur_revocation_points = {
3004 let first_idx = <U48 as Readable<R>>::read(reader)?.0;
3008 let first_point = Readable::read(reader)?;
3009 let second_point_slice: [u8; 33] = Readable::read(reader)?;
3010 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
3011 Some((first_idx, first_point, None))
3013 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
3018 let our_to_self_delay: u16 = Readable::read(reader)?;
3019 let their_to_self_delay: Option<u16> = Some(Readable::read(reader)?);
3021 let mut old_secrets = [([0; 32], 1 << 48); 49];
3022 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
3023 *secret = Readable::read(reader)?;
3024 *idx = Readable::read(reader)?;
3027 macro_rules! read_htlc_in_commitment {
3030 let offered: bool = Readable::read(reader)?;
3031 let amount_msat: u64 = Readable::read(reader)?;
3032 let cltv_expiry: u32 = Readable::read(reader)?;
3033 let payment_hash: PaymentHash = Readable::read(reader)?;
3034 let transaction_output_index: Option<u32> = Readable::read(reader)?;
3036 HTLCOutputInCommitment {
3037 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
3043 let remote_claimable_outpoints_len: u64 = Readable::read(reader)?;
3044 let mut remote_claimable_outpoints = HashMap::with_capacity(cmp::min(remote_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
3045 for _ in 0..remote_claimable_outpoints_len {
3046 let txid: Sha256dHash = Readable::read(reader)?;
3047 let htlcs_count: u64 = Readable::read(reader)?;
3048 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
3049 for _ in 0..htlcs_count {
3050 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable<R>>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
3052 if let Some(_) = remote_claimable_outpoints.insert(txid, htlcs) {
3053 return Err(DecodeError::InvalidValue);
3057 let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
3058 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
3059 for _ in 0..remote_commitment_txn_on_chain_len {
3060 let txid: Sha256dHash = Readable::read(reader)?;
3061 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
3062 let outputs_count = <u64 as Readable<R>>::read(reader)?;
3063 let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
3064 for _ in 0..outputs_count {
3065 outputs.push(Readable::read(reader)?);
3067 if let Some(_) = remote_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
3068 return Err(DecodeError::InvalidValue);
3072 let remote_hash_commitment_number_len: u64 = Readable::read(reader)?;
3073 let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
3074 for _ in 0..remote_hash_commitment_number_len {
3075 let payment_hash: PaymentHash = Readable::read(reader)?;
3076 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
3077 if let Some(_) = remote_hash_commitment_number.insert(payment_hash, commitment_number) {
3078 return Err(DecodeError::InvalidValue);
3082 macro_rules! read_local_tx {
3085 let tx = <LocalCommitmentTransaction as Readable<R>>::read(reader)?;
3086 let revocation_key = Readable::read(reader)?;
3087 let a_htlc_key = Readable::read(reader)?;
3088 let b_htlc_key = Readable::read(reader)?;
3089 let delayed_payment_key = Readable::read(reader)?;
3090 let per_commitment_point = Readable::read(reader)?;
3091 let feerate_per_kw: u64 = Readable::read(reader)?;
3093 let htlcs_len: u64 = Readable::read(reader)?;
3094 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_len as usize, MAX_ALLOC_SIZE / 128));
3095 for _ in 0..htlcs_len {
3096 let htlc = read_htlc_in_commitment!();
3097 let sigs = match <u8 as Readable<R>>::read(reader)? {
3099 1 => Some(Readable::read(reader)?),
3100 _ => return Err(DecodeError::InvalidValue),
3102 htlcs.push((htlc, sigs, Readable::read(reader)?));
3107 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, per_commitment_point, feerate_per_kw,
3114 let prev_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
3117 Some(read_local_tx!())
3119 _ => return Err(DecodeError::InvalidValue),
3122 let current_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
3125 Some(read_local_tx!())
3127 _ => return Err(DecodeError::InvalidValue),
3130 let current_remote_commitment_number = <U48 as Readable<R>>::read(reader)?.0;
3132 let payment_preimages_len: u64 = Readable::read(reader)?;
3133 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
3134 for _ in 0..payment_preimages_len {
3135 let preimage: PaymentPreimage = Readable::read(reader)?;
3136 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3137 if let Some(_) = payment_preimages.insert(hash, preimage) {
3138 return Err(DecodeError::InvalidValue);
3142 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3143 let destination_script = Readable::read(reader)?;
3144 let to_remote_rescue = match <u8 as Readable<R>>::read(reader)? {
3147 let to_remote_script = Readable::read(reader)?;
3148 let local_key = Readable::read(reader)?;
3149 Some((to_remote_script, local_key))
3151 _ => return Err(DecodeError::InvalidValue),
3154 let pending_claim_requests_len: u64 = Readable::read(reader)?;
3155 let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
3156 for _ in 0..pending_claim_requests_len {
3157 pending_claim_requests.insert(Readable::read(reader)?, Readable::read(reader)?);
3160 let claimable_outpoints_len: u64 = Readable::read(reader)?;
3161 let mut claimable_outpoints = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
3162 for _ in 0..claimable_outpoints_len {
3163 let outpoint = Readable::read(reader)?;
3164 let ancestor_claim_txid = Readable::read(reader)?;
3165 let height = Readable::read(reader)?;
3166 claimable_outpoints.insert(outpoint, (ancestor_claim_txid, height));
3169 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
3170 let mut onchain_events_waiting_threshold_conf = HashMap::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
3171 for _ in 0..waiting_threshold_conf_len {
3172 let height_target = Readable::read(reader)?;
3173 let events_len: u64 = Readable::read(reader)?;
3174 let mut events = Vec::with_capacity(cmp::min(events_len as usize, MAX_ALLOC_SIZE / 128));
3175 for _ in 0..events_len {
3176 let ev = match <u8 as Readable<R>>::read(reader)? {
3178 let claim_request = Readable::read(reader)?;
3179 OnchainEvent::Claim {
3184 let htlc_source = Readable::read(reader)?;
3185 let hash = Readable::read(reader)?;
3186 OnchainEvent::HTLCUpdate {
3187 htlc_update: (htlc_source, hash)
3191 let outpoint = Readable::read(reader)?;
3192 let input_material = Readable::read(reader)?;
3193 OnchainEvent::ContentiousOutpoint {
3198 _ => return Err(DecodeError::InvalidValue),
3202 onchain_events_waiting_threshold_conf.insert(height_target, events);
3205 Ok((last_block_hash.clone(), ChannelMonitor {
3206 commitment_transaction_number_obscure_factor,
3209 their_htlc_base_key,
3210 their_delayed_payment_base_key,
3211 funding_redeemscript,
3212 channel_value_satoshis,
3213 their_cur_revocation_points,
3216 their_to_self_delay,
3219 remote_claimable_outpoints,
3220 remote_commitment_txn_on_chain,
3221 remote_hash_commitment_number,
3223 prev_local_signed_commitment_tx,
3224 current_local_signed_commitment_tx,
3225 current_remote_commitment_number,
3232 pending_claim_requests,
3234 claimable_outpoints,
3236 onchain_events_waiting_threshold_conf,
3248 use bitcoin::blockdata::script::{Script, Builder};
3249 use bitcoin::blockdata::opcodes;
3250 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
3251 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
3252 use bitcoin::util::bip143;
3253 use bitcoin_hashes::Hash;
3254 use bitcoin_hashes::sha256::Hash as Sha256;
3255 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
3256 use bitcoin_hashes::hex::FromHex;
3258 use ln::channelmanager::{PaymentPreimage, PaymentHash};
3259 use ln::channelmonitor::{ChannelMonitor, InputDescriptors};
3261 use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys, LocalCommitmentTransaction};
3262 use util::test_utils::TestLogger;
3263 use secp256k1::key::{SecretKey,PublicKey};
3264 use secp256k1::Secp256k1;
3265 use rand::{thread_rng,Rng};
3269 fn test_per_commitment_storage() {
3270 // Test vectors from BOLT 3:
3271 let mut secrets: Vec<[u8; 32]> = Vec::new();
3272 let mut monitor: ChannelMonitor;
3273 let secp_ctx = Secp256k1::new();
3274 let logger = Arc::new(TestLogger::new());
3276 macro_rules! test_secrets {
3278 let mut idx = 281474976710655;
3279 for secret in secrets.iter() {
3280 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
3283 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
3284 assert!(monitor.get_secret(idx).is_none());
3289 // insert_secret correct sequence
3290 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
3293 secrets.push([0; 32]);
3294 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3295 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3298 secrets.push([0; 32]);
3299 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3300 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
3303 secrets.push([0; 32]);
3304 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3305 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
3308 secrets.push([0; 32]);
3309 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3310 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
3313 secrets.push([0; 32]);
3314 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
3315 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
3318 secrets.push([0; 32]);
3319 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
3320 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
3323 secrets.push([0; 32]);
3324 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
3325 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
3328 secrets.push([0; 32]);
3329 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
3330 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
3335 // insert_secret #1 incorrect
3336 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
3339 secrets.push([0; 32]);
3340 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
3341 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3344 secrets.push([0; 32]);
3345 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3346 assert_eq!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap_err().0,
3347 "Previous secret did not match new one");
3351 // insert_secret #2 incorrect (#1 derived from incorrect)
3352 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
3355 secrets.push([0; 32]);
3356 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
3357 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3360 secrets.push([0; 32]);
3361 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
3362 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
3365 secrets.push([0; 32]);
3366 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3367 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
3370 secrets.push([0; 32]);
3371 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3372 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
3373 "Previous secret did not match new one");
3377 // insert_secret #3 incorrect
3378 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
3381 secrets.push([0; 32]);
3382 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3383 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3386 secrets.push([0; 32]);
3387 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3388 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
3391 secrets.push([0; 32]);
3392 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
3393 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
3396 secrets.push([0; 32]);
3397 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3398 assert_eq!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap_err().0,
3399 "Previous secret did not match new one");
3403 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
3404 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
3407 secrets.push([0; 32]);
3408 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
3409 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3412 secrets.push([0; 32]);
3413 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
3414 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
3417 secrets.push([0; 32]);
3418 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
3419 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
3422 secrets.push([0; 32]);
3423 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
3424 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
3427 secrets.push([0; 32]);
3428 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
3429 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
3432 secrets.push([0; 32]);
3433 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
3434 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
3437 secrets.push([0; 32]);
3438 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
3439 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
3442 secrets.push([0; 32]);
3443 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
3444 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
3445 "Previous secret did not match new one");
3449 // insert_secret #5 incorrect
3450 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
3453 secrets.push([0; 32]);
3454 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3455 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3458 secrets.push([0; 32]);
3459 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3460 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
3463 secrets.push([0; 32]);
3464 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3465 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
3468 secrets.push([0; 32]);
3469 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3470 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
3473 secrets.push([0; 32]);
3474 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
3475 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
3478 secrets.push([0; 32]);
3479 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
3480 assert_eq!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap_err().0,
3481 "Previous secret did not match new one");
3485 // insert_secret #6 incorrect (5 derived from incorrect)
3486 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
3489 secrets.push([0; 32]);
3490 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3491 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3494 secrets.push([0; 32]);
3495 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3496 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
3499 secrets.push([0; 32]);
3500 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3501 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
3504 secrets.push([0; 32]);
3505 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3506 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
3509 secrets.push([0; 32]);
3510 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
3511 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
3514 secrets.push([0; 32]);
3515 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
3516 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
3519 secrets.push([0; 32]);
3520 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
3521 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
3524 secrets.push([0; 32]);
3525 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
3526 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
3527 "Previous secret did not match new one");
3531 // insert_secret #7 incorrect
3532 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
3535 secrets.push([0; 32]);
3536 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3537 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3540 secrets.push([0; 32]);
3541 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3542 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
3545 secrets.push([0; 32]);
3546 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3547 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
3550 secrets.push([0; 32]);
3551 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3552 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
3555 secrets.push([0; 32]);
3556 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
3557 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
3560 secrets.push([0; 32]);
3561 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
3562 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
3565 secrets.push([0; 32]);
3566 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
3567 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
3570 secrets.push([0; 32]);
3571 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
3572 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
3573 "Previous secret did not match new one");
3577 // insert_secret #8 incorrect
3578 monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
3581 secrets.push([0; 32]);
3582 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3583 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
3586 secrets.push([0; 32]);
3587 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3588 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
3591 secrets.push([0; 32]);
3592 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3593 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
3596 secrets.push([0; 32]);
3597 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3598 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
3601 secrets.push([0; 32]);
3602 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
3603 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
3606 secrets.push([0; 32]);
3607 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
3608 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
3611 secrets.push([0; 32]);
3612 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
3613 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
3616 secrets.push([0; 32]);
3617 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
3618 assert_eq!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap_err().0,
3619 "Previous secret did not match new one");
3624 fn test_prune_preimages() {
3625 let secp_ctx = Secp256k1::new();
3626 let logger = Arc::new(TestLogger::new());
3628 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3629 macro_rules! dummy_keys {
3633 per_commitment_point: dummy_key.clone(),
3634 revocation_key: dummy_key.clone(),
3635 a_htlc_key: dummy_key.clone(),
3636 b_htlc_key: dummy_key.clone(),
3637 a_delayed_payment_key: dummy_key.clone(),
3638 b_payment_key: dummy_key.clone(),
3643 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3645 let mut preimages = Vec::new();
3647 let mut rng = thread_rng();
3649 let mut preimage = PaymentPreimage([0; 32]);
3650 rng.fill_bytes(&mut preimage.0[..]);
3651 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3652 preimages.push((preimage, hash));
3656 macro_rules! preimages_slice_to_htlc_outputs {
3657 ($preimages_slice: expr) => {
3659 let mut res = Vec::new();
3660 for (idx, preimage) in $preimages_slice.iter().enumerate() {
3661 res.push((HTLCOutputInCommitment {
3665 payment_hash: preimage.1.clone(),
3666 transaction_output_index: Some(idx as u32),
3673 macro_rules! preimages_to_local_htlcs {
3674 ($preimages_slice: expr) => {
3676 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
3677 let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
3683 macro_rules! test_preimages_exist {
3684 ($preimages_slice: expr, $monitor: expr) => {
3685 for preimage in $preimages_slice {
3686 assert!($monitor.payment_preimages.contains_key(&preimage.1));
3691 // Prune with one old state and a local commitment tx holding a few overlaps with the
3693 let mut monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
3694 monitor.their_to_self_delay = Some(10);
3696 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
3697 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
3698 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
3699 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
3700 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key);
3701 for &(ref preimage, ref hash) in preimages.iter() {
3702 monitor.provide_payment_preimage(hash, preimage);
3705 // Now provide a secret, pruning preimages 10-15
3706 let mut secret = [0; 32];
3707 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3708 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
3709 assert_eq!(monitor.payment_preimages.len(), 15);
3710 test_preimages_exist!(&preimages[0..10], monitor);
3711 test_preimages_exist!(&preimages[15..20], monitor);
3713 // Now provide a further secret, pruning preimages 15-17
3714 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3715 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
3716 assert_eq!(monitor.payment_preimages.len(), 13);
3717 test_preimages_exist!(&preimages[0..10], monitor);
3718 test_preimages_exist!(&preimages[17..20], monitor);
3720 // Now update local commitment tx info, pruning only element 18 as we still care about the
3721 // previous commitment tx's preimages too
3722 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
3723 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3724 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
3725 assert_eq!(monitor.payment_preimages.len(), 12);
3726 test_preimages_exist!(&preimages[0..10], monitor);
3727 test_preimages_exist!(&preimages[18..20], monitor);
3729 // But if we do it again, we'll prune 5-10
3730 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]));
3731 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3732 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
3733 assert_eq!(monitor.payment_preimages.len(), 5);
3734 test_preimages_exist!(&preimages[0..5], monitor);
3738 fn test_claim_txn_weight_computation() {
3739 // We test Claim txn weight, knowing that we want expected weigth and
3740 // not actual case to avoid sigs and time-lock delays hell variances.
3742 let secp_ctx = Secp256k1::new();
3743 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3744 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3745 let mut sum_actual_sigs = 0;
3747 macro_rules! sign_input {
3748 ($sighash_parts: expr, $input: expr, $idx: expr, $amount: expr, $input_type: expr, $sum_actual_sigs: expr) => {
3749 let htlc = HTLCOutputInCommitment {
3750 offered: if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::OfferedHTLC { true } else { false },
3752 cltv_expiry: 2 << 16,
3753 payment_hash: PaymentHash([1; 32]),
3754 transaction_output_index: Some($idx),
3756 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) };
3757 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeem_script, $amount)[..]);
3758 let sig = secp_ctx.sign(&sighash, &privkey);
3759 $input.witness.push(sig.serialize_der().to_vec());
3760 $input.witness[0].push(SigHashType::All as u8);
3761 sum_actual_sigs += $input.witness[0].len();
3762 if *$input_type == InputDescriptors::RevokedOutput {
3763 $input.witness.push(vec!(1));
3764 } else if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::RevokedReceivedHTLC {
3765 $input.witness.push(pubkey.clone().serialize().to_vec());
3766 } else if *$input_type == InputDescriptors::ReceivedHTLC {
3767 $input.witness.push(vec![0]);
3769 $input.witness.push(PaymentPreimage([1; 32]).0.to_vec());
3771 $input.witness.push(redeem_script.into_bytes());
3772 println!("witness[0] {}", $input.witness[0].len());
3773 println!("witness[1] {}", $input.witness[1].len());
3774 println!("witness[2] {}", $input.witness[2].len());
3778 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3779 let txid = Sha256dHash::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3781 // Justice tx with 1 to_local, 2 revoked offered HTLCs, 1 revoked received HTLCs
3782 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3784 claim_tx.input.push(TxIn {
3785 previous_output: BitcoinOutPoint {
3789 script_sig: Script::new(),
3790 sequence: 0xfffffffd,
3791 witness: Vec::new(),
3794 claim_tx.output.push(TxOut {
3795 script_pubkey: script_pubkey.clone(),
3798 let base_weight = claim_tx.get_weight();
3799 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3800 let inputs_des = vec![InputDescriptors::RevokedOutput, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedReceivedHTLC];
3801 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3802 sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3804 assert_eq!(base_weight + ChannelMonitor::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
3806 // Claim tx with 1 offered HTLCs, 3 received HTLCs
3807 claim_tx.input.clear();
3808 sum_actual_sigs = 0;
3810 claim_tx.input.push(TxIn {
3811 previous_output: BitcoinOutPoint {
3815 script_sig: Script::new(),
3816 sequence: 0xfffffffd,
3817 witness: Vec::new(),
3820 let base_weight = claim_tx.get_weight();
3821 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3822 let inputs_des = vec![InputDescriptors::OfferedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC];
3823 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3824 sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3826 assert_eq!(base_weight + ChannelMonitor::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
3828 // Justice tx with 1 revoked HTLC-Success tx output
3829 claim_tx.input.clear();
3830 sum_actual_sigs = 0;
3831 claim_tx.input.push(TxIn {
3832 previous_output: BitcoinOutPoint {
3836 script_sig: Script::new(),
3837 sequence: 0xfffffffd,
3838 witness: Vec::new(),
3840 let base_weight = claim_tx.get_weight();
3841 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3842 let inputs_des = vec![InputDescriptors::RevokedOutput];
3843 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3844 sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3846 assert_eq!(base_weight + ChannelMonitor::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs));
3849 // Further testing is done in the ChannelManager integration tests.