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::{CounterpartyCommitmentSecrets, 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, ChannelKeys};
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};
48 /// An update generated by the underlying Channel itself which contains some new information the
49 /// ChannelMonitor should be made aware of.
50 #[cfg_attr(test, derive(PartialEq))]
53 pub struct ChannelMonitorUpdate {
54 pub(super) updates: Vec<ChannelMonitorUpdateStep>,
55 /// The sequence number of this update. Updates *must* be replayed in-order according to this
56 /// sequence number (and updates may panic if they are not). The update_id values are strictly
57 /// increasing and increase by one for each new update.
59 /// This sequence number is also used to track up to which points updates which returned
60 /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
61 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
65 impl Writeable for ChannelMonitorUpdate {
66 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
67 self.update_id.write(w)?;
68 (self.updates.len() as u64).write(w)?;
69 for update_step in self.updates.iter() {
70 update_step.write(w)?;
75 impl<R: ::std::io::Read> Readable<R> for ChannelMonitorUpdate {
76 fn read(r: &mut R) -> Result<Self, DecodeError> {
77 let update_id: u64 = Readable::read(r)?;
78 let len: u64 = Readable::read(r)?;
79 let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::std::mem::size_of::<ChannelMonitorUpdateStep>()));
81 updates.push(Readable::read(r)?);
83 Ok(Self { update_id, updates })
87 /// An error enum representing a failure to persist a channel monitor update.
89 pub enum ChannelMonitorUpdateErr {
90 /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
91 /// our state failed, but is expected to succeed at some point in the future).
93 /// Such a failure will "freeze" a channel, preventing us from revoking old states or
94 /// submitting new commitment transactions to the remote party. Once the update(s) which failed
95 /// have been successfully applied, ChannelManager::channel_monitor_updated can be used to
96 /// restore the channel to an operational state.
98 /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If
99 /// you return a TemporaryFailure you must ensure that it is written to disk safely before
100 /// writing out the latest ChannelManager state.
102 /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
103 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
104 /// to claim it on this channel) and those updates must be applied wherever they can be. At
105 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
106 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
107 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
110 /// Note that even if updates made after TemporaryFailure succeed you must still call
111 /// channel_monitor_updated to ensure you have the latest monitor and re-enable normal channel
114 /// Note that the update being processed here will not be replayed for you when you call
115 /// ChannelManager::channel_monitor_updated, so you must store the update itself along
116 /// with the persisted ChannelMonitor on your own local disk prior to returning a
117 /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the
118 /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at
121 /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
122 /// remote location (with local copies persisted immediately), it is anticipated that all
123 /// updates will return TemporaryFailure until the remote copies could be updated.
125 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
126 /// different watchtower and cannot update with all watchtowers that were previously informed
127 /// of this channel). This will force-close the channel in question.
129 /// Should also be used to indicate a failure to update the local copy of the channel monitor.
133 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
134 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::update_monitor this
135 /// means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was
137 /// Contains a human-readable error message.
139 pub struct MonitorUpdateError(pub &'static str);
141 /// Simple structure send back by ManyChannelMonitor in case of HTLC detected onchain from a
142 /// forward channel and from which info are needed to update HTLC in a backward channel.
143 #[derive(Clone, PartialEq)]
144 pub struct HTLCUpdate {
145 pub(super) payment_hash: PaymentHash,
146 pub(super) payment_preimage: Option<PaymentPreimage>,
147 pub(super) source: HTLCSource
149 impl_writeable!(HTLCUpdate, 0, { payment_hash, payment_preimage, source });
151 /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between
152 /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing
153 /// events to it, while also taking any add/update_monitor events and passing them to some remote
156 /// Note that any updates to a channel's monitor *must* be applied to each instance of the
157 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
158 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
159 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
161 /// User needs to notify implementors of ManyChannelMonitor when a new block is connected or
162 /// disconnected using their `block_connected` and `block_disconnected` methods. However, rather
163 /// than calling these methods directly, the user should register implementors as listeners to the
164 /// BlockNotifier and call the BlockNotifier's `block_(dis)connected` methods, which will notify
165 /// all registered listeners in one go.
166 pub trait ManyChannelMonitor<ChanSigner: ChannelKeys>: Send + Sync {
167 /// Adds a monitor for the given `funding_txo`.
169 /// Implementer must also ensure that the funding_txo txid *and* outpoint are registered with
170 /// any relevant ChainWatchInterfaces such that the provided monitor receives block_connected
171 /// callbacks with the funding transaction, or any spends of it.
173 /// Further, the implementer must also ensure that each output returned in
174 /// monitor.get_outputs_to_watch() is registered to ensure that the provided monitor learns about
175 /// any spends of any of the outputs.
177 /// Any spends of outputs which should have been registered which aren't passed to
178 /// ChannelMonitors via block_connected may result in FUNDS LOSS.
179 fn add_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr>;
181 /// Updates a monitor for the given `funding_txo`.
183 /// Implementer must also ensure that the funding_txo txid *and* outpoint are registered with
184 /// any relevant ChainWatchInterfaces such that the provided monitor receives block_connected
185 /// callbacks with the funding transaction, or any spends of it.
187 /// Further, the implementer must also ensure that each output returned in
188 /// monitor.get_watch_outputs() is registered to ensure that the provided monitor learns about
189 /// any spends of any of the outputs.
191 /// Any spends of outputs which should have been registered which aren't passed to
192 /// ChannelMonitors via block_connected may result in FUNDS LOSS.
193 fn update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr>;
195 /// Used by ChannelManager to get list of HTLC resolved onchain and which needed to be updated
196 /// with success or failure.
198 /// You should probably just call through to
199 /// ChannelMonitor::get_and_clear_pending_htlcs_updated() for each ChannelMonitor and return
201 fn get_and_clear_pending_htlcs_updated(&self) -> Vec<HTLCUpdate>;
204 /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a
205 /// watchtower or watch our own channels.
207 /// Note that you must provide your own key by which to refer to channels.
209 /// If you're accepting remote monitors (ie are implementing a watchtower), you must verify that
210 /// users cannot overwrite a given channel by providing a duplicate key. ie you should probably
211 /// index by a PublicKey which is required to sign any updates.
213 /// If you're using this for local monitoring of your own channels, you probably want to use
214 /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
215 pub struct SimpleManyChannelMonitor<Key, ChanSigner: ChannelKeys, T: Deref, F: Deref>
216 where T::Target: BroadcasterInterface,
217 F::Target: FeeEstimator
219 #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
220 pub monitors: Mutex<HashMap<Key, ChannelMonitor<ChanSigner>>>,
222 monitors: Mutex<HashMap<Key, ChannelMonitor<ChanSigner>>>,
223 chain_monitor: Arc<ChainWatchInterface>,
225 pending_events: Mutex<Vec<events::Event>>,
230 impl<'a, Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, T: Deref + Sync + Send, F: Deref + Sync + Send>
231 ChainListener for SimpleManyChannelMonitor<Key, ChanSigner, T, F>
232 where T::Target: BroadcasterInterface,
233 F::Target: FeeEstimator
235 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
236 let block_hash = header.bitcoin_hash();
237 let mut new_events: Vec<events::Event> = Vec::with_capacity(0);
239 let mut monitors = self.monitors.lock().unwrap();
240 for monitor in monitors.values_mut() {
241 let (txn_outputs, spendable_outputs) = monitor.block_connected(txn_matched, height, &block_hash, &*self.broadcaster, &*self.fee_estimator);
242 if spendable_outputs.len() > 0 {
243 new_events.push(events::Event::SpendableOutputs {
244 outputs: spendable_outputs,
248 for (ref txid, ref outputs) in txn_outputs {
249 for (idx, output) in outputs.iter().enumerate() {
250 self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey);
255 let mut pending_events = self.pending_events.lock().unwrap();
256 pending_events.append(&mut new_events);
259 fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
260 let block_hash = header.bitcoin_hash();
261 let mut monitors = self.monitors.lock().unwrap();
262 for monitor in monitors.values_mut() {
263 monitor.block_disconnected(disconnected_height, &block_hash, &*self.broadcaster, &*self.fee_estimator);
268 impl<Key : Send + cmp::Eq + hash::Hash + 'static, ChanSigner: ChannelKeys, T: Deref, F: Deref> SimpleManyChannelMonitor<Key, ChanSigner, T, F>
269 where T::Target: BroadcasterInterface,
270 F::Target: FeeEstimator
272 /// Creates a new object which can be used to monitor several channels given the chain
273 /// interface with which to register to receive notifications.
274 pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: T, logger: Arc<Logger>, feeest: F) -> SimpleManyChannelMonitor<Key, ChanSigner, T, F> {
275 let res = SimpleManyChannelMonitor {
276 monitors: Mutex::new(HashMap::new()),
279 pending_events: Mutex::new(Vec::new()),
281 fee_estimator: feeest,
287 /// Adds or updates the monitor which monitors the channel referred to by the given key.
288 pub fn add_monitor_by_key(&self, key: Key, monitor: ChannelMonitor<ChanSigner>) -> Result<(), MonitorUpdateError> {
289 let mut monitors = self.monitors.lock().unwrap();
290 let entry = match monitors.entry(key) {
291 hash_map::Entry::Occupied(_) => return Err(MonitorUpdateError("Channel monitor for given key is already present")),
292 hash_map::Entry::Vacant(e) => e,
294 match monitor.key_storage {
295 Storage::Local { ref funding_info, .. } => {
298 return Err(MonitorUpdateError("Try to update a useless monitor without funding_txo !"));
300 &Some((ref outpoint, ref script)) => {
301 log_trace!(self, "Got new Channel Monitor for channel {}", log_bytes!(outpoint.to_channel_id()[..]));
302 self.chain_monitor.install_watch_tx(&outpoint.txid, script);
303 self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script);
307 Storage::Watchtower { .. } => {
308 self.chain_monitor.watch_all_txn();
311 for (txid, outputs) in monitor.get_outputs_to_watch().iter() {
312 for (idx, script) in outputs.iter().enumerate() {
313 self.chain_monitor.install_watch_outpoint((*txid, idx as u32), script);
316 entry.insert(monitor);
320 /// Updates the monitor which monitors the channel referred to by the given key.
321 pub fn update_monitor_by_key(&self, key: Key, update: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
322 let mut monitors = self.monitors.lock().unwrap();
323 match monitors.get_mut(&key) {
324 Some(orig_monitor) => {
325 log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_info!(orig_monitor.key_storage));
326 orig_monitor.update_monitor(update)
328 None => Err(MonitorUpdateError("No such monitor registered"))
333 impl<ChanSigner: ChannelKeys, T: Deref + Sync + Send, F: Deref + Sync + Send> ManyChannelMonitor<ChanSigner> for SimpleManyChannelMonitor<OutPoint, ChanSigner, T, F>
334 where T::Target: BroadcasterInterface,
335 F::Target: FeeEstimator
337 fn add_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
338 match self.add_monitor_by_key(funding_txo, monitor) {
340 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
344 fn update_monitor(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> {
345 match self.update_monitor_by_key(funding_txo, update) {
347 Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
351 fn get_and_clear_pending_htlcs_updated(&self) -> Vec<HTLCUpdate> {
352 let mut pending_htlcs_updated = Vec::new();
353 for chan in self.monitors.lock().unwrap().values_mut() {
354 pending_htlcs_updated.append(&mut chan.get_and_clear_pending_htlcs_updated());
356 pending_htlcs_updated
360 impl<Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, T: Deref, F: Deref> events::EventsProvider for SimpleManyChannelMonitor<Key, ChanSigner, T, F>
361 where T::Target: BroadcasterInterface,
362 F::Target: FeeEstimator
364 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
365 let mut pending_events = self.pending_events.lock().unwrap();
366 let mut ret = Vec::new();
367 mem::swap(&mut ret, &mut *pending_events);
372 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
373 /// instead claiming it in its own individual transaction.
374 const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
375 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
376 /// HTLC-Success transaction.
377 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
378 /// transaction confirmed (and we use it in a few more, equivalent, places).
379 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 6;
380 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
381 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
382 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
383 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
384 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
385 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
386 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
387 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
388 /// accurate block height.
389 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
390 /// with at worst this delay, so we are not only using this value as a mercy for them but also
391 /// us as a safeguard to delay with enough time.
392 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
393 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding inbound
394 /// HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us losing money.
395 /// We use also this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
396 /// It may cause spurrious generation of bumped claim txn but that's allright given the outpoint is already
397 /// solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
398 /// keeping bumping another claim tx to solve the outpoint.
399 pub(crate) const ANTI_REORG_DELAY: u32 = 6;
401 enum Storage<ChanSigner: ChannelKeys> {
404 funding_key: SecretKey,
405 revocation_base_key: SecretKey,
406 htlc_base_key: SecretKey,
407 delayed_payment_base_key: SecretKey,
408 payment_base_key: SecretKey,
409 shutdown_pubkey: PublicKey,
410 funding_info: Option<(OutPoint, Script)>,
411 current_remote_commitment_txid: Option<Sha256dHash>,
412 prev_remote_commitment_txid: Option<Sha256dHash>,
415 revocation_base_key: PublicKey,
416 htlc_base_key: PublicKey,
420 #[cfg(any(test, feature = "fuzztarget"))]
421 impl<ChanSigner: ChannelKeys> PartialEq for Storage<ChanSigner> {
422 fn eq(&self, other: &Self) -> bool {
424 Storage::Local { ref keys, .. } => {
427 Storage::Local { ref keys, .. } => keys.pubkeys() == k.pubkeys(),
428 Storage::Watchtower { .. } => false,
431 Storage::Watchtower {ref revocation_base_key, ref htlc_base_key} => {
432 let (rbk, hbk) = (revocation_base_key, htlc_base_key);
434 Storage::Local { .. } => false,
435 Storage::Watchtower {ref revocation_base_key, ref htlc_base_key} =>
436 revocation_base_key == rbk && htlc_base_key == hbk,
443 #[derive(Clone, PartialEq)]
444 struct LocalSignedTx {
445 /// txid of the transaction in tx, just used to make comparison faster
447 tx: LocalCommitmentTransaction,
448 revocation_key: PublicKey,
449 a_htlc_key: PublicKey,
450 b_htlc_key: PublicKey,
451 delayed_payment_key: PublicKey,
452 per_commitment_point: PublicKey,
454 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
458 enum InputDescriptors {
463 RevokedOutput, // either a revoked to_local output on commitment tx, a revoked HTLC-Timeout output or a revoked HTLC-Success output
466 /// When ChannelMonitor discovers an onchain outpoint being a step of a channel and that it needs
467 /// to generate a tx to push channel state forward, we cache outpoint-solving tx material to build
468 /// a new bumped one in case of lenghty confirmation delay
469 #[derive(Clone, PartialEq)]
473 pubkey: Option<PublicKey>,
481 preimage: Option<PaymentPreimage>,
487 sigs: (Signature, Signature),
488 preimage: Option<PaymentPreimage>,
493 impl Writeable for InputMaterial {
494 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
496 &InputMaterial::Revoked { ref script, ref pubkey, ref key, ref is_htlc, ref amount} => {
497 writer.write_all(&[0; 1])?;
498 script.write(writer)?;
499 pubkey.write(writer)?;
500 writer.write_all(&key[..])?;
502 writer.write_all(&[0; 1])?;
504 writer.write_all(&[1; 1])?;
506 writer.write_all(&byte_utils::be64_to_array(*amount))?;
508 &InputMaterial::RemoteHTLC { ref script, ref key, ref preimage, ref amount, ref locktime } => {
509 writer.write_all(&[1; 1])?;
510 script.write(writer)?;
512 preimage.write(writer)?;
513 writer.write_all(&byte_utils::be64_to_array(*amount))?;
514 writer.write_all(&byte_utils::be32_to_array(*locktime))?;
516 &InputMaterial::LocalHTLC { ref script, ref sigs, ref preimage, ref amount } => {
517 writer.write_all(&[2; 1])?;
518 script.write(writer)?;
519 sigs.0.write(writer)?;
520 sigs.1.write(writer)?;
521 preimage.write(writer)?;
522 writer.write_all(&byte_utils::be64_to_array(*amount))?;
529 impl<R: ::std::io::Read> Readable<R> for InputMaterial {
530 fn read(reader: &mut R) -> Result<Self, DecodeError> {
531 let input_material = match <u8 as Readable<R>>::read(reader)? {
533 let script = Readable::read(reader)?;
534 let pubkey = Readable::read(reader)?;
535 let key = Readable::read(reader)?;
536 let is_htlc = match <u8 as Readable<R>>::read(reader)? {
539 _ => return Err(DecodeError::InvalidValue),
541 let amount = Readable::read(reader)?;
542 InputMaterial::Revoked {
551 let script = Readable::read(reader)?;
552 let key = Readable::read(reader)?;
553 let preimage = Readable::read(reader)?;
554 let amount = Readable::read(reader)?;
555 let locktime = Readable::read(reader)?;
556 InputMaterial::RemoteHTLC {
565 let script = Readable::read(reader)?;
566 let their_sig = Readable::read(reader)?;
567 let our_sig = Readable::read(reader)?;
568 let preimage = Readable::read(reader)?;
569 let amount = Readable::read(reader)?;
570 InputMaterial::LocalHTLC {
572 sigs: (their_sig, our_sig),
577 _ => return Err(DecodeError::InvalidValue),
583 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
584 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
585 #[derive(Clone, PartialEq)]
587 /// Outpoint under claim process by our own tx, once this one get enough confirmations, we remove it from
588 /// bump-txn candidate buffer.
590 claim_request: Sha256dHash,
592 /// HTLC output getting solved by a timeout, at maturation we pass upstream payment source information to solve
593 /// inbound HTLC in backward channel. Note, in case of preimage, we pass info to upstream without delay as we can
594 /// only win from it, so it's never an OnchainEvent
596 htlc_update: (HTLCSource, PaymentHash),
598 /// Claim tx aggregate multiple claimable outpoints. One of the outpoint may be claimed by a remote party tx.
599 /// In this case, we need to drop the outpoint and regenerate a new claim tx. By safety, we keep tracking
600 /// the outpoint to be sure to resurect it back to the claim tx if reorgs happen.
601 ContentiousOutpoint {
602 outpoint: BitcoinOutPoint,
603 input_material: InputMaterial,
607 /// Higher-level cache structure needed to re-generate bumped claim txn if needed
608 #[derive(Clone, PartialEq)]
609 pub struct ClaimTxBumpMaterial {
610 // At every block tick, used to check if pending claiming tx is taking too
611 // much time for confirmation and we need to bump it.
613 // Tracked in case of reorg to wipe out now-superflous bump material
614 feerate_previous: u64,
615 // Soonest timelocks among set of outpoints claimed, used to compute
616 // a priority of not feerate
617 soonest_timelock: u32,
618 // Cache of script, pubkey, sig or key to solve claimable outputs scriptpubkey.
619 per_input_material: HashMap<BitcoinOutPoint, InputMaterial>,
622 impl Writeable for ClaimTxBumpMaterial {
623 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
624 writer.write_all(&byte_utils::be32_to_array(self.height_timer))?;
625 writer.write_all(&byte_utils::be64_to_array(self.feerate_previous))?;
626 writer.write_all(&byte_utils::be32_to_array(self.soonest_timelock))?;
627 writer.write_all(&byte_utils::be64_to_array(self.per_input_material.len() as u64))?;
628 for (outp, tx_material) in self.per_input_material.iter() {
630 tx_material.write(writer)?;
636 impl<R: ::std::io::Read> Readable<R> for ClaimTxBumpMaterial {
637 fn read(reader: &mut R) -> Result<Self, DecodeError> {
638 let height_timer = Readable::read(reader)?;
639 let feerate_previous = Readable::read(reader)?;
640 let soonest_timelock = Readable::read(reader)?;
641 let per_input_material_len: u64 = Readable::read(reader)?;
642 let mut per_input_material = HashMap::with_capacity(cmp::min(per_input_material_len as usize, MAX_ALLOC_SIZE / 128));
643 for _ in 0 ..per_input_material_len {
644 let outpoint = Readable::read(reader)?;
645 let input_material = Readable::read(reader)?;
646 per_input_material.insert(outpoint, input_material);
648 Ok(Self { height_timer, feerate_previous, soonest_timelock, per_input_material })
652 const SERIALIZATION_VERSION: u8 = 1;
653 const MIN_SERIALIZATION_VERSION: u8 = 1;
655 #[cfg_attr(test, derive(PartialEq))]
657 pub(super) enum ChannelMonitorUpdateStep {
658 LatestLocalCommitmentTXInfo {
659 // TODO: We really need to not be generating a fully-signed transaction in Channel and
660 // passing it here, we need to hold off so that the ChanSigner can enforce a
661 // only-sign-local-state-for-broadcast once invariant:
662 commitment_tx: LocalCommitmentTransaction,
663 local_keys: chan_utils::TxCreationKeys,
665 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
667 LatestRemoteCommitmentTXInfo {
668 unsigned_commitment_tx: Transaction, // TODO: We should actually only need the txid here
669 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
670 commitment_number: u64,
671 their_revocation_point: PublicKey,
674 payment_preimage: PaymentPreimage,
680 /// Indicates our channel is likely a stale version, we're closing, but this update should
681 /// allow us to spend what is ours if our counterparty broadcasts their latest state.
682 RescueRemoteCommitmentTXInfo {
683 their_current_per_commitment_point: PublicKey,
687 impl Writeable for ChannelMonitorUpdateStep {
688 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
690 &ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { ref commitment_tx, ref local_keys, ref feerate_per_kw, ref htlc_outputs } => {
692 commitment_tx.write(w)?;
693 local_keys.write(w)?;
694 feerate_per_kw.write(w)?;
695 (htlc_outputs.len() as u64).write(w)?;
696 for &(ref output, ref signature, ref source) in htlc_outputs.iter() {
702 &ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo { ref unsigned_commitment_tx, ref htlc_outputs, ref commitment_number, ref their_revocation_point } => {
704 unsigned_commitment_tx.write(w)?;
705 commitment_number.write(w)?;
706 their_revocation_point.write(w)?;
707 (htlc_outputs.len() as u64).write(w)?;
708 for &(ref output, ref source) in htlc_outputs.iter() {
711 &None => 0u8.write(w)?,
719 &ChannelMonitorUpdateStep::PaymentPreimage { ref payment_preimage } => {
721 payment_preimage.write(w)?;
723 &ChannelMonitorUpdateStep::CommitmentSecret { ref idx, ref secret } => {
728 &ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { ref their_current_per_commitment_point } => {
730 their_current_per_commitment_point.write(w)?;
736 impl<R: ::std::io::Read> Readable<R> for ChannelMonitorUpdateStep {
737 fn read(r: &mut R) -> Result<Self, DecodeError> {
738 match Readable::read(r)? {
740 Ok(ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo {
741 commitment_tx: Readable::read(r)?,
742 local_keys: Readable::read(r)?,
743 feerate_per_kw: Readable::read(r)?,
745 let len: u64 = Readable::read(r)?;
746 let mut res = Vec::new();
748 res.push((Readable::read(r)?, Readable::read(r)?, Readable::read(r)?));
755 Ok(ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo {
756 unsigned_commitment_tx: Readable::read(r)?,
757 commitment_number: Readable::read(r)?,
758 their_revocation_point: Readable::read(r)?,
760 let len: u64 = Readable::read(r)?;
761 let mut res = Vec::new();
763 res.push((Readable::read(r)?, <Option<HTLCSource> as Readable<R>>::read(r)?.map(|o| Box::new(o))));
770 Ok(ChannelMonitorUpdateStep::PaymentPreimage {
771 payment_preimage: Readable::read(r)?,
775 Ok(ChannelMonitorUpdateStep::CommitmentSecret {
776 idx: Readable::read(r)?,
777 secret: Readable::read(r)?,
781 Ok(ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo {
782 their_current_per_commitment_point: Readable::read(r)?,
785 _ => Err(DecodeError::InvalidValue),
790 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
791 /// on-chain transactions to ensure no loss of funds occurs.
793 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
794 /// information and are actively monitoring the chain.
795 pub struct ChannelMonitor<ChanSigner: ChannelKeys> {
796 latest_update_id: u64,
797 commitment_transaction_number_obscure_factor: u64,
799 key_storage: Storage<ChanSigner>,
800 their_htlc_base_key: Option<PublicKey>,
801 their_delayed_payment_base_key: Option<PublicKey>,
802 funding_redeemscript: Option<Script>,
803 channel_value_satoshis: Option<u64>,
804 // first is the idx of the first of the two revocation points
805 their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
807 our_to_self_delay: u16,
808 their_to_self_delay: Option<u16>,
810 commitment_secrets: CounterpartyCommitmentSecrets,
811 remote_claimable_outpoints: HashMap<Sha256dHash, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
812 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
813 /// Nor can we figure out their commitment numbers without the commitment transaction they are
814 /// spending. Thus, in order to claim them via revocation key, we track all the remote
815 /// commitment transactions which we find on-chain, mapping them to the commitment number which
816 /// can be used to derive the revocation key and claim the transactions.
817 remote_commitment_txn_on_chain: HashMap<Sha256dHash, (u64, Vec<Script>)>,
818 /// Cache used to make pruning of payment_preimages faster.
819 /// Maps payment_hash values to commitment numbers for remote transactions for non-revoked
820 /// remote transactions (ie should remain pretty small).
821 /// Serialized to disk but should generally not be sent to Watchtowers.
822 remote_hash_commitment_number: HashMap<PaymentHash, u64>,
824 // We store two local commitment transactions to avoid any race conditions where we may update
825 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
826 // various monitors for one channel being out of sync, and us broadcasting a local
827 // transaction for which we have deleted claim information on some watchtowers.
828 prev_local_signed_commitment_tx: Option<LocalSignedTx>,
829 current_local_signed_commitment_tx: Option<LocalSignedTx>,
831 // Used just for ChannelManager to make sure it has the latest channel data during
833 current_remote_commitment_number: u64,
835 payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
837 pending_htlcs_updated: Vec<HTLCUpdate>,
839 destination_script: Script,
840 // Thanks to data loss protection, we may be able to claim our non-htlc funds
841 // back, this is the script we have to spend from but we need to
842 // scan every commitment transaction for that
843 to_remote_rescue: Option<(Script, SecretKey)>,
845 // Used to track claiming requests. If claim tx doesn't confirm before height timer expiration we need to bump
846 // it (RBF or CPFP). If an input has been part of an aggregate tx at first claim try, we need to keep it within
847 // another bumped aggregate tx to comply with RBF rules. We may have multiple claiming txn in the flight for the
848 // same set of outpoints. One of the outpoints may be spent by a transaction not issued by us. That's why at
849 // block connection we scan all inputs and if any of them is among a set of a claiming request we test for set
850 // equality between spending transaction and claim request. If true, it means transaction was one our claiming one
851 // after a security delay of 6 blocks we remove pending claim request. If false, it means transaction wasn't and
852 // we need to regenerate new claim request we reduced set of stil-claimable outpoints.
853 // Key is identifier of the pending claim request, i.e the txid of the initial claiming transaction generated by
854 // us and is immutable until all outpoint of the claimable set are post-anti-reorg-delay solved.
855 // Entry is cache of elements need to generate a bumped claiming transaction (see ClaimTxBumpMaterial)
856 #[cfg(test)] // Used in functional_test to verify sanitization
857 pub pending_claim_requests: HashMap<Sha256dHash, ClaimTxBumpMaterial>,
859 pending_claim_requests: HashMap<Sha256dHash, ClaimTxBumpMaterial>,
861 // Used to link outpoints claimed in a connected block to a pending claim request.
862 // Key is outpoint than monitor parsing has detected we have keys/scripts to claim
863 // Value is (pending claim request identifier, confirmation_block), identifier
864 // is txid of the initial claiming transaction and is immutable until outpoint is
865 // post-anti-reorg-delay solved, confirmaiton_block is used to erase entry if
866 // block with output gets disconnected.
867 #[cfg(test)] // Used in functional_test to verify sanitization
868 pub claimable_outpoints: HashMap<BitcoinOutPoint, (Sha256dHash, u32)>,
870 claimable_outpoints: HashMap<BitcoinOutPoint, (Sha256dHash, u32)>,
872 // Used to track onchain events, i.e transactions parts of channels confirmed on chain, on which
873 // we have to take actions once they reach enough confs. Key is a block height timer, i.e we enforce
874 // actions when we receive a block with given height. Actions depend on OnchainEvent type.
875 onchain_events_waiting_threshold_conf: HashMap<u32, Vec<OnchainEvent>>,
877 // If we get serialized out and re-read, we need to make sure that the chain monitoring
878 // interface knows about the TXOs that we want to be notified of spends of. We could probably
879 // be smart and derive them from the above storage fields, but its much simpler and more
880 // Obviously Correct (tm) if we just keep track of them explicitly.
881 outputs_to_watch: HashMap<Sha256dHash, Vec<Script>>,
883 // We simply modify last_block_hash in Channel's block_connected so that serialization is
884 // consistent but hopefully the users' copy handles block_connected in a consistent way.
885 // (we do *not*, however, update them in update_monitor to ensure any local user copies keep
886 // their last_block_hash from its state and not based on updated copies that didn't run through
887 // the full block_connected).
888 pub(crate) last_block_hash: Sha256dHash,
889 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
892 macro_rules! subtract_high_prio_fee {
893 ($self: ident, $fee_estimator: expr, $value: expr, $predicted_weight: expr, $used_feerate: expr) => {
895 $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority);
896 let mut fee = $used_feerate * ($predicted_weight as u64) / 1000;
898 $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
899 fee = $used_feerate * ($predicted_weight as u64) / 1000;
901 $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background);
902 fee = $used_feerate * ($predicted_weight as u64) / 1000;
904 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)",
908 log_warn!($self, "Used low priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
914 log_warn!($self, "Used medium priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
927 #[cfg(any(test, feature = "fuzztarget"))]
928 /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
929 /// underlying object
930 impl<ChanSigner: ChannelKeys> PartialEq for ChannelMonitor<ChanSigner> {
931 fn eq(&self, other: &Self) -> bool {
932 if self.latest_update_id != other.latest_update_id ||
933 self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
934 self.key_storage != other.key_storage ||
935 self.their_htlc_base_key != other.their_htlc_base_key ||
936 self.their_delayed_payment_base_key != other.their_delayed_payment_base_key ||
937 self.funding_redeemscript != other.funding_redeemscript ||
938 self.channel_value_satoshis != other.channel_value_satoshis ||
939 self.their_cur_revocation_points != other.their_cur_revocation_points ||
940 self.our_to_self_delay != other.our_to_self_delay ||
941 self.their_to_self_delay != other.their_to_self_delay ||
942 self.commitment_secrets != other.commitment_secrets ||
943 self.remote_claimable_outpoints != other.remote_claimable_outpoints ||
944 self.remote_commitment_txn_on_chain != other.remote_commitment_txn_on_chain ||
945 self.remote_hash_commitment_number != other.remote_hash_commitment_number ||
946 self.prev_local_signed_commitment_tx != other.prev_local_signed_commitment_tx ||
947 self.current_remote_commitment_number != other.current_remote_commitment_number ||
948 self.current_local_signed_commitment_tx != other.current_local_signed_commitment_tx ||
949 self.payment_preimages != other.payment_preimages ||
950 self.pending_htlcs_updated != other.pending_htlcs_updated ||
951 self.destination_script != other.destination_script ||
952 self.to_remote_rescue != other.to_remote_rescue ||
953 self.pending_claim_requests != other.pending_claim_requests ||
954 self.claimable_outpoints != other.claimable_outpoints ||
955 self.onchain_events_waiting_threshold_conf != other.onchain_events_waiting_threshold_conf ||
956 self.outputs_to_watch != other.outputs_to_watch
965 impl<ChanSigner: ChannelKeys + Writeable> ChannelMonitor<ChanSigner> {
966 /// Serializes into a vec, with various modes for the exposed pub fns
967 fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
968 //TODO: We still write out all the serialization here manually instead of using the fancy
969 //serialization framework we have, we should migrate things over to it.
970 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
971 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
973 self.latest_update_id.write(writer)?;
975 // Set in initial Channel-object creation, so should always be set by now:
976 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
978 macro_rules! write_option {
985 &None => 0u8.write(writer)?,
990 match self.key_storage {
991 Storage::Local { ref keys, ref funding_key, ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, ref payment_base_key, ref shutdown_pubkey, ref funding_info, ref current_remote_commitment_txid, ref prev_remote_commitment_txid } => {
992 writer.write_all(&[0; 1])?;
994 writer.write_all(&funding_key[..])?;
995 writer.write_all(&revocation_base_key[..])?;
996 writer.write_all(&htlc_base_key[..])?;
997 writer.write_all(&delayed_payment_base_key[..])?;
998 writer.write_all(&payment_base_key[..])?;
999 writer.write_all(&shutdown_pubkey.serialize())?;
1000 match funding_info {
1001 &Some((ref outpoint, ref script)) => {
1002 writer.write_all(&outpoint.txid[..])?;
1003 writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
1004 script.write(writer)?;
1007 debug_assert!(false, "Try to serialize a useless Local monitor !");
1010 current_remote_commitment_txid.write(writer)?;
1011 prev_remote_commitment_txid.write(writer)?;
1013 Storage::Watchtower { .. } => unimplemented!(),
1016 writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
1017 writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
1018 self.funding_redeemscript.as_ref().unwrap().write(writer)?;
1019 self.channel_value_satoshis.unwrap().write(writer)?;
1021 match self.their_cur_revocation_points {
1022 Some((idx, pubkey, second_option)) => {
1023 writer.write_all(&byte_utils::be48_to_array(idx))?;
1024 writer.write_all(&pubkey.serialize())?;
1025 match second_option {
1026 Some(second_pubkey) => {
1027 writer.write_all(&second_pubkey.serialize())?;
1030 writer.write_all(&[0; 33])?;
1035 writer.write_all(&byte_utils::be48_to_array(0))?;
1039 writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
1040 writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
1042 self.commitment_secrets.write(writer)?;
1044 macro_rules! serialize_htlc_in_commitment {
1045 ($htlc_output: expr) => {
1046 writer.write_all(&[$htlc_output.offered as u8; 1])?;
1047 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
1048 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
1049 writer.write_all(&$htlc_output.payment_hash.0[..])?;
1050 $htlc_output.transaction_output_index.write(writer)?;
1054 writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
1055 for (ref txid, ref htlc_infos) in self.remote_claimable_outpoints.iter() {
1056 writer.write_all(&txid[..])?;
1057 writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
1058 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
1059 serialize_htlc_in_commitment!(htlc_output);
1060 write_option!(htlc_source);
1064 writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
1065 for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
1066 writer.write_all(&txid[..])?;
1067 writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
1068 (txouts.len() as u64).write(writer)?;
1069 for script in txouts.iter() {
1070 script.write(writer)?;
1074 if for_local_storage {
1075 writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
1076 for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
1077 writer.write_all(&payment_hash.0[..])?;
1078 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1081 writer.write_all(&byte_utils::be64_to_array(0))?;
1084 macro_rules! serialize_local_tx {
1085 ($local_tx: expr) => {
1086 $local_tx.tx.write(writer)?;
1087 writer.write_all(&$local_tx.revocation_key.serialize())?;
1088 writer.write_all(&$local_tx.a_htlc_key.serialize())?;
1089 writer.write_all(&$local_tx.b_htlc_key.serialize())?;
1090 writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
1091 writer.write_all(&$local_tx.per_commitment_point.serialize())?;
1093 writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
1094 writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
1095 for &(ref htlc_output, ref sig, ref htlc_source) in $local_tx.htlc_outputs.iter() {
1096 serialize_htlc_in_commitment!(htlc_output);
1097 if let &Some(ref their_sig) = sig {
1099 writer.write_all(&their_sig.serialize_compact())?;
1103 write_option!(htlc_source);
1108 if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
1109 writer.write_all(&[1; 1])?;
1110 serialize_local_tx!(prev_local_tx);
1112 writer.write_all(&[0; 1])?;
1115 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
1116 writer.write_all(&[1; 1])?;
1117 serialize_local_tx!(cur_local_tx);
1119 writer.write_all(&[0; 1])?;
1122 if for_local_storage {
1123 writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
1125 writer.write_all(&byte_utils::be48_to_array(0))?;
1128 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
1129 for payment_preimage in self.payment_preimages.values() {
1130 writer.write_all(&payment_preimage.0[..])?;
1133 writer.write_all(&byte_utils::be64_to_array(self.pending_htlcs_updated.len() as u64))?;
1134 for data in self.pending_htlcs_updated.iter() {
1135 data.write(writer)?;
1138 self.last_block_hash.write(writer)?;
1139 self.destination_script.write(writer)?;
1140 if let Some((ref to_remote_script, ref local_key)) = self.to_remote_rescue {
1141 writer.write_all(&[1; 1])?;
1142 to_remote_script.write(writer)?;
1143 local_key.write(writer)?;
1145 writer.write_all(&[0; 1])?;
1148 writer.write_all(&byte_utils::be64_to_array(self.pending_claim_requests.len() as u64))?;
1149 for (ref ancestor_claim_txid, claim_tx_data) in self.pending_claim_requests.iter() {
1150 ancestor_claim_txid.write(writer)?;
1151 claim_tx_data.write(writer)?;
1154 writer.write_all(&byte_utils::be64_to_array(self.claimable_outpoints.len() as u64))?;
1155 for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
1156 outp.write(writer)?;
1157 claim_and_height.0.write(writer)?;
1158 claim_and_height.1.write(writer)?;
1161 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
1162 for (ref target, ref events) in self.onchain_events_waiting_threshold_conf.iter() {
1163 writer.write_all(&byte_utils::be32_to_array(**target))?;
1164 writer.write_all(&byte_utils::be64_to_array(events.len() as u64))?;
1165 for ev in events.iter() {
1167 OnchainEvent::Claim { ref claim_request } => {
1168 writer.write_all(&[0; 1])?;
1169 claim_request.write(writer)?;
1171 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1172 writer.write_all(&[1; 1])?;
1173 htlc_update.0.write(writer)?;
1174 htlc_update.1.write(writer)?;
1176 OnchainEvent::ContentiousOutpoint { ref outpoint, ref input_material } => {
1177 writer.write_all(&[2; 1])?;
1178 outpoint.write(writer)?;
1179 input_material.write(writer)?;
1185 (self.outputs_to_watch.len() as u64).write(writer)?;
1186 for (txid, output_scripts) in self.outputs_to_watch.iter() {
1187 txid.write(writer)?;
1188 (output_scripts.len() as u64).write(writer)?;
1189 for script in output_scripts.iter() {
1190 script.write(writer)?;
1197 /// Writes this monitor into the given writer, suitable for writing to disk.
1199 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
1200 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
1201 /// the "reorg path" (ie not just starting at the same height but starting at the highest
1202 /// common block that appears on your best chain as well as on the chain which contains the
1203 /// last block hash returned) upon deserializing the object!
1204 pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
1205 self.write(writer, true)
1208 /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
1210 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
1211 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
1212 /// the "reorg path" (ie not just starting at the same height but starting at the highest
1213 /// common block that appears on your best chain as well as on the chain which contains the
1214 /// last block hash returned) upon deserializing the object!
1215 pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
1216 self.write(writer, false)
1220 impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
1221 pub(super) fn new(keys: ChanSigner, shutdown_pubkey: &PublicKey,
1222 our_to_self_delay: u16, destination_script: &Script, funding_info: (OutPoint, Script),
1223 their_htlc_base_key: &PublicKey, their_delayed_payment_base_key: &PublicKey,
1224 their_to_self_delay: u16, funding_redeemscript: Script, channel_value_satoshis: u64,
1225 commitment_transaction_number_obscure_factor: u64,
1226 logger: Arc<Logger>) -> ChannelMonitor<ChanSigner> {
1228 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
1229 let funding_key = keys.funding_key().clone();
1230 let revocation_base_key = keys.revocation_base_key().clone();
1231 let htlc_base_key = keys.htlc_base_key().clone();
1232 let delayed_payment_base_key = keys.delayed_payment_base_key().clone();
1233 let payment_base_key = keys.payment_base_key().clone();
1235 latest_update_id: 0,
1236 commitment_transaction_number_obscure_factor,
1238 key_storage: Storage::Local {
1241 revocation_base_key,
1243 delayed_payment_base_key,
1245 shutdown_pubkey: shutdown_pubkey.clone(),
1246 funding_info: Some(funding_info),
1247 current_remote_commitment_txid: None,
1248 prev_remote_commitment_txid: None,
1250 their_htlc_base_key: Some(their_htlc_base_key.clone()),
1251 their_delayed_payment_base_key: Some(their_delayed_payment_base_key.clone()),
1252 funding_redeemscript: Some(funding_redeemscript),
1253 channel_value_satoshis: Some(channel_value_satoshis),
1254 their_cur_revocation_points: None,
1256 our_to_self_delay: our_to_self_delay,
1257 their_to_self_delay: Some(their_to_self_delay),
1259 commitment_secrets: CounterpartyCommitmentSecrets::new(),
1260 remote_claimable_outpoints: HashMap::new(),
1261 remote_commitment_txn_on_chain: HashMap::new(),
1262 remote_hash_commitment_number: HashMap::new(),
1264 prev_local_signed_commitment_tx: None,
1265 current_local_signed_commitment_tx: None,
1266 current_remote_commitment_number: 1 << 48,
1268 payment_preimages: HashMap::new(),
1269 pending_htlcs_updated: Vec::new(),
1271 destination_script: destination_script.clone(),
1272 to_remote_rescue: None,
1274 pending_claim_requests: HashMap::new(),
1276 claimable_outpoints: HashMap::new(),
1278 onchain_events_waiting_threshold_conf: HashMap::new(),
1279 outputs_to_watch: HashMap::new(),
1281 last_block_hash: Default::default(),
1282 secp_ctx: Secp256k1::new(),
1287 fn get_witnesses_weight(inputs: &[InputDescriptors]) -> usize {
1288 let mut tx_weight = 2; // count segwit flags
1290 // We use expected weight (and not actual) as signatures and time lock delays may vary
1291 tx_weight += match inp {
1292 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
1293 &InputDescriptors::RevokedOfferedHTLC => {
1294 1 + 1 + 73 + 1 + 33 + 1 + 133
1296 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
1297 &InputDescriptors::RevokedReceivedHTLC => {
1298 1 + 1 + 73 + 1 + 33 + 1 + 139
1300 // number_of_witness_elements + sig_length + remotehtlc_sig + preimage_length + preimage + witness_script_length + witness_script
1301 &InputDescriptors::OfferedHTLC => {
1302 1 + 1 + 73 + 1 + 32 + 1 + 133
1304 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
1305 &InputDescriptors::ReceivedHTLC => {
1306 1 + 1 + 73 + 1 + 1 + 1 + 139
1308 // number_of_witness_elements + sig_length + revocation_sig + true_length + op_true + witness_script_length + witness_script
1309 &InputDescriptors::RevokedOutput => {
1310 1 + 1 + 73 + 1 + 1 + 1 + 77
1317 fn get_height_timer(current_height: u32, timelock_expiration: u32) -> u32 {
1318 if timelock_expiration <= current_height || timelock_expiration - current_height <= 3 {
1319 return current_height + 1
1320 } else if timelock_expiration - current_height <= 15 {
1321 return current_height + 3
1326 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1327 /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
1328 /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
1329 pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
1330 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1331 return Err(MonitorUpdateError("Previous secret did not match new one"));
1334 // Prune HTLCs from the previous remote commitment tx so we don't generate failure/fulfill
1335 // events for now-revoked/fulfilled HTLCs.
1336 if let Storage::Local { ref mut prev_remote_commitment_txid, .. } = self.key_storage {
1337 if let Some(txid) = prev_remote_commitment_txid.take() {
1338 for &mut (_, ref mut source) in self.remote_claimable_outpoints.get_mut(&txid).unwrap() {
1344 if !self.payment_preimages.is_empty() {
1345 let local_signed_commitment_tx = self.current_local_signed_commitment_tx.as_ref().expect("Channel needs at least an initial commitment tx !");
1346 let prev_local_signed_commitment_tx = self.prev_local_signed_commitment_tx.as_ref();
1347 let min_idx = self.get_min_seen_secret();
1348 let remote_hash_commitment_number = &mut self.remote_hash_commitment_number;
1350 self.payment_preimages.retain(|&k, _| {
1351 for &(ref htlc, _, _) in &local_signed_commitment_tx.htlc_outputs {
1352 if k == htlc.payment_hash {
1356 if let Some(prev_local_commitment_tx) = prev_local_signed_commitment_tx {
1357 for &(ref htlc, _, _) in prev_local_commitment_tx.htlc_outputs.iter() {
1358 if k == htlc.payment_hash {
1363 let contains = if let Some(cn) = remote_hash_commitment_number.get(&k) {
1370 remote_hash_commitment_number.remove(&k);
1379 /// Informs this monitor of the latest remote (ie non-broadcastable) commitment transaction.
1380 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1381 /// possibly future revocation/preimage information) to claim outputs where possible.
1382 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1383 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) {
1384 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
1385 // so that a remote monitor doesn't learn anything unless there is a malicious close.
1386 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
1388 for &(ref htlc, _) in &htlc_outputs {
1389 self.remote_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
1392 let new_txid = unsigned_commitment_tx.txid();
1393 log_trace!(self, "Tracking new remote commitment transaction with txid {} at commitment number {} with {} HTLC outputs", new_txid, commitment_number, htlc_outputs.len());
1394 log_trace!(self, "New potential remote commitment transaction: {}", encode::serialize_hex(unsigned_commitment_tx));
1395 if let Storage::Local { ref mut current_remote_commitment_txid, ref mut prev_remote_commitment_txid, .. } = self.key_storage {
1396 *prev_remote_commitment_txid = current_remote_commitment_txid.take();
1397 *current_remote_commitment_txid = Some(new_txid);
1399 self.remote_claimable_outpoints.insert(new_txid, htlc_outputs);
1400 self.current_remote_commitment_number = commitment_number;
1401 //TODO: Merge this into the other per-remote-transaction output storage stuff
1402 match self.their_cur_revocation_points {
1403 Some(old_points) => {
1404 if old_points.0 == commitment_number + 1 {
1405 self.their_cur_revocation_points = Some((old_points.0, old_points.1, Some(their_revocation_point)));
1406 } else if old_points.0 == commitment_number + 2 {
1407 if let Some(old_second_point) = old_points.2 {
1408 self.their_cur_revocation_points = Some((old_points.0 - 1, old_second_point, Some(their_revocation_point)));
1410 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1413 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1417 self.their_cur_revocation_points = Some((commitment_number, their_revocation_point, None));
1422 pub(super) fn provide_rescue_remote_commitment_tx_info(&mut self, their_revocation_point: PublicKey) {
1423 match self.key_storage {
1424 Storage::Local { ref payment_base_key, ref keys, .. } => {
1425 if let Ok(payment_key) = chan_utils::derive_public_key(&self.secp_ctx, &their_revocation_point, &keys.pubkeys().payment_basepoint) {
1426 let to_remote_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1427 .push_slice(&Hash160::hash(&payment_key.serialize())[..])
1429 if let Ok(to_remote_key) = chan_utils::derive_private_key(&self.secp_ctx, &their_revocation_point, &payment_base_key) {
1430 self.to_remote_rescue = Some((to_remote_script, to_remote_key));
1434 Storage::Watchtower { .. } => {}
1438 /// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
1439 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
1440 /// is important that any clones of this channel monitor (including remote clones) by kept
1441 /// up-to-date as our local commitment transaction is updated.
1442 /// Panics if set_their_to_self_delay has never been called.
1443 pub(super) fn provide_latest_local_commitment_tx_info(&mut self, commitment_tx: LocalCommitmentTransaction, local_keys: chan_utils::TxCreationKeys, feerate_per_kw: u64, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), MonitorUpdateError> {
1444 if self.their_to_self_delay.is_none() {
1445 return Err(MonitorUpdateError("Got a local commitment tx info update before we'd set basic information about the channel"));
1447 self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
1448 self.current_local_signed_commitment_tx = Some(LocalSignedTx {
1449 txid: commitment_tx.txid(),
1451 revocation_key: local_keys.revocation_key,
1452 a_htlc_key: local_keys.a_htlc_key,
1453 b_htlc_key: local_keys.b_htlc_key,
1454 delayed_payment_key: local_keys.a_delayed_payment_key,
1455 per_commitment_point: local_keys.per_commitment_point,
1462 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
1463 /// commitment_tx_infos which contain the payment hash have been revoked.
1464 pub(super) fn provide_payment_preimage(&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage) {
1465 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
1468 /// Used in Channel to cheat wrt the update_ids since it plays games, will be removed soon!
1469 pub(super) fn update_monitor_ooo(&mut self, mut updates: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
1470 for update in updates.updates.drain(..) {
1472 ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { commitment_tx, local_keys, feerate_per_kw, htlc_outputs } =>
1473 self.provide_latest_local_commitment_tx_info(commitment_tx, local_keys, feerate_per_kw, htlc_outputs)?,
1474 ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo { unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point } =>
1475 self.provide_latest_remote_commitment_tx_info(&unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point),
1476 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } =>
1477 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage),
1478 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } =>
1479 self.provide_secret(idx, secret)?,
1480 ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { their_current_per_commitment_point } =>
1481 self.provide_rescue_remote_commitment_tx_info(their_current_per_commitment_point),
1484 self.latest_update_id = updates.update_id;
1488 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1491 /// panics if the given update is not the next update by update_id.
1492 pub fn update_monitor(&mut self, mut updates: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
1493 if self.latest_update_id + 1 != updates.update_id {
1494 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
1496 for update in updates.updates.drain(..) {
1498 ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { commitment_tx, local_keys, feerate_per_kw, htlc_outputs } =>
1499 self.provide_latest_local_commitment_tx_info(commitment_tx, local_keys, feerate_per_kw, htlc_outputs)?,
1500 ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo { unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point } =>
1501 self.provide_latest_remote_commitment_tx_info(&unsigned_commitment_tx, htlc_outputs, commitment_number, their_revocation_point),
1502 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } =>
1503 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage),
1504 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } =>
1505 self.provide_secret(idx, secret)?,
1506 ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { their_current_per_commitment_point } =>
1507 self.provide_rescue_remote_commitment_tx_info(their_current_per_commitment_point),
1510 self.latest_update_id = updates.update_id;
1514 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1516 pub fn get_latest_update_id(&self) -> u64 {
1517 self.latest_update_id
1520 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1521 pub fn get_funding_txo(&self) -> Option<OutPoint> {
1522 match self.key_storage {
1523 Storage::Local { ref funding_info, .. } => {
1524 match funding_info {
1525 &Some((outpoint, _)) => Some(outpoint),
1529 Storage::Watchtower { .. } => {
1535 /// Gets a list of txids, with their output scripts (in the order they appear in the
1536 /// transaction), which we must learn about spends of via block_connected().
1537 pub fn get_outputs_to_watch(&self) -> &HashMap<Sha256dHash, Vec<Script>> {
1538 &self.outputs_to_watch
1541 /// Gets the sets of all outpoints which this ChannelMonitor expects to hear about spends of.
1542 /// Generally useful when deserializing as during normal operation the return values of
1543 /// block_connected are sufficient to ensure all relevant outpoints are being monitored (note
1544 /// that the get_funding_txo outpoint and transaction must also be monitored for!).
1545 pub fn get_monitored_outpoints(&self) -> Vec<(Sha256dHash, u32, &Script)> {
1546 let mut res = Vec::with_capacity(self.remote_commitment_txn_on_chain.len() * 2);
1547 for (ref txid, &(_, ref outputs)) in self.remote_commitment_txn_on_chain.iter() {
1548 for (idx, output) in outputs.iter().enumerate() {
1549 res.push(((*txid).clone(), idx as u32, output));
1555 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1556 /// ChannelManager via ManyChannelMonitor::get_and_clear_pending_htlcs_updated().
1557 pub fn get_and_clear_pending_htlcs_updated(&mut self) -> Vec<HTLCUpdate> {
1558 let mut ret = Vec::new();
1559 mem::swap(&mut ret, &mut self.pending_htlcs_updated);
1563 /// Can only fail if idx is < get_min_seen_secret
1564 pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
1565 self.commitment_secrets.get_secret(idx)
1568 pub(super) fn get_min_seen_secret(&self) -> u64 {
1569 self.commitment_secrets.get_min_seen_secret()
1572 pub(super) fn get_cur_remote_commitment_number(&self) -> u64 {
1573 self.current_remote_commitment_number
1576 pub(super) fn get_cur_local_commitment_number(&self) -> u64 {
1577 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
1578 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)
1579 } else { 0xffff_ffff_ffff }
1582 /// Attempts to claim a remote commitment transaction's outputs using the revocation key and
1583 /// data in remote_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
1584 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
1585 /// HTLC-Success/HTLC-Timeout transactions.
1586 /// Return updates for HTLC pending in the channel and failed automatically by the broadcast of
1587 /// revoked remote commitment tx
1588 fn check_spend_remote_transaction<F: Deref>(&mut self, tx: &Transaction, height: u32, fee_estimator: F) -> (Vec<Transaction>, (Sha256dHash, Vec<TxOut>), Vec<SpendableOutputDescriptor>)
1589 where F::Target: FeeEstimator
1591 // Most secp and related errors trying to create keys means we have no hope of constructing
1592 // a spend transaction...so we return no transactions to broadcast
1593 let mut txn_to_broadcast = Vec::new();
1594 let mut watch_outputs = Vec::new();
1595 let mut spendable_outputs = Vec::new();
1597 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
1598 let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
1600 macro_rules! ignore_error {
1601 ( $thing : expr ) => {
1604 Err(_) => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
1609 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);
1610 if commitment_number >= self.get_min_seen_secret() {
1611 let secret = self.get_secret(commitment_number).unwrap();
1612 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
1613 let (revocation_pubkey, b_htlc_key, local_payment_key) = match self.key_storage {
1614 Storage::Local { ref keys, ref payment_base_key, .. } => {
1615 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1616 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().revocation_basepoint)),
1617 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().htlc_basepoint)),
1618 Some(ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &payment_base_key))))
1620 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1621 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1622 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key)),
1623 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &htlc_base_key)),
1627 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()));
1628 let a_htlc_key = match self.their_htlc_base_key {
1629 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
1630 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)),
1633 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
1634 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1636 let local_payment_p2wpkh = if let Some(payment_key) = local_payment_key {
1637 // Note that the Network here is ignored as we immediately drop the address for the
1638 // script_pubkey version.
1639 let payment_hash160 = Hash160::hash(&PublicKey::from_secret_key(&self.secp_ctx, &payment_key).serialize());
1640 Some(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_hash160[..]).into_script())
1643 let mut total_value = 0;
1644 let mut inputs = Vec::new();
1645 let mut inputs_info = Vec::new();
1646 let mut inputs_desc = Vec::new();
1648 for (idx, outp) in tx.output.iter().enumerate() {
1649 if outp.script_pubkey == revokeable_p2wsh {
1651 previous_output: BitcoinOutPoint {
1652 txid: commitment_txid,
1655 script_sig: Script::new(),
1656 sequence: 0xfffffffd,
1657 witness: Vec::new(),
1659 inputs_desc.push(InputDescriptors::RevokedOutput);
1660 inputs_info.push((None, outp.value, self.our_to_self_delay as u32));
1661 total_value += outp.value;
1662 } else if Some(&outp.script_pubkey) == local_payment_p2wpkh.as_ref() {
1663 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1664 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1665 key: local_payment_key.unwrap(),
1666 output: outp.clone(),
1671 macro_rules! sign_input {
1672 ($sighash_parts: expr, $input: expr, $htlc_idx: expr, $amount: expr) => {
1674 let (sig, redeemscript, revocation_key) = match self.key_storage {
1675 Storage::Local { ref revocation_base_key, .. } => {
1676 let redeemscript = if $htlc_idx.is_none() { revokeable_redeemscript.clone() } else {
1677 let htlc = &per_commitment_option.unwrap()[$htlc_idx.unwrap()].0;
1678 chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey)
1680 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]);
1681 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
1682 (self.secp_ctx.sign(&sighash, &revocation_key), redeemscript, revocation_key)
1684 Storage::Watchtower { .. } => {
1688 $input.witness.push(sig.serialize_der().to_vec());
1689 $input.witness[0].push(SigHashType::All as u8);
1690 if $htlc_idx.is_none() {
1691 $input.witness.push(vec!(1));
1693 $input.witness.push(revocation_pubkey.serialize().to_vec());
1695 $input.witness.push(redeemscript.clone().into_bytes());
1696 (redeemscript, revocation_key)
1701 if let Some(ref per_commitment_data) = per_commitment_option {
1702 inputs.reserve_exact(per_commitment_data.len());
1704 for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1705 if let Some(transaction_output_index) = htlc.transaction_output_index {
1706 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1707 if transaction_output_index as usize >= tx.output.len() ||
1708 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1709 tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1710 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
1713 previous_output: BitcoinOutPoint {
1714 txid: commitment_txid,
1715 vout: transaction_output_index,
1717 script_sig: Script::new(),
1718 sequence: 0xfffffffd,
1719 witness: Vec::new(),
1721 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
1723 inputs_desc.push(if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC });
1724 inputs_info.push((Some(idx), tx.output[transaction_output_index as usize].value, htlc.cltv_expiry));
1725 total_value += tx.output[transaction_output_index as usize].value;
1727 let mut single_htlc_tx = Transaction {
1731 output: vec!(TxOut {
1732 script_pubkey: self.destination_script.clone(),
1733 value: htlc.amount_msat / 1000,
1736 let predicted_weight = single_htlc_tx.get_weight() + Self::get_witnesses_weight(&[if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC }]);
1737 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
1738 let mut used_feerate;
1739 if subtract_high_prio_fee!(self, fee_estimator, single_htlc_tx.output[0].value, predicted_weight, used_feerate) {
1740 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
1741 let (redeemscript, revocation_key) = sign_input!(sighash_parts, single_htlc_tx.input[0], Some(idx), htlc.amount_msat / 1000);
1742 assert!(predicted_weight >= single_htlc_tx.get_weight());
1743 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);
1744 let mut per_input_material = HashMap::with_capacity(1);
1745 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 });
1746 match self.claimable_outpoints.entry(single_htlc_tx.input[0].previous_output) {
1747 hash_map::Entry::Occupied(_) => {},
1748 hash_map::Entry::Vacant(entry) => { entry.insert((single_htlc_tx.txid(), height)); }
1750 match self.pending_claim_requests.entry(single_htlc_tx.txid()) {
1751 hash_map::Entry::Occupied(_) => {},
1752 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock: htlc.cltv_expiry, per_input_material }); }
1754 txn_to_broadcast.push(single_htlc_tx);
1761 if !inputs.is_empty() || !txn_to_broadcast.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
1762 // We're definitely a remote commitment transaction!
1763 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());
1764 watch_outputs.append(&mut tx.output.clone());
1765 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1767 macro_rules! check_htlc_fails {
1768 ($txid: expr, $commitment_tx: expr) => {
1769 if let Some(ref outpoints) = self.remote_claimable_outpoints.get($txid) {
1770 for &(ref htlc, ref source_option) in outpoints.iter() {
1771 if let &Some(ref source) = source_option {
1772 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);
1773 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1774 hash_map::Entry::Occupied(mut entry) => {
1775 let e = entry.get_mut();
1776 e.retain(|ref event| {
1778 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1779 return htlc_update.0 != **source
1784 e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1786 hash_map::Entry::Vacant(entry) => {
1787 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1795 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1796 if let &Some(ref txid) = current_remote_commitment_txid {
1797 check_htlc_fails!(txid, "current");
1799 if let &Some(ref txid) = prev_remote_commitment_txid {
1800 check_htlc_fails!(txid, "remote");
1803 // No need to check local commitment txn, symmetric HTLCSource must be present as per-htlc data on remote commitment tx
1805 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
1807 let outputs = vec!(TxOut {
1808 script_pubkey: self.destination_script.clone(),
1811 let mut spend_tx = Transaction {
1818 let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&inputs_desc[..]);
1820 let mut used_feerate;
1821 if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, used_feerate) {
1822 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs);
1825 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
1827 let mut per_input_material = HashMap::with_capacity(spend_tx.input.len());
1828 let mut soonest_timelock = ::std::u32::MAX;
1829 for info in inputs_info.iter() {
1830 if info.2 <= soonest_timelock {
1831 soonest_timelock = info.2;
1834 let height_timer = Self::get_height_timer(height, soonest_timelock);
1835 let spend_txid = spend_tx.txid();
1836 for (input, info) in spend_tx.input.iter_mut().zip(inputs_info.iter()) {
1837 let (redeemscript, revocation_key) = sign_input!(sighash_parts, input, info.0, info.1);
1838 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);
1839 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 });
1840 match self.claimable_outpoints.entry(input.previous_output) {
1841 hash_map::Entry::Occupied(_) => {},
1842 hash_map::Entry::Vacant(entry) => { entry.insert((spend_txid, height)); }
1845 match self.pending_claim_requests.entry(spend_txid) {
1846 hash_map::Entry::Occupied(_) => {},
1847 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock, per_input_material }); }
1850 assert!(predicted_weight >= spend_tx.get_weight());
1852 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
1853 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
1854 output: spend_tx.output[0].clone(),
1856 txn_to_broadcast.push(spend_tx);
1857 } else if let Some(per_commitment_data) = per_commitment_option {
1858 // While this isn't useful yet, there is a potential race where if a counterparty
1859 // revokes a state at the same time as the commitment transaction for that state is
1860 // confirmed, and the watchtower receives the block before the user, the user could
1861 // upload a new ChannelMonitor with the revocation secret but the watchtower has
1862 // already processed the block, resulting in the remote_commitment_txn_on_chain entry
1863 // not being generated by the above conditional. Thus, to be safe, we go ahead and
1865 watch_outputs.append(&mut tx.output.clone());
1866 self.remote_commitment_txn_on_chain.insert(commitment_txid, (commitment_number, tx.output.iter().map(|output| { output.script_pubkey.clone() }).collect()));
1868 log_trace!(self, "Got broadcast of non-revoked remote commitment transaction {}", commitment_txid);
1870 macro_rules! check_htlc_fails {
1871 ($txid: expr, $commitment_tx: expr, $id: tt) => {
1872 if let Some(ref latest_outpoints) = self.remote_claimable_outpoints.get($txid) {
1873 $id: for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1874 if let &Some(ref source) = source_option {
1875 // Check if the HTLC is present in the commitment transaction that was
1876 // broadcast, but not if it was below the dust limit, which we should
1877 // fail backwards immediately as there is no way for us to learn the
1878 // payment_preimage.
1879 // Note that if the dust limit were allowed to change between
1880 // commitment transactions we'd want to be check whether *any*
1881 // broadcastable commitment transaction has the HTLC in it, but it
1882 // cannot currently change after channel initialization, so we don't
1884 for &(ref broadcast_htlc, ref broadcast_source) in per_commitment_data.iter() {
1885 if broadcast_htlc.transaction_output_index.is_some() && Some(source) == broadcast_source.as_ref() {
1889 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);
1890 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
1891 hash_map::Entry::Occupied(mut entry) => {
1892 let e = entry.get_mut();
1893 e.retain(|ref event| {
1895 OnchainEvent::HTLCUpdate { ref htlc_update } => {
1896 return htlc_update.0 != **source
1901 e.push(OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())});
1903 hash_map::Entry::Vacant(entry) => {
1904 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ((**source).clone(), htlc.payment_hash.clone())}]);
1912 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
1913 if let &Some(ref txid) = current_remote_commitment_txid {
1914 check_htlc_fails!(txid, "current", 'current_loop);
1916 if let &Some(ref txid) = prev_remote_commitment_txid {
1917 check_htlc_fails!(txid, "previous", 'prev_loop);
1921 if let Some(revocation_points) = self.their_cur_revocation_points {
1922 let revocation_point_option =
1923 if revocation_points.0 == commitment_number { Some(&revocation_points.1) }
1924 else if let Some(point) = revocation_points.2.as_ref() {
1925 if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
1927 if let Some(revocation_point) = revocation_point_option {
1928 let (revocation_pubkey, b_htlc_key) = match self.key_storage {
1929 Storage::Local { ref keys, .. } => {
1930 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &keys.pubkeys().revocation_basepoint)),
1931 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &keys.pubkeys().htlc_basepoint)))
1933 Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
1934 (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
1935 ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &htlc_base_key)))
1938 let a_htlc_key = match self.their_htlc_base_key {
1939 None => return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs),
1940 Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
1943 for (idx, outp) in tx.output.iter().enumerate() {
1944 if outp.script_pubkey.is_v0_p2wpkh() {
1945 match self.key_storage {
1946 Storage::Local { ref payment_base_key, .. } => {
1947 if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &revocation_point, &payment_base_key) {
1948 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1949 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1951 output: outp.clone(),
1955 Storage::Watchtower { .. } => {}
1957 break; // Only to_remote ouput is claimable
1961 let mut total_value = 0;
1962 let mut inputs = Vec::new();
1963 let mut inputs_desc = Vec::new();
1964 let mut inputs_info = Vec::new();
1966 macro_rules! sign_input {
1967 ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr, $idx: expr) => {
1969 let (sig, redeemscript, htlc_key) = match self.key_storage {
1970 Storage::Local { ref htlc_base_key, .. } => {
1971 let htlc = &per_commitment_option.unwrap()[$idx as usize].0;
1972 let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1973 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]);
1974 let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
1975 (self.secp_ctx.sign(&sighash, &htlc_key), redeemscript, htlc_key)
1977 Storage::Watchtower { .. } => {
1981 $input.witness.push(sig.serialize_der().to_vec());
1982 $input.witness[0].push(SigHashType::All as u8);
1983 $input.witness.push($preimage);
1984 $input.witness.push(redeemscript.clone().into_bytes());
1985 (redeemscript, htlc_key)
1990 for (idx, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
1991 if let Some(transaction_output_index) = htlc.transaction_output_index {
1992 let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
1993 if transaction_output_index as usize >= tx.output.len() ||
1994 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1995 tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1996 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
1998 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2001 previous_output: BitcoinOutPoint {
2002 txid: commitment_txid,
2003 vout: transaction_output_index,
2005 script_sig: Script::new(),
2006 sequence: 0xff_ff_ff_fd,
2007 witness: Vec::new(),
2009 if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
2011 inputs_desc.push(if htlc.offered { InputDescriptors::OfferedHTLC } else { InputDescriptors::ReceivedHTLC });
2012 inputs_info.push((payment_preimage, tx.output[transaction_output_index as usize].value, htlc.cltv_expiry, idx));
2013 total_value += tx.output[transaction_output_index as usize].value;
2015 let mut single_htlc_tx = Transaction {
2019 output: vec!(TxOut {
2020 script_pubkey: self.destination_script.clone(),
2021 value: htlc.amount_msat / 1000,
2024 let predicted_weight = single_htlc_tx.get_weight() + Self::get_witnesses_weight(&[if htlc.offered { InputDescriptors::OfferedHTLC } else { InputDescriptors::ReceivedHTLC }]);
2025 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
2026 let mut used_feerate;
2027 if subtract_high_prio_fee!(self, fee_estimator, single_htlc_tx.output[0].value, predicted_weight, used_feerate) {
2028 let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
2029 let (redeemscript, htlc_key) = sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.0.to_vec(), idx);
2030 assert!(predicted_weight >= single_htlc_tx.get_weight());
2031 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
2032 outpoint: BitcoinOutPoint { txid: single_htlc_tx.txid(), vout: 0 },
2033 output: single_htlc_tx.output[0].clone(),
2035 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);
2036 let mut per_input_material = HashMap::with_capacity(1);
2037 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 });
2038 match self.claimable_outpoints.entry(single_htlc_tx.input[0].previous_output) {
2039 hash_map::Entry::Occupied(_) => {},
2040 hash_map::Entry::Vacant(entry) => { entry.insert((single_htlc_tx.txid(), height)); }
2042 match self.pending_claim_requests.entry(single_htlc_tx.txid()) {
2043 hash_map::Entry::Occupied(_) => {},
2044 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock: htlc.cltv_expiry, per_input_material}); }
2046 txn_to_broadcast.push(single_htlc_tx);
2052 // TODO: If the HTLC has already expired, potentially merge it with the
2053 // rest of the claim transaction, as above.
2055 previous_output: BitcoinOutPoint {
2056 txid: commitment_txid,
2057 vout: transaction_output_index,
2059 script_sig: Script::new(),
2060 sequence: 0xff_ff_ff_fd,
2061 witness: Vec::new(),
2063 let mut timeout_tx = Transaction {
2065 lock_time: htlc.cltv_expiry,
2067 output: vec!(TxOut {
2068 script_pubkey: self.destination_script.clone(),
2069 value: htlc.amount_msat / 1000,
2072 let predicted_weight = timeout_tx.get_weight() + Self::get_witnesses_weight(&[InputDescriptors::ReceivedHTLC]);
2073 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
2074 let mut used_feerate;
2075 if subtract_high_prio_fee!(self, fee_estimator, timeout_tx.output[0].value, predicted_weight, used_feerate) {
2076 let sighash_parts = bip143::SighashComponents::new(&timeout_tx);
2077 let (redeemscript, htlc_key) = sign_input!(sighash_parts, timeout_tx.input[0], htlc.amount_msat / 1000, vec![0], idx);
2078 assert!(predicted_weight >= timeout_tx.get_weight());
2079 //TODO: track SpendableOutputDescriptor
2080 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);
2081 let mut per_input_material = HashMap::with_capacity(1);
2082 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 });
2083 match self.claimable_outpoints.entry(timeout_tx.input[0].previous_output) {
2084 hash_map::Entry::Occupied(_) => {},
2085 hash_map::Entry::Vacant(entry) => { entry.insert((timeout_tx.txid(), height)); }
2087 match self.pending_claim_requests.entry(timeout_tx.txid()) {
2088 hash_map::Entry::Occupied(_) => {},
2089 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock: htlc.cltv_expiry, per_input_material }); }
2092 txn_to_broadcast.push(timeout_tx);
2097 if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); } // Nothing to be done...probably a false positive/local tx
2099 let outputs = vec!(TxOut {
2100 script_pubkey: self.destination_script.clone(),
2103 let mut spend_tx = Transaction {
2110 let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&inputs_desc[..]);
2112 let mut used_feerate;
2113 if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, used_feerate) {
2114 return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs);
2117 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
2119 let mut per_input_material = HashMap::with_capacity(spend_tx.input.len());
2120 let mut soonest_timelock = ::std::u32::MAX;
2121 for info in inputs_info.iter() {
2122 if info.2 <= soonest_timelock {
2123 soonest_timelock = info.2;
2126 let height_timer = Self::get_height_timer(height, soonest_timelock);
2127 let spend_txid = spend_tx.txid();
2128 for (input, info) in spend_tx.input.iter_mut().zip(inputs_info.iter()) {
2129 let (redeemscript, htlc_key) = sign_input!(sighash_parts, input, info.1, (info.0).0.to_vec(), info.3);
2130 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);
2131 per_input_material.insert(input.previous_output, InputMaterial::RemoteHTLC { script: redeemscript, key: htlc_key, preimage: Some(*(info.0)), amount: info.1, locktime: 0});
2132 match self.claimable_outpoints.entry(input.previous_output) {
2133 hash_map::Entry::Occupied(_) => {},
2134 hash_map::Entry::Vacant(entry) => { entry.insert((spend_txid, height)); }
2137 match self.pending_claim_requests.entry(spend_txid) {
2138 hash_map::Entry::Occupied(_) => {},
2139 hash_map::Entry::Vacant(entry) => { entry.insert(ClaimTxBumpMaterial { height_timer, feerate_previous: used_feerate, soonest_timelock, per_input_material }); }
2141 assert!(predicted_weight >= spend_tx.get_weight());
2142 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
2143 outpoint: BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 },
2144 output: spend_tx.output[0].clone(),
2146 txn_to_broadcast.push(spend_tx);
2149 } else if let Some((ref to_remote_rescue, ref local_key)) = self.to_remote_rescue {
2150 for (idx, outp) in tx.output.iter().enumerate() {
2151 if to_remote_rescue == &outp.script_pubkey {
2152 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
2153 outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
2154 key: local_key.clone(),
2155 output: outp.clone(),
2161 (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs)
2164 /// Attempts to claim a remote HTLC-Success/HTLC-Timeout's outputs using the revocation key
2165 fn check_spend_remote_htlc<F: Deref>(&mut self, tx: &Transaction, commitment_number: u64, height: u32, fee_estimator: F) -> (Option<Transaction>, Option<SpendableOutputDescriptor>)
2166 where F::Target: FeeEstimator
2168 //TODO: send back new outputs to guarantee pending_claim_request consistency
2169 if tx.input.len() != 1 || tx.output.len() != 1 {
2173 macro_rules! ignore_error {
2174 ( $thing : expr ) => {
2177 Err(_) => return (None, None)
2182 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (None, None); };
2183 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2184 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2185 let revocation_pubkey = match self.key_storage {
2186 Storage::Local { ref keys, .. } => {
2187 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().revocation_basepoint))
2189 Storage::Watchtower { ref revocation_base_key, .. } => {
2190 ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key))
2193 let delayed_key = match self.their_delayed_payment_base_key {
2194 None => return (None, None),
2195 Some(their_delayed_payment_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &their_delayed_payment_base_key)),
2197 let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
2198 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
2199 let htlc_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
2201 let mut inputs = Vec::new();
2204 if tx.output[0].script_pubkey == revokeable_p2wsh { //HTLC transactions have one txin, one txout
2206 previous_output: BitcoinOutPoint {
2210 script_sig: Script::new(),
2211 sequence: 0xfffffffd,
2212 witness: Vec::new(),
2214 amount = tx.output[0].value;
2217 if !inputs.is_empty() {
2218 let outputs = vec!(TxOut {
2219 script_pubkey: self.destination_script.clone(),
2223 let mut spend_tx = Transaction {
2229 let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&[InputDescriptors::RevokedOutput]);
2230 let mut used_feerate;
2231 if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, used_feerate) {
2232 return (None, None);
2235 let sighash_parts = bip143::SighashComponents::new(&spend_tx);
2237 let (sig, revocation_key) = match self.key_storage {
2238 Storage::Local { ref revocation_base_key, .. } => {
2239 let sighash = hash_to_message!(&sighash_parts.sighash_all(&spend_tx.input[0], &redeemscript, amount)[..]);
2240 let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key));
2241 (self.secp_ctx.sign(&sighash, &revocation_key), revocation_key)
2243 Storage::Watchtower { .. } => {
2247 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
2248 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
2249 spend_tx.input[0].witness.push(vec!(1));
2250 spend_tx.input[0].witness.push(redeemscript.clone().into_bytes());
2252 assert!(predicted_weight >= spend_tx.get_weight());
2253 let outpoint = BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 };
2254 let output = spend_tx.output[0].clone();
2255 let height_timer = Self::get_height_timer(height, height + self.our_to_self_delay as u32);
2256 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);
2257 let mut per_input_material = HashMap::with_capacity(1);
2258 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 });
2259 match self.claimable_outpoints.entry(spend_tx.input[0].previous_output) {
2260 hash_map::Entry::Occupied(_) => {},
2261 hash_map::Entry::Vacant(entry) => { entry.insert((spend_tx.txid(), height)); }
2263 match self.pending_claim_requests.entry(spend_tx.txid()) {
2264 hash_map::Entry::Occupied(_) => {},
2265 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 }); }
2267 (Some(spend_tx), Some(SpendableOutputDescriptor::StaticOutput { outpoint, output }))
2268 } else { (None, None) }
2271 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)>) {
2272 let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
2273 let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
2274 let mut watch_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
2275 let mut pending_claims = Vec::with_capacity(local_tx.htlc_outputs.len());
2277 macro_rules! add_dynamic_output {
2278 ($father_tx: expr, $vout: expr) => {
2279 if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, &local_tx.per_commitment_point, delayed_payment_base_key) {
2280 spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WSH {
2281 outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
2282 key: local_delayedkey,
2283 witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
2284 to_self_delay: self.our_to_self_delay,
2285 output: $father_tx.output[$vout as usize].clone(),
2291 let redeemscript = chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.their_to_self_delay.unwrap(), &local_tx.delayed_payment_key);
2292 let revokeable_p2wsh = redeemscript.to_v0_p2wsh();
2293 for (idx, output) in local_tx.tx.without_valid_witness().output.iter().enumerate() {
2294 if output.script_pubkey == revokeable_p2wsh {
2295 add_dynamic_output!(local_tx.tx.without_valid_witness(), idx as u32);
2300 if let &Storage::Local { ref htlc_base_key, .. } = &self.key_storage {
2301 for &(ref htlc, ref sigs, _) in local_tx.htlc_outputs.iter() {
2302 if let Some(transaction_output_index) = htlc.transaction_output_index {
2303 if let &Some(ref their_sig) = sigs {
2305 log_trace!(self, "Broadcasting HTLC-Timeout transaction against local commitment transactions");
2306 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);
2307 let (our_sig, htlc_script) = match
2308 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) {
2313 add_dynamic_output!(htlc_timeout_tx, 0);
2314 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
2315 let mut per_input_material = HashMap::with_capacity(1);
2316 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});
2317 //TODO: with option_simplified_commitment track outpoint too
2318 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);
2319 pending_claims.push((htlc_timeout_tx.txid(), ClaimTxBumpMaterial { height_timer, feerate_previous: 0, soonest_timelock: htlc.cltv_expiry, per_input_material }));
2320 res.push(htlc_timeout_tx);
2322 if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2323 log_trace!(self, "Broadcasting HTLC-Success transaction against local commitment transactions");
2324 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);
2325 let (our_sig, htlc_script) = match
2326 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) {
2331 add_dynamic_output!(htlc_success_tx, 0);
2332 let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
2333 let mut per_input_material = HashMap::with_capacity(1);
2334 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});
2335 //TODO: with option_simplified_commitment track outpoint too
2336 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);
2337 pending_claims.push((htlc_success_tx.txid(), ClaimTxBumpMaterial { height_timer, feerate_previous: 0, soonest_timelock: htlc.cltv_expiry, per_input_material }));
2338 res.push(htlc_success_tx);
2341 watch_outputs.push(local_tx.tx.without_valid_witness().output[transaction_output_index as usize].clone());
2342 } else { panic!("Should have sigs for non-dust local tx outputs!") }
2347 (res, spendable_outputs, watch_outputs, pending_claims)
2350 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
2351 /// revoked using data in local_claimable_outpoints.
2352 /// Should not be used if check_spend_revoked_transaction succeeds.
2353 fn check_spend_local_transaction(&mut self, tx: &Transaction, height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, (Sha256dHash, Vec<TxOut>)) {
2354 let commitment_txid = tx.txid();
2355 let mut local_txn = Vec::new();
2356 let mut spendable_outputs = Vec::new();
2357 let mut watch_outputs = Vec::new();
2359 macro_rules! wait_threshold_conf {
2360 ($height: expr, $source: expr, $commitment_tx: expr, $payment_hash: expr) => {
2361 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);
2362 match self.onchain_events_waiting_threshold_conf.entry($height + ANTI_REORG_DELAY - 1) {
2363 hash_map::Entry::Occupied(mut entry) => {
2364 let e = entry.get_mut();
2365 e.retain(|ref event| {
2367 OnchainEvent::HTLCUpdate { ref htlc_update } => {
2368 return htlc_update.0 != $source
2373 e.push(OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)});
2375 hash_map::Entry::Vacant(entry) => {
2376 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: ($source, $payment_hash)}]);
2382 macro_rules! append_onchain_update {
2383 ($updates: expr) => {
2384 local_txn.append(&mut $updates.0);
2385 spendable_outputs.append(&mut $updates.1);
2386 watch_outputs.append(&mut $updates.2);
2387 for claim in $updates.3 {
2388 match self.pending_claim_requests.entry(claim.0) {
2389 hash_map::Entry::Occupied(_) => {},
2390 hash_map::Entry::Vacant(entry) => { entry.insert(claim.1); }
2396 // HTLCs set may differ between last and previous local commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
2397 let mut is_local_tx = false;
2399 if let &mut Some(ref mut local_tx) = &mut self.current_local_signed_commitment_tx {
2400 if local_tx.txid == commitment_txid {
2401 match self.key_storage {
2402 Storage::Local { ref funding_key, .. } => {
2403 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2409 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
2410 if local_tx.txid == commitment_txid {
2412 log_trace!(self, "Got latest local commitment tx broadcast, searching for available HTLCs to claim");
2413 assert!(local_tx.tx.has_local_sig());
2414 match self.key_storage {
2415 Storage::Local { ref delayed_payment_base_key, .. } => {
2416 let mut res = self.broadcast_by_local_state(local_tx, delayed_payment_base_key, height);
2417 append_onchain_update!(res);
2419 Storage::Watchtower { .. } => { }
2423 if let &mut Some(ref mut local_tx) = &mut self.prev_local_signed_commitment_tx {
2424 if local_tx.txid == commitment_txid {
2425 match self.key_storage {
2426 Storage::Local { ref funding_key, .. } => {
2427 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2433 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
2434 if local_tx.txid == commitment_txid {
2436 log_trace!(self, "Got previous local commitment tx broadcast, searching for available HTLCs to claim");
2437 assert!(local_tx.tx.has_local_sig());
2438 match self.key_storage {
2439 Storage::Local { ref delayed_payment_base_key, .. } => {
2440 let mut res = self.broadcast_by_local_state(local_tx, delayed_payment_base_key, height);
2441 append_onchain_update!(res);
2443 Storage::Watchtower { .. } => { }
2448 macro_rules! fail_dust_htlcs_after_threshold_conf {
2449 ($local_tx: expr) => {
2450 for &(ref htlc, _, ref source) in &$local_tx.htlc_outputs {
2451 if htlc.transaction_output_index.is_none() {
2452 if let &Some(ref source) = source {
2453 wait_threshold_conf!(height, source.clone(), "lastest", htlc.payment_hash.clone());
2461 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
2462 fail_dust_htlcs_after_threshold_conf!(local_tx);
2464 if let &Some(ref local_tx) = &self.prev_local_signed_commitment_tx {
2465 fail_dust_htlcs_after_threshold_conf!(local_tx);
2469 (local_txn, spendable_outputs, (commitment_txid, watch_outputs))
2472 /// Generate a spendable output event when closing_transaction get registered onchain.
2473 fn check_spend_closing_transaction(&self, tx: &Transaction) -> Option<SpendableOutputDescriptor> {
2474 if tx.input[0].sequence == 0xFFFFFFFF && !tx.input[0].witness.is_empty() && tx.input[0].witness.last().unwrap().len() == 71 {
2475 match self.key_storage {
2476 Storage::Local { ref shutdown_pubkey, .. } => {
2477 let our_channel_close_key_hash = Hash160::hash(&shutdown_pubkey.serialize());
2478 let shutdown_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script();
2479 for (idx, output) in tx.output.iter().enumerate() {
2480 if shutdown_script == output.script_pubkey {
2481 return Some(SpendableOutputDescriptor::StaticOutput {
2482 outpoint: BitcoinOutPoint { txid: tx.txid(), vout: idx as u32 },
2483 output: output.clone(),
2488 Storage::Watchtower { .. } => {
2489 //TODO: we need to ensure an offline client will generate the event when it
2490 // comes back online after only the watchtower saw the transaction
2497 /// Used by ChannelManager deserialization to broadcast the latest local state if its copy of
2498 /// the Channel was out-of-date. You may use it to get a broadcastable local toxic tx in case of
2499 /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our remote side knows
2500 /// a higher revocation secret than the local commitment number we are aware of. Broadcasting these
2501 /// transactions are UNSAFE, as they allow remote side to punish you. Nevertheless you may want to
2502 /// broadcast them if remote don't close channel with his higher commitment transaction after a
2503 /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
2504 /// out-of-band the other node operator to coordinate with him if option is available to you.
2505 /// In any-case, choice is up to the user.
2506 pub fn get_latest_local_commitment_txn(&mut self) -> Vec<Transaction> {
2507 log_trace!(self, "Getting signed latest local commitment transaction!");
2508 if let &mut Some(ref mut local_tx) = &mut self.current_local_signed_commitment_tx {
2509 match self.key_storage {
2510 Storage::Local { ref funding_key, .. } => {
2511 local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2516 if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
2517 let mut res = vec![local_tx.tx.with_valid_witness().clone()];
2518 match self.key_storage {
2519 Storage::Local { ref delayed_payment_base_key, .. } => {
2520 res.append(&mut self.broadcast_by_local_state(local_tx, delayed_payment_base_key, 0).0);
2521 // 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.
2522 // The data will be re-generated and tracked in check_spend_local_transaction if we get a confirmation.
2524 _ => panic!("Can only broadcast by local channelmonitor"),
2532 /// Called by SimpleManyChannelMonitor::block_connected, which implements
2533 /// ChainListener::block_connected.
2534 /// Eventually this should be pub and, roughly, implement ChainListener, however this requires
2535 /// &mut self, as well as returns new spendable outputs and outpoints to watch for spending of
2537 fn block_connected<B: Deref, F: Deref>(&mut self, txn_matched: &[&Transaction], height: u32, block_hash: &Sha256dHash, broadcaster: B, fee_estimator: F)-> (Vec<(Sha256dHash, Vec<TxOut>)>, Vec<SpendableOutputDescriptor>)
2538 where B::Target: BroadcasterInterface,
2539 F::Target: FeeEstimator
2541 for tx in txn_matched {
2542 let mut output_val = 0;
2543 for out in tx.output.iter() {
2544 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2545 output_val += out.value;
2546 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2550 log_trace!(self, "Block {} at height {} connected with {} txn matched", block_hash, height, txn_matched.len());
2551 let mut watch_outputs = Vec::new();
2552 let mut spendable_outputs = Vec::new();
2553 let mut bump_candidates = HashSet::new();
2554 for tx in txn_matched {
2555 if tx.input.len() == 1 {
2556 // Assuming our keys were not leaked (in which case we're screwed no matter what),
2557 // commitment transactions and HTLC transactions will all only ever have one input,
2558 // which is an easy way to filter out any potential non-matching txn for lazy
2560 let prevout = &tx.input[0].previous_output;
2561 let mut txn: Vec<Transaction> = Vec::new();
2562 let funding_txo = match self.key_storage {
2563 Storage::Local { ref funding_info, .. } => {
2564 funding_info.clone()
2566 Storage::Watchtower { .. } => {
2570 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) {
2571 if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
2572 let (remote_txn, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(&tx, height, &*fee_estimator);
2574 spendable_outputs.append(&mut spendable_output);
2575 if !new_outputs.1.is_empty() {
2576 watch_outputs.push(new_outputs);
2579 let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(&tx, height);
2580 spendable_outputs.append(&mut spendable_output);
2582 if !new_outputs.1.is_empty() {
2583 watch_outputs.push(new_outputs);
2587 if !funding_txo.is_none() && txn.is_empty() {
2588 if let Some(spendable_output) = self.check_spend_closing_transaction(&tx) {
2589 spendable_outputs.push(spendable_output);
2593 if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
2594 let (tx, spendable_output) = self.check_spend_remote_htlc(&tx, commitment_number, height, &*fee_estimator);
2595 if let Some(tx) = tx {
2598 if let Some(spendable_output) = spendable_output {
2599 spendable_outputs.push(spendable_output);
2603 for tx in txn.iter() {
2604 log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
2605 broadcaster.broadcast_transaction(tx);
2608 // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2609 // can also be resolved in a few other ways which can have more than one output. Thus,
2610 // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2611 self.is_resolving_htlc_output(&tx, height);
2613 // Scan all input to verify is one of the outpoint spent is of interest for us
2614 let mut claimed_outputs_material = Vec::new();
2615 for inp in &tx.input {
2616 if let Some(first_claim_txid_height) = self.claimable_outpoints.get(&inp.previous_output) {
2617 // If outpoint has claim request pending on it...
2618 if let Some(claim_material) = self.pending_claim_requests.get_mut(&first_claim_txid_height.0) {
2619 //... we need to verify equality between transaction outpoints and claim request
2620 // outpoints to know if transaction is the original claim or a bumped one issued
2622 let mut set_equality = true;
2623 if claim_material.per_input_material.len() != tx.input.len() {
2624 set_equality = false;
2626 for (claim_inp, tx_inp) in claim_material.per_input_material.keys().zip(tx.input.iter()) {
2627 if *claim_inp != tx_inp.previous_output {
2628 set_equality = false;
2633 macro_rules! clean_claim_request_after_safety_delay {
2635 let new_event = OnchainEvent::Claim { claim_request: first_claim_txid_height.0.clone() };
2636 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2637 hash_map::Entry::Occupied(mut entry) => {
2638 if !entry.get().contains(&new_event) {
2639 entry.get_mut().push(new_event);
2642 hash_map::Entry::Vacant(entry) => {
2643 entry.insert(vec![new_event]);
2649 // If this is our transaction (or our counterparty spent all the outputs
2650 // before we could anyway with same inputs order than us), wait for
2651 // ANTI_REORG_DELAY and clean the RBF tracking map.
2653 clean_claim_request_after_safety_delay!();
2654 } else { // If false, generate new claim request with update outpoint set
2655 for input in tx.input.iter() {
2656 if let Some(input_material) = claim_material.per_input_material.remove(&input.previous_output) {
2657 claimed_outputs_material.push((input.previous_output, input_material));
2659 // If there are no outpoints left to claim in this request, drop it entirely after ANTI_REORG_DELAY.
2660 if claim_material.per_input_material.is_empty() {
2661 clean_claim_request_after_safety_delay!();
2664 //TODO: recompute soonest_timelock to avoid wasting a bit on fees
2665 bump_candidates.insert(first_claim_txid_height.0.clone());
2667 break; //No need to iterate further, either tx is our or their
2669 panic!("Inconsistencies between pending_claim_requests map and claimable_outpoints map");
2673 for (outpoint, input_material) in claimed_outputs_material.drain(..) {
2674 let new_event = OnchainEvent::ContentiousOutpoint { outpoint, input_material };
2675 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
2676 hash_map::Entry::Occupied(mut entry) => {
2677 if !entry.get().contains(&new_event) {
2678 entry.get_mut().push(new_event);
2681 hash_map::Entry::Vacant(entry) => {
2682 entry.insert(vec![new_event]);
2687 let should_broadcast = if let Some(_) = self.current_local_signed_commitment_tx {
2688 self.would_broadcast_at_height(height)
2690 if let Some(ref mut cur_local_tx) = self.current_local_signed_commitment_tx {
2691 if should_broadcast {
2692 match self.key_storage {
2693 Storage::Local { ref funding_key, .. } => {
2694 cur_local_tx.tx.add_local_sig(funding_key, self.funding_redeemscript.as_ref().unwrap(), self.channel_value_satoshis.unwrap(), &self.secp_ctx);
2700 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
2701 if should_broadcast {
2702 log_trace!(self, "Broadcast onchain {}", log_tx!(cur_local_tx.tx.with_valid_witness()));
2703 broadcaster.broadcast_transaction(&cur_local_tx.tx.with_valid_witness());
2704 match self.key_storage {
2705 Storage::Local { ref delayed_payment_base_key, .. } => {
2706 let (txs, mut spendable_output, new_outputs, _) = self.broadcast_by_local_state(&cur_local_tx, delayed_payment_base_key, height);
2707 spendable_outputs.append(&mut spendable_output);
2708 if !new_outputs.is_empty() {
2709 watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
2712 log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
2713 broadcaster.broadcast_transaction(&tx);
2716 Storage::Watchtower { .. } => { },
2720 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&height) {
2723 OnchainEvent::Claim { claim_request } => {
2724 // We may remove a whole set of claim outpoints here, as these one may have
2725 // been aggregated in a single tx and claimed so atomically
2726 if let Some(bump_material) = self.pending_claim_requests.remove(&claim_request) {
2727 for outpoint in bump_material.per_input_material.keys() {
2728 self.claimable_outpoints.remove(&outpoint);
2732 OnchainEvent::HTLCUpdate { htlc_update } => {
2733 log_trace!(self, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!((htlc_update.1).0));
2734 self.pending_htlcs_updated.push(HTLCUpdate {
2735 payment_hash: htlc_update.1,
2736 payment_preimage: None,
2737 source: htlc_update.0,
2740 OnchainEvent::ContentiousOutpoint { outpoint, .. } => {
2741 self.claimable_outpoints.remove(&outpoint);
2746 for (first_claim_txid, ref mut cached_claim_datas) in self.pending_claim_requests.iter_mut() {
2747 if cached_claim_datas.height_timer == height {
2748 bump_candidates.insert(first_claim_txid.clone());
2751 for first_claim_txid in bump_candidates.iter() {
2752 if let Some((new_timer, new_feerate)) = {
2753 if let Some(claim_material) = self.pending_claim_requests.get(first_claim_txid) {
2754 if let Some((new_timer, new_feerate, bump_tx)) = self.bump_claim_tx(height, &claim_material, &*fee_estimator) {
2755 broadcaster.broadcast_transaction(&bump_tx);
2756 Some((new_timer, new_feerate))
2758 } else { unreachable!(); }
2760 if let Some(claim_material) = self.pending_claim_requests.get_mut(first_claim_txid) {
2761 claim_material.height_timer = new_timer;
2762 claim_material.feerate_previous = new_feerate;
2763 } else { unreachable!(); }
2766 self.last_block_hash = block_hash.clone();
2767 for &(ref txid, ref output_scripts) in watch_outputs.iter() {
2768 self.outputs_to_watch.insert(txid.clone(), output_scripts.iter().map(|o| o.script_pubkey.clone()).collect());
2770 (watch_outputs, spendable_outputs)
2773 fn block_disconnected<B: Deref, F: Deref>(&mut self, height: u32, block_hash: &Sha256dHash, broadcaster: B, fee_estimator: F)
2774 where B::Target: BroadcasterInterface,
2775 F::Target: FeeEstimator
2777 log_trace!(self, "Block {} at height {} disconnected", block_hash, height);
2778 let mut bump_candidates = HashMap::new();
2779 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&(height + ANTI_REORG_DELAY - 1)) {
2781 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2782 //- our claim tx on a commitment tx output
2783 //- resurect outpoint back in its claimable set and regenerate tx
2786 OnchainEvent::ContentiousOutpoint { outpoint, input_material } => {
2787 if let Some(ancestor_claimable_txid) = self.claimable_outpoints.get(&outpoint) {
2788 if let Some(claim_material) = self.pending_claim_requests.get_mut(&ancestor_claimable_txid.0) {
2789 claim_material.per_input_material.insert(outpoint, input_material);
2790 // Using a HashMap guarantee us than if we have multiple outpoints getting
2791 // resurrected only one bump claim tx is going to be broadcast
2792 bump_candidates.insert(ancestor_claimable_txid.clone(), claim_material.clone());
2800 for (_, claim_material) in bump_candidates.iter_mut() {
2801 if let Some((new_timer, new_feerate, bump_tx)) = self.bump_claim_tx(height, &claim_material, &*fee_estimator) {
2802 claim_material.height_timer = new_timer;
2803 claim_material.feerate_previous = new_feerate;
2804 broadcaster.broadcast_transaction(&bump_tx);
2807 for (ancestor_claim_txid, claim_material) in bump_candidates.drain() {
2808 self.pending_claim_requests.insert(ancestor_claim_txid.0, claim_material);
2810 //TODO: if we implement cross-block aggregated claim transaction we need to refresh set of outpoints and regenerate tx but
2811 // right now if one of the outpoint get disconnected, just erase whole pending claim request.
2812 let mut remove_request = Vec::new();
2813 self.claimable_outpoints.retain(|_, ref v|
2815 remove_request.push(v.0.clone());
2818 for req in remove_request {
2819 self.pending_claim_requests.remove(&req);
2821 self.last_block_hash = block_hash.clone();
2824 pub(super) fn would_broadcast_at_height(&self, height: u32) -> bool {
2825 // We need to consider all HTLCs which are:
2826 // * in any unrevoked remote commitment transaction, as they could broadcast said
2827 // transactions and we'd end up in a race, or
2828 // * are in our latest local commitment transaction, as this is the thing we will
2829 // broadcast if we go on-chain.
2830 // Note that we consider HTLCs which were below dust threshold here - while they don't
2831 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
2832 // to the source, and if we don't fail the channel we will have to ensure that the next
2833 // updates that peer sends us are update_fails, failing the channel if not. It's probably
2834 // easier to just fail the channel as this case should be rare enough anyway.
2835 macro_rules! scan_commitment {
2836 ($htlcs: expr, $local_tx: expr) => {
2837 for ref htlc in $htlcs {
2838 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
2839 // chain with enough room to claim the HTLC without our counterparty being able to
2840 // time out the HTLC first.
2841 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
2842 // concern is being able to claim the corresponding inbound HTLC (on another
2843 // channel) before it expires. In fact, we don't even really care if our
2844 // counterparty here claims such an outbound HTLC after it expired as long as we
2845 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
2846 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
2847 // we give ourselves a few blocks of headroom after expiration before going
2848 // on-chain for an expired HTLC.
2849 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
2850 // from us until we've reached the point where we go on-chain with the
2851 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
2852 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
2853 // aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
2854 // inbound_cltv == height + CLTV_CLAIM_BUFFER
2855 // outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
2856 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
2857 // CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
2858 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
2859 // The final, above, condition is checked for statically in channelmanager
2860 // with CHECK_CLTV_EXPIRY_SANITY_2.
2861 let htlc_outbound = $local_tx == htlc.offered;
2862 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
2863 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
2864 log_info!(self, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
2871 if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
2872 scan_commitment!(cur_local_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
2875 if let Storage::Local { ref current_remote_commitment_txid, ref prev_remote_commitment_txid, .. } = self.key_storage {
2876 if let &Some(ref txid) = current_remote_commitment_txid {
2877 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2878 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2881 if let &Some(ref txid) = prev_remote_commitment_txid {
2882 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(txid) {
2883 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
2891 /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a local
2892 /// or remote commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
2893 fn is_resolving_htlc_output(&mut self, tx: &Transaction, height: u32) {
2894 'outer_loop: for input in &tx.input {
2895 let mut payment_data = None;
2896 let revocation_sig_claim = (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && input.witness[1].len() == 33)
2897 || (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && input.witness[1].len() == 33);
2898 let accepted_preimage_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::AcceptedHTLC);
2899 let offered_preimage_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC);
2901 macro_rules! log_claim {
2902 ($tx_info: expr, $local_tx: expr, $htlc: expr, $source_avail: expr) => {
2903 // We found the output in question, but aren't failing it backwards
2904 // as we have no corresponding source and no valid remote commitment txid
2905 // to try a weak source binding with same-hash, same-value still-valid offered HTLC.
2906 // This implies either it is an inbound HTLC or an outbound HTLC on a revoked transaction.
2907 let outbound_htlc = $local_tx == $htlc.offered;
2908 if ($local_tx && revocation_sig_claim) ||
2909 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
2910 log_error!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
2911 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2912 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2913 if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back" });
2915 log_info!(self, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
2916 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
2917 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
2918 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
2923 macro_rules! check_htlc_valid_remote {
2924 ($remote_txid: expr, $htlc_output: expr) => {
2925 if let &Some(txid) = $remote_txid {
2926 for &(ref pending_htlc, ref pending_source) in self.remote_claimable_outpoints.get(&txid).unwrap() {
2927 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
2928 if let &Some(ref source) = pending_source {
2929 log_claim!("revoked remote commitment tx", false, pending_htlc, true);
2930 payment_data = Some(((**source).clone(), $htlc_output.payment_hash));
2939 macro_rules! scan_commitment {
2940 ($htlcs: expr, $tx_info: expr, $local_tx: expr) => {
2941 for (ref htlc_output, source_option) in $htlcs {
2942 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
2943 if let Some(ref source) = source_option {
2944 log_claim!($tx_info, $local_tx, htlc_output, true);
2945 // We have a resolution of an HTLC either from one of our latest
2946 // local commitment transactions or an unrevoked remote commitment
2947 // transaction. This implies we either learned a preimage, the HTLC
2948 // has timed out, or we screwed up. In any case, we should now
2949 // resolve the source HTLC with the original sender.
2950 payment_data = Some(((*source).clone(), htlc_output.payment_hash));
2951 } else if !$local_tx {
2952 if let Storage::Local { ref current_remote_commitment_txid, .. } = self.key_storage {
2953 check_htlc_valid_remote!(current_remote_commitment_txid, htlc_output);
2955 if payment_data.is_none() {
2956 if let Storage::Local { ref prev_remote_commitment_txid, .. } = self.key_storage {
2957 check_htlc_valid_remote!(prev_remote_commitment_txid, htlc_output);
2961 if payment_data.is_none() {
2962 log_claim!($tx_info, $local_tx, htlc_output, false);
2963 continue 'outer_loop;
2970 if let Some(ref current_local_signed_commitment_tx) = self.current_local_signed_commitment_tx {
2971 if input.previous_output.txid == current_local_signed_commitment_tx.txid {
2972 scan_commitment!(current_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2973 "our latest local commitment tx", true);
2976 if let Some(ref prev_local_signed_commitment_tx) = self.prev_local_signed_commitment_tx {
2977 if input.previous_output.txid == prev_local_signed_commitment_tx.txid {
2978 scan_commitment!(prev_local_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
2979 "our previous local commitment tx", true);
2982 if let Some(ref htlc_outputs) = self.remote_claimable_outpoints.get(&input.previous_output.txid) {
2983 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
2984 "remote commitment tx", false);
2987 // Check that scan_commitment, above, decided there is some source worth relaying an
2988 // HTLC resolution backwards to and figure out whether we learned a preimage from it.
2989 if let Some((source, payment_hash)) = payment_data {
2990 let mut payment_preimage = PaymentPreimage([0; 32]);
2991 if accepted_preimage_claim {
2992 payment_preimage.0.copy_from_slice(&input.witness[3]);
2993 self.pending_htlcs_updated.push(HTLCUpdate {
2995 payment_preimage: Some(payment_preimage),
2998 } else if offered_preimage_claim {
2999 payment_preimage.0.copy_from_slice(&input.witness[1]);
3000 self.pending_htlcs_updated.push(HTLCUpdate {
3002 payment_preimage: Some(payment_preimage),
3006 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);
3007 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
3008 hash_map::Entry::Occupied(mut entry) => {
3009 let e = entry.get_mut();
3010 e.retain(|ref event| {
3012 OnchainEvent::HTLCUpdate { ref htlc_update } => {
3013 return htlc_update.0 != source
3018 e.push(OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)});
3020 hash_map::Entry::Vacant(entry) => {
3021 entry.insert(vec![OnchainEvent::HTLCUpdate { htlc_update: (source, payment_hash)}]);
3029 /// 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
3030 /// (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.
3031 fn bump_claim_tx<F: Deref>(&self, height: u32, cached_claim_datas: &ClaimTxBumpMaterial, fee_estimator: F) -> Option<(u32, u64, Transaction)>
3032 where F::Target: FeeEstimator
3034 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
3035 let mut inputs = Vec::new();
3036 for outp in cached_claim_datas.per_input_material.keys() {
3038 previous_output: *outp,
3039 script_sig: Script::new(),
3040 sequence: 0xfffffffd,
3041 witness: Vec::new(),
3044 let mut bumped_tx = Transaction {
3048 output: vec![TxOut {
3049 script_pubkey: self.destination_script.clone(),
3054 macro_rules! RBF_bump {
3055 ($amount: expr, $old_feerate: expr, $fee_estimator: expr, $predicted_weight: expr) => {
3057 let mut used_feerate;
3058 // If old feerate inferior to actual one given back by Fee Estimator, use it to compute new fee...
3059 let new_fee = if $old_feerate < $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority) {
3060 let mut value = $amount;
3061 if subtract_high_prio_fee!(self, $fee_estimator, value, $predicted_weight, used_feerate) {
3062 // Overflow check is done in subtract_high_prio_fee
3065 log_trace!(self, "Can't new-estimation bump new claiming tx, amount {} is too small", $amount);
3068 // ...else just increase the previous feerate by 25% (because that's a nice number)
3070 let fee = $old_feerate * $predicted_weight / 750;
3072 log_trace!(self, "Can't 25% bump new claiming tx, amount {} is too small", $amount);
3078 let previous_fee = $old_feerate * $predicted_weight / 1000;
3079 let min_relay_fee = MIN_RELAY_FEE_SAT_PER_1000_WEIGHT * $predicted_weight / 1000;
3080 // BIP 125 Opt-in Full Replace-by-Fee Signaling
3081 // * 3. The replacement transaction pays an absolute fee of at least the sum paid by the original transactions.
3082 // * 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.
3083 let new_fee = if new_fee < previous_fee + min_relay_fee {
3084 new_fee + previous_fee + min_relay_fee - new_fee
3088 Some((new_fee, new_fee * 1000 / $predicted_weight))
3093 let new_timer = Self::get_height_timer(height, cached_claim_datas.soonest_timelock);
3094 let mut inputs_witnesses_weight = 0;
3096 for per_outp_material in cached_claim_datas.per_input_material.values() {
3097 match per_outp_material {
3098 &InputMaterial::Revoked { ref script, ref is_htlc, ref amount, .. } => {
3099 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!() });
3102 &InputMaterial::RemoteHTLC { ref preimage, ref amount, .. } => {
3103 inputs_witnesses_weight += Self::get_witnesses_weight(if preimage.is_some() { &[InputDescriptors::OfferedHTLC] } else { &[InputDescriptors::ReceivedHTLC] });
3106 &InputMaterial::LocalHTLC { .. } => { return None; }
3110 let predicted_weight = bumped_tx.get_weight() + inputs_witnesses_weight;
3112 if let Some((new_fee, feerate)) = RBF_bump!(amt, cached_claim_datas.feerate_previous, fee_estimator, predicted_weight as u64) {
3113 // If new computed fee is superior at the whole claimable amount burn all in fees
3115 bumped_tx.output[0].value = 0;
3117 bumped_tx.output[0].value = amt - new_fee;
3119 new_feerate = feerate;
3123 assert!(new_feerate != 0);
3125 for (i, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() {
3126 match per_outp_material {
3127 &InputMaterial::Revoked { ref script, ref pubkey, ref key, ref is_htlc, ref amount } => {
3128 let sighash_parts = bip143::SighashComponents::new(&bumped_tx);
3129 let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &script, *amount)[..]);
3130 let sig = self.secp_ctx.sign(&sighash, &key);
3131 bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
3132 bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
3134 bumped_tx.input[i].witness.push(pubkey.unwrap().clone().serialize().to_vec());
3136 bumped_tx.input[i].witness.push(vec!(1));
3138 bumped_tx.input[i].witness.push(script.clone().into_bytes());
3139 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);
3141 &InputMaterial::RemoteHTLC { ref script, ref key, ref preimage, ref amount, ref locktime } => {
3142 if !preimage.is_some() { bumped_tx.lock_time = *locktime };
3143 let sighash_parts = bip143::SighashComponents::new(&bumped_tx);
3144 let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &script, *amount)[..]);
3145 let sig = self.secp_ctx.sign(&sighash, &key);
3146 bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
3147 bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
3148 if let &Some(preimage) = preimage {
3149 bumped_tx.input[i].witness.push(preimage.clone().0.to_vec());
3151 bumped_tx.input[i].witness.push(vec![0]);
3153 bumped_tx.input[i].witness.push(script.clone().into_bytes());
3154 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);
3156 &InputMaterial::LocalHTLC { .. } => {
3157 //TODO : Given that Local Commitment Transaction and HTLC-Timeout/HTLC-Success are counter-signed by peer, we can't
3158 // RBF them. Need a Lightning specs change and package relay modification :
3159 // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-November/016518.html
3164 assert!(predicted_weight >= bumped_tx.get_weight());
3165 Some((new_timer, new_feerate, bumped_tx))
3169 const MAX_ALLOC_SIZE: usize = 64*1024;
3171 impl<R: ::std::io::Read, ChanSigner: ChannelKeys + Readable<R>> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelMonitor<ChanSigner>) {
3172 fn read(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
3173 let secp_ctx = Secp256k1::new();
3174 macro_rules! unwrap_obj {
3178 Err(_) => return Err(DecodeError::InvalidValue),
3183 let _ver: u8 = Readable::read(reader)?;
3184 let min_ver: u8 = Readable::read(reader)?;
3185 if min_ver > SERIALIZATION_VERSION {
3186 return Err(DecodeError::UnknownVersion);
3189 let latest_update_id: u64 = Readable::read(reader)?;
3190 let commitment_transaction_number_obscure_factor = <U48 as Readable<R>>::read(reader)?.0;
3192 let key_storage = match <u8 as Readable<R>>::read(reader)? {
3194 let keys = Readable::read(reader)?;
3195 let funding_key = Readable::read(reader)?;
3196 let revocation_base_key = Readable::read(reader)?;
3197 let htlc_base_key = Readable::read(reader)?;
3198 let delayed_payment_base_key = Readable::read(reader)?;
3199 let payment_base_key = Readable::read(reader)?;
3200 let shutdown_pubkey = Readable::read(reader)?;
3201 // Technically this can fail and serialize fail a round-trip, but only for serialization of
3202 // barely-init'd ChannelMonitors that we can't do anything with.
3203 let outpoint = OutPoint {
3204 txid: Readable::read(reader)?,
3205 index: Readable::read(reader)?,
3207 let funding_info = Some((outpoint, Readable::read(reader)?));
3208 let current_remote_commitment_txid = Readable::read(reader)?;
3209 let prev_remote_commitment_txid = Readable::read(reader)?;
3213 revocation_base_key,
3215 delayed_payment_base_key,
3219 current_remote_commitment_txid,
3220 prev_remote_commitment_txid,
3223 _ => return Err(DecodeError::InvalidValue),
3226 let their_htlc_base_key = Some(Readable::read(reader)?);
3227 let their_delayed_payment_base_key = Some(Readable::read(reader)?);
3228 let funding_redeemscript = Some(Readable::read(reader)?);
3229 let channel_value_satoshis = Some(Readable::read(reader)?);
3231 let their_cur_revocation_points = {
3232 let first_idx = <U48 as Readable<R>>::read(reader)?.0;
3236 let first_point = Readable::read(reader)?;
3237 let second_point_slice: [u8; 33] = Readable::read(reader)?;
3238 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
3239 Some((first_idx, first_point, None))
3241 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
3246 let our_to_self_delay: u16 = Readable::read(reader)?;
3247 let their_to_self_delay: Option<u16> = Some(Readable::read(reader)?);
3249 let commitment_secrets = Readable::read(reader)?;
3251 macro_rules! read_htlc_in_commitment {
3254 let offered: bool = Readable::read(reader)?;
3255 let amount_msat: u64 = Readable::read(reader)?;
3256 let cltv_expiry: u32 = Readable::read(reader)?;
3257 let payment_hash: PaymentHash = Readable::read(reader)?;
3258 let transaction_output_index: Option<u32> = Readable::read(reader)?;
3260 HTLCOutputInCommitment {
3261 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
3267 let remote_claimable_outpoints_len: u64 = Readable::read(reader)?;
3268 let mut remote_claimable_outpoints = HashMap::with_capacity(cmp::min(remote_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
3269 for _ in 0..remote_claimable_outpoints_len {
3270 let txid: Sha256dHash = Readable::read(reader)?;
3271 let htlcs_count: u64 = Readable::read(reader)?;
3272 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
3273 for _ in 0..htlcs_count {
3274 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable<R>>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
3276 if let Some(_) = remote_claimable_outpoints.insert(txid, htlcs) {
3277 return Err(DecodeError::InvalidValue);
3281 let remote_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
3282 let mut remote_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(remote_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
3283 for _ in 0..remote_commitment_txn_on_chain_len {
3284 let txid: Sha256dHash = Readable::read(reader)?;
3285 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
3286 let outputs_count = <u64 as Readable<R>>::read(reader)?;
3287 let mut outputs = Vec::with_capacity(cmp::min(outputs_count as usize, MAX_ALLOC_SIZE / 8));
3288 for _ in 0..outputs_count {
3289 outputs.push(Readable::read(reader)?);
3291 if let Some(_) = remote_commitment_txn_on_chain.insert(txid, (commitment_number, outputs)) {
3292 return Err(DecodeError::InvalidValue);
3296 let remote_hash_commitment_number_len: u64 = Readable::read(reader)?;
3297 let mut remote_hash_commitment_number = HashMap::with_capacity(cmp::min(remote_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
3298 for _ in 0..remote_hash_commitment_number_len {
3299 let payment_hash: PaymentHash = Readable::read(reader)?;
3300 let commitment_number = <U48 as Readable<R>>::read(reader)?.0;
3301 if let Some(_) = remote_hash_commitment_number.insert(payment_hash, commitment_number) {
3302 return Err(DecodeError::InvalidValue);
3306 macro_rules! read_local_tx {
3309 let tx = <LocalCommitmentTransaction as Readable<R>>::read(reader)?;
3310 let revocation_key = Readable::read(reader)?;
3311 let a_htlc_key = Readable::read(reader)?;
3312 let b_htlc_key = Readable::read(reader)?;
3313 let delayed_payment_key = Readable::read(reader)?;
3314 let per_commitment_point = Readable::read(reader)?;
3315 let feerate_per_kw: u64 = Readable::read(reader)?;
3317 let htlcs_len: u64 = Readable::read(reader)?;
3318 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_len as usize, MAX_ALLOC_SIZE / 128));
3319 for _ in 0..htlcs_len {
3320 let htlc = read_htlc_in_commitment!();
3321 let sigs = match <u8 as Readable<R>>::read(reader)? {
3323 1 => Some(Readable::read(reader)?),
3324 _ => return Err(DecodeError::InvalidValue),
3326 htlcs.push((htlc, sigs, Readable::read(reader)?));
3331 tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, per_commitment_point, feerate_per_kw,
3338 let prev_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
3341 Some(read_local_tx!())
3343 _ => return Err(DecodeError::InvalidValue),
3346 let current_local_signed_commitment_tx = match <u8 as Readable<R>>::read(reader)? {
3349 Some(read_local_tx!())
3351 _ => return Err(DecodeError::InvalidValue),
3354 let current_remote_commitment_number = <U48 as Readable<R>>::read(reader)?.0;
3356 let payment_preimages_len: u64 = Readable::read(reader)?;
3357 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
3358 for _ in 0..payment_preimages_len {
3359 let preimage: PaymentPreimage = Readable::read(reader)?;
3360 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3361 if let Some(_) = payment_preimages.insert(hash, preimage) {
3362 return Err(DecodeError::InvalidValue);
3366 let pending_htlcs_updated_len: u64 = Readable::read(reader)?;
3367 let mut pending_htlcs_updated = Vec::with_capacity(cmp::min(pending_htlcs_updated_len as usize, MAX_ALLOC_SIZE / (32 + 8*3)));
3368 for _ in 0..pending_htlcs_updated_len {
3369 pending_htlcs_updated.push(Readable::read(reader)?);
3372 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3373 let destination_script = Readable::read(reader)?;
3374 let to_remote_rescue = match <u8 as Readable<R>>::read(reader)? {
3377 let to_remote_script = Readable::read(reader)?;
3378 let local_key = Readable::read(reader)?;
3379 Some((to_remote_script, local_key))
3381 _ => return Err(DecodeError::InvalidValue),
3384 let pending_claim_requests_len: u64 = Readable::read(reader)?;
3385 let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
3386 for _ in 0..pending_claim_requests_len {
3387 pending_claim_requests.insert(Readable::read(reader)?, Readable::read(reader)?);
3390 let claimable_outpoints_len: u64 = Readable::read(reader)?;
3391 let mut claimable_outpoints = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
3392 for _ in 0..claimable_outpoints_len {
3393 let outpoint = Readable::read(reader)?;
3394 let ancestor_claim_txid = Readable::read(reader)?;
3395 let height = Readable::read(reader)?;
3396 claimable_outpoints.insert(outpoint, (ancestor_claim_txid, height));
3399 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
3400 let mut onchain_events_waiting_threshold_conf = HashMap::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
3401 for _ in 0..waiting_threshold_conf_len {
3402 let height_target = Readable::read(reader)?;
3403 let events_len: u64 = Readable::read(reader)?;
3404 let mut events = Vec::with_capacity(cmp::min(events_len as usize, MAX_ALLOC_SIZE / 128));
3405 for _ in 0..events_len {
3406 let ev = match <u8 as Readable<R>>::read(reader)? {
3408 let claim_request = Readable::read(reader)?;
3409 OnchainEvent::Claim {
3414 let htlc_source = Readable::read(reader)?;
3415 let hash = Readable::read(reader)?;
3416 OnchainEvent::HTLCUpdate {
3417 htlc_update: (htlc_source, hash)
3421 let outpoint = Readable::read(reader)?;
3422 let input_material = Readable::read(reader)?;
3423 OnchainEvent::ContentiousOutpoint {
3428 _ => return Err(DecodeError::InvalidValue),
3432 onchain_events_waiting_threshold_conf.insert(height_target, events);
3435 let outputs_to_watch_len: u64 = Readable::read(reader)?;
3436 let mut outputs_to_watch = HashMap::with_capacity(cmp::min(outputs_to_watch_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<Sha256dHash>() + mem::size_of::<Vec<Script>>())));
3437 for _ in 0..outputs_to_watch_len {
3438 let txid = Readable::read(reader)?;
3439 let outputs_len: u64 = Readable::read(reader)?;
3440 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Script>()));
3441 for _ in 0..outputs_len {
3442 outputs.push(Readable::read(reader)?);
3444 if let Some(_) = outputs_to_watch.insert(txid, outputs) {
3445 return Err(DecodeError::InvalidValue);
3449 Ok((last_block_hash.clone(), ChannelMonitor {
3451 commitment_transaction_number_obscure_factor,
3454 their_htlc_base_key,
3455 their_delayed_payment_base_key,
3456 funding_redeemscript,
3457 channel_value_satoshis,
3458 their_cur_revocation_points,
3461 their_to_self_delay,
3464 remote_claimable_outpoints,
3465 remote_commitment_txn_on_chain,
3466 remote_hash_commitment_number,
3468 prev_local_signed_commitment_tx,
3469 current_local_signed_commitment_tx,
3470 current_remote_commitment_number,
3473 pending_htlcs_updated,
3478 pending_claim_requests,
3480 claimable_outpoints,
3482 onchain_events_waiting_threshold_conf,
3495 use bitcoin::blockdata::script::{Script, Builder};
3496 use bitcoin::blockdata::opcodes;
3497 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
3498 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
3499 use bitcoin::util::bip143;
3500 use bitcoin_hashes::Hash;
3501 use bitcoin_hashes::sha256::Hash as Sha256;
3502 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
3503 use bitcoin_hashes::hex::FromHex;
3505 use chain::transaction::OutPoint;
3506 use ln::channelmanager::{PaymentPreimage, PaymentHash};
3507 use ln::channelmonitor::{ChannelMonitor, InputDescriptors};
3509 use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys, LocalCommitmentTransaction};
3510 use util::test_utils::TestLogger;
3511 use secp256k1::key::{SecretKey,PublicKey};
3512 use secp256k1::Secp256k1;
3513 use rand::{thread_rng,Rng};
3515 use chain::keysinterface::InMemoryChannelKeys;
3518 fn test_prune_preimages() {
3519 let secp_ctx = Secp256k1::new();
3520 let logger = Arc::new(TestLogger::new());
3522 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3523 macro_rules! dummy_keys {
3527 per_commitment_point: dummy_key.clone(),
3528 revocation_key: dummy_key.clone(),
3529 a_htlc_key: dummy_key.clone(),
3530 b_htlc_key: dummy_key.clone(),
3531 a_delayed_payment_key: dummy_key.clone(),
3532 b_payment_key: dummy_key.clone(),
3537 let dummy_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3539 let mut preimages = Vec::new();
3541 let mut rng = thread_rng();
3543 let mut preimage = PaymentPreimage([0; 32]);
3544 rng.fill_bytes(&mut preimage.0[..]);
3545 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3546 preimages.push((preimage, hash));
3550 macro_rules! preimages_slice_to_htlc_outputs {
3551 ($preimages_slice: expr) => {
3553 let mut res = Vec::new();
3554 for (idx, preimage) in $preimages_slice.iter().enumerate() {
3555 res.push((HTLCOutputInCommitment {
3559 payment_hash: preimage.1.clone(),
3560 transaction_output_index: Some(idx as u32),
3567 macro_rules! preimages_to_local_htlcs {
3568 ($preimages_slice: expr) => {
3570 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
3571 let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
3577 macro_rules! test_preimages_exist {
3578 ($preimages_slice: expr, $monitor: expr) => {
3579 for preimage in $preimages_slice {
3580 assert!($monitor.payment_preimages.contains_key(&preimage.1));
3585 let keys = InMemoryChannelKeys::new(
3587 SecretKey::from_slice(&[41; 32]).unwrap(),
3588 SecretKey::from_slice(&[41; 32]).unwrap(),
3589 SecretKey::from_slice(&[41; 32]).unwrap(),
3590 SecretKey::from_slice(&[41; 32]).unwrap(),
3591 SecretKey::from_slice(&[41; 32]).unwrap(),
3596 // Prune with one old state and a local commitment tx holding a few overlaps with the
3598 let mut monitor = ChannelMonitor::new(keys,
3599 &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0, &Script::new(),
3600 (OutPoint { txid: Sha256dHash::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
3601 &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
3602 &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
3603 0, Script::new(), 46, 0, logger.clone());
3605 monitor.their_to_self_delay = Some(10);
3607 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10])).unwrap();
3608 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
3609 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
3610 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
3611 monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key);
3612 for &(ref preimage, ref hash) in preimages.iter() {
3613 monitor.provide_payment_preimage(hash, preimage);
3616 // Now provide a secret, pruning preimages 10-15
3617 let mut secret = [0; 32];
3618 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3619 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
3620 assert_eq!(monitor.payment_preimages.len(), 15);
3621 test_preimages_exist!(&preimages[0..10], monitor);
3622 test_preimages_exist!(&preimages[15..20], monitor);
3624 // Now provide a further secret, pruning preimages 15-17
3625 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3626 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
3627 assert_eq!(monitor.payment_preimages.len(), 13);
3628 test_preimages_exist!(&preimages[0..10], monitor);
3629 test_preimages_exist!(&preimages[17..20], monitor);
3631 // Now update local commitment tx info, pruning only element 18 as we still care about the
3632 // previous commitment tx's preimages too
3633 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5])).unwrap();
3634 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3635 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
3636 assert_eq!(monitor.payment_preimages.len(), 12);
3637 test_preimages_exist!(&preimages[0..10], monitor);
3638 test_preimages_exist!(&preimages[18..20], monitor);
3640 // But if we do it again, we'll prune 5-10
3641 monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3])).unwrap();
3642 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3643 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
3644 assert_eq!(monitor.payment_preimages.len(), 5);
3645 test_preimages_exist!(&preimages[0..5], monitor);
3649 fn test_claim_txn_weight_computation() {
3650 // We test Claim txn weight, knowing that we want expected weigth and
3651 // not actual case to avoid sigs and time-lock delays hell variances.
3653 let secp_ctx = Secp256k1::new();
3654 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3655 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3656 let mut sum_actual_sigs = 0;
3658 macro_rules! sign_input {
3659 ($sighash_parts: expr, $input: expr, $idx: expr, $amount: expr, $input_type: expr, $sum_actual_sigs: expr) => {
3660 let htlc = HTLCOutputInCommitment {
3661 offered: if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::OfferedHTLC { true } else { false },
3663 cltv_expiry: 2 << 16,
3664 payment_hash: PaymentHash([1; 32]),
3665 transaction_output_index: Some($idx),
3667 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) };
3668 let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeem_script, $amount)[..]);
3669 let sig = secp_ctx.sign(&sighash, &privkey);
3670 $input.witness.push(sig.serialize_der().to_vec());
3671 $input.witness[0].push(SigHashType::All as u8);
3672 sum_actual_sigs += $input.witness[0].len();
3673 if *$input_type == InputDescriptors::RevokedOutput {
3674 $input.witness.push(vec!(1));
3675 } else if *$input_type == InputDescriptors::RevokedOfferedHTLC || *$input_type == InputDescriptors::RevokedReceivedHTLC {
3676 $input.witness.push(pubkey.clone().serialize().to_vec());
3677 } else if *$input_type == InputDescriptors::ReceivedHTLC {
3678 $input.witness.push(vec![0]);
3680 $input.witness.push(PaymentPreimage([1; 32]).0.to_vec());
3682 $input.witness.push(redeem_script.into_bytes());
3683 println!("witness[0] {}", $input.witness[0].len());
3684 println!("witness[1] {}", $input.witness[1].len());
3685 println!("witness[2] {}", $input.witness[2].len());
3689 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
3690 let txid = Sha256dHash::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
3692 // Justice tx with 1 to_local, 2 revoked offered HTLCs, 1 revoked received HTLCs
3693 let mut claim_tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() };
3695 claim_tx.input.push(TxIn {
3696 previous_output: BitcoinOutPoint {
3700 script_sig: Script::new(),
3701 sequence: 0xfffffffd,
3702 witness: Vec::new(),
3705 claim_tx.output.push(TxOut {
3706 script_pubkey: script_pubkey.clone(),
3709 let base_weight = claim_tx.get_weight();
3710 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3711 let inputs_des = vec![InputDescriptors::RevokedOutput, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedOfferedHTLC, InputDescriptors::RevokedReceivedHTLC];
3712 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3713 sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3715 assert_eq!(base_weight + ChannelMonitor::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
3717 // Claim tx with 1 offered HTLCs, 3 received HTLCs
3718 claim_tx.input.clear();
3719 sum_actual_sigs = 0;
3721 claim_tx.input.push(TxIn {
3722 previous_output: BitcoinOutPoint {
3726 script_sig: Script::new(),
3727 sequence: 0xfffffffd,
3728 witness: Vec::new(),
3731 let base_weight = claim_tx.get_weight();
3732 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3733 let inputs_des = vec![InputDescriptors::OfferedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC, InputDescriptors::ReceivedHTLC];
3734 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3735 sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3737 assert_eq!(base_weight + ChannelMonitor::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
3739 // Justice tx with 1 revoked HTLC-Success tx output
3740 claim_tx.input.clear();
3741 sum_actual_sigs = 0;
3742 claim_tx.input.push(TxIn {
3743 previous_output: BitcoinOutPoint {
3747 script_sig: Script::new(),
3748 sequence: 0xfffffffd,
3749 witness: Vec::new(),
3751 let base_weight = claim_tx.get_weight();
3752 let sighash_parts = bip143::SighashComponents::new(&claim_tx);
3753 let inputs_des = vec![InputDescriptors::RevokedOutput];
3754 for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
3755 sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
3757 assert_eq!(base_weight + ChannelMonitor::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs));
3760 // Further testing is done in the ChannelManager integration tests.