Skip to content

Commit b53d02a

Browse files
committed
Split out BroadcastInterface, ChainWatchInterface monitors re-enter from called listeners
1 parent c4e7161 commit b53d02a

File tree

7 files changed

+89
-104
lines changed

7 files changed

+89
-104
lines changed

Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ non_bitcoin_chain_hash_routing = []
1515

1616
[dependencies]
1717
bitcoin = "0.11"
18-
bitcoin-chain = { git = "https://github.com/rust-bitcoin/rust-bitcoin-chain", branch = "master" }
1918
rust-crypto = "0.2"
2019
rand = "0.4"
2120
secp256k1 = "0.8"

src/chain/bitcoincorerpcchain.rs

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
use bitcoin::blockdata::transaction::Transaction;
21
use bitcoin::blockdata::script::Script;
2+
use bitcoin::blockdata::block::{Block, BlockHeader};
33
use bitcoin::util::hash::Sha256dHash;
44

5-
use chain::chaininterface::{ChainWatchInterface,ChainWatchInterfaceUtil,ChainListener};
5+
use chain::chaininterface::{ChainWatchInterface,ChainWatchInterfaceUtil,ChainListener, BroadcasterInterface};
66

77
use std::sync::Weak;
88

@@ -23,19 +23,29 @@ impl ChainWatchInterface for BitcoinCoreRPCClientChain {
2323
self.util.watch_all_txn()
2424
}
2525

26-
fn broadcast_transaction(&self, _tx: &Transaction) {
27-
unimplemented!()
28-
}
29-
3026
fn register_listener(&self, listener: Weak<ChainListener>) {
3127
self.util.register_listener(listener)
3228
}
3329
}
3430

31+
impl BroadcasterInterface for BitcoinCoreRPCClientChain {
32+
fn broadcast_transaction(&self, tx: &Transaction) -> Result<(), Box<Error>> {
33+
unimplemented!()
34+
}
35+
}
36+
3537
impl BitcoinCoreRPCClientChain {
3638
pub fn new() -> BitcoinCoreRPCClientChain {
3739
BitcoinCoreRPCClientChain {
3840
util: ChainWatchInterfaceUtil::new(),
3941
}
4042
}
43+
44+
pub fn block_connected(&self, block: &Block, height: u32) {
45+
self.util.block_connected(block, height)
46+
}
47+
48+
pub fn block_disconnected(&self, header: &BlockHeader) {
49+
self.util.block_disconnected(header)
50+
}
4151
}

src/chain/chaininterface.rs

Lines changed: 65 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
use bitcoin::blockdata::block::BlockHeader;
1+
use std::error::Error;
2+
use bitcoin::blockdata::block::{Block, BlockHeader};
23
use bitcoin::blockdata::transaction::Transaction;
34
use bitcoin::blockdata::script::Script;
45
use bitcoin::util::hash::Sha256dHash;
5-
6-
use std::sync::{Weak,Mutex};
6+
use std::sync::{Mutex,Weak};
7+
use std::sync::atomic::{AtomicUsize, Ordering};
78

89
/// An interface to request notification of certain scripts as they appear the
910
/// chain.
@@ -21,13 +22,18 @@ pub trait ChainWatchInterface: Sync + Send {
2122
/// Indicates that a listener needs to see all transactions.
2223
fn watch_all_txn(&self);
2324

24-
/// Sends a transaction out to (hopefully) be mined
25-
fn broadcast_transaction(&self, tx: &Transaction);
26-
2725
fn register_listener(&self, listener: Weak<ChainListener>);
2826
//TODO: unregister
2927
}
3028

