1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-11-18 05:28:40 +00:00
trezor-firmware/trezorlib/tx_api.py

141 lines
4.9 KiB
Python
Raw Normal View History

# This file is part of the Trezor project.
2016-11-25 21:53:55 +00:00
#
# Copyright (C) 2012-2018 SatoshiLabs and contributors
2016-11-25 21:53:55 +00:00
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.
2016-11-25 21:53:55 +00:00
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the License along with this library.
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
2016-11-25 21:53:55 +00:00
2014-03-28 18:47:53 +00:00
import binascii
2018-08-13 16:21:24 +00:00
import json
2014-05-28 12:38:44 +00:00
from decimal import Decimal
2018-08-13 16:21:24 +00:00
2016-05-20 14:08:55 +00:00
import requests
2016-05-26 15:20:44 +00:00
from . import messages as proto
2018-08-13 16:21:24 +00:00
cache_dir = None
2016-10-21 13:24:30 +00:00
2017-06-23 19:31:42 +00:00
class TxApi(object):
def __init__(self, network, url=None):
self.network = network
self.url = url
def get_url(self, *args):
2018-08-21 17:03:07 +00:00
return "/".join(map(str, [self.url, "api"] + list(args)))
2018-07-25 09:38:35 +00:00
2017-06-18 22:00:26 +00:00
def fetch_json(self, resource, resourceid):
global cache_dir
if cache_dir:
2018-08-13 16:21:24 +00:00
cache_file = "%s/%s_%s_%s.json" % (
cache_dir,
self.network,
resource,
resourceid,
)
2017-06-23 19:31:42 +00:00
try: # looking into cache first
j = json.load(open(cache_file), parse_float=str)
return j
except Exception:
pass
if not self.url:
raise RuntimeError("No URL specified and tx not in cache")
try:
url = self.get_url(resource, resourceid)
2018-08-13 16:21:24 +00:00
r = requests.get(url, headers={"User-agent": "Mozilla/5.0"})
j = r.json(parse_float=str)
except Exception:
2018-08-13 16:21:24 +00:00
raise RuntimeError("URL error: %s" % url)
if cache_dir and cache_file:
2017-06-23 19:31:42 +00:00
try: # saving into cache
2018-08-13 16:21:24 +00:00
json.dump(j, open(cache_file, "w"))
except Exception:
pass
return j
2014-03-28 20:34:15 +00:00
def get_tx(self, txhash):
raise NotImplementedError
2016-05-01 12:21:20 +00:00
class TxApiInsight(TxApi):
2018-07-25 09:38:35 +00:00
def __init__(self, network, url=None, zcash=None, bip115=False):
super().__init__(network, url)
self.zcash = zcash
2018-07-25 09:38:35 +00:00
self.bip115 = bip115
if url:
self.pushtx_url = self.url + "/tx/send"
def get_block_hash(self, block_number):
j = self.fetch_json("block-index", block_number)
return binascii.unhexlify(j["blockHash"])
def current_height(self):
r = requests.get(self.get_url("status?q=getBlockCount"))
j = r.json(parse_float=str)
block_height = j["info"]["blocks"]
return block_height
2016-05-01 12:21:20 +00:00
def get_tx(self, txhash):
2016-05-01 12:21:20 +00:00
2018-08-13 16:21:24 +00:00
data = self.fetch_json("tx", txhash)
2016-05-01 12:21:20 +00:00
t = proto.TransactionType()
2018-08-13 16:21:24 +00:00
t.version = data["version"]
t.lock_time = data["locktime"]
2016-05-01 12:21:20 +00:00
2018-08-13 16:21:24 +00:00
for vin in data["vin"]:
i = t._add_inputs()
2018-08-13 16:21:24 +00:00
if "coinbase" in vin.keys():
2017-06-23 19:31:42 +00:00
i.prev_hash = b"\0" * 32
i.prev_index = 0xffffffff # signed int -1
2018-08-13 16:21:24 +00:00
i.script_sig = binascii.unhexlify(vin["coinbase"])
i.sequence = vin["sequence"]
2014-03-28 20:34:15 +00:00
else:
2018-08-13 16:21:24 +00:00
i.prev_hash = binascii.unhexlify(vin["txid"])
i.prev_index = vin["vout"]
i.script_sig = binascii.unhexlify(vin["scriptSig"]["hex"])
i.sequence = vin["sequence"]
2014-03-28 18:47:53 +00:00
2018-08-13 16:21:24 +00:00
for vout in data["vout"]:
o = t._add_bin_outputs()
2018-08-13 16:21:24 +00:00
o.amount = int(Decimal(vout["value"]) * 100000000)
o.script_pubkey = binascii.unhexlify(vout["scriptPubKey"]["hex"])
2018-07-25 09:38:35 +00:00
if self.bip115 and o.script_pubkey[-1] == 0xb4:
# Verify if coin implements replay protection bip115 and script includes checkblockatheight opcode. 0xb4 - is op_code (OP_CHECKBLOCKATHEIGHT)
# <OP_32> <32-byte block hash> <OP_3> <3-byte block height> <OP_CHECKBLOCKATHEIGHT>
tail = o.script_pubkey[-38:]
o.block_hash = tail[1:33] # <32-byte block hash>
2018-08-13 16:21:24 +00:00
o.block_height = int.from_bytes(
tail[34:37], byteorder="little"
) # <3-byte block height>
2016-05-20 14:08:55 +00:00
if self.zcash:
2018-08-13 16:21:24 +00:00
t.overwintered = data.get("fOverwintered", False)
t.expiry = data.get("nExpiryHeight", False)
2018-06-05 14:02:51 +00:00
if t.version >= 2:
2018-08-13 16:21:24 +00:00
joinsplit_cnt = len(data["vjoinsplit"])
if joinsplit_cnt == 0:
2018-08-13 16:21:24 +00:00
t.extra_data = b"\x00"
else:
if joinsplit_cnt >= 253:
# we assume cnt < 253, so we can treat varIntLen(cnt) as 1
2018-08-13 16:21:24 +00:00
raise ValueError("Too many joinsplits")
extra_data_len = 1 + joinsplit_cnt * 1802 + 32 + 64
2018-08-13 16:21:24 +00:00
raw = self.fetch_json("rawtx", txhash)
raw = binascii.unhexlify(raw["rawtx"])
t.extra_data = raw[-extra_data_len:]
2014-03-28 18:47:53 +00:00
return t