fix for notifications
[electrum-nvc.git] / scripts / validate_tx
1 #!/usr/bin/env python
2
3 import sys, hashlib
4 from electrum import Interface
5 from electrum.bitcoin import Hash, rev_hex, int_to_hex, hash_encode, hash_decode
6
7 """validate a transaction (SPV)"""
8
9 i = Interface({'server':'ecdsa.org:50002:s'})
10 i.start()
11
12
13 def hash_merkle_root(merkle_s, target_hash, pos):
14     h = hash_decode(target_hash)
15     for i in range(len(merkle_s)):
16         item = merkle_s[i]
17         h = Hash( hash_decode(item) + h ) if ((pos >> i) & 1) else Hash( h + hash_decode(item) )
18     return hash_encode(h)
19
20
21 def hash_header(res):
22     header = int_to_hex(res.get('version'),4) \
23         + rev_hex(res.get('prev_block_hash')) \
24         + rev_hex(res.get('merkle_root')) \
25         + int_to_hex(int(res.get('timestamp')),4) \
26         + int_to_hex(int(res.get('bits')),4) \
27         + int_to_hex(int(res.get('nonce')),4)
28     return rev_hex(Hash(header.decode('hex')).encode('hex'))
29
30
31 def verify_tx(tx_hash):
32     
33     res = i.synchronous_get([ ('blockchain.transaction.get_merkle',[tx_hash]) ])[0]
34     raw_tx = i.synchronous_get([ ('blockchain.transaction.get',[tx_hash, res['block_height']]) ])[0]
35     assert hash_encode(Hash(raw_tx.decode('hex'))) == tx_hash
36
37     merkle_root = hash_merkle_root(res['merkle'], tx_hash, res['pos'])
38     tx_height = res.get('block_height')
39     headers_requests = []
40     for height in range(tx_height-10,tx_height+10):
41         headers_requests.append( ('blockchain.block.get_header',[height]) )
42     headers = i.synchronous_get(headers_requests)
43     _hash = None
44     for header in headers:
45         if _hash: assert _hash == header.get('prev_block_hash')
46         _hash = hash_header(header)
47         height = header.get('block_height')
48         if height==tx_height:
49             assert header.get('merkle_root') == merkle_root
50             print height, _hash, '*'
51         else:
52             print height, _hash
53
54 try:
55     tx = sys.argv[1]
56 except:
57     tx = '587430e52af2cec98b3fd543083469ffa7a5f5dd2bd569898a7897a64e2eb031'
58
59 verify_tx(tx)
60