4 from electrum import Interface
5 from electrum.bitcoin import Hash, rev_hex, int_to_hex, hash_encode, hash_decode
7 """validate a transaction (SPV)"""
9 i = Interface({'server':'ecdsa.org:50002:s'})
13 def hash_merkle_root(merkle_s, target_hash, pos):
14 h = hash_decode(target_hash)
15 for i in range(len(merkle_s)):
17 h = Hash( hash_decode(item) + h ) if ((pos >> i) & 1) else Hash( h + hash_decode(item) )
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'))
31 def verify_tx(tx_hash):
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
37 merkle_root = hash_merkle_root(res['merkle'], tx_hash, res['pos'])
38 tx_height = res.get('block_height')
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)
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')
49 assert header.get('merkle_root') == merkle_root
50 print height, _hash, '*'
57 tx = '587430e52af2cec98b3fd543083469ffa7a5f5dd2bd569898a7897a64e2eb031'