Skip to content

Commit 630f8ca

Browse files
committed
Replace ChainWatchInterface in NetGraphMsgHandler
ChainWatchInterface was intended as an interface for watching rather than accessing the chain. Remove get_chain_utxo and add chain::Access trait for this behavior. Wrap it with an Option in NetGraphMsgHandler in order to simplify the error interface.
1 parent e18a288 commit 630f8ca

File tree

10 files changed

+130
-119
lines changed

10 files changed

+130
-119
lines changed

ARCH.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,9 @@ At a high level, some of the common interfaces fit together as follows:
5151
--------------- / (as EventsProvider)
5252
| PeerManager |- \ /
5353
--------------- \ /
54-
| ----------------------- \ /
55-
| | ChainWatchInterface | v
56-
| ----------------------- ---------
54+
| ----------------- \ /
55+
| | chain::Access | v
56+
| ----------------- ---------
5757
| | | Event |
5858
(as RoutingMessageHandler) v ---------
5959
\ --------------------

fuzz/src/full_stack.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ use bitcoin::hashes::HashEngine as TraitImportEngine;
1717
use bitcoin::hashes::sha256::Hash as Sha256;
1818
use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
1919

20-
use lightning::chain::chaininterface::{BroadcasterInterface,ConfirmationTarget,ChainListener,FeeEstimator,ChainWatchInterfaceUtil};
20+
use lightning::chain;
21+
use lightning::chain::chaininterface::{BroadcasterInterface,ConfirmationTarget,ChainListener,FeeEstimator};
2122
use lightning::chain::transaction::OutPoint;
2223
use lightning::chain::keysinterface::{InMemoryChannelKeys, KeysInterface};
2324
use lightning::ln::channelmonitor;
@@ -138,7 +139,7 @@ type ChannelMan = ChannelManager<
138139
EnforcingChannelKeys,
139140
Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
140141
Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>;
141-
type PeerMan<'a> = PeerManager<Peer<'a>, Arc<ChannelMan>, Arc<NetGraphMsgHandler<Arc<ChainWatchInterfaceUtil>, Arc<dyn Logger>>>, Arc<dyn Logger>>;
142+
type PeerMan<'a> = PeerManager<Peer<'a>, Arc<ChannelMan>, Arc<NetGraphMsgHandler<Arc<dyn chain::Access>, Arc<dyn Logger>>>, Arc<dyn Logger>>;
142143

143144
struct MoneyLossDetector<'a> {
144145
manager: Arc<ChannelMan>,
@@ -330,7 +331,6 @@ pub fn do_test(data: &[u8], logger: &Arc<dyn Logger>) {
330331
Err(_) => return,
331332
};
332333

333-
let watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin));
334334
let broadcast = Arc::new(TestBroadcaster{});
335335
let monitor = Arc::new(channelmonitor::SimpleManyChannelMonitor::new(broadcast.clone(), Arc::clone(&logger), fee_est.clone()));
336336

@@ -341,7 +341,7 @@ pub fn do_test(data: &[u8], logger: &Arc<dyn Logger>) {
341341
config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
342342
let channelmanager = Arc::new(ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0));
343343
let our_id = PublicKey::from_secret_key(&Secp256k1::signing_only(), &keys_manager.get_node_secret());
344-
let net_graph_msg_handler = Arc::new(NetGraphMsgHandler::new(watch.clone(), Arc::clone(&logger)));
344+
let net_graph_msg_handler = Arc::new(NetGraphMsgHandler::new(None, Arc::clone(&logger)));
345345

