forked from lightningdevkit/rust-lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchannelmonitor.rs
3568 lines (3272 loc) · 159 KB
/
channelmonitor.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! The logic to monitor for on-chain transactions and create the relevant claim responses lives
//! here.
//!
//! ChannelMonitor objects are generated by ChannelManager in response to relevant
//! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
//! be made in responding to certain messages, see [`chain::Watch`] for more.
//!
//! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
//! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
//! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
//! security-domain-separated system design, you should consider having multiple paths for
//! ChannelMonitors to get out of the HSM and onto monitoring devices.
use bitcoin::blockdata::block::{Block, BlockHeader};
use bitcoin::blockdata::transaction::{TxOut,Transaction};
use bitcoin::blockdata::script::{Script, Builder};
use bitcoin::blockdata::opcodes;
use bitcoin::hashes::Hash;
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
use bitcoin::secp256k1::{Secp256k1,Signature};
use bitcoin::secp256k1::key::{SecretKey,PublicKey};
use bitcoin::secp256k1;
use ln::{PaymentHash, PaymentPreimage};
use ln::msgs::DecodeError;
use ln::chan_utils;
use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCType, ChannelTransactionParameters, HolderCommitmentTransaction};
use ln::channelmanager::HTLCSource;
use chain;
use chain::{BestBlock, WatchedOutput};
use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
use chain::transaction::{OutPoint, TransactionData};
use chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, Sign, KeysInterface};
use chain::onchaintx::OnchainTxHandler;
use chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedOutput, RevokedHTLCOutput};
use chain::Filter;
use util::logger::Logger;
use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, U48, OptionDeserWrapper};
use util::byte_utils;
use util::events::Event;
use prelude::*;
use core::{cmp, mem};
use io::{self, Error};
use core::ops::Deref;
use sync::Mutex;
/// An update generated by the underlying Channel itself which contains some new information the
/// ChannelMonitor should be made aware of.
#[cfg_attr(any(test, feature = "fuzztarget", feature = "_test_utils"), derive(PartialEq))]
#[derive(Clone)]
#[must_use]
pub struct ChannelMonitorUpdate {
pub(crate) updates: Vec<ChannelMonitorUpdateStep>,
/// The sequence number of this update. Updates *must* be replayed in-order according to this
/// sequence number (and updates may panic if they are not). The update_id values are strictly
/// increasing and increase by one for each new update, with one exception specified below.
///
/// This sequence number is also used to track up to which points updates which returned
/// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
/// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
///
/// The only instance where update_id values are not strictly increasing is the case where we
/// allow post-force-close updates with a special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. See
/// its docs for more details.
pub update_id: u64,
}
/// If:
/// (1) a channel has been force closed and
/// (2) we receive a preimage from a forward link that allows us to spend an HTLC output on
/// this channel's (the backward link's) broadcasted commitment transaction
/// then we allow the `ChannelManager` to send a `ChannelMonitorUpdate` with this update ID,
/// with the update providing said payment preimage. No other update types are allowed after
/// force-close.
pub const CLOSED_CHANNEL_UPDATE_ID: u64 = core::u64::MAX;
impl Writeable for ChannelMonitorUpdate {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
write_ver_prefix!(w, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
self.update_id.write(w)?;
(self.updates.len() as u64).write(w)?;
for update_step in self.updates.iter() {
update_step.write(w)?;
}
write_tlv_fields!(w, {});
Ok(())
}
}
impl Readable for ChannelMonitorUpdate {
fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
let _ver = read_ver_prefix!(r, SERIALIZATION_VERSION);
let update_id: u64 = Readable::read(r)?;
let len: u64 = Readable::read(r)?;
let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<ChannelMonitorUpdateStep>()));
for _ in 0..len {
if let Some(upd) = MaybeReadable::read(r)? {
updates.push(upd);
}
}
read_tlv_fields!(r, {});
Ok(Self { update_id, updates })
}
}
/// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
/// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::update_monitor this
/// means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was
/// corrupted.
/// Contains a developer-readable error message.
#[derive(Clone, Debug)]
pub struct MonitorUpdateError(pub &'static str);
/// An event to be processed by the ChannelManager.
#[derive(Clone, PartialEq)]
pub enum MonitorEvent {
/// A monitor event containing an HTLCUpdate.
HTLCEvent(HTLCUpdate),
/// A monitor event that the Channel's commitment transaction was confirmed.
CommitmentTxConfirmed(OutPoint),
/// Indicates a [`ChannelMonitor`] update has completed. See
/// [`ChannelMonitorUpdateErr::TemporaryFailure`] for more information on how this is used.
///
/// [`ChannelMonitorUpdateErr::TemporaryFailure`]: super::ChannelMonitorUpdateErr::TemporaryFailure
UpdateCompleted {
/// The funding outpoint of the [`ChannelMonitor`] that was updated
funding_txo: OutPoint,
/// The Update ID from [`ChannelMonitorUpdate::update_id`] which was applied or
/// [`ChannelMonitor::get_latest_update_id`].
///
/// Note that this should only be set to a given update's ID if all previous updates for the
/// same [`ChannelMonitor`] have been applied and persisted.
monitor_update_id: u64,
},
/// Indicates a [`ChannelMonitor`] update has failed. See
/// [`ChannelMonitorUpdateErr::PermanentFailure`] for more information on how this is used.
///
/// [`ChannelMonitorUpdateErr::PermanentFailure`]: super::ChannelMonitorUpdateErr::PermanentFailure
UpdateFailed(OutPoint),
}
impl_writeable_tlv_based_enum_upgradable!(MonitorEvent,
// Note that UpdateCompleted and UpdateFailed are currently never serialized to disk as they are
// generated only in ChainMonitor
(0, UpdateCompleted) => {
(0, funding_txo, required),
(2, monitor_update_id, required),
},
;
(2, HTLCEvent),
(4, CommitmentTxConfirmed),
(6, UpdateFailed),
);
/// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
/// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
/// preimage claim backward will lead to loss of funds.
#[derive(Clone, PartialEq)]
pub struct HTLCUpdate {
pub(crate) payment_hash: PaymentHash,
pub(crate) payment_preimage: Option<PaymentPreimage>,
pub(crate) source: HTLCSource,
pub(crate) onchain_value_satoshis: Option<u64>,
}
impl_writeable_tlv_based!(HTLCUpdate, {
(0, payment_hash, required),
(1, onchain_value_satoshis, option),
(2, source, required),
(4, payment_preimage, option),
});
/// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
/// instead claiming it in its own individual transaction.
pub(crate) const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
/// If an HTLC expires within this many blocks, force-close the channel to broadcast the
/// HTLC-Success transaction.
/// In other words, this is an upper bound on how many blocks we think it can take us to get a
/// transaction confirmed (and we use it in a few more, equivalent, places).
pub(crate) const CLTV_CLAIM_BUFFER: u32 = 18;
/// Number of blocks by which point we expect our counterparty to have seen new blocks on the
/// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
/// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
/// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
/// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
/// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
/// due to expiration but increase the cost of funds being locked longuer in case of failure.
/// This delay also cover a low-power peer being slow to process blocks and so being behind us on
/// accurate block height.
/// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
/// with at worst this delay, so we are not only using this value as a mercy for them but also
/// us as a safeguard to delay with enough time.
pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
/// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding
/// inbound HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us
/// losing money.
///
/// Note that this is a library-wide security assumption. If a reorg deeper than this number of
/// blocks occurs, counterparties may be able to steal funds or claims made by and balances exposed
/// by a [`ChannelMonitor`] may be incorrect.
// We also use this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
// It may cause spurious generation of bumped claim txn but that's alright given the outpoint is already
// solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
// keep bumping another claim tx to solve the outpoint.
pub const ANTI_REORG_DELAY: u32 = 6;
/// Number of blocks before confirmation at which we fail back an un-relayed HTLC or at which we
/// refuse to accept a new HTLC.
///
/// This is used for a few separate purposes:
/// 1) if we've received an MPP HTLC to us and it expires within this many blocks and we are
/// waiting on additional parts (or waiting on the preimage for any HTLC from the user), we will
/// fail this HTLC,
/// 2) if we receive an HTLC within this many blocks of its expiry (plus one to avoid a race
/// condition with the above), we will fail this HTLC without telling the user we received it,
/// 3) if we are waiting on a connection or a channel state update to send an HTLC to a peer, and
/// that HTLC expires within this many blocks, we will simply fail the HTLC instead.
///
/// (1) is all about protecting us - we need enough time to update the channel state before we hit
/// CLTV_CLAIM_BUFFER, at which point we'd go on chain to claim the HTLC with the preimage.
///
/// (2) is the same, but with an additional buffer to avoid accepting an HTLC which is immediately
/// in a race condition between the user connecting a block (which would fail it) and the user
/// providing us the preimage (which would claim it).
///
/// (3) is about our counterparty - we don't want to relay an HTLC to a counterparty when they may
/// end up force-closing the channel on us to claim it.
pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS;
// TODO(devrandom) replace this with HolderCommitmentTransaction
#[derive(Clone, PartialEq)]
struct HolderSignedTx {
/// txid of the transaction in tx, just used to make comparison faster
txid: Txid,
revocation_key: PublicKey,
a_htlc_key: PublicKey,
b_htlc_key: PublicKey,
delayed_payment_key: PublicKey,
per_commitment_point: PublicKey,
htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
to_self_value_sat: u64,
feerate_per_kw: u32,
}
impl_writeable_tlv_based!(HolderSignedTx, {
(0, txid, required),
// Note that this is filled in with data from OnchainTxHandler if it's missing.
// For HolderSignedTx objects serialized with 0.0.100+, this should be filled in.
(1, to_self_value_sat, (default_value, u64::max_value())),
(2, revocation_key, required),
(4, a_htlc_key, required),
(6, b_htlc_key, required),
(8, delayed_payment_key, required),
(10, per_commitment_point, required),
(12, feerate_per_kw, required),
(14, htlc_outputs, vec_type)
});
/// We use this to track static counterparty commitment transaction data and to generate any
/// justice or 2nd-stage preimage/timeout transactions.
#[derive(PartialEq)]
struct CounterpartyCommitmentParameters {
counterparty_delayed_payment_base_key: PublicKey,
counterparty_htlc_base_key: PublicKey,
on_counterparty_tx_csv: u16,
}
impl Writeable for CounterpartyCommitmentParameters {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
w.write_all(&byte_utils::be64_to_array(0))?;
write_tlv_fields!(w, {
(0, self.counterparty_delayed_payment_base_key, required),
(2, self.counterparty_htlc_base_key, required),
(4, self.on_counterparty_tx_csv, required),
});
Ok(())
}
}
impl Readable for CounterpartyCommitmentParameters {
fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
let counterparty_commitment_transaction = {
// Versions prior to 0.0.100 had some per-HTLC state stored here, which is no longer
// used. Read it for compatibility.
let per_htlc_len: u64 = Readable::read(r)?;
for _ in 0..per_htlc_len {
let _txid: Txid = Readable::read(r)?;
let htlcs_count: u64 = Readable::read(r)?;
for _ in 0..htlcs_count {
let _htlc: HTLCOutputInCommitment = Readable::read(r)?;
}
}
let mut counterparty_delayed_payment_base_key = OptionDeserWrapper(None);
let mut counterparty_htlc_base_key = OptionDeserWrapper(None);
let mut on_counterparty_tx_csv: u16 = 0;
read_tlv_fields!(r, {
(0, counterparty_delayed_payment_base_key, required),
(2, counterparty_htlc_base_key, required),
(4, on_counterparty_tx_csv, required),
});
CounterpartyCommitmentParameters {
counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
on_counterparty_tx_csv,
}
};
Ok(counterparty_commitment_transaction)
}
}
/// An entry for an [`OnchainEvent`], stating the block height when the event was observed and the
/// transaction causing it.
///
/// Used to determine when the on-chain event can be considered safe from a chain reorganization.
#[derive(PartialEq)]
struct OnchainEventEntry {
txid: Txid,
height: u32,
event: OnchainEvent,
}
impl OnchainEventEntry {
fn confirmation_threshold(&self) -> u32 {
let mut conf_threshold = self.height + ANTI_REORG_DELAY - 1;
match self.event {
OnchainEvent::MaturingOutput {
descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor)
} => {
// A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
// it's broadcastable when we see the previous block.
conf_threshold = cmp::max(conf_threshold, self.height + descriptor.to_self_delay as u32 - 1);
},
OnchainEvent::FundingSpendConfirmation { on_local_output_csv: Some(csv), .. } |
OnchainEvent::HTLCSpendConfirmation { on_to_local_output_csv: Some(csv), .. } => {
// A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
// it's broadcastable when we see the previous block.
conf_threshold = cmp::max(conf_threshold, self.height + csv as u32 - 1);
},
_ => {},
}
conf_threshold
}
fn has_reached_confirmation_threshold(&self, best_block: &BestBlock) -> bool {
best_block.height() >= self.confirmation_threshold()
}
}
/// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
/// once they mature to enough confirmations (ANTI_REORG_DELAY)
#[derive(PartialEq)]
enum OnchainEvent {
/// An outbound HTLC failing after a transaction is confirmed. Used
/// * when an outbound HTLC output is spent by us after the HTLC timed out
/// * an outbound HTLC which was not present in the commitment transaction which appeared
/// on-chain (either because it was not fully committed to or it was dust).
/// Note that this is *not* used for preimage claims, as those are passed upstream immediately,
/// appearing only as an `HTLCSpendConfirmation`, below.
HTLCUpdate {
source: HTLCSource,
payment_hash: PaymentHash,
onchain_value_satoshis: Option<u64>,
/// None in the second case, above, ie when there is no relevant output in the commitment
/// transaction which appeared on chain.
input_idx: Option<u32>,
},
MaturingOutput {
descriptor: SpendableOutputDescriptor,
},
/// A spend of the funding output, either a commitment transaction or a cooperative closing
/// transaction.
FundingSpendConfirmation {
/// The CSV delay for the output of the funding spend transaction (implying it is a local
/// commitment transaction, and this is the delay on the to_self output).
on_local_output_csv: Option<u16>,
},
/// A spend of a commitment transaction HTLC output, set in the cases where *no* `HTLCUpdate`
/// is constructed. This is used when
/// * an outbound HTLC is claimed by our counterparty with a preimage, causing us to
/// immediately claim the HTLC on the inbound edge and track the resolution here,
/// * an inbound HTLC is claimed by our counterparty (with a timeout),
/// * an inbound HTLC is claimed by us (with a preimage).
/// * a revoked-state HTLC transaction was broadcasted, which was claimed by the revocation
/// signature.
HTLCSpendConfirmation {
input_idx: u32,
/// If the claim was made by either party with a preimage, this is filled in
preimage: Option<PaymentPreimage>,
/// If the claim was made by us on an inbound HTLC against a local commitment transaction,
/// we set this to the output CSV value which we will have to wait until to spend the
/// output (and generate a SpendableOutput event).
on_to_local_output_csv: Option<u16>,
},
}
impl Writeable for OnchainEventEntry {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
write_tlv_fields!(writer, {
(0, self.txid, required),
(2, self.height, required),
(4, self.event, required),
});
Ok(())
}
}
impl MaybeReadable for OnchainEventEntry {
fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
let mut txid = Default::default();
let mut height = 0;
let mut event = None;
read_tlv_fields!(reader, {
(0, txid, required),
(2, height, required),
(4, event, ignorable),
});
if let Some(ev) = event {
Ok(Some(Self { txid, height, event: ev }))
} else {
Ok(None)
}
}
}
impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
(0, HTLCUpdate) => {
(0, source, required),
(1, onchain_value_satoshis, option),
(2, payment_hash, required),
(3, input_idx, option),
},
(1, MaturingOutput) => {
(0, descriptor, required),
},
(3, FundingSpendConfirmation) => {
(0, on_local_output_csv, option),
},
(5, HTLCSpendConfirmation) => {
(0, input_idx, required),
(2, preimage, option),
(4, on_to_local_output_csv, option),
},
);
#[cfg_attr(any(test, feature = "fuzztarget", feature = "_test_utils"), derive(PartialEq))]
#[derive(Clone)]
pub(crate) enum ChannelMonitorUpdateStep {
LatestHolderCommitmentTXInfo {
commitment_tx: HolderCommitmentTransaction,
htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
},
LatestCounterpartyCommitmentTXInfo {
commitment_txid: Txid,
htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
commitment_number: u64,
their_revocation_point: PublicKey,
},
PaymentPreimage {
payment_preimage: PaymentPreimage,
},
CommitmentSecret {
idx: u64,
secret: [u8; 32],
},
/// Used to indicate that the no future updates will occur, and likely that the latest holder
/// commitment transaction(s) should be broadcast, as the channel has been force-closed.
ChannelForceClosed {
/// If set to false, we shouldn't broadcast the latest holder commitment transaction as we
/// think we've fallen behind!
should_broadcast: bool,
},
ShutdownScript {
scriptpubkey: Script,
},
}
impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
(0, LatestHolderCommitmentTXInfo) => {
(0, commitment_tx, required),
(2, htlc_outputs, vec_type),
},
(1, LatestCounterpartyCommitmentTXInfo) => {
(0, commitment_txid, required),
(2, commitment_number, required),
(4, their_revocation_point, required),
(6, htlc_outputs, vec_type),
},
(2, PaymentPreimage) => {
(0, payment_preimage, required),
},
(3, CommitmentSecret) => {
(0, idx, required),
(2, secret, required),
},
(4, ChannelForceClosed) => {
(0, should_broadcast, required),
},
(5, ShutdownScript) => {
(0, scriptpubkey, required),
},
);
/// Details about the balance(s) available for spending once the channel appears on chain.
///
/// See [`ChannelMonitor::get_claimable_balances`] for more details on when these will or will not
/// be provided.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(test, derive(PartialOrd, Ord))]
pub enum Balance {
/// The channel is not yet closed (or the commitment or closing transaction has not yet
/// appeared in a block). The given balance is claimable (less on-chain fees) if the channel is
/// force-closed now.
ClaimableOnChannelClose {
/// The amount available to claim, in satoshis, excluding the on-chain fees which will be
/// required to do so.
claimable_amount_satoshis: u64,
},
/// The channel has been closed, and the given balance is ours but awaiting confirmations until
/// we consider it spendable.
ClaimableAwaitingConfirmations {
/// The amount available to claim, in satoshis, possibly excluding the on-chain fees which
/// were spent in broadcasting the transaction.
claimable_amount_satoshis: u64,
/// The height at which an [`Event::SpendableOutputs`] event will be generated for this
/// amount.
confirmation_height: u32,
},
/// The channel has been closed, and the given balance should be ours but awaiting spending
/// transaction confirmation. If the spending transaction does not confirm in time, it is
/// possible our counterparty can take the funds by broadcasting an HTLC timeout on-chain.
///
/// Once the spending transaction confirms, before it has reached enough confirmations to be
/// considered safe from chain reorganizations, the balance will instead be provided via
/// [`Balance::ClaimableAwaitingConfirmations`].
ContentiousClaimable {
/// The amount available to claim, in satoshis, excluding the on-chain fees which will be
/// required to do so.
claimable_amount_satoshis: u64,
/// The height at which the counterparty may be able to claim the balance if we have not
/// done so.
timeout_height: u32,
},
/// HTLCs which we sent to our counterparty which are claimable after a timeout (less on-chain
/// fees) if the counterparty does not know the preimage for the HTLCs. These are somewhat
/// likely to be claimed by our counterparty before we do.
MaybeClaimableHTLCAwaitingTimeout {
/// The amount available to claim, in satoshis, excluding the on-chain fees which will be
/// required to do so.
claimable_amount_satoshis: u64,
/// The height at which we will be able to claim the balance if our counterparty has not
/// done so.
claimable_height: u32,
},
}
/// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY.
#[derive(PartialEq)]
struct IrrevocablyResolvedHTLC {
input_idx: u32,
/// Only set if the HTLC claim was ours using a payment preimage
payment_preimage: Option<PaymentPreimage>,
}
impl_writeable_tlv_based!(IrrevocablyResolvedHTLC, {
(0, input_idx, required),
(2, payment_preimage, option),
});
/// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
/// on-chain transactions to ensure no loss of funds occurs.
///
/// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
/// information and are actively monitoring the chain.
///
/// Pending Events or updated HTLCs which have not yet been read out by
/// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
/// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
/// gotten are fully handled before re-serializing the new state.
///
/// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
/// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
/// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
/// returned block hash and the the current chain and then reconnecting blocks to get to the
/// best chain) upon deserializing the object!
pub struct ChannelMonitor<Signer: Sign> {
#[cfg(test)]
pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
#[cfg(not(test))]
inner: Mutex<ChannelMonitorImpl<Signer>>,
}
pub(crate) struct ChannelMonitorImpl<Signer: Sign> {
latest_update_id: u64,
commitment_transaction_number_obscure_factor: u64,
destination_script: Script,
broadcasted_holder_revokable_script: Option<(Script, PublicKey, PublicKey)>,
counterparty_payment_script: Script,
shutdown_script: Option<Script>,
channel_keys_id: [u8; 32],
holder_revocation_basepoint: PublicKey,
funding_info: (OutPoint, Script),
current_counterparty_commitment_txid: Option<Txid>,
prev_counterparty_commitment_txid: Option<Txid>,
counterparty_commitment_params: CounterpartyCommitmentParameters,
funding_redeemscript: Script,
channel_value_satoshis: u64,
// first is the idx of the first of the two revocation points
their_cur_revocation_points: Option<(u64, PublicKey, Option<PublicKey>)>,
on_holder_tx_csv: u16,
commitment_secrets: CounterpartyCommitmentSecrets,
/// The set of outpoints in each counterparty commitment transaction. We always need at least
/// the payment hash from `HTLCOutputInCommitment` to claim even a revoked commitment
/// transaction broadcast as we need to be able to construct the witness script in all cases.
counterparty_claimable_outpoints: HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
/// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
/// Nor can we figure out their commitment numbers without the commitment transaction they are
/// spending. Thus, in order to claim them via revocation key, we track all the counterparty
/// commitment transactions which we find on-chain, mapping them to the commitment number which
/// can be used to derive the revocation key and claim the transactions.
counterparty_commitment_txn_on_chain: HashMap<Txid, u64>,
/// Cache used to make pruning of payment_preimages faster.
/// Maps payment_hash values to commitment numbers for counterparty transactions for non-revoked
/// counterparty transactions (ie should remain pretty small).
/// Serialized to disk but should generally not be sent to Watchtowers.
counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
// We store two holder commitment transactions to avoid any race conditions where we may update
// some monitors (potentially on watchtowers) but then fail to update others, resulting in the
// various monitors for one channel being out of sync, and us broadcasting a holder
// transaction for which we have deleted claim information on some watchtowers.
prev_holder_signed_commitment_tx: Option<HolderSignedTx>,
current_holder_commitment_tx: HolderSignedTx,
// Used just for ChannelManager to make sure it has the latest channel data during
// deserialization
current_counterparty_commitment_number: u64,
// Used just for ChannelManager to make sure it has the latest channel data during
// deserialization
current_holder_commitment_number: u64,
payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
// Note that `MonitorEvent`s MUST NOT be generated during update processing, only generated
// during chain data processing. This prevents a race in `ChainMonitor::update_channel` (and
// presumably user implementations thereof as well) where we update the in-memory channel
// object, then before the persistence finishes (as it's all under a read-lock), we return
// pending events to the user or to the relevant `ChannelManager`. Then, on reload, we'll have
// the pre-event state here, but have processed the event in the `ChannelManager`.
// Note that because the `event_lock` in `ChainMonitor` is only taken in
// block/transaction-connected events and *not* during block/transaction-disconnected events,
// we further MUST NOT generate events during block/transaction-disconnection.
pending_monitor_events: Vec<MonitorEvent>,
pending_events: Vec<Event>,
// Used to track on-chain events (i.e., transactions part of channels confirmed on chain) on
// which to take actions once they reach enough confirmations. Each entry includes the
// transaction's id and the height when the transaction was confirmed on chain.
onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
// If we get serialized out and re-read, we need to make sure that the chain monitoring
// interface knows about the TXOs that we want to be notified of spends of. We could probably
// be smart and derive them from the above storage fields, but its much simpler and more
// Obviously Correct (tm) if we just keep track of them explicitly.
outputs_to_watch: HashMap<Txid, Vec<(u32, Script)>>,
#[cfg(test)]
pub onchain_tx_handler: OnchainTxHandler<Signer>,
#[cfg(not(test))]
onchain_tx_handler: OnchainTxHandler<Signer>,
// This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the
// channel has been force-closed. After this is set, no further holder commitment transaction
// updates may occur, and we panic!() if one is provided.
lockdown_from_offchain: bool,
// Set once we've signed a holder commitment transaction and handed it over to our
// OnchainTxHandler. After this is set, no future updates to our holder commitment transactions
// may occur, and we fail any such monitor updates.
//
// In case of update rejection due to a locally already signed commitment transaction, we
// nevertheless store update content to track in case of concurrent broadcast by another
// remote monitor out-of-order with regards to the block view.
holder_tx_signed: bool,
funding_spend_confirmed: Option<Txid>,
/// The set of HTLCs which have been either claimed or failed on chain and have reached
/// the requisite confirmations on the claim/fail transaction (either ANTI_REORG_DELAY or the
/// spending CSV for revocable outputs).
htlcs_resolved_on_chain: Vec<IrrevocablyResolvedHTLC>,
// We simply modify best_block in Channel's block_connected so that serialization is
// consistent but hopefully the users' copy handles block_connected in a consistent way.
// (we do *not*, however, update them in update_monitor to ensure any local user copies keep
// their best_block from its state and not based on updated copies that didn't run through
// the full block_connected).
best_block: BestBlock,
secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
}
/// Transaction outputs to watch for on-chain spends.
pub type TransactionOutputs = (Txid, Vec<(u32, TxOut)>);
#[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
/// Used only in testing and fuzztarget to check serialization roundtrips don't change the
/// underlying object
impl<Signer: Sign> PartialEq for ChannelMonitor<Signer> {
fn eq(&self, other: &Self) -> bool {
let inner = self.inner.lock().unwrap();
let other = other.inner.lock().unwrap();
inner.eq(&other)
}
}
#[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
/// Used only in testing and fuzztarget to check serialization roundtrips don't change the
/// underlying object
impl<Signer: Sign> PartialEq for ChannelMonitorImpl<Signer> {
fn eq(&self, other: &Self) -> bool {
if self.latest_update_id != other.latest_update_id ||
self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
self.destination_script != other.destination_script ||
self.broadcasted_holder_revokable_script != other.broadcasted_holder_revokable_script ||
self.counterparty_payment_script != other.counterparty_payment_script ||
self.channel_keys_id != other.channel_keys_id ||
self.holder_revocation_basepoint != other.holder_revocation_basepoint ||
self.funding_info != other.funding_info ||
self.current_counterparty_commitment_txid != other.current_counterparty_commitment_txid ||
self.prev_counterparty_commitment_txid != other.prev_counterparty_commitment_txid ||
self.counterparty_commitment_params != other.counterparty_commitment_params ||
self.funding_redeemscript != other.funding_redeemscript ||
self.channel_value_satoshis != other.channel_value_satoshis ||
self.their_cur_revocation_points != other.their_cur_revocation_points ||
self.on_holder_tx_csv != other.on_holder_tx_csv ||
self.commitment_secrets != other.commitment_secrets ||
self.counterparty_claimable_outpoints != other.counterparty_claimable_outpoints ||
self.counterparty_commitment_txn_on_chain != other.counterparty_commitment_txn_on_chain ||
self.counterparty_hash_commitment_number != other.counterparty_hash_commitment_number ||
self.prev_holder_signed_commitment_tx != other.prev_holder_signed_commitment_tx ||
self.current_counterparty_commitment_number != other.current_counterparty_commitment_number ||
self.current_holder_commitment_number != other.current_holder_commitment_number ||
self.current_holder_commitment_tx != other.current_holder_commitment_tx ||
self.payment_preimages != other.payment_preimages ||
self.pending_monitor_events != other.pending_monitor_events ||
self.pending_events.len() != other.pending_events.len() || // We trust events to round-trip properly
self.onchain_events_awaiting_threshold_conf != other.onchain_events_awaiting_threshold_conf ||
self.outputs_to_watch != other.outputs_to_watch ||
self.lockdown_from_offchain != other.lockdown_from_offchain ||
self.holder_tx_signed != other.holder_tx_signed ||
self.funding_spend_confirmed != other.funding_spend_confirmed ||
self.htlcs_resolved_on_chain != other.htlcs_resolved_on_chain
{
false
} else {
true
}
}
}
impl<Signer: Sign> Writeable for ChannelMonitor<Signer> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
self.inner.lock().unwrap().write(writer)
}
}
// These are also used for ChannelMonitorUpdate, above.
const SERIALIZATION_VERSION: u8 = 1;
const MIN_SERIALIZATION_VERSION: u8 = 1;
impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
self.latest_update_id.write(writer)?;
// Set in initial Channel-object creation, so should always be set by now:
U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
self.destination_script.write(writer)?;
if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
writer.write_all(&[0; 1])?;
broadcasted_holder_revokable_script.0.write(writer)?;
broadcasted_holder_revokable_script.1.write(writer)?;
broadcasted_holder_revokable_script.2.write(writer)?;
} else {
writer.write_all(&[1; 1])?;
}
self.counterparty_payment_script.write(writer)?;
match &self.shutdown_script {
Some(script) => script.write(writer)?,
None => Script::new().write(writer)?,
}
self.channel_keys_id.write(writer)?;
self.holder_revocation_basepoint.write(writer)?;
writer.write_all(&self.funding_info.0.txid[..])?;
writer.write_all(&byte_utils::be16_to_array(self.funding_info.0.index))?;
self.funding_info.1.write(writer)?;
self.current_counterparty_commitment_txid.write(writer)?;
self.prev_counterparty_commitment_txid.write(writer)?;
self.counterparty_commitment_params.write(writer)?;
self.funding_redeemscript.write(writer)?;
self.channel_value_satoshis.write(writer)?;
match self.their_cur_revocation_points {
Some((idx, pubkey, second_option)) => {
writer.write_all(&byte_utils::be48_to_array(idx))?;
writer.write_all(&pubkey.serialize())?;
match second_option {
Some(second_pubkey) => {
writer.write_all(&second_pubkey.serialize())?;
},
None => {
writer.write_all(&[0; 33])?;
},
}
},
None => {
writer.write_all(&byte_utils::be48_to_array(0))?;
},
}
writer.write_all(&byte_utils::be16_to_array(self.on_holder_tx_csv))?;
self.commitment_secrets.write(writer)?;
macro_rules! serialize_htlc_in_commitment {
($htlc_output: expr) => {
writer.write_all(&[$htlc_output.offered as u8; 1])?;
writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
writer.write_all(&$htlc_output.payment_hash.0[..])?;
$htlc_output.transaction_output_index.write(writer)?;
}
}
writer.write_all(&byte_utils::be64_to_array(self.counterparty_claimable_outpoints.len() as u64))?;
for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() {
writer.write_all(&txid[..])?;
writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
serialize_htlc_in_commitment!(htlc_output);
htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
}
}
writer.write_all(&byte_utils::be64_to_array(self.counterparty_commitment_txn_on_chain.len() as u64))?;
for (ref txid, commitment_number) in self.counterparty_commitment_txn_on_chain.iter() {
writer.write_all(&txid[..])?;
writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
}
writer.write_all(&byte_utils::be64_to_array(self.counterparty_hash_commitment_number.len() as u64))?;
for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() {
writer.write_all(&payment_hash.0[..])?;
writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
}
if let Some(ref prev_holder_tx) = self.prev_holder_signed_commitment_tx {
writer.write_all(&[1; 1])?;
prev_holder_tx.write(writer)?;
} else {
writer.write_all(&[0; 1])?;
}
self.current_holder_commitment_tx.write(writer)?;
writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?;
writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?;
writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
for payment_preimage in self.payment_preimages.values() {
writer.write_all(&payment_preimage.0[..])?;
}
writer.write_all(&(self.pending_monitor_events.iter().filter(|ev| match ev {
MonitorEvent::HTLCEvent(_) => true,
MonitorEvent::CommitmentTxConfirmed(_) => true,
_ => false,
}).count() as u64).to_be_bytes())?;
for event in self.pending_monitor_events.iter() {
match event {
MonitorEvent::HTLCEvent(upd) => {
0u8.write(writer)?;
upd.write(writer)?;
},
MonitorEvent::CommitmentTxConfirmed(_) => 1u8.write(writer)?,
_ => {}, // Covered in the TLV writes below
}
}
writer.write_all(&byte_utils::be64_to_array(self.pending_events.len() as u64))?;
for event in self.pending_events.iter() {
event.write(writer)?;
}
self.best_block.block_hash().write(writer)?;
writer.write_all(&byte_utils::be32_to_array(self.best_block.height()))?;
writer.write_all(&byte_utils::be64_to_array(self.onchain_events_awaiting_threshold_conf.len() as u64))?;
for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
entry.write(writer)?;
}
(self.outputs_to_watch.len() as u64).write(writer)?;
for (txid, idx_scripts) in self.outputs_to_watch.iter() {
txid.write(writer)?;
(idx_scripts.len() as u64).write(writer)?;
for (idx, script) in idx_scripts.iter() {
idx.write(writer)?;
script.write(writer)?;
}
}
self.onchain_tx_handler.write(writer)?;
self.lockdown_from_offchain.write(writer)?;
self.holder_tx_signed.write(writer)?;
write_tlv_fields!(writer, {
(1, self.funding_spend_confirmed, option),
(3, self.htlcs_resolved_on_chain, vec_type),
(5, self.pending_monitor_events, vec_type),
});
Ok(())
}
}
impl<Signer: Sign> ChannelMonitor<Signer> {
pub(crate) fn new(secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_script: Option<Script>,
on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script),
channel_parameters: &ChannelTransactionParameters,
funding_redeemscript: Script, channel_value_satoshis: u64,
commitment_transaction_number_obscure_factor: u64,
initial_holder_commitment_tx: HolderCommitmentTransaction,
best_block: BestBlock) -> ChannelMonitor<Signer> {
assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
let payment_key_hash = WPubkeyHash::hash(&keys.pubkeys().payment_point.serialize());
let counterparty_payment_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_key_hash[..]).into_script();
let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
let counterparty_commitment_params = CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv };
let channel_keys_id = keys.channel_keys_id();
let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
// block for Rust 1.34 compat
let (holder_commitment_tx, current_holder_commitment_number) = {
let trusted_tx = initial_holder_commitment_tx.trust();
let txid = trusted_tx.txid();
let tx_keys = trusted_tx.keys();
let holder_commitment_tx = HolderSignedTx {
txid,
revocation_key: tx_keys.revocation_key,
a_htlc_key: tx_keys.broadcaster_htlc_key,
b_htlc_key: tx_keys.countersignatory_htlc_key,
delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
per_commitment_point: tx_keys.per_commitment_point,
htlc_outputs: Vec::new(), // There are never any HTLCs in the initial commitment transactions
to_self_value_sat: initial_holder_commitment_tx.to_broadcaster_value_sat(),
feerate_per_kw: trusted_tx.feerate_per_kw(),
};
(holder_commitment_tx, trusted_tx.commitment_number())
};
let onchain_tx_handler =
OnchainTxHandler::new(destination_script.clone(), keys,
channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx.clone());
let mut outputs_to_watch = HashMap::new();
outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
ChannelMonitor {
inner: Mutex::new(ChannelMonitorImpl {
latest_update_id: 0,
commitment_transaction_number_obscure_factor,