def addr_funct(hashpubkey, pr): if pr is None: return dic={'L':'30', 'm':'6f', 'M':'32', '3':'05', '2':'c4', 'Q':'3a', '4':'08', 'l':True, 't':False} if pr in dic: pr=dic[pr] prs=['30', '6f', '32', '05', 'c4', '3a', '08', True, False] if pr not in prs: return None if isinstance(pr, int): try: spk = binascii.unhexlify(hashpubkey) if spk[0]: version = spk[0] - 0x30 else: version = 0 program = spk[2:] if pr: return bech32.encode('ltc', version, program) else: return bech32.encode('tltc', version, program) except: return p=hashpubkey p=p.upper() p=pr+p p2=p.upper() p2=sha256(p2) p2=p2.upper() p2=sha256(p2) p2=p2.upper() p3=p+p2[0:8] p3=bytes.fromhex(p3) p3=base58.b58encode(p3) return str(p3)[2:-1]
def creaChiavi(self): chiave1 = self.lnChiave1.text() chiave2 = self.lnChiave2.text() priv = hashlib.sha256(chiave2.encode('utf-8')).hexdigest() if (chiave1 == "m"): key = bit.Key.from_hex(priv) else: key = bit.PrivateKeyTestnet.from_hex(priv) hashkey = hashlib.sha256(key.public_key).digest() ripemd160 = hashlib.new("ripemd160") ripemd160.update(hashkey) keyhash = ripemd160.digest() self.lnPrivateKey.setText( key.to_hex()) #print("Private Key: ", key.to_hex()) self.lnPublicKey.setText( utils.bytes_to_hex(key.public_key, True) ) #print("Public Key: ", utils.bytes_to_hex(key.public_key, True)) self.lnKeyHash.setText( keyhash.hex() + " (ripemd160(sha256(pub)))" ) #print("KeyHas: ", keyhash.hex(), "(ripemd160(sha256(pub)))") self.lnWif.setText( key.to_wif()) #print("WIF: ", key.to_wif()) self.lnAddress.setText( key.address + " P2PKH") #print("Address: ", key.address, "P2PKH") self.lnSegwit.setText( key.segwit_address ) #print("SegWit Addr: ", key.segwit_address) if (chiave1 == "m"): bech = bech32.encode('bc', 0, keyhash) else: bech = bech32.encode('tb', 0, keyhash) self.lnBech32.setText(bech) #print("Bech32 Addr: ", bech) #Abilita tutti i pulsanti per copiare nella Clipboard self.btnClipboard_1.setEnabled(True) self.btnClipboard_2.setEnabled(True) self.btnClipboard_3.setEnabled(True) self.btnClipboard_4.setEnabled(True) self.btnClipboard_5.setEnabled(True) self.btnClipboard_6.setEnabled(True) self.btnClipboard_7.setEnabled(True)
def make_ms_address(M, keys, idx=0, is_change=0, addr_fmt=AF_P2SH, testnet=1, **make_redeem_args): # Construct addr and script need to represent a p2sh address import bech32 from pycoin.encoding import b2a_hashed_base58, hash160 if 'path_mapper' not in make_redeem_args: make_redeem_args['path_mapper'] = lambda cosigner: [HARD(45), cosigner, is_change, idx] script, pubkeys, xfp_paths = make_redeem(M, keys, **make_redeem_args) if addr_fmt == AF_P2WSH: hrp = ['bc', 'tb'][testnet] data = sha256(script).digest() addr = bech32.encode(hrp, 0, data) scriptPubKey = bytes([0x0, 0x20]) + data else: if addr_fmt == AF_P2SH: digest = hash160(script) elif addr_fmt == AF_P2WSH_P2SH: digest = hash160(b'\x00\x20' + sha256(script).digest()) else: raise ValueError(addr_fmt) prefix = bytes([196]) if testnet else bytes([5]) addr = b2a_hashed_base58(prefix + digest) scriptPubKey = bytes([0xa9, 0x14]) + digest + bytes([0x87]) return addr, scriptPubKey, script, zip(pubkeys, xfp_paths)
def get_bech32(compressed_publkey): hrp = 'tb' witver = 0 sha256 = hashlib.sha256(bytes.fromhex(compressed_publkey)) ripemd160 = hashlib.new('ripemd160') ripemd160.update(sha256.digest()) witprog = ripemd160.digest() bech32_addr = bech32.encode(hrp, witver, witprog) return bech32_addr
def witness_p2wphk_script_to_bech32_address(p2wphk_script, main_net=True): witness_script = p2wphk_script.decode("hex") hrp = BECH32_HRP if not main_net: hrp = BECH32_HRP_TEST witness_script_bytes = [ord(c) for c in witness_script] return encode(hrp, witness_script_bytes[0], witness_script_bytes[2:])
def test_change_p2sh_p2wpkh(start_sign, end_sign, check_against_bitcoind, cap_story, case): # not fraud: output address encoded in various equiv forms from pycoin.tx.Tx import Tx from pycoin.tx.TxOut import TxOut # NOTE: out#1 is change: #chg_addr = 'mvBGHpVtTyjmcfSsy6f715nbTGvwgbgbwo' psbt = open('data/example-change.psbt', 'rb').read() b4 = BasicPSBT().parse(psbt) t = Tx.parse(BytesIO(b4.txn)) pkh = t.txs_out[1].hash160() if case == 'p2wpkh': t.txs_out[1].script = bytes([0, 20]) + bytes(pkh) from bech32 import encode expect_addr = encode('tb', 0, pkh) elif case == 'p2sh': spk = bytes([0xa9, 0x14]) + pkh + bytes([0x87]) b4.outputs[1].redeem_script = bytes([0, 20]) + bytes(pkh) t.txs_out[1].script = spk expect_addr = t.txs_out[1].address('XTN') b4.txn = t.as_bin() with BytesIO() as fd: b4.serialize(fd) mod_psbt = fd.getvalue() open('debug/mod-%s.psbt' % case, 'wb').write(mod_psbt) start_sign(mod_psbt) time.sleep(.1) _, story = cap_story() check_against_bitcoind(B2A(b4.txn), Decimal('0.00000294'), change_outs=[ 1, ], dests=[(1, expect_addr)]) #print(story) assert expect_addr in story assert parse_change_back(story) == (Decimal('1.09997082'), [expect_addr]) signed = end_sign(True)
def witness_redeemscript_to_bech32_address(redeemscript, main_net=True): redeemscript = redeemscript.decode("hex") d32 = utils.sha256(redeemscript) witness_script = OP_0 + chr(len(d32)) + d32 hrp = BECH32_HRP if not main_net: hrp = BECH32_HRP_TEST witness_script_bytes = [ord(c) for c in witness_script] return encode(hrp, witness_script_bytes[0], witness_script_bytes[2:])
def witness_pubkey_to_bech32_address(pubkey, main_net=True): pubkey = pubkey.decode("hex") d20 = utils.hash160(pubkey) witness_script = OP_0 + chr(len(d20)) + d20 hrp = BECH32_HRP if not main_net: hrp = BECH32_HRP_TEST witness_script_bytes = [ord(c) for c in witness_script] return encode(hrp, witness_script_bytes[0], witness_script_bytes[2:])
def get_address_name(inorout, network): try: if type(inorout) == TxOut: address = network.address.for_script(inorout.puzzle_script()) elif type(inorout) == Spendable: address = network.address.for_script(inorout.puzzle_script()) else: # address from tx input if (len(inorout.witness) == 2) and (inorout.script == b''): # Witness PubKeyHash (pay-to-witness-pubkeyhash / P2WPKH) address = bech32.encode(network.ui._bech32_hrp, 0x00, hash160(inorout.witness[1])) elif (len(inorout.witness) > 2) and (inorout.script == b''): # Witness ScriptHash (pay-to-witness-scripthash / P2WSH) address = bech32.encode(network.ui._bech32_hrp, 0x00, sha256(inorout.witness[-1])) else: address = inorout.address(network.ui) if address == '(unknown)': address = network.ui.address_for_p2sh(hash160(inorout.script[1:])) except: address = 'bad script' return address
def scriptpubkey_to_bech32_address(data: bytes) -> BTCAddress: """Return a native SegWit (bech32) address given a scriptpubkey""" version = data[0] if OpCodes.op_1 <= data[0:1] <= OpCodes.op_16: version -= 0x50 elif data[0:1] != OpCodes.op_0: raise EncodingError(f'Invalid bech32 scriptpubkey: {data.hex()}') address = bech32.encode('bc', version, data[2:]) if not address: # should not happen raise EncodingError('Could not derive bech32 address from given scriptpubkey') return BTCAddress(address)
def test_valid_address(self): """Test whether valid addresses decode to the correct output.""" for (address, hexscript) in VALID_ADDRESS: hrp = "bc" witver, witprog = bech32.decode(hrp, address) if witver is None: hrp = "tb" witver, witprog = bech32.decode(hrp, address) self.assertIsNotNone(witver) scriptpubkey = segwit_scriptpubkey(witver, witprog) self.assertEqual(scriptpubkey, binascii.unhexlify(hexscript)) addr = bech32.encode(hrp, witver, witprog) self.assertEqual(address.lower(), addr)
def pubhex2address_bitcoin_segwit(pubhex): """Public Key Hex -> Bitcoin Segwit Address""" import hashlib, bech32 pubkey_bytes = bytes.fromhex(pubhex) # hrp = 'bc' if mainnet # network_byte = \x00 if mainnet # address = bech32(hrp, network_byte, ripemd160(sha256(pubkey))) hashed_pubkey_bytes = hashlib.sha256(pubkey_bytes).digest() hashed_hashed_pubkey_bytes = hashlib.new('ripemd160', hashed_pubkey_bytes).digest() return bech32.encode(hrp='bc', witver=0, witprog=hashed_hashed_pubkey_bytes)
def pk_to_p2wpkh(compressed, network): pk_hash = hash160(compressed) redeemScript = bytes.fromhex(f"0014{pk_hash.hex()}") spk = binascii.unhexlify(redeemScript.hex()) version = spk[0] - 0x50 if spk[0] else 0 program = spk[2:] if network == "testnet": prefix = 'tb' elif network == "simnet": prefix = 'sb' elif network == "mainnet": prefix = 'bc' else: return "Enter the network: tesnet/simnet/mainnet" return bech32.encode(prefix, version, program)
def pubkey_to_bech32_address(data: bytes, witver: int) -> BTCAddress: """ Bitcoin pubkey to bech32 address Source: https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#witness-program https://github.com/mcdallas/cryptotools/blob/master/btctools/address.py May raise: - EncodingError if address could not be derived from public key """ witprog = hash160(data) result = bech32.encode('bc', witver, witprog) if not result: raise EncodingError('Could not derive bech32 address from given public key') return BTCAddress(result)
def bech32_address_from_compressed_publkey(compressed_publkey, network): if network is NETWORKS.BITCOIN: hrp = 'bc' elif network is NETWORKS.TESTNET: hrp = 'tb' else: prRed( "bech32_address_from_compressed_publkey:\n[WRONG NETWORK TYPE]" ) return witver = 0 sha256 = hashlib.sha256(bytes.fromhex(compressed_publkey)) ripemd160 = hashlib.new('ripemd160') ripemd160.update(sha256.digest()) witprog = ripemd160.digest() # print(witprog.hex()) bech32_addr = bech32.encode(hrp, witver, witprog) return bech32_addr
def _get_current_pending_commission(self): operator = bech32.encode('cosmosvaloper', bech32.decode(self.address)[1]) try: response = urlopen(f"{LCD}/distribution/validators/{operator}").read() data = json.loads(response.decode('utf-8')) except: # if it failed, it's (likely/hopefully) just because this address # is not a validator at all, so just set data to {} and move on data = {} if data.get('val_commission') is None: return 0.0 relevant_commission = list(filter(lambda bal: bal['denom'] == args.denom, data['val_commission'])) try: amount = float(relevant_commission[0]['amount']) * (10 ** -args.scale) except IndexError: print(f"No relevant commission balances found for {operator} (in {args.denom}). Did you specify the correct `denom`?") exit(1) return round(amount, 3)
# test_bech32 import bech32 print("--- basic bech32 test ---") lnurl = bech32.encode("lnurl", 1, b"https://someURLforLNnode") print("lnurl: ", lnurl) # > lnurl1pdp68gurn8ghj7um0d4j425jvvehhynzwdehkgeg0tppps
def parse_address(version, h): return bech32.encode('hs', int(version), binascii.unhexlify(h))
def bech32_address(pub): # starts with bc1 keyhash = hashlib.new("ripemd160", hashlib.sha256( binascii.unhexlify(pub)).digest()).digest() return bech32.encode('bc', 0, keyhash)
def _bech32enc(self, ohash160, network='mainnet'): bechenc = bech32.encode( "bc", 0, ohash160) if network == 'mainnet' else bech32.encode( "tb", 0, ohash160) return bechenc
def script_to_bech32(witprog: bytes, witver: int, testnet=False) -> str: """https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#witness-program""" if testnet: return bech32.encode('tb', witver, witprog) else: return bech32.encode('bc', witver, witprog)
def test_invalid_address_enc(self): """Test whether address encoding fails on invalid input.""" for hrp, version, length in INVALID_ADDRESS_ENC: code = bech32.encode(hrp, version, [0] * length) self.assertIsNone(code)