def asm(script): """Turns a script into a symbolic representation""" if isinstance(script, str): script = hex_to_bytes(script) else: script = copy(script) def read(n): nonlocal script data = script[:n] assert data or n == 0, 'EOF' script = script[n:] return data results = [] while script: byte = bytes_to_int(read(1)) op = OP(byte) if byte in range(1, 76): results.append(bytes_to_hex(read(byte))) elif byte == 76: bytes_to_read = bytes_to_int(read(1)) results.append(bytes_to_hex(read(bytes_to_read))) elif byte == 77: bytes_to_read = bytes_to_int(read(2)) results.append(bytes_to_hex(read(bytes_to_read))) elif byte == 78: bytes_to_read = bytes_to_int(read(4)) results.append(bytes_to_hex(read(bytes_to_read))) else: results.append(str(op)) return ' '.join(results)
def json(self): result = { "txid": bytes_to_hex(self.output), "vout": self.index, "scriptSig": { "hex": bytes_to_hex(self.script) } } if self.segwit: result['witness'] = [bytes_to_hex(wit) for wit in self.witness] result["sequence"] = self.sequence return result
def test_address_to_script(self): """https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#test-vectors""" valid = { 'BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4': '0014751e76e8199196d454941c45d1b3a323f1433bd6', 'tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7': '00201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262', 'bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7k7grplx': '5128751e76e8199196d454941c45d1b3a323f1433bd6751e76e8199196d454941c45d1b3a323f1433bd6', 'BC1SW50QA3JX3S': '6002751e', 'bc1zw508d6qejxtdg4y5r3zarvaryvg6kdaj': '5210751e76e8199196d454941c45d1b3a323', 'tb1qqqqqp399et2xygdj5xreqhjjvcmzhxw4aywxecjdzew6hylgvsesrxh6hy': '0020000000c4a5cad46221b2a187905e5266362b99d5e91c6ce24d165dab93e86433' } invalid = [ 'tc1qw508d6qejxtdg4y5r3zarvary0c5xw7kg3g4ty', 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t5', 'BC13W508D6QEJXTDG4Y5R3ZARVARY0C5XW7KN40WF2', 'bc1rw5uspcuh', 'bc10w508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7kw5rljs90', 'BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P', 'tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sL5k7', 'bc1zw508d6qejxtdg4y5r3zarvaryvqyzf3du', 'tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3pjxtptv', 'bc1gmk9yu' ] for addr, script in valid.items(): self.assertEqual(bytes_to_hex(address_to_script(addr)), script) for addr in invalid: with self.assertRaises(bech32.Bech32DecodeError): address_to_script(addr)
def decode_scriptpubkey(script): from cryptotools.BTC.address import get_address return { "hex": bytes_to_hex(script) if isinstance(script, bytes) else script, "asm": asm(script), "type": get_type(script).value, "address": get_address(script) }
def test_bip39(self): with open(HERE / 'vectors' / 'mnemonic.txt') as fileobj: data = json.load(fileobj) for entropy, mnemonic, seed, master in data['english']: my_seed = to_seed(mnemonic, passphrase='TREZOR') self.assertEqual(bytes_to_hex(my_seed), seed) xprv = Xprv.from_seed(seed) self.assertEqual(xprv.encode(), master)
def json(self): return { "txid": bytes_to_hex(self.txid()[::-1]), # TODO "version": self.version, "size": len(self.serialize()), "locktime": self.lock_time, "vin": [inp.json() for inp in self.inputs], "vout": [out.json(i) for i, out in enumerate(self.outputs)] }
def send(source, to, fee, private): addr = Address(source) prv_to_addr = private.to_public().to_address(addr.type().value) assert source == prv_to_addr, 'This private key does not correspond to the given address' tx = addr.send(to=to, fee=fee, private=private) assert tx.verify(), 'Something went wrong, could not verify signed transaction' result = tx.broadcast() if result == 'Transaction Submitted': return bytes_to_hex(tx.txid()[::-1]) raise UpstreamError(result)
def json(self): result = { "txid": bytes_to_hex(self.output), "vout": self.index, "scriptSig": { "hex": bytes_to_hex(self.script) } } if self.segwit: result['witness'] = [bytes_to_hex(wit) for wit in self.witness] result["sequence"] = self.sequence try: redeem = bytes_to_hex(self.redeem()) result['scriptSig']['redeem'] = redeem result['scriptSig']['redeem_asm'] = asm(redeem) except Exception: pass return result
def get(cls, txhash): """Construct a transaction from it's tx id by getting the raw data from the configured backend""" from urllib.error import HTTPError if isinstance(txhash, bytes): txhash = bytes_to_hex(txhash) backend = current_backend() txhex = backend.get_tx(txhash) sleep(0.1) try: return cls.from_hex(txhex) except SerializationError as e: e.txhash = txhash raise e
def test_p2sh(self): script = secrets.token_bytes(32) scripthash = hash160(script) payload = {'RIPEMDWithHash': '05' + bytes_to_hex(scripthash)} data = urllib.parse.urlencode(payload).encode('ascii') req = urllib.request.Request(self.url, data) with urllib.request.urlopen(req) as response: html = HtmlLegacyAddress() html.feed(response.read().decode('utf-8')) address = html.address self.assertEqual(script_to_address(script, 'P2SH'), address) self.assertEqual(address_type(address), ADDRESS.P2SH)
def is_signed(self) -> bool: output_type = self.ref().type() nested = self.is_nested() if output_type == TX.P2PKH: try: sig, pub = self.asm().split(' ') except ValueError: return False return is_signature(sig[:-2]) and is_pubkey(pub) elif output_type == TX.P2WPKH or nested == TX.P2WPKH: try: return is_signature(self.witness[0][:-1]) # and is_pubkey(self.witness[-1]) except ScriptValidationError: return False elif output_type == TX.P2WSH or nested == TX.P2WSH: return any(is_signature(bytes_to_hex(item)[:-2]) for item in self.witness) elif output_type == TX.P2SH: return any((is_signature(item[:-2]) for item in self.asm().split(' '))) elif output_type == TX.P2PK: return is_signature(self.asm()[:-2])
def get(cls, txhash): """Construct a transaction from it's tx id by getting the raw data from blockchain.info""" import urllib.request from urllib.error import HTTPError if isinstance(txhash, bytes): txhash = bytes_to_hex(txhash) url = network('rawtx_url').format(txid=txhash) req = urllib.request.Request(url) sleep(0.1) try: with urllib.request.urlopen(req) as resp: try: return cls.from_hex(resp.read().decode()) except SerializationError as e: e.txhash = txhash raise e except HTTPError as e: resp = e.read().decode() raise UpstreamError(resp)
def hex(self): return bytes_to_hex(self.serialize())
def print(self): print(self.asm()) print([bytes_to_hex(i) for i in self.stack])
def hex(self, compressed=False, compact=False) -> str: return bytes_to_hex(self.encode(compressed=compressed, compact=compact))
def pbkdf2_hex(data, salt, iterations=1000, keylen=24, hashfunc=None): """Like :func:`pbkdf2_bin` but returns a hex encoded string.""" return bytes_to_hex(pbkdf2_bin(data, salt, iterations, keylen, hashfunc))
def hex(self): return bytes_to_hex(self.encode())