346346
let peers = RefCell::new([false; 256]);
347347
let mut loss_detector = MoneyLossDetector::new(&peers, channelmanager.clone(), monitor.clone(), PeerManager::new(MessageHandler {

fuzz/src/router.rs

Lines changed: 13 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
use bitcoin::blockdata::script::{Script, Builder};
2-
use bitcoin::blockdata::block::BlockHeader;
3-
use bitcoin::blockdata::transaction::Transaction;
4-
use bitcoin::hash_types::{Txid, BlockHash};
1+
use bitcoin::blockdata::script::Builder;
2+
use bitcoin::blockdata::transaction::TxOut;
3+
use bitcoin::hash_types::BlockHash;
54

6-
use lightning::chain::chaininterface::{ChainError,ChainWatchInterface};
5+
use lightning::chain;
76
use lightning::ln::channelmanager::ChannelDetails;
87
use lightning::ln::features::InitFeatures;
98
use lightning::ln::msgs;
@@ -68,26 +67,16 @@ impl InputData {
6867
}
6968
}
7069

71-
struct DummyChainWatcher {
70+
struct FuzzChainSource {
7271
input: Arc<InputData>,
7372
}
74-
75-
impl ChainWatchInterface for DummyChainWatcher {
76-
fn install_watch_tx(&self, _txid: &Txid, _script_pub_key: &Script) { }
77-
fn install_watch_outpoint(&self, _outpoint: (Txid, u32), _out_script: &Script) { }
78-
fn watch_all_txn(&self) { }
79-
fn filter_block(&self, _header: &BlockHeader, _txdata: &[(usize, &Transaction)]) -> Vec<usize> {
80-
Vec::new()
81-
}
82-
fn reentered(&self) -> usize { 0 }
83-
84-
fn get_chain_utxo(&self, _genesis_hash: BlockHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
73+
impl chain::Access for FuzzChainSource {
74+
fn get_utxo(&self, _genesis_hash: &BlockHash, _short_channel_id: u64) -> Result<TxOut, chain::AccessError> {
8575
match self.input.get_slice(2) {
86-
Some(&[0, _]) => Err(ChainError::NotSupported),
87-
Some(&[1, _]) => Err(ChainError::NotWatched),
88-
Some(&[2, _]) => Err(ChainError::UnknownTx),
89-
Some(&[_, x]) => Ok((Builder::new().push_int(x as i64).into_script().to_v0_p2wsh(), 0)),
90-
None => Err(ChainError::UnknownTx),
76+
Some(&[0, _]) => Err(chain::AccessError::UnknownChain),
77+
Some(&[1, _]) => Err(chain::AccessError::UnknownTx),
78+
Some(&[_, x]) => Ok(TxOut { value: 0, script_pubkey: Builder::new().push_int(x as i64).into_script().to_v0_p2wsh() }),
79+
None => Err(chain::AccessError::UnknownTx),
9180
_ => unreachable!(),
9281
}
9382
}
@@ -152,12 +141,12 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
152141
}
153142

154143
let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new("".to_owned(), out));
155-
let chain_monitor = Arc::new(DummyChainWatcher {
144+
let chain_source = Arc::new(FuzzChainSource {
156145
input: Arc::clone(&input),
157146
});
158147

159148
let our_pubkey = get_pubkey!();
160-
let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
149+
let net_graph_msg_handler = NetGraphMsgHandler::new(Some(chain_source), Arc::clone(&logger));
161150

162151
loop {
163152
match get_slice!(1)[0] {

lightning-net-tokio/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,10 @@
2525
//! type TxBroadcaster = dyn lightning::chain::chaininterface::BroadcasterInterface;
2626
//! type FeeEstimator = dyn lightning::chain::chaininterface::FeeEstimator;
2727
//! type Logger = dyn lightning::util::logger::Logger;
28-
//! type ChainWatchInterface = dyn lightning::chain::chaininterface::ChainWatchInterface;
28+
//! type ChainAccess = dyn lightning::chain::Access;
2929
//! type ChannelMonitor = lightning::ln::channelmonitor::SimpleManyChannelMonitor<lightning::chain::transaction::OutPoint, lightning::chain::keysinterface::InMemoryChannelKeys, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>>;
3030
//! type ChannelManager = lightning::ln::channelmanager::SimpleArcChannelManager<ChannelMonitor, TxBroadcaster, FeeEstimator, Logger>;
31-
//! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
31+
//! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainAccess, Logger>;
3232
//!
3333
//! // Connect to node with pubkey their_node_id at addr:
3434
//! async fn connect_to_node(peer_manager: PeerManager, channel_monitor: Arc<ChannelMonitor>, channel_manager: ChannelManager, their_node_id: PublicKey, addr: SocketAddr) {

lightning/src/chain/mod.rs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,37 @@
11
//! Structs and traits which allow other parts of rust-lightning to interact with the blockchain.
22
33
use bitcoin::blockdata::script::Script;
4-
use bitcoin::hash_types::Txid;
4+
use bitcoin::blockdata::transaction::TxOut;
5+
use bitcoin::hash_types::{BlockHash, Txid};
56

67
use chain::transaction::OutPoint;
78

89
pub mod chaininterface;
910
pub mod transaction;
1011
pub mod keysinterface;
1112

13+
/// The `Access` trait defines behavior for accessing chain data and state, such as blocks and UTXO.
14+
pub trait Access: Send + Sync {
15+
/// Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
16+
/// Returns an error if `genesis_hash` is for a different chain or if such a transaction output
17+
/// is unknown.
18+
///
19+
/// [`short_channel_id`]: https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md#definition-of-short_channel_id
20+
fn get_utxo(&self, genesis_hash: &BlockHash, short_channel_id: u64) -> Result<TxOut, AccessError>;
21+
}
22+
23+
/// An error when accessing the chain via [`Access`].
24+
///
25+
/// [`Access`]: trait.Access.html
26+
#[derive(Clone)]
27+
pub enum AccessError {
28+
/// The requested chain is unknown.
29+
UnknownChain,
30+
31+
/// The requested transaction doesn't exist or hasn't confirmed.
32+
UnknownTx,
33+
}
34+
1235
/// An interface for providing [`WatchEvent`]s.
1336
///
1437
/// [`WatchEvent`]: enum.WatchEvent.html

lightning/src/ln/functional_test_utils.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -103,12 +103,12 @@ pub fn disconnect_block<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, header: &Blo
103103
pub struct TestChanMonCfg {
104104
pub tx_broadcaster: test_utils::TestBroadcaster,
105105
pub fee_estimator: test_utils::TestFeeEstimator,
106-
pub chain_monitor: chaininterface::ChainWatchInterfaceUtil,
106+
pub chain_source: test_utils::TestChainSource,
107107
pub logger: test_utils::TestLogger,
108108
}
109109

110110
pub struct NodeCfg<'a> {
111-
pub chain_monitor: &'a chaininterface::ChainWatchInterfaceUtil,
111+
pub chain_source: &'a test_utils::TestChainSource,
112112
pub tx_broadcaster: &'a test_utils::TestBroadcaster,
113113
pub fee_estimator: &'a test_utils::TestFeeEstimator,
114114
pub chan_monitor: test_utils::TestChannelMonitor<'a>,
@@ -119,12 +119,12 @@ pub struct NodeCfg<'a> {
119119

120120
pub struct Node<'a, 'b: 'a, 'c: 'b> {
121121
pub block_notifier: chaininterface::BlockNotifierRef<'a>,
122-
pub chain_monitor: &'c chaininterface::ChainWatchInterfaceUtil,
122+
pub chain_source: &'c test_utils::TestChainSource,
123123
pub tx_broadcaster: &'c test_utils::TestBroadcaster,
124124
pub chan_monitor: &'b test_utils::TestChannelMonitor<'c>,
125125
pub keys_manager: &'b test_utils::TestKeysInterface,
126126
pub node: &'a ChannelManager<EnforcingChannelKeys, &'b TestChannelMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>,
127-
pub net_graph_msg_handler: NetGraphMsgHandler<&'c chaininterface::ChainWatchInterfaceUtil, &'c test_utils::TestLogger>,
127+
pub net_graph_msg_handler: NetGraphMsgHandler<&'c test_utils::TestChainSource, &'c test_utils::TestLogger>,
128128
pub node_seed: [u8; 32],
129129
pub network_payment_count: Rc<RefCell<u8>>,
130130
pub network_chan_count: Rc<RefCell<u32>>,
@@ -147,7 +147,7 @@ impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> {
147147
let network_graph_deser = <NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap();
148148
assert!(network_graph_deser == *self.net_graph_msg_handler.network_graph.read().unwrap());
149149
let net_graph_msg_handler = NetGraphMsgHandler::from_net_graph(
150-
self.chain_monitor, self.logger, network_graph_deser
150+
Some(self.chain_source), self.logger, network_graph_deser
151151
);
152152
let mut chan_progress = 0;
153153
loop {
@@ -1099,9 +1099,9 @@ pub fn create_chanmon_cfgs(node_count: usize) -> Vec<TestChanMonCfg> {
10991099
for i in 0..node_count {
11001100
let tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
11011101
let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
1102-
let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
1102+
let chain_source = test_utils::TestChainSource::new(Network::Testnet);
11031103
let logger = test_utils::TestLogger::with_id(format!("node {}", i));
1104-
chan_mon_cfgs.push(TestChanMonCfg{ tx_broadcaster, fee_estimator, chain_monitor, logger });
1104+
chan_mon_cfgs.push(TestChanMonCfg{ tx_broadcaster, fee_estimator, chain_source, logger });
11051105
}
11061106

11071107
chan_mon_cfgs
@@ -1114,7 +1114,7 @@ pub fn create_node_cfgs<'a>(node_count: usize, chanmon_cfgs: &'a Vec<TestChanMon
11141114
let seed = [i as u8; 32];
11151115
let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
11161116
let chan_monitor = test_utils::TestChannelMonitor::new(&chanmon_cfgs[i].tx_broadcaster, &chanmon_cfgs[i].logger, &chanmon_cfgs[i].fee_estimator);
1117-
nodes.push(NodeCfg { chain_monitor: &chanmon_cfgs[i].chain_monitor, logger: &chanmon_cfgs[i].logger, tx_broadcaster: &chanmon_cfgs[i].tx_broadcaster, fee_estimator: &chanmon_cfgs[i].fee_estimator, chan_monitor, keys_manager, node_seed: seed });
1117+
nodes.push(NodeCfg { chain_source: &chanmon_cfgs[i].chain_source, logger: &chanmon_cfgs[i].logger, tx_broadcaster: &chanmon_cfgs[i].tx_broadcaster, fee_estimator: &chanmon_cfgs[i].fee_estimator, chan_monitor, keys_manager, node_seed: seed });
11181118
}
11191119

11201120
nodes
@@ -1143,8 +1143,8 @@ pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec<NodeC
11431143
let block_notifier = chaininterface::BlockNotifier::new();
11441144
block_notifier.register_listener(&cfgs[i].chan_monitor.simple_monitor as &chaininterface::ChainListener);
11451145
block_notifier.register_listener(&chan_mgrs[i] as &chaininterface::ChainListener);
1146-
let net_graph_msg_handler = NetGraphMsgHandler::new(cfgs[i].chain_monitor, cfgs[i].logger);
1147-
nodes.push(Node{ chain_monitor: &cfgs[i].chain_monitor, block_notifier,
1146+
let net_graph_msg_handler = NetGraphMsgHandler::new(None, cfgs[i].logger);
1147+
nodes.push(Node{ chain_source: cfgs[i].chain_source, block_notifier,
11481148
tx_broadcaster: cfgs[i].tx_broadcaster, chan_monitor: &cfgs[i].chan_monitor,
11491149
keys_manager: &cfgs[i].keys_manager, node: &chan_mgrs[i], net_graph_msg_handler,
11501150
node_seed: cfgs[i].node_seed, network_chan_count: chan_count.clone(),

lightning/src/ln/functional_tests.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
55
use chain::transaction::OutPoint;
66
use chain::keysinterface::{ChannelKeys, KeysInterface, SpendableOutputDescriptor};
7-
use chain::chaininterface::{ChainListener, ChainWatchInterfaceUtil, BlockNotifier};
7+
use chain::chaininterface::{ChainListener, BlockNotifier};
88
use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
99
use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,HTLCForwardInfo,RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
1010
use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ManyChannelMonitor, ANTI_REORG_DELAY};
@@ -5487,7 +5487,7 @@ fn test_key_derivation_params() {
54875487
let seed = [42; 32];
54885488
let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
54895489
let chan_monitor = test_utils::TestChannelMonitor::new(&chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator);
5490-
let node = NodeCfg { chain_monitor: &chanmon_cfgs[0].chain_monitor, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chan_monitor, keys_manager, node_seed: seed };
5490+
let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chan_monitor, keys_manager, node_seed: seed };
54915491
let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
54925492
node_cfgs.remove(0);
54935493
node_cfgs.insert(0, node);
@@ -7329,7 +7329,7 @@ fn test_data_loss_protect() {
73297329
let logger;
73307330
let fee_estimator;
73317331
let tx_broadcaster;
7332-
let chain_monitor;
7332+
let chain_source;
73337333
let monitor;
73347334
let node_state_0;
73357335
let chanmon_cfgs = create_chanmon_cfgs(2);
@@ -7353,7 +7353,7 @@ fn test_data_loss_protect() {
73537353
// Restore node A from previous state
73547354
logger = test_utils::TestLogger::with_id(format!("node {}", 0));
73557355
let mut chan_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0)).unwrap().1;
7356-
chain_monitor = ChainWatchInterfaceUtil::new(Network::Testnet);
7356+
chain_source = test_utils::TestChainSource::new(Network::Testnet);
73577357
tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
73587358
fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
73597359
keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
@@ -7374,7 +7374,7 @@ fn test_data_loss_protect() {
73747374
nodes[0].node = &node_state_0;
73757375
assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
73767376
nodes[0].chan_monitor = &monitor;
7377-
nodes[0].chain_monitor = &chain_monitor;
7377+
nodes[0].chain_source = &chain_source;
73787378

73797379
nodes[0].block_notifier = BlockNotifier::new();
73807380
nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);

0 commit comments

Comments
 (0)