Skip to content

Commit ad9dda2

Browse files
committed
Merge pull request #11 from tamasblummer/chaininterface (squashed)
2 parents c4e7161 + e87e377 commit ad9dda2

10 files changed

+85
-109
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@
33
Cargo.lock
44
/target/
55
**/*.rs.bk
6+
.idea

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: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use bitcoin::blockdata::transaction::Transaction;
22
use bitcoin::blockdata::script::Script;
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,15 +23,17 @@ 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) {
33+
unimplemented!()
34+
}
35+
}
36+
3537
impl BitcoinCoreRPCClientChain {
3638
pub fn new() -> BitcoinCoreRPCClientChain {
3739
BitcoinCoreRPCClientChain {

src/chain/chaininterface.rs

Lines changed: 67 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
use bitcoin::blockdata::block::BlockHeader;
1+
use bitcoin::blockdata::block::{Block, BlockHeader};
22
use bitcoin::blockdata::transaction::Transaction;
33
use bitcoin::blockdata::script::Script;
44
use bitcoin::util::hash::Sha256dHash;
5-
6-
use std::sync::{Weak,Mutex};
5+
use std::sync::{Mutex,Weak,MutexGuard};
6+
use std::sync::atomic::{AtomicUsize, Ordering};
77

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

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

28+
/// An interface to send a transaction to connected Bitcoin peers.
29+
/// This is for final settlement. An error might indicate that no peers can be reached or
30+
/// that peers rejected the transaction.
31+
pub trait BroadcasterInterface: Sync + Send {
32+
/// Sends a transaction out to (hopefully) be mined
33+
fn broadcast_transaction(&self, tx: &Transaction);
34+
}
35+
3136
/// A trait indicating a desire to listen for events from the chain
3237
pub trait ChainListener: Sync + Send {
3338
/// Notifies a listener that a block was connected.
@@ -54,67 +59,105 @@ pub enum ConfirmationTarget {
5459
/// called from inside the library in response to ChainListener events, P2P events, or timer
5560
/// events).
5661
pub trait FeeEstimator: Sync + Send {
57-
fn get_est_sat_per_vbyte(&self, ConfirmationTarget) -> u64;
62+
fn get_est_sat_per_vbyte(&self, confirmation_target: ConfirmationTarget) -> u64;
5863
}
5964

6065
/// Utility to capture some common parts of ChainWatchInterface implementors.
6166
/// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
6267
pub struct ChainWatchInterfaceUtil {
6368
watched: Mutex<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>, //TODO: Something clever to optimize this
6469
listeners: Mutex<Vec<Weak<ChainListener>>>,
70+
reentered: AtomicUsize
6571
}
6672

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) {
73+
/// Register listener
74+
impl ChainWatchInterface for ChainWatchInterfaceUtil {
75+
fn install_watch_script(&self, script_pub_key: Script) {
7676
let mut watched = self.watched.lock().unwrap();
77-
watched.0.push(Script::from(spk));
77+
watched.0.push(Script::from(script_pub_key));
78+
self.reentered.fetch_add(1, Ordering::Relaxed);
7879
}
7980

80-
pub fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32)) {
81+
fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32)) {
8182
let mut watched = self.watched.lock().unwrap();
8283
watched.1.push(outpoint);
84+
self.reentered.fetch_add(1, Ordering::Relaxed);
8385
}
8486

85-
pub fn watch_all_txn(&self) { //TODO: refcnt this?
87+
fn watch_all_txn(&self) {
8688
let mut watched = self.watched.lock().unwrap();
8789
watched.2 = true;
90+
self.reentered.fetch_add(1, Ordering::Relaxed);
8891
}
8992

90-
pub fn register_listener(&self, listener: Weak<ChainListener>) {
93+
fn register_listener(&self, listener: Weak<ChainListener>) {
9194
let mut vec = self.listeners.lock().unwrap();
9295
vec.push(listener);
9396
}
97+
}
9498

95-
pub fn do_call_block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
99+
impl ChainWatchInterfaceUtil {
100+
pub fn new() -> ChainWatchInterfaceUtil {
101+
ChainWatchInterfaceUtil {
102+
watched: Mutex::new((Vec::new(), Vec::new(), false)),
103+
listeners: Mutex::new(Vec::new()),
104+
reentered: AtomicUsize::new(1)
105+
}
106+
}
107+
108+
/// notify listener that a block was connected
109+
/// notification will repeat if notified listener register new listeners
110+
pub fn block_connected_with_filtering(&self, block: &Block, height: u32) {
111+
let mut reentered = true;
112+
while reentered {
113+
let mut matched = Vec::new();
114+
let mut matched_index = Vec::new();
115+
{
116+
let watched = self.watched.lock().unwrap();
117+
for (index, transaction) in block.txdata.iter().enumerate() {
118+
if self.does_match_tx_unguarded(transaction, &watched) {
119+
matched.push(transaction);
120+
matched_index.push(index as u32);
121+
}
122+
}
123+
}
124+
reentered = self.block_connected_checked(&block.header, height, matched.as_slice(), matched_index.as_slice());
125+
}
126+
}
127+
128+
/// notify listener that a block was disconnected
129+
pub fn block_disconnected(&self, header: &BlockHeader) {
96130
let listeners = self.listeners.lock().unwrap().clone();
97131
for listener in listeners.iter() {
98132
match listener.upgrade() {
99-
Some(arc) => arc.block_connected(header, height, txn_matched, indexes_of_txn_matched),
133+
Some(arc) => arc.block_disconnected(header),
100134
None => ()
101135
}
102136
}
103137
}
104138

105-
pub fn do_call_block_disconnected(&self, header: &BlockHeader) {
139+
/// call listeners for connected blocks if they are still around.
140+
/// returns true if notified listeners registered additional listener
141+
pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) -> bool {
142+
let last_seen = self.reentered.load(Ordering::Relaxed);
143+
106144
let listeners = self.listeners.lock().unwrap().clone();
107145
for listener in listeners.iter() {
108146
match listener.upgrade() {
109-
Some(arc) => arc.block_disconnected(header),
147+
Some(arc) => arc.block_connected(header, height, txn_matched, indexes_of_txn_matched),
110148
None => ()
111149
}
112150
}
151+
return last_seen != self.reentered.load(Ordering::Relaxed);
113152
}
114153

115154
/// Checks if a given transaction matches the current filter
116155
pub fn does_match_tx(&self, tx: &Transaction) -> bool {
117156
let watched = self.watched.lock().unwrap();
157+
self.does_match_tx_unguarded (tx, &watched)
158+
}
159+
160+
fn does_match_tx_unguarded (&self, tx: &Transaction, watched: &MutexGuard<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>) -> bool {
118161
if watched.2 {
119162
return true;
120163
}

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/channelmanager.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1392,10 +1392,10 @@ mod tests {
13921392
fn confirm_transaction(chain: &test_utils::TestWatchInterface, tx: &Transaction) {
13931393
let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
13941394
let chan_id = unsafe { CHAN_COUNT };
1395-
chain.watch_util.do_call_block_connected(&header, 1, &[tx; 1], &[chan_id as u32; 1]);
1395+
chain.watch_util.block_connected_checked(&header, 1, &[tx; 1], &[chan_id as u32; 1]);
13961396
for i in 2..100 {
13971397
header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1398-
chain.watch_util.do_call_block_connected(&header, i, &[tx; 0], &[0; 0]);
1398+
chain.watch_util.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
13991399
}
14001400
}
14011401

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
}

src/util/test_utils.rs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,6 @@ impl chaininterface::ChainWatchInterface for TestWatchInterface {
3131
fn watch_all_txn(&self) {
3232
unimplemented!();
3333
}
34-
fn broadcast_transaction(&self, _tx: &Transaction) {
35-
unimplemented!();
36-
}
3734
fn register_listener(&self, listener: Weak<chaininterface::ChainListener>) {
3835
self.watch_util.register_listener(listener);
3936
}

0 commit comments

Comments
 (0)