You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
1.8 KiB
66 lines
1.8 KiB
#!/usr/bin/env python |
|
|
|
import sys, hashlib |
|
from electrum import Interface |
|
from electrum.bitcoin import Hash, rev_hex, int_to_hex |
|
|
|
"""validate a transaction (SPV)""" |
|
|
|
|
|
i = Interface({'server':'ecdsa.org:50002:s'}) |
|
i.start() |
|
|
|
|
|
encode = lambda x: x[::-1].encode('hex') |
|
decode = lambda x: x.decode('hex')[::-1] |
|
|
|
|
|
def merkle_root(merkle_s, target_hash): |
|
h = decode(target_hash) |
|
for item in merkle_s: |
|
is_left = item[0] == 'L' |
|
if is_left: |
|
h = Hash( h + decode(item[1:]) ) |
|
else: |
|
h = Hash( decode(item[1:]) + h ) |
|
return encode(h) |
|
|
|
|
|
def hash_header(res): |
|
header = int_to_hex(res.get('version'),4) \ |
|
+ rev_hex(res.get('prev_block_hash')) \ |
|
+ rev_hex(res.get('merkle_root')) \ |
|
+ int_to_hex(int(res.get('timestamp')),4) \ |
|
+ int_to_hex(int(res.get('bits')),4) \ |
|
+ int_to_hex(int(res.get('nonce')),4) |
|
return rev_hex(Hash(header.decode('hex')).encode('hex')) |
|
|
|
|
|
def verify_tx(tx_hash): |
|
|
|
res = i.synchronous_get([ ('blockchain.transaction.get_merkle',[tx_hash]) ])[0] |
|
assert res.get('merkle_root') == merkle_root(res['merkle'], tx_hash) |
|
block_height = res.get('block_height') |
|
print block_height |
|
|
|
headers_requests = [] |
|
for height in range(block_height-10,block_height+10): |
|
headers_requests.append( ('blockchain.block.get_header',[height]) ) |
|
res = i.synchronous_get(headers_requests) |
|
|
|
_hash = None |
|
for header in res: |
|
if _hash: assert _hash == header.get('prev_block_hash') |
|
_hash = hash_header(header) |
|
print _hash |
|
if height==block_height: |
|
assert header.get('merkle_root') == res.get('merkle_root') |
|
|
|
|
|
try: |
|
tx = sys.argv[1] |
|
except: |
|
tx = '587430e52af2cec98b3fd543083469ffa7a5f5dd2bd569898a7897a64e2eb031' |
|
|
|
verify_tx(tx) |
|
|
|
|