29+
/// An interface to send a transaction to connected Bitcoin peers.
30+
/// This is for final settlement. An error might indicate that no peers can be reached or
31+
/// that peers rejected the transaction.
32+
pub trait BroadcasterInterface: Sync + Send {
33+
/// Sends a transaction out to (hopefully) be mined
34+
fn broadcast_transaction(&self, tx: &Transaction) -> Result<(), Box<Error>>;
35+
}
36+
3137
/// A trait indicating a desire to listen for events from the chain
3238
pub trait ChainListener: Sync + Send {
3339
/// Notifies a listener that a block was connected.
@@ -54,45 +60,80 @@ pub enum ConfirmationTarget {
5460
/// called from inside the library in response to ChainListener events, P2P events, or timer
5561
/// events).
5662
pub trait FeeEstimator: Sync + Send {
57-
fn get_est_sat_per_vbyte(&self, ConfirmationTarget) -> u64;
63+
fn get_est_sat_per_vbyte(&self, confirmation_target: ConfirmationTarget) -> u64;
5864
}
5965

6066
/// Utility to capture some common parts of ChainWatchInterface implementors.
6167
/// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
6268
pub struct ChainWatchInterfaceUtil {
6369
watched: Mutex<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>, //TODO: Something clever to optimize this
6470
listeners: Mutex<Vec<Weak<ChainListener>>>,
71+
reentered: AtomicUsize
6572
}
6673

67-
impl ChainWatchInterfaceUtil {
68-
pub fn new() -> ChainWatchInterfaceUtil {
69-
ChainWatchInterfaceUtil {
70-
watched: Mutex::new((Vec::new(), Vec::new(), false)),
71-
listeners: Mutex::new(Vec::new()),
72-
}
73-
}
74-
75-
pub fn install_watch_script(&self, spk: Script) {
74+
/// Register listener
75+
impl ChainWatchInterface for ChainWatchInterfaceUtil {
76+
fn install_watch_script(&self, script_pub_key: Script) {
7677
let mut watched = self.watched.lock().unwrap();
77-
watched.0.push(Script::from(spk));
78+
watched.0.push(Script::from(script_pub_key));
79+
self.reentered.fetch_add(1, Ordering::Relaxed);
7880
}
7981

80-
pub fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32)) {
82+
fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32)) {
8183
let mut watched = self.watched.lock().unwrap();
8284
watched.1.push(outpoint);
85+
self.reentered.fetch_add(1, Ordering::Relaxed);
8386
}
8487

85-
pub fn watch_all_txn(&self) { //TODO: refcnt this?
88+
fn watch_all_txn(&self) {
8689
let mut watched = self.watched.lock().unwrap();
8790
watched.2 = true;
91+
self.reentered.fetch_add(1, Ordering::Relaxed);
8892
}
8993

90-
pub fn register_listener(&self, listener: Weak<ChainListener>) {
94+
fn register_listener(&self, listener: Weak<ChainListener>) {
9195
let mut vec = self.listeners.lock().unwrap();
9296
vec.push(listener);
9397
}
98+
}
99+
100+
impl ChainWatchInterfaceUtil {
101+
pub fn new() -> ChainWatchInterfaceUtil {
102+
ChainWatchInterfaceUtil {
103+
watched: Mutex::new((Vec::new(), Vec::new(), false)),
104+
listeners: Mutex::new(Vec::new()),
105+
reentered: AtomicUsize::new(1)
106+
}
107+
}
108+
109+
/// notify listener that a block was connected
110+
/// notification will repeat if notified listener register new listeners
111+
pub fn block_connected(&self, block: &Block, height: u32) {
112+
let mut watch = self.reentered.load(Ordering::Relaxed);
113+
let mut last_seen = 0;
114+
// re-scan if new watch added during previous scan
115+
while last_seen != watch {
116+
let mut matched = Vec::new();
117+
let mut matched_index = Vec::new();
118+
for (index, transaction) in block.txdata.iter().enumerate() {
119+
if self.does_match_tx(transaction) {
120+
matched.push(transaction);
121+
matched_index.push(index as u32);
122+
}
123+
}
124+
last_seen = watch;
125+
self.do_call_block_connected(&block.header, height, matched.as_slice(), matched_index.as_slice());
126+
watch = self.reentered.load(Ordering::Relaxed);
127+
}
128+
}
129+
130+
/// notify listener that a block was disconnected
131+
pub fn block_disconnected(&self, header: &BlockHeader) {
132+
self.do_call_block_disconnected(header);
133+
}
94134

95-
pub fn do_call_block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
135+
/// call listeners for connected blocks if they are still around
136+
fn do_call_block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
96137
let listeners = self.listeners.lock().unwrap().clone();
97138
for listener in listeners.iter() {
98139
match listener.upgrade() {
@@ -102,7 +143,8 @@ impl ChainWatchInterfaceUtil {
102143
}
103144
}
104145

105-
pub fn do_call_block_disconnected(&self, header: &BlockHeader) {
146+
/// call listeners for disconnected blocks if they are still around
147+
fn do_call_block_disconnected(&self, header: &BlockHeader) {
106148
let listeners = self.listeners.lock().unwrap().clone();
107149
for listener in listeners.iter() {
108150
match listener.upgrade() {
@@ -113,7 +155,7 @@ impl ChainWatchInterfaceUtil {
113155
}
114156

115157
/// Checks if a given transaction matches the current filter
116-
pub fn does_match_tx(&self, tx: &Transaction) -> bool {
158+
fn does_match_tx(&self, tx: &Transaction) -> bool {
117159
let watched = self.watched.lock().unwrap();
118160
if watched.2 {
119161
return true;

src/chain/mod.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
11
pub mod chaininterface;
22
pub mod bitcoincorerpcchain;
3-
pub mod rustbitcoinchain;

src/chain/rustbitcoinchain.rs

Lines changed: 0 additions & 66 deletions
This file was deleted.

src/lib.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
#![crate_name = "lightning"]
22

33
extern crate bitcoin;
4-
extern crate bitcoin_chain;
54
extern crate secp256k1;
65
extern crate rand;
76
extern crate crypto;

src/ln/channelmonitor.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use secp256k1::key::{SecretKey,PublicKey};
1313
use ln::msgs::HandleError;
1414
use ln::chan_utils;
1515
use ln::chan_utils::HTLCOutputInCommitment;
16-
use chain::chaininterface::{ChainListener,ChainWatchInterface};
16+
use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface};
1717

1818
use std::collections::HashMap;
1919
use std::sync::{Arc,Mutex};
@@ -39,24 +39,26 @@ pub trait ManyChannelMonitor: Send + Sync {
3939
pub struct SimpleManyChannelMonitor<Key> {
4040
monitors: Mutex<HashMap<Key, ChannelMonitor>>,
4141
chain_monitor: Arc<ChainWatchInterface>,
42+
broadcaster: Arc<BroadcasterInterface>
4243
}
4344

4445
impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
4546
fn block_connected(&self, _header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
4647
let monitors = self.monitors.lock().unwrap();
4748
for monitor in monitors.values() {
48-
monitor.block_connected(txn_matched, height, &*self.chain_monitor);
49+
monitor.block_connected(txn_matched, height, &*self.broadcaster);
4950
}
5051
}
5152

5253
fn block_disconnected(&self, _: &BlockHeader) { }
5354
}
5455

5556
impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
56-
pub fn new(chain_monitor: Arc<ChainWatchInterface>) -> Arc<SimpleManyChannelMonitor<Key>> {
57+
pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>) -> Arc<SimpleManyChannelMonitor<Key>> {
5758
let res = Arc::new(SimpleManyChannelMonitor {
5859
monitors: Mutex::new(HashMap::new()),
59-
chain_monitor: chain_monitor,
60+
chain_monitor,
61+
broadcaster
6062
});
6163
let weak_res = Arc::downgrade(&res);
6264
res.chain_monitor.register_listener(weak_res);
@@ -443,7 +445,7 @@ impl ChannelMonitor {
443445
txn_to_broadcast
444446
}
445447

446-
fn block_connected(&self, txn_matched: &[&Transaction], height: u32, chain_monitor: &ChainWatchInterface) {
448+
fn block_connected(&self, txn_matched: &[&Transaction], height: u32, broadcaster: &BroadcasterInterface) {
447449
for tx in txn_matched {
448450
if tx.input.len() != 1 {
449451
// We currently only ever sign something spending a commitment or HTLC
@@ -454,7 +456,7 @@ impl ChannelMonitor {
454456
for txin in tx.input.iter() {
455457
if self.funding_txo.is_none() || (txin.prev_hash == self.funding_txo.unwrap().0 && txin.prev_index == self.funding_txo.unwrap().1 as u32) {
456458
for tx in self.check_spend_transaction(tx, height).iter() {
457-
chain_monitor.broadcast_transaction(tx);
459+
broadcaster.broadcast_transaction(tx); // TODO: use result
458460
}
459461
}
460462
}

0 commit comments

Comments
 (0)