select the longest blockchain from several servers
[electrum-nvc.git] / lib / verifier.py
1 #!/usr/bin/env python
2 #
3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2012 thomasv@ecdsa.org
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19
20 import threading, time, Queue, os, sys, shutil
21 from util import user_dir, appdata_dir, print_error
22 from bitcoin import *
23
24
25
26
27 class TxVerifier(threading.Thread):
28     """ Simple Payment Verification """
29
30     def __init__(self, interface, blockchain, storage):
31         threading.Thread.__init__(self)
32         self.daemon = True
33         self.storage = storage
34         self.blockchain = blockchain
35         self.interface = interface
36         self.transactions    = {}                                 # requested verifications (with height sent by the requestor)
37         self.interface.register_channel('txverifier')
38         self.verified_tx     = storage.get('verified_tx3',{})      # height, timestamp of verified transactions
39         self.merkle_roots    = storage.get('merkle_roots',{})      # hashed by me
40         self.lock = threading.Lock()
41         self.running = False
42
43
44     def get_confirmations(self, tx):
45         """ return the number of confirmations of a monitored transaction. """
46         with self.lock:
47             if tx in self.verified_tx:
48                 height, timestamp, pos = self.verified_tx[tx]
49                 conf = (self.blockchain.local_height - height + 1)
50                 if conf <= 0: timestamp = None
51
52             elif tx in self.transactions:
53                 conf = -1
54                 timestamp = None
55
56             else:
57                 conf = 0
58                 timestamp = None
59
60         return conf, timestamp
61
62
63     def get_txpos(self, tx_hash):
64         "return position, even if the tx is unverified"
65         with self.lock:
66             x = self.verified_tx.get(tx_hash)
67             y = self.transactions.get(tx_hash)
68         if x:
69             height, timestamp, pos = x
70             return height, pos
71         elif y:
72             return y, 0
73         else:
74             return 1e12, 0
75
76
77     def get_height(self, tx_hash):
78         with self.lock:
79             v = self.verified_tx.get(tx_hash)
80         height = v[0] if v else None
81         return height
82
83
84     def add(self, tx_hash, tx_height):
85         """ add a transaction to the list of monitored transactions. """
86         assert tx_height > 0
87         with self.lock:
88             if tx_hash not in self.transactions.keys():
89                 self.transactions[tx_hash] = tx_height
90
91     def stop(self):
92         with self.lock: self.running = False
93         self.interface.poke('verifier')
94
95     def is_running(self):
96         with self.lock: return self.running
97
98     def run(self):
99         with self.lock:
100             self.running = True
101         requested_merkle = []
102
103         while self.is_running():
104             # request missing tx
105             for tx_hash, tx_height in self.transactions.items():
106                 if tx_hash not in self.verified_tx:
107                     if self.merkle_roots.get(tx_hash) is None and tx_hash not in requested_merkle:
108                         print_error('requesting merkle', tx_hash)
109                         self.interface.send([ ('blockchain.transaction.get_merkle',[tx_hash, tx_height]) ], 'txverifier')
110                         requested_merkle.append(tx_hash)
111
112             try:
113                 r = self.interface.get_response('txverifier',timeout=1)
114             except Queue.Empty:
115                 continue
116             if not r: continue
117
118             if r.get('error'):
119                 print_error('Verifier received an error:', r)
120                 continue
121
122             # 3. handle response
123             method = r['method']
124             params = r['params']
125             result = r['result']
126
127             if method == 'blockchain.transaction.get_merkle':
128                 tx_hash = params[0]
129                 self.verify_merkle(tx_hash, result)
130                 requested_merkle.remove(tx_hash)
131
132
133     def verify_merkle(self, tx_hash, result):
134         tx_height = result.get('block_height')
135         pos = result.get('pos')
136         self.merkle_roots[tx_hash] = self.hash_merkle_root(result['merkle'], tx_hash, pos)
137         header = self.blockchain.read_header(tx_height)
138         if not header: return
139         assert header.get('merkle_root') == self.merkle_roots[tx_hash]
140         # we passed all the tests
141         timestamp = header.get('timestamp')
142         with self.lock:
143             self.verified_tx[tx_hash] = (tx_height, timestamp, pos)
144         print_error("verified %s"%tx_hash)
145         self.storage.put('verified_tx3', self.verified_tx, True)
146         self.interface.trigger_callback('updated')
147
148
149     def hash_merkle_root(self, merkle_s, target_hash, pos):
150         h = hash_decode(target_hash)
151         for i in range(len(merkle_s)):
152             item = merkle_s[i]
153             h = Hash( hash_decode(item) + h ) if ((pos >> i) & 1) else Hash( h + hash_decode(item) )
154         return hash_encode(h)
155
156
157
158     def undo_verifications(self, height):
159         with self.lock:
160             items = self.verified_tx.items()[:]
161         for tx_hash, item in items:
162             tx_height, timestamp, pos = item
163             if tx_height >= height:
164                 print_error("redoing", tx_hash)
165                 with self.lock:
166                     self.verified_tx.pop(tx_hash)
167                     if tx_hash in self.merkle_roots:
168                         self.merkle_roots.pop(tx_hash)