Example #1
0
 def test_invalid_address(self):
     """Test whether invalid addresses fail to decode."""
     for test in INVALID_ADDRESS:
         witver, _ = bech32.decode("bc", test)
         self.assertIsNone(witver)
         witver, _ = bech32.decode("tb", test)
         self.assertIsNone(witver)
Example #2
0
 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)
Example #3
0
def build_output_script_from_address(address: str) -> Optional[bytes]:
    """
    Compute the output script for a given address.
    """
    # Try to decode a base58 address
    try:
        decoded = base58.b58decode_check(address)
        version = decoded[0]
        hash = decoded[1:]

        if version == P2PKH_ADDRESS_HEADER:
            return _build_p2pkh_output_script(hash)

        if version == P2SH_ADDRESS_HEADER:
            return _build_p2sh_output_script(hash)

    except ValueError:
        pass

    # Try to decode a bech32 address
    try:
        version, hash = bech32.decode(BECH32_HRP, address)

        if version == 0:
            return _build_segwit_output_script(hash)

    except ValueError:
        pass

    return None
Example #4
0
 def get_hashed_pbk_from_addr(addr):
     a = addr
     if a[0:2] in ('bc', 'tb'):
         lul, decoded = bech32.decode(a[0:2], a)
         hashed_pbk = "".join(list(map('{:02x}'.format, decoded)))
     else:
         hashed_pbk = base58.b58decode_check(a)[1:].hex()
     return hashed_pbk
Example #5
0
def get_witness_prog(addr, testnet=False):
  hrp = "tb" if testnet else "bc"
  ret = bech32.decode(hrp, addr)
  witness_prog = str(bytearray(ret[1]))

  if len(witness_prog) == 32:
    raise UnsupportedFormat("Error: We dont support P2SH segwit addresses. (" + addr + ")")
  
  ver = struct.pack("<B", ret[0])

  return witness_prog, ver
def bech32_to_scripthash(address):
    hrp, data = bech32.bech32_decode(address)
    witver, witprog = bech32.decode(hrp, address)
    script = [witver, len(witprog)] + witprog
    script = ''.join('{:02x}'.format(x) for x in script)
    scripthash = hashlib.sha256(binascii.unhexlify(script)).hexdigest()
    rev = ''
    i = len(scripthash) - 2
    while i >= 0:
        rev += scripthash[i:i + 2]
        i -= 2
    return rev
Example #7
0
def process(csvfile):
    with open(csvfile, 'r') as f:
        for i, row in enumerate(f):
            if i == 0:
                print(row[:-1] + ',ripemd')
                continue
            elif row.strip() == '':
                break

            if row[:3].lower() == 'bc1':
                _, script_int = bech32.decode('bc', row.split(',')[0].lower())
                ripemd_encoded = binascii.hexlify(bytearray(script_int))
            else:
                ripemd_bin = tocondensed(row.split(',')[0])
                ripemd_encoded = binascii.hexlify(ripemd_bin)
            print(row[:-1] + ',' + ripemd_encoded.decode())
    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)
Example #9
0
def is_valid_bech32_address(value: str) -> bool:
    """Validates a bitcoin SegWit address for the mainnet
    """

    decoded = bech32.decode('bc', value)
    return decoded != (None, None)
Example #10
0
def validate_address(addr):
    try:
        _, data = bech32.decode('hs', addr)
        return data is not None
    except Exception as e:
        return False