d933416a71759d40a8f28c32baa18935536de6fe
[rust-lightning] / src / chain / rustbitcoinchain.rs
1 use bitcoin_chain::blockchain::Blockchain;
2 use bitcoin::blockdata::transaction::Transaction;
3 use bitcoin::blockdata::block::Block;
4 use bitcoin::blockdata::script::Script;
5 use bitcoin::network::constants::Network;
6 use bitcoin::util::hash::Sha256dHash;
7
8 use chain::chaininterface::{ChainWatchInterface,ChainWatchInterfaceUtil,ChainListener};
9
10 use std::sync::{Mutex,Weak};
11
12 /// Implements a ChainWatchInterface using rust-bitcoin's Blockchain class
13 pub struct ChainWatchImpl {
14         chain: Mutex<Blockchain>,
15         util: ChainWatchInterfaceUtil
16 }
17
18 unsafe impl Send for ChainWatchImpl {} //TODO: GAH WTF
19 unsafe impl Sync for ChainWatchImpl {} //TODO: GAH WTF
20
21 impl ChainWatchInterface for ChainWatchImpl {
22         fn install_watch_script(&self, spk: Script) {
23                 self.util.install_watch_script(spk)
24         }
25
26         fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32)) {
27                 self.util.install_watch_outpoint(outpoint)
28         }
29
30         fn watch_all_txn(&self) {
31                 self.util.watch_all_txn()
32         }
33
34         fn broadcast_transaction(&self, _tx: &Transaction) {
35                 unimplemented!()
36         }
37
38         fn register_listener(&self, listener: Weak<ChainListener>) {
39                 self.util.register_listener(listener)
40         }
41 }
42
43 impl ChainWatchImpl {
44         pub fn new(network: Network) -> ChainWatchImpl {
45                 ChainWatchImpl {
46                         chain: Mutex::new(Blockchain::new(network)),
47                         util: ChainWatchInterfaceUtil::new(),
48                 }
49         }
50
51         pub fn add_block(&mut self, block: Block) {
52                 {
53                         let mut txn_matched: Vec<&Transaction> = Vec::new();
54                         let mut indexes_of_txn_matched = Vec::new();
55                         for (idx, tx) in block.txdata.iter().enumerate() {
56                                 if self.util.does_match_tx(&tx) {
57                                         txn_matched.push(tx);
58                                         indexes_of_txn_matched.push(idx as u32);
59                                 }
60                         }
61                         //TODO: Height
62                         self.util.do_call_block_connected(&block.header, 0, &txn_matched[..], &indexes_of_txn_matched[..]);
63                 }
64                 self.chain.lock().unwrap().add_block(block).unwrap();
65         }
66 }