def test_to_legacy_p2sh(self): self.assertEqual( convert.to_legacy_address('3CWFddi6m4ndiGyKqzYvsFYagqDLPVMTzC'), '3CWFddi6m4ndiGyKqzYvsFYagqDLPVMTzC') self.assertEqual( convert.to_legacy_address( 'bitcoincash:ppm2qsznhks23z7629mms6s4cwef74vcwvn0h829pq'), '3CWFddi6m4ndiGyKqzYvsFYagqDLPVMTzC')
def test_to_legacy_p2sh_testnet(self): self.assertEqual( convert.to_legacy_address('2MwikwR6hoVijCmr1u8UgzFMHFP6rpQyRvP'), '2MwikwR6hoVijCmr1u8UgzFMHFP6rpQyRvP') self.assertEqual( convert.to_legacy_address( 'bchtest:pqc3tyspqwn95retv5k3c5w4fdq0cxvv95u36gfk00'), '2MwikwR6hoVijCmr1u8UgzFMHFP6rpQyRvP')
def test_to_legacy_p2pkh_testnet(self): self.assertEqual( convert.to_legacy_address('mqp7vM7eU7Vu9NPH1V7s7pPg5FFBMo6SWK'), 'mqp7vM7eU7Vu9NPH1V7s7pPg5FFBMo6SWK') self.assertEqual( convert.to_legacy_address( 'bchtest:qpc0qh2xc3tfzsljq79w37zx02kwvzm4gydm222qg8'), 'mqp7vM7eU7Vu9NPH1V7s7pPg5FFBMo6SWK')
def test_to_legacy_p2pkh(self): self.assertEqual( convert.to_legacy_address('155fzsEBHy9Ri2bMQ8uuuR3tv1YzcDywd4'), '155fzsEBHy9Ri2bMQ8uuuR3tv1YzcDywd4') self.assertEqual( convert.to_legacy_address( 'bitcoincash:qqkv9wr69ry2p9l53lxp635va4h86wv435995w8p2h'), '155fzsEBHy9Ri2bMQ8uuuR3tv1YzcDywd4')
def get_balance(cls, address): # As of 2018-05-16, cashexplorer.bitcoin.com only supports legacy addresses. address = cashaddress.to_legacy_address(address) r = requests.get(cls.MAIN_BALANCE_API.format(address), timeout=DEFAULT_TIMEOUT) if r.status_code != 200: # pragma: no cover raise ConnectionError return r.json()
def verify_tx_with_amount(addr, amount): _legacy = convert.to_legacy_address(addr) _json_addr = get_api_addr(addr) #print(json.dumps(_json_addr, indent=4)) if len(_json_addr['transactions']) > 0: for _txid in _json_addr['transactions']: print('txid: ' + _txid) _json_tx = get_api_tx(_txid) #print(json.dumps(_json_tx, indent=4)) for _out in _json_tx['vout']: if float(_out['value']) == float(amount): if _legacy == _out['scriptPubKey']['addresses'][ 0] or addr.lstrip('bitcoincash:') == _out[ 'scriptPubKey']['addresses'][0]: print('FOUND!') print(_out['value']) _tx = { "value": amount, "input_address": addr, "confirmations": _json_tx['confirmations'], "transaction_hash": _txid, "input_transaction_hash": _txid, "destination_address": addr, } return _tx return False
def get_balance(cls, address): if not cls.NEW_ADDRESS_SUPPORTED: address = cashaddress.to_legacy_address(address) r = requests.get((cls.MAIN_ENDPOINT+cls.MAIN_BALANCE_API).format(address), timeout=DEFAULT_TIMEOUT) if r.status_code != 200: # pragma: no cover raise ConnectionError return r.json()
def verify(addr, amount): _legacy = convert.to_legacy_address(addr) _json_addr = get_api_addr(addr) if _json_addr['unconfirmedBalance'] == float( amount) or _json_addr['balance'] == float(amount): for _txid in _json_addr['transactions']: print('txid: ' + _txid) _json_tx = get_api_tx(_txid) for _out in _json_tx['vout']: if float(_out['value']) == float(amount): if _legacy == _out['scriptPubKey']['addresses'][ 0] or addr.lstrip('bitcoincash:') == _out[ 'scriptPubKey']['addresses'][0]: print('FOUND!') print(_out['value']) _tx = { "received": 1, "receive_address": addr, "amount": amount, "confirmations": _json_tx['confirmations'], "txid": _txid, } return _tx return {"received": 0}
def get_transactions(cls, address): address = cashaddress.to_legacy_address(address) r = requests.get(cls.MAIN_ADDRESS_API.format(address), timeout=DEFAULT_TIMEOUT) if r.status_code != 200: # pragma: no cover raise ConnectionError return r.json()['transactions']
def get_transactions(cls, address): # As of 2018-05-16, cashexplorer.bitcoin.com only supports legacy addresses. address = cashaddress.to_legacy_address(address) r = requests.get(cls.MAIN_ADDRESS_API + address, timeout=DEFAULT_TIMEOUT) if r.status_code != 200: # pragma: no cover raise ConnectionError return r.json()['transactions']
def get_balance(cls, address): address = cashaddress.to_legacy_address(address) r = requests.get(cls.MAIN_BALANCE_API.format(address), timeout=DEFAULT_TIMEOUT) if r.status_code != 200: # pragma: no cover raise ConnectionError return r.json()
def bitcoinAddress2bin(btcAddress): """convert a bitcoin address to binary data capable of being put in a CScript""" #print("btcAddress = ", btcAddress) legacyAddressBytes = b'' # btcAddress contains prefix if convert.is_valid(btcAddress): # 2nd argument "1" is included for regtest; otherwise, omit the second argument legacyAddressBytes = convert.to_legacy_address(btcAddress, 1).encode() else: assert(0) # should not arrive here return legacyAddressBytes
def get_transactions(cls, address): """ :param address: :return:list of transaction hash """ if not cls.NEW_ADDRESS_SUPPORTED: address = cashaddress.to_legacy_address(address) r = requests.get(cls.MAIN_ENDPOINT+cls.MAIN_ADDRESS_API + address, timeout=DEFAULT_TIMEOUT) if r.status_code != 200: # pragma: no cover raise ConnectionError return r.json()['transactions']
def get_unspent(cls, address): address = cashaddress.to_legacy_address(address) r = requests.get(cls.MAIN_UNSPENT_API.format(address), timeout=DEFAULT_TIMEOUT) if r.status_code != 200: # pragma: no cover raise ConnectionError return [ Unspent(currency_to_satoshi(tx['amount'], 'bsv'), tx['confirmations'], tx['scriptPubKey'], tx['txid'], tx['vout']) for tx in r.json() ]
def get_unspent(cls, address): # As of 2018-05-16, cashexplorer.bitcoin.com only supports legacy addresses. address = cashaddress.to_legacy_address(address) r = requests.get(cls.MAIN_UNSPENT_API.format(address), timeout=DEFAULT_TIMEOUT) if r.status_code != 200: # pragma: no cover raise ConnectionError return [ Unspent(currency_to_satoshi(tx['amount'], 'bch'), tx['confirmations'], tx['scriptPubKey'], tx['txid'], tx['vout']) for tx in r.json() ]
def process(rpc_connection, nblktime): if len(g_exUserAddrs) == 0: return [] txs = BTC_ListTransactions.process(rpc_connection, '*', 100000000) retTxs = [] for tx in txs: strLegacyAddr = convert.to_legacy_address(tx["address"].strip()) tx["address"] = strLegacyAddr.strip() # print(tx) if int(str(tx['blocktime'])) >= nblktime and tx["address"].strip( ) in g_exUserAddrs: retTxs.append(tx) return retTxs
def read_bch_file(): with open(input_bch_filename) as f: bch_list = f.read().rstrip('\n').split('\n') print('\n\nLoaded ' + str(len(bch_list)) +' BitcoinCash address from the file') xx_list = list() for line in bch_list: try: xx = convert.to_legacy_address('bitcoincash:'+line) except: continue xx_list.append(xx) print('\nIgnored ' + str(len(bch_list) - len(xx_list)) +' BitcoinCash address before converting to H160') return xx_list
def get_txs(address): """Gets utxos for given legacy address""" address = cashaddress.to_legacy_address(address) headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } r = requests.get( 'https://api.bitindex.network/api/v2/addrs/txs?address={}'.format( address), headers=headers) return r.json()
def get_api_addr(addr): _legacy = convert.to_legacy_address(addr) _addr = { 'caddr': addr, 'legacy': _legacy, } _api = randomize() _request = _api['api_addr'].format(**_addr) print(_request) _r = requests.get(_request) _json_addr = _r.json() return _json_addr
def utxo(rpcconn, addrs, minconf=1, maxconf=9999999, opt=None): argAddrs = addrs if isinstance(addrs, list) else [addrs] if opt == None: commands = [["listunspent", minconf, maxconf, argAddrs, True]] else: commands = [["listunspent", minconf, maxconf, argAddrs, True, opt]] utxos = rpcconn.batch_(commands)[0] #要进行地址格式的转换 for i in range(len(utxos)): cashAddr = utxos[i]['address'] legacyAddr = convert.to_legacy_address(cashAddr) utxos[i]['address'] = legacyAddr utxos[i]['cashaddress'] = cashAddr return utxos
def get_utxo(address): """gets utxos for given address BitIndex api""" address = cashaddress.to_legacy_address(address) json_payload = json.dumps({"addrs": address}) headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } r = requests.post('https://api.bitindex.network/api/addrs/utxo', data=json_payload, headers=headers) return [ Unspent(amount=currency_to_satoshi(tx['amount'], 'bsv'), script=tx['scriptPubKey'], txid=tx['txid'], txindex=tx['vout'], confirmations=tx['confirmations']) for tx in r.json() ]
def get_transactions_by_addresses(cls,addresses,start_index=0,stop_index=50): if stop_index-start_index>50: raise ValueError('Range between start_index ({}) and stop_index ' '({}) less than or equal to 50!'.format(start_index,stop_index)) if isinstance(addresses,str): addresses=[addresses] if not cls.NEW_ADDRESS_SUPPORTED: addresses = [cashaddress.to_legacy_address(address) for address in addresses] addresses_str=','.join(addresses) r=requests.get((cls.MAIN_ENDPOINT + cls.MAIN_TXS_BY_ADDRESSES_API). format(addresses_str,start_index,stop_index), timeout=DEFAULT_TIMEOUT) if r.status_code!=200: raise ConnectionError data=r.json() total_txs=data['totalItems'] txs=data['items'] #type:list return total_txs,txs
def generate_payment(parameters, ip_addr): _amount = False _label = False _payment = False _uri = "" _uri_params = "" _qr = "/qr?addr=" _qr_params = "" if 'amount' in parameters: _amount = parameters.amount _qr_params += "&amount=" + _amount _uri_params += "?amount=" + _amount else: abort(400, "Specify an amount!") if 'label' in parameters: _label = parameters.label _qr_params += "&label=" + _label if _amount: _uri_params += "&message=" + _label else: _uri_params += "?message=" + _label _addr = get_address(ip_addr, _amount, _label) _legacy = convert.to_legacy_address(_addr) _qr += _addr + _qr_params _uri = _addr + _uri_params _payreq = { "payment": { "amount": _amount, #"addr": _addr.lstrip('BITCOINCASH:'), "addr": _addr, "legacy_addr": _legacy, "label": _label, "qr_img": _qr, "payment_uri": _uri, } } _json = json.dumps(_payreq) return _json
def verify_tx(addr): _legacy = convert.to_legacy_address(addr) _addr = { 'caddr': addr, 'legacy': _legacy, } _json_addr = get_api_addr(addr) _amount = _json_addr['unconfirmedBalance'] if _json_addr[ 'unconfirmedBalance'] != 0 else _json_addr['totalReceived'] #print(json.dumps(_json_addr, indent=4)) if len(_json_addr['transactions']) == 1: print('tx: ' + _json_addr['transactions'][0]) _txid = _json_addr['transactions'][0] _request = api_tx + _txid _r = requests.get(_request) _json_tx = _r.json() #print(json.dumps(_json_tx, indent=4)) for _out in _json_tx['vout']: if float(_out['value']) == _amount: if _legacy == _out['scriptPubKey']['addresses'][ 0] or addr.lstrip('bitcoincash:') == _out[ 'scriptPubKey']['addresses'][0]: print('FOUND!') print(_out['value']) _tx = { "value": _amount, "input_address": addr, "confirmations": _json_tx['confirmations'], "transaction_hash": _txid, "input_transaction_hash": _txid, "destination_address": addr, } return _tx return False
from cashaddress import convert import sys if len(sys.argv) != 2: print("usage : bhcconvert <cashAddrss>") else: addrss = sys.argv[1] addrss = addrss.replace('bitcoincash:', '') if convert.is_valid('bitcoincash:' + addrss): print(convert.to_legacy_address('bitcoincash:' + addrss)) else: sys.stderr.write('Invalid address\n')
def address_to_public_key_hash(address): # Support cashaddr and "legacy" for now. address = cashaddress.to_legacy_address(address) get_version(address) return b58decode_check(address)[1:]
get_transaction( 'fef8e336024a23c76155819ceda562b5a05da33c5d24757137d0db84ce23fbb3')) print() print( get_transaction_btc( 'a7e3babfd7658cfa5ebf5d9b1477da0b40cab68d75c7bc8638eaafcba066b062')) print() print(get_transactions('qqa0dwrk79um6wgmzk9rrv303l2qwppuk5vmr8taqq')) k = Key('L3KavUvcjBj7pzKBMS4doKyJpBY4nJJbm31VnVwhcC26mTvCP3Lh') # k = PrivateKeyTestnet('cPW1zL9JJzgTKwQyHYeQ8KE5Cdo33fGE15QcZiWDCWKHhU43KsU2') # print(k.public_key) print(k.address) # print(k._public_key) # print(k.public_point) address = convert.to_legacy_address(k.address) print(address) bchaddr = convert.to_cash_address('13A8QNwEeuYyvcPSJwR4F5xDr6RUryLVfw') # print(bchaddr) # print(k.to_wif()) print(k.get_balance(currency='satoshi')) # print(k.unspents) # print(k.transactions) print(k.get_transactions()) print(k.get_unspents()) txid = k.send([('13A8QNwEeuYyvcPSJwR4F5xDr6RUryLVfw', 0.01001, 'bch')], fee=452) print(txid) print(get_balance('qz7xc0vl85nck65ffrsx5wvewjznp9lflgktxc5878', currency='bch'))
def to_legacy_address(self, addr): return to_string(to_legacy_address(addr))
def test_to_legacy_p2sh_regtest(self): self.assertEqual(convert.to_legacy_address('2MwSNRexxm3uhAKF696xq3ztdiqgMj36rJo'), '2MwSNRexxm3uhAKF696xq3ztdiqgMj36rJo') self.assertEqual(convert.to_legacy_address('bchreg:pqklc8ehp365xvtru6a394e4wxz52nt5nurac3g7rq'), '2MwSNRexxm3uhAKF696xq3ztdiqgMj36rJo')
def test_to_legacy_p2pkh_regtest(self): self.assertEqual(convert.to_legacy_address('moehusBtUt3aKW5c2p3ZTRkSTRrr3dpnwe'), 'moehusBtUt3aKW5c2p3ZTRkSTRrr3dpnwe') self.assertEqual(convert.to_legacy_address('bchreg:qpvns5lcufh5haf5jt79fk8trcw4j8c3nsvhdappvt'), 'moehusBtUt3aKW5c2p3ZTRkSTRrr3dpnwe')