Utility for syncing a set of chain listeners
[rust-lightning] / lightning / src / chain / mod.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Structs and traits which allow other parts of rust-lightning to interact with the blockchain.
11
12 use bitcoin::blockdata::block::{Block, BlockHeader};
13 use bitcoin::blockdata::script::Script;
14 use bitcoin::blockdata::transaction::TxOut;
15 use bitcoin::hash_types::{BlockHash, Txid};
16
17 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent};
18 use chain::keysinterface::Sign;
19 use chain::transaction::OutPoint;
20
21 pub mod chaininterface;
22 pub mod chainmonitor;
23 pub mod channelmonitor;
24 pub mod transaction;
25 pub mod keysinterface;
26
27 /// An error when accessing the chain via [`Access`].
28 ///
29 /// [`Access`]: trait.Access.html
30 #[derive(Clone)]
31 pub enum AccessError {
32         /// The requested chain is unknown.
33         UnknownChain,
34
35         /// The requested transaction doesn't exist or hasn't confirmed.
36         UnknownTx,
37 }
38
39 /// The `Access` trait defines behavior for accessing chain data and state, such as blocks and
40 /// UTXOs.
41 pub trait Access: Send + Sync {
42         /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
43         /// Returns an error if `genesis_hash` is for a different chain or if such a transaction output
44         /// is unknown.
45         ///
46         /// [`short_channel_id`]: https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md#definition-of-short_channel_id
47         fn get_utxo(&self, genesis_hash: &BlockHash, short_channel_id: u64) -> Result<TxOut, AccessError>;
48 }
49
50 /// The `Listen` trait is used to be notified of when blocks have been connected or disconnected
51 /// from the chain.
52 ///
53 /// Useful when needing to replay chain data upon startup or as new chain events occur.
54 pub trait Listen {
55         /// Notifies the listener that a block was added at the given height.
56         fn block_connected(&self, block: &Block, height: u32);
57
58         /// Notifies the listener that a block was removed at the given height.
59         fn block_disconnected(&self, header: &BlockHeader, height: u32);
60 }
61
62 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
63 /// blocks are connected and disconnected.
64 ///
65 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
66 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
67 /// channel state changes and HTLCs are resolved. See method documentation for specific
68 /// requirements.
69 ///
70 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
71 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
72 /// without taking any further action such as persisting the current state.
73 ///
74 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
75 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
76 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
77 /// funds in the channel. See [`ChannelMonitorUpdateErr`] for more details about how to handle
78 /// multiple instances.
79 ///
80 /// [`ChannelMonitor`]: channelmonitor/struct.ChannelMonitor.html
81 /// [`ChannelMonitorUpdateErr`]: channelmonitor/enum.ChannelMonitorUpdateErr.html
82 /// [`PermanentFailure`]: channelmonitor/enum.ChannelMonitorUpdateErr.html#variant.PermanentFailure
83 pub trait Watch<ChannelSigner: Sign>: Send + Sync {
84         /// Watches a channel identified by `funding_txo` using `monitor`.
85         ///
86         /// Implementations are responsible for watching the chain for the funding transaction along
87         /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
88         /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
89         ///
90         /// [`get_outputs_to_watch`]: channelmonitor/struct.ChannelMonitor.html#method.get_outputs_to_watch
91         /// [`block_connected`]: channelmonitor/struct.ChannelMonitor.html#method.block_connected
92         /// [`block_disconnected`]: channelmonitor/struct.ChannelMonitor.html#method.block_disconnected
93         fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
94
95         /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
96         ///
97         /// Implementations must call [`update_monitor`] with the given update. See
98         /// [`ChannelMonitorUpdateErr`] for invariants around returning an error.
99         ///
100         /// [`update_monitor`]: channelmonitor/struct.ChannelMonitor.html#method.update_monitor
101         /// [`ChannelMonitorUpdateErr`]: channelmonitor/enum.ChannelMonitorUpdateErr.html
102         fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr>;
103
104         /// Returns any monitor events since the last call. Subsequent calls must only return new
105         /// events.
106         fn release_pending_monitor_events(&self) -> Vec<MonitorEvent>;
107 }
108
109 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
110 /// channels.
111 ///
112 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
113 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
114 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
115 /// receiving full blocks from a chain source, any further filtering is unnecessary.
116 ///
117 /// After an output has been registered, subsequent block retrievals from the chain source must not
118 /// exclude any transactions matching the new criteria nor any in-block descendants of such
119 /// transactions.
120 ///
121 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
122 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
123 /// processed later. Then, in order to block until the data has been processed, any `Watch`
124 /// invocation that has called the `Filter` must return [`TemporaryFailure`].
125 ///
126 /// [`Watch`]: trait.Watch.html
127 /// [`TemporaryFailure`]: channelmonitor/enum.ChannelMonitorUpdateErr.html#variant.TemporaryFailure
128 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
129 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
130 pub trait Filter: Send + Sync {
131         /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
132         /// a spending condition.
133         fn register_tx(&self, txid: &Txid, script_pubkey: &Script);
134
135         /// Registers interest in spends of a transaction output identified by `outpoint` having
136         /// `script_pubkey` as the spending condition.
137         fn register_output(&self, outpoint: &OutPoint, script_pubkey: &Script);
138 }
139
140 impl<T: Listen> Listen for std::ops::Deref<Target = T> {
141         fn block_connected(&self, block: &Block, height: u32) {
142                 (**self).block_connected(block, height);
143         }
144
145         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
146                 (**self).block_disconnected(header, height);
147         }
148 }
149
150 impl<T: std::ops::Deref, U: std::ops::Deref> Listen for (T, U)
151 where
152         T::Target: Listen,
153         U::Target: Listen,
154 {
155         fn block_connected(&self, block: &Block, height: u32) {
156                 self.0.block_connected(block, height);
157                 self.1.block_connected(block, height);
158         }
159
160         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
161                 self.0.block_disconnected(header, height);
162                 self.1.block_disconnected(header, height);
163         }
164 }