def search_query(s): if s.isdigit() or len(s) == 64 and s[:8] == '00000000': return redirect(url_for('main.block', network='btc', blockid=s)) if check_txid(s): return redirect(url_for('main.transaction', network='btc', txid=s)) try: key_dict = get_key_format(s) if not key_dict or 'networks' not in key_dict or 'format' not in key_dict: flash(_('Invalid search query, not a valid address or key'), category='error') return redirect(url_for('main.index')) network_name = key_dict['networks'] if not network_name: network_name = 'bitcoin' elif isinstance(network_name, list): network_name = 'bitcoin' if 'bitcoin' in network_name else network_name[ 0] network = [ x for x, y in network_code_translation.items() if y == network_name ][0] if key_dict['format'] == 'address': if Address.import_address(s): return redirect( url_for('main.address', address=s, network=network)) elif key_dict['format']: return redirect(url_for('main.key', key=s, network=network)) flash(_('No address, key or transaction found.'), category='error') return redirect(url_for('main.index')) except Exception as e: flash(_('Not a valid address, key or transaction ID. Response: %s' % e), category='error') return redirect(url_for('main.index'))
def _addresslist_convert(self, addresslist): addresslist_class = [] for addr in addresslist: if not isinstance(addr, Address): addresslist_class.append( Address.import_address( addr, network_overrides=self.network_overrides)) return addresslist_class
def check_address(address=None, error_on_empty=False): if not address: if error_on_empty: return False return True try: assert (Address.import_address(address).address == address) except (AssertionError, EncodingError): return False return True
def gettransaction(self, tx_id): res = self.compose_request('dashboards/transaction/', data=tx_id) tx = res['data'][tx_id]['transaction'] confirmations = 0 if tx['block_id'] <= 0 else res['context']['state'] - tx['block_id'] status = 'unconfirmed' if confirmations: status = 'confirmed' witness_type = 'legacy' if tx['has_witness']: witness_type = 'segwit' input_total = tx['input_total'] t = Transaction(locktime=tx['lock_time'], version=tx['version'], network=self.network, fee=tx['fee'], size=tx['size'], txid=tx['hash'], date=None if not confirmations else datetime.strptime(tx['time'], "%Y-%m-%d %H:%M:%S"), confirmations=confirmations, block_height=tx['block_id'] if tx['block_id'] > 0 else None, status=status, input_total=input_total, coinbase=tx['is_coinbase'], output_total=tx['output_total'], witness_type=witness_type) index_n = 0 if not res['data'][tx_id]['inputs']: # This is a coinbase transaction, add input t.add_input(prev_txid=b'\00' * 32, output_n=0, value=0) for ti in res['data'][tx_id]['inputs']: if ti['spending_witness']: # witnesses = b"".join([varstr(bytes.fromhex(x)) for x in ti['spending_witness'].split(",")]) witnesses = ti['spending_witness'].split(",") address = Address.parse(ti['recipient']) if address.script_type == 'p2sh': witness_type = 'p2sh-segwit' else: witness_type = 'segwit' t.add_input(prev_txid=ti['transaction_hash'], output_n=ti['index'], unlocking_script=ti['spending_signature_hex'], witnesses=witnesses, index_n=index_n, value=ti['value'], address=address, witness_type=witness_type, sequence=ti['spending_sequence'], strict=False) else: t.add_input(prev_txid=ti['transaction_hash'], output_n=ti['index'], unlocking_script=ti['spending_signature_hex'], index_n=index_n, value=ti['value'], address=ti['recipient'], unlocking_script_unsigned=ti['script_hex'], sequence=ti['spending_sequence'], strict=False) index_n += 1 for to in res['data'][tx_id]['outputs']: try: deserialize_address(to['recipient'], network=self.network.name) addr = to['recipient'] except EncodingError: addr = '' t.add_output(value=to['value'], address=addr, lock_script=to['script_hex'], spent=to['is_spent'], output_n=to['index'], spending_txid=to['spending_transaction_hash'], spending_index_n=to['spending_index'], strict=False) return t
def _parse_transaction(self, tx): status = 'unconfirmed' if tx['confirmations']: status = 'confirmed' witness_type = 'legacy' if 'inputs' in tx and [ti['witness'] for ti in tx['inputs'] if ti['witness'] and ti['witness'] != ['NULL']]: witness_type = 'segwit' input_total = tx['input_amount_int'] t_time = None if tx['time']: t_time = datetime.utcfromtimestamp(tx['time']) if tx['coinbase']: input_total = tx['output_amount_int'] t = Transaction(locktime=tx['locktime'], version=int(tx['version']), network=self.network, fee=tx['fee_int'], size=tx['size'], hash=tx['txid'], date=t_time, confirmations=tx['confirmations'], block_height=tx['block'], status=status, input_total=input_total, coinbase=tx['coinbase'], output_total=tx['output_amount_int'], witness_type=witness_type) index_n = 0 if tx['coinbase']: t.add_input(prev_hash=b'\00' * 32, output_n=0, value=input_total) else: for ti in tx['inputs']: unlocking_script = ti['script_sig']['hex'] witness_type = 'legacy' if ti['witness'] and ti['witness'] != ['NULL']: address = Address.import_address(ti['addresses'][0]) if address.script_type == 'p2sh': witness_type = 'p2sh-segwit' else: witness_type = 'segwit' unlocking_script = b"".join([varstr(to_bytes(x)) for x in ti['witness']]) t.add_input(prev_hash=ti['txid'], output_n=ti['vout'], unlocking_script=unlocking_script, index_n=index_n, value=ti['value_int'], address=ti['addresses'][0], sequence=ti['sequence'], witness_type=witness_type) index_n += 1 for to in tx['outputs']: spent = False spending_txid = None if 'spend_txid' in to and to['spend_txid']: spent = True spending_txid = to['spend_txid'] address = '' if to['addresses']: address = to['addresses'][0] t.add_output(value=to['value_int'], address=address, lock_script=to['script_pub_key']['hex'], spent=spent, output_n=to['n'], spending_txid=spending_txid) return t
def validate_address(network, address): """Validate the BTC address :param network: testnet or mainnet :type network: str :param address: address :type address: str :returns: True or False """ try: address = Address.import_address( address=address, network=('bitcoin' if network == 'mainnet' else network)) return True except: return False
def _address_convert(self, address): if not isinstance(address, Address): return Address.import_address( address, network_overrides=self.network_overrides, network=self.network.name)
# # Addresses # print("\n=== Deserialize address ===") pprint(deserialize_address('12ooWd8Xag7hsgP9PBPnmyGe36VeUrpMSH')) print("\n=== Deserialize bech32 address ===") pprint( deserialize_address( 'bc1qtlktwxgx3xu3r7fnt04q06e4gflpvmm70qw66rjckzyc0n54elxqsgqlpy')) print("\n=== Create addreses from public key ===") pk = HDKey().public_hex print("Public key: %s" % pk) print(Address(pk).address) print(Address(pk, script_type='p2sh').address) print(Address(pk, encoding='bech32').address) print(Address(pk, script_type='p2sh', encoding='bech32').address) print(Address(pk, encoding='bech32', network='litecoin').address) print(Address(pk, encoding='bech32', network='dash').address) # # Multisig and segwit WIF key import # print("\n=== Import Segwit p2wpkh WIF key ===") wif = 'zprvAWgYBBk7JR8GkLNSb2QvWhAjydfXoCkSBhvHichpYbqXHDYECcySV5dg1Bw2ybwfJmoLfU1NVzbiD95DVwP34nXPScCzUrLCa3c3WXtkNri' k = HDKey(wif) print("Witness type derived from wif %s is segwit (%s)" % (wif, k.witness_type))