1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-12-16 03:18:09 +00:00
trezor-firmware/trezorlib/tx_api.py

92 lines
2.5 KiB
Python
Raw Normal View History

2014-03-28 18:47:53 +00:00
import binascii
import urllib2
import json
try:
from filecache import filecache, MONTH
except:
def filecache(x):
def _inner(y):
return y
return _inner
MONTH = None
import types_pb2 as proto_types
2014-04-02 17:31:47 +00:00
def op_push_data(data):
l = len(data)
if l < 0x4C:
return chr(l) + data
elif i < 0xFF:
return '\x4C' + chr(l) + data
elif i < 0xFFFF:
return '\x4D' + struct.pack("<H", i) + data
2014-03-29 20:31:17 +00:00
else:
2014-04-02 17:31:47 +00:00
return '\x4E' + struct.pack("<I", i) + data
2014-03-29 20:31:17 +00:00
def opcode_serialize(opcode):
2014-04-02 17:31:47 +00:00
mapping = {
'OP_TRUE' : '\x51',
'OP_RETURN' : '\x6A',
'OP_DUP' : '\x76',
'OP_EQUAL' : '\x87',
'OP_EQUALVERIFY' : '\x88',
'OP_RIPEMD160' : '\xA6',
'OP_SHA1' : '\xA7',
'OP_SHA256' : '\xA8',
'OP_HASH160' : '\xA9',
'OP_HASH256' : '\xAA',
'OP_CHECKSIG' : '\xAC',
'OP_CHECKSIGVERIFY' : '\xAD',
'OP_CHECKMULTISIG' : '\xAE',
'OP_CHECKMULTISIGVERIFY' : '\xAF',
}
# check if it is known opcode
if mapping.has_key(opcode):
return mapping[opcode]
2014-03-29 20:31:17 +00:00
# it's probably hex data
try:
x = binascii.unhexlify(opcode)
2014-04-02 17:31:47 +00:00
return op_push_data(x)
2014-03-29 20:31:17 +00:00
except:
raise Exception('Unknown script opcode: %s' % opcode)
2014-03-28 20:34:15 +00:00
def bitcore_tx(url):
f = urllib2.urlopen(url)
data = json.load(f)
2014-03-28 18:47:53 +00:00
2014-03-28 20:34:15 +00:00
t = proto_types.TransactionType()
t.version = data['version']
t.lock_time = data['locktime']
2014-03-28 18:47:53 +00:00
2014-03-28 20:34:15 +00:00
for vin in data['vin']:
2014-03-28 18:47:53 +00:00
i = t.inputs.add()
2014-03-28 20:34:15 +00:00
i.prev_hash = binascii.unhexlify(vin['txid'])
i.prev_index = vin['vout']
2014-03-29 20:31:17 +00:00
asm = vin['scriptSig']['asm'].split(' ')
asm = [ opcode_serialize(x) for x in asm ]
i.script_sig = ''.join(asm)
2014-03-29 23:44:42 +00:00
i.sequence = vin['sequence']
2014-03-28 18:47:53 +00:00
2014-03-28 20:34:15 +00:00
for vout in data['vout']:
2014-04-07 14:25:03 +00:00
o = t.bin_outputs.add()
2014-03-28 20:34:15 +00:00
o.amount = int(vout['value'] * 100000000)
2014-03-28 20:48:48 +00:00
asm = vout['scriptPubKey']['asm'].split(' ')
2014-03-29 20:31:17 +00:00
asm = [ opcode_serialize(x) for x in asm ]
o.script_pubkey = ''.join(asm)
2014-03-28 18:47:53 +00:00
2014-03-28 20:34:15 +00:00
return t
class TXAPIBitcoin(object):
@filecache(MONTH)
def get_tx(self, txhash):
url = 'http://live.bitcore.io/api/tx/%s' % txhash
return bitcore_tx(url)
2014-03-28 18:47:53 +00:00
2014-03-28 20:34:15 +00:00
class TXAPITestnet(object):
2014-03-28 18:47:53 +00:00
2014-03-28 20:34:15 +00:00
@filecache(MONTH)
def get_tx(self, txhash):
url = 'http://test.bitcore.io/api/tx/%s' % txhash
return bitcore_tx(url)