New port numbers
[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, network, storage):
31         threading.Thread.__init__(self)
32         self.daemon = True
33         self.storage = storage
34         self.network = network
35         self.transactions    = {}                                 # requested verifications (with height sent by the requestor)
36         self.verified_tx     = storage.get('verified_tx3',{})      # height, timestamp of verified transactions
37         self.merkle_roots    = storage.get('merkle_roots',{})      # hashed by me
38         self.lock = threading.Lock()
39         self.running = False
40         self.queue = Queue.Queue()
41
42
43     def get_confirmations(self, tx):
44         """ return the number of confirmations of a monitored transaction. """
45         with self.lock:
46             if tx in self.verified_tx:
47                 height, timestamp, pos = self.verified_tx[tx]
48                 conf = (self.network.get_local_height() - height + 1)
49                 if conf <= 0: timestamp = None
50
51             elif tx in self.transactions:
52                 conf = -1
53                 timestamp = None
54
55             else:
56                 conf = 0
57                 timestamp = None
58
59         return conf, timestamp
60
61
62     def get_txpos(self, tx_hash):
63         "return position, even if the tx is unverified"
64         with self.lock:
65             x = self.verified_tx.get(tx_hash)
66             y = self.transactions.get(tx_hash)
67         if x:
68             height, timestamp, pos = x
69             return height, pos
70         elif y:
71             return y, 0
72         else:
73             return 1e12, 0
74
75
76     def get_height(self, tx_hash):
77         with self.lock:
78             v = self.verified_tx.get(tx_hash)
79         height = v[0] if v else None
80         return height
81
82
83     def add(self, tx_hash, tx_height):
84         """ add a transaction to the list of monitored transactions. """
85         assert tx_height > 0
86         with self.lock:
87             if tx_hash not in self.transactions.keys():
88                 self.transactions[tx_hash] = tx_height
89
90     def stop(self):
91         with self.lock: self.running = False
92
93     def is_running(self):
94         with self.lock: return self.running
95
96     def run(self):
97         with self.lock:
98             self.running = True
99         requested_merkle = []
100
101         while self.is_running():
102             # request missing tx
103             for tx_hash, tx_height in self.transactions.items():
104                 if tx_hash not in self.verified_tx:
105                     # do not request merkle branch before headers are available
106                     if tx_height > self.network.blockchain.height():
107                         continue
108                     if self.merkle_roots.get(tx_hash) is None and tx_hash not in requested_merkle:
109                         if self.network.send([ ('blockchain.transaction.get_merkle',[tx_hash, tx_height]) ], lambda i,r: self.queue.put(r)):
110                             print_error('requesting merkle', tx_hash)
111                             requested_merkle.append(tx_hash)
112
113             try:
114                 r = self.queue.get(timeout=1)
115             except Queue.Empty:
116                 continue
117
118             if not r: continue
119
120             if r.get('error'):
121                 print_error('Verifier received an error:', r)
122                 continue
123
124             # 3. handle response
125             method = r['method']
126             params = r['params']
127             result = r['result']
128
129             if method == 'blockchain.transaction.get_merkle':
130                 tx_hash = params[0]
131                 self.verify_merkle(tx_hash, result)
132                 requested_merkle.remove(tx_hash)
133
134
135     def verify_merkle(self, tx_hash, result):
136         tx_height = result.get('block_height')
137         pos = result.get('pos')
138         self.merkle_roots[tx_hash] = self.hash_merkle_root(result['merkle'], tx_hash, pos)
139         header = self.network.get_header(tx_height)
140         if not header: return
141         assert header.get('merkle_root') == self.merkle_roots[tx_hash]
142         # we passed all the tests
143         timestamp = header.get('timestamp')
144         with self.lock:
145             self.verified_tx[tx_hash] = (tx_height, timestamp, pos)
146         print_error("verified %s"%tx_hash)
147         self.storage.put('verified_tx3', self.verified_tx, True)
148         self.network.trigger_callback('updated')
149
150
151     def hash_merkle_root(self, merkle_s, target_hash, pos):
152         h = hash_decode(target_hash)
153         for i in range(len(merkle_s)):
154             item = merkle_s[i]
155             h = Hash( hash_decode(item) + h ) if ((pos >> i) & 1) else Hash( h + hash_decode(item) )
156         return hash_encode(h)
157
158
159
160     def undo_verifications(self, height):
161         with self.lock:
162             items = self.verified_tx.items()[:]
163         for tx_hash, item in items:
164             tx_height, timestamp, pos = item
165             if tx_height >= height:
166                 print_error("redoing", tx_hash)
167                 with self.lock:
168                     self.verified_tx.pop(tx_hash)
169                     if tx_hash in self.merkle_roots:
170                         self.merkle_roots.pop(tx_hash)