예제 #1
0
    def doit(given_addr, path=None, addr_fmt=None, script=None):
        if not script:
            try:
                # prefer using xpub if we can
                mk = BIP32Node.from_wallet_key(master_xpub)
                sk = mk.subkey_for_path(path[2:])
            except PublicPrivateMismatchError:
                mk = BIP32Node.from_wallet_key(simulator_fixed_xprv)
                sk = mk.subkey_for_path(path[2:])


        if addr_fmt == AF_CLASSIC:
            # easy
            assert sk.address() == given_addr

        elif addr_fmt & AFC_PUBKEY:

            pkh = sk.hash160(use_uncompressed=False)

            if addr_fmt == AF_P2WPKH:
                hrp, data = bech32_decode(given_addr)
                decoded = convertbits(data[1:], 5, 8, False)
                assert hrp in {'tb', 'bc' }
                assert bytes(decoded[-20:]) == pkh
            else:
                assert addr_fmt == AF_P2WPKH_P2SH
                assert given_addr[0] in '23'
                expect = a2b_hashed_base58(given_addr)[1:]
                assert len(expect) == 20
                assert hash160(b'\x00\x14' + pkh) == expect

        elif addr_fmt & AFC_SCRIPT:
            assert script, 'need a redeem/witness script'
            if addr_fmt == AF_P2SH:
                assert given_addr[0] in '23'
                expect = a2b_hashed_base58(given_addr)[1:]
                assert hash160(script) == expect

            elif addr_fmt == AF_P2WSH:
                hrp, data = bech32_decode(given_addr)
                assert hrp in {'tb', 'bc' }
                decoded = convertbits(data[1:], 5, 8, False)
                assert bytes(decoded[-32:]) == sha256(script).digest()

            elif addr_fmt == AF_P2WSH_P2SH:
                assert given_addr[0] in '23'
                expect = a2b_hashed_base58(given_addr)[1:]
                assert hash160(b'\x00\x20' + sha256(script).digest()) == expect

            else:
                raise pytest.fail(f'not ready for {addr_fmt:x} yet')
        else:
            raise ValueError(addr_fmt)

        return sk if not script else None
예제 #2
0
    def test() -> None:
        recipient: ed25519.SigningKey = ed25519.SigningKey(b'\1' * 32)
        recipientPub: bytes = recipient.get_verifying_key().to_bytes()
        address: str = bech32_encode(
            "mr", convertbits(bytes([0]) + recipientPub, 8, 5))

        otherRecipient: bytes = ed25519.SigningKey(
            b'\2' * 32).get_verifying_key().to_bytes()
        otherAddress: str = bech32_encode(
            "mr", convertbits(bytes([0]) + otherRecipient, 8, 5))

        #Create a Send.
        send: Send = Send.fromJSON(vectors["send"])
        if rpc.meros.liveTransaction(send) != rpc.meros.live.recv():
            raise TestError("Meros didn't broadcast back a Send.")
        if rpc.call("transactions", "getUTXOs", {"address": address}) != []:
            raise TestError(
                "Meros considered an unconfirmed Transaction's outputs as UTXOs."
            )
        verify(rpc, send.hash)

        #Spend it.
        spendingSend: Send = Send.fromJSON(vectors["spendingSend"])
        if rpc.meros.liveTransaction(spendingSend) != rpc.meros.live.recv():
            raise TestError("Meros didn't broadcast back a Send.")
        if rpc.call("transactions", "getUTXOs", {"address": address}) != []:
            raise TestError(
                "Meros didn't consider a Transaction's inputs as spent.")

        #Verify with another party, so it won't be majority verified, yet will still have a Verification.
        mineBlock(rpc, 1)
        verify(rpc, spendingSend.hash, 1)
        #Verify it didn't create a UTXO.
        if rpc.call("transactions", "getUTXOs",
                    {"address": otherAddress}) != []:
            raise TestError("Unverified Transaction created a UTXO.")

        #Finalize.
        for _ in range(6):
            mineBlock(rpc)

        #Check the UTXOs were created.
        if rpc.call("transactions", "getUTXOs", {"address": otherAddress}) != [
            {
                "hash": spendingSend.hash.hex().upper(),
                "nonce": 0
            }
        ]:
            raise TestError(
                "Meros didn't consider a finalized Transaction's outputs as UTXOs."
            )

        raise SuccessError()
예제 #3
0
def pubkey_to_address(pubkey: str) -> str:
    pubkey_bytes = bytes.fromhex(pubkey)
    s = hashlib.new("sha256", pubkey_bytes).digest()
    r = hashlib.new("ripemd160", s).digest()
    #return bech32.bech32_encode("cosmos", bech32.convertbits(r, 8, 5))
    #friday
    return bech32.bech32_encode("friday", bech32.convertbits(r, 8, 5))
예제 #4
0
    def doit(given_addr, path, addr_fmt):
        mk = BIP32Node.from_wallet_key(master_xpub)
        sk = mk.subkey_for_path(path[2:])

        if addr_fmt == AF_CLASSIC:
            # easy
            assert sk.address() == given_addr

        elif addr_fmt & AFC_PUBKEY:

            pkh = sk.hash160(use_uncompressed=False)

            if addr_fmt == AF_P2WPKH:
                hrp, data = bech32_decode(given_addr)
                decoded = convertbits(data[1:], 5, 8, False)
                assert hrp in {'tb', 'bc'}
                assert bytes(decoded[-20:]) == pkh
            else:
                assert addr_fmt == AF_P2WPKH_P2SH
                assert given_addr[0] in '23'
                expect = a2b_hashed_base58(given_addr)[1:]
                assert len(expect) == 20
                assert hash160(b'\x00\x14' + pkh) == expect

        elif addr_fmt & AFC_SCRIPT:
            raise pytest.fail('multisig/p2sh addr not handled')
        else:
            raise ValueError(addr_fmt)
예제 #5
0
파일: TGUReorgTest.py 프로젝트: Vyryn/Meros
  def test() -> None:
    recipient: Ristretto.SigningKey = Ristretto.SigningKey(b'\1' * 32)
    recipientPub: bytes = recipient.get_verifying_key()
    address: str = bech32_encode("mr", convertbits(bytes([0]) + recipientPub, 8, 5))

    #Create a Send.
    send: Send = Send.fromJSON(vectors["send"])
    if rpc.meros.liveTransaction(send) != rpc.meros.live.recv():
      raise TestError("Meros didn't broadcast back a Send.")
    verify(rpc, send.hash)
    if rpc.call("transactions", "getUTXOs", {"address": address}) != [{"hash": send.hash.hex().upper(), "nonce": 0}]:
      raise TestError("Meros didn't consider a confirmed Transaction's outputs as UTXOs.")
    #Spend it, with a newer Mint as an input as well so we can prune it without pruning the original.
    newerSend: Send = createSend(rpc, [Claim.fromJSON(vectors["newerMintClaim"])], recipientPub)
    _: Send = createSend(rpc, [send, newerSend], bytes(32), recipient)
    if rpc.call("transactions", "getUTXOs", {"address": address}) != []:
      raise TestError("Meros thinks the recipient has UTXOs.")

    #Remove the spending Send by pruning its ancestor (a Mint).
    reorg(rpc, Blockchain.fromJSON(vectors["blocksWithoutNewerMint"]))
    #Meros should add back its parent as an UTXO.
    if rpc.call("transactions", "getUTXOs", {"address": address}) != [{"hash": send.hash.hex().upper(), "nonce": 0}]:
      raise TestError("Meros didn't consider a Transaction without spenders as an UTXO.")
    #Remove the original Send and verify its outputs are no longer considered UTXOs.
    reorg(rpc, Blockchain.fromJSON(vectors["blocksWithoutOlderMint"]))
    if rpc.call("transactions", "getUTXOs", {"address": address}) != []:
      raise TestError("Meros didn't remove the outputs of a pruned Transaction as UTXOs.")

    raise SuccessError()
예제 #6
0
    def public_key_to_address(self,
                              public_key: bytes = None,
                              hrp: str = None) -> str:
        """
        Function to find the readable address from the public key.

        Execution of this function is as follows::

            public_key_to_address(public_key=b'\x02o\x1f\xfbL\x96\xe8\x1e\xb0\x12V\x80\xc7t\xfc\xb40R\xaeu\xf3{\xf6\xd7m]\xd1\xa9\x91\xa8\xe0Df',
                                  hrp=None)

        The expected return result for this function is as follows::

            tswth1upcgussnx4p3jegwj3x2fccwlajwckkzgstrp8

        :param public_key: Byte representation of the wallets public key.
        :return: String and human readable Tradehub address.
        """
        if hrp is None:
            hrp = self.DEFAULT_BECH32_PREFIX
        s = hashlib.new("sha256", public_key).digest()
        r = hashlib.new("ripemd160", s).digest()
        five_bit_r = bech32.convertbits(r, 8, 5)
        assert five_bit_r is not None, "Unsuccessful bech32.convertbits call"
        return bech32.bech32_encode(hrp, five_bit_r)
예제 #7
0
def patch(state: Optional[Dict], delegating: Optional[Dict],
          config: Config) -> Dict:
    tasks = [
        _patch_schedule_task(task, int(x["height"]), config)
        for x in state.get("tasks") or [] for task in x.get("Schedule", [])
    ]
    if delegating:
        for cluster in delegating.get("clusters", None) or []:
            t: str = modulo_to_time(cluster["modulo"], config)
            tasks.extend({
                "handler_name":
                "delegating/accrue",
                "time":
                t,
                "data":
                base64.standard_b64encode(
                    bytes(
                        bech32.convertbits(bech32.bech32_decode(acc)[1], 5,
                                           8))).decode()
            } for acc in cluster["accounts"])

    tasks.append({
        "handler_name":
        "referral/status-bonus",
        "time":
        height_to_time(((config.initial_height - 1) // ONE_WEEK_BLOCKS + 1) *
                       ONE_WEEK_BLOCKS, config)
    })

    return {
        "params": {
            "day_nanos": str(24 * 60**2 * 10**9 // config.time_quotient)
        },
        "tasks": tasks
    }
예제 #8
0
def generate_wallet():
    priv_key: secp256k1.PrivateKey = secp256k1.PrivateKey()
    pub_key: secp256k1.PublicKey = priv_key.pubkey
    byte_arr = pub_key.serialize(compressed=True)
    s = hashlib.new("sha256", byte_arr).digest()
    r = hashlib.new("ripemd160", s).digest()
    bech_addr = bech32.bech32_encode("cosmos", bech32.convertbits(r, 8, 5))
    return bech_addr, byte_arr.hex(), priv_key.serialize()
예제 #9
0
    def module_address(self, name):
        """
        get address of module accounts

        :param name: name of module account, values: {options}
        """
        data = hashlib.sha256(ModuleAccount(name).value.encode()).digest()[:20]
        return bech32.bech32_encode("cro", bech32.convertbits(data, 8, 5))
예제 #10
0
def pubkey_to_address(pubkey: str) -> str:
    '''converts pubkey to address'''
    pubkey_bytes = binascii.unhexlify(pubkey)

    s = hashlib.new("sha256", pubkey_bytes).digest()
    r = hashlib.new("ripemd160", s).digest()

    return bech32.bech32_encode("ouro", bech32.convertbits(r, 8, 5))
예제 #11
0
def bech32decode(bech):
    ''' Decode bech32 string into prefix and bytearray of data
    '''
    hrp, data = bech32.bech32_decode(bech)
    # Return early if we couldn't parse the input string
    if data is None:
        return hrp, False
    converted = bech32.convertbits(data, 5, 8, False)
    return hrp, converted
예제 #12
0
 def _to_bech32(self, prefix: str) -> str:
     five_bit_r = convertbits(
         # Append prefix public key type follow amino spec.
         bytes.fromhex("eb5ae98721") + self.verify_key.to_string("compressed"),
         8,
         5,
     )
     assert five_bit_r is not None, "Unsuccessful bech32.convertbits call"
     return bech32_encode(prefix, five_bit_r)
예제 #13
0
 def _from_bech32(cls, bech: str, prefix: str) -> PublicKey:
     hrp, bz = bech32_decode(bech)
     assert hrp == prefix, "Invalid bech32 prefix"
     bz = convertbits(bz, 5, 8, False)
     self = cls(_error_do_not_use_init_directly=True)
     self.verify_key = VerifyingKey.from_string(
         bytes(bz[5:]), curve=SECP256k1, hashfunc=hashlib.sha256
     )
     return self
예제 #14
0
def pubhex2address_cosmos(pubhex, prefix='cosmos'):
    import hashlib, bech32
    pubhex_bytes = bytes.fromhex(pubhex)
    hashed_pubkey_bytes = hashlib.sha256(pubhex_bytes).digest()
    hashed_hashed_pubkey_bytes = hashlib.new('ripemd160',
                                             hashed_pubkey_bytes).digest()
    hashed_hashed_pubkey_bytes_base5 = bech32.convertbits(
        hashed_hashed_pubkey_bytes, 8, 5)
    return bech32.bech32_encode(prefix, hashed_hashed_pubkey_bytes_base5)
예제 #15
0
def convertHexPubKey(hex_pub_key, output_format="ed25519"):
    raw_pub_key = binascii.unhexlify(hex_pub_key)
    bech32_pub_key = bech32.bech32_encode("ed25519_pk", bech32.convertbits(raw_pub_key, 8, 5))
    if output_format == "ed25519":
        return bech32_pub_key
    elif output_format == "jcliaddr":
        return "jcliaddr_" + hex_pub_key
    else:
        print(f"output format {output_format} not supported!")
예제 #16
0
파일: Lib.py 프로젝트: Vyryn/Meros
def decodeAddress(
  address: str
) -> bytes:
  decoded: Union[Tuple[None, None], Tuple[str, List[int]]] = bech32_decode(address)
  if decoded[1] is None:
    raise TestError("Decoding an invalid address.")
  res: List[int] = convertbits(decoded[1], 5, 8)
  if res[0] != 0:
    raise TestError("Decoding an address which isn't a Public Key.")
  return bytes(res[1:33])
예제 #17
0
    def _from_bech32(cls, bech: str, prefix: str) -> "Address":
        hrp, bz = bech32_decode(bech)
        assert hrp == prefix, "Invalid bech32 prefix"
        if bz is None:
            raise DecodeError("Cannot decode bech32")
        eight_bit_r = convertbits(bz, 5, 8, False)
        if eight_bit_r is None:
            raise ConvertError("Cannot convert to 8 bit")

        return cls(bytes(eight_bit_r))
예제 #18
0
 def public_key_to_address(self,
                           public_key: bytes = None,
                           hrp: str = None) -> str:
     if hrp is None:
         hrp = self.DEFAULT_BECH32_PREFIX
     s = hashlib.new("sha256", public_key).digest()
     r = hashlib.new("ripemd160", s).digest()
     five_bit_r = bech32.convertbits(r, 8, 5)
     assert five_bit_r is not None, "Unsuccessful bech32.convertbits call"
     return bech32.bech32_encode(hrp, five_bit_r)
예제 #19
0
 def decode_bytes(bech32_string):
     try:
         hrp, data = bech32_decode(bech32_string)
     except:
         return None, None
     if not hrp:
         return None, None
     deconverted = convertbits(data, 5, 8, False)
     assert deconverted
     decoded = bytes(deconverted)
     return hrp, decoded
예제 #20
0
파일: helpers.py 프로젝트: 21isenough/lnurl
def _url_encode(url: str) -> str:
    """
    Encode a URL without validating it first and return a bech32 LNURL string.
    Use `lnurl.encode()` for validation and to get a `Lnurl` object.
    """
    try:
        lnurl = bech32_encode("lnurl",
                              convertbits(url.encode("utf-8"), 8, 5, True))
    except UnicodeEncodeError:  # pragma: nocover
        raise InvalidUrl

    return lnurl.upper()
예제 #21
0
파일: helpers.py 프로젝트: 21isenough/lnurl
def _lnurl_decode(lnurl: str) -> str:
    """
    Decode a LNURL and return a url string without performing any validation on it.
    Use `lnurl.decode()` for validation and to get `Url` object.
    """
    hrp, data = _bech32_decode(_lnurl_clean(lnurl), allowed_hrp={"lnurl"})

    try:
        url = bytes(convertbits(data, 5, 8, False)).decode("utf-8")
    except UnicodeDecodeError:  # pragma: nocover
        raise InvalidLnurl

    return url
예제 #22
0
    def set_address(self):
        pk = self.private_key.verifying_key.to_string("compressed")

        h = hashlib.new('sha256')
        h.update(pk)
        s = h.digest()

        h = hashlib.new('ripemd160')
        h.update(s)
        r = h.digest()

        self.address = bech32.bech32_encode(ADDRESS_PREFIX,
                                            bech32.convertbits(r, 8, 5, True))
예제 #23
0
    def _get_bech(self, prefix: str, payload: str) -> str:
        """Return a bech32 address.

        Computed as bech32 string from the account prefix
        and the account address.

        Note: The `witver` should not be included.
              This is why `bech32.bech32_encode` is used over `bech32.encode`
              which includes the `witver` by default
        """
        return bech32.bech32_encode(
            prefix, bech32.convertbits(bytes.fromhex(payload), 8, 5)
        )
예제 #24
0
    def get_address_from_public_key(public_key: str) -> str:
        """
        Get the address from the public key.

        :param public_key: the public key
        :return: str
        """
        public_key_bytes = bytes.fromhex(public_key)
        s = hashlib.new("sha256", public_key_bytes).digest()
        r = hashlib.new("ripemd160", s).digest()
        five_bit_r = convertbits(r, 8, 5)
        assert five_bit_r is not None, "Unsuccessful bech32.convertbits call"
        address = bech32_encode("cosmos", five_bit_r)
        return address
 def __get_seed_keys(self):
     """
     retrieve the nodeids of the ln seed nodes from lseed.bitcoinstats.com
     """
     domain = "lseed.bitcoinstats.com"
     srv_records = dns.resolver.query(domain, "SRV")
     res = []
     for srv in srv_records:
         bech32 = str(srv.target).rstrip(".").split(".")[0]
         data = bech32_decode(bech32)[1]
         decoded = convertbits(data, 5, 4)
         res.append("".join(
             ['{:1x}'.format(integer) for integer in decoded])[:-1])
     return res
예제 #26
0
    def get_address_from_public_key(cls, public_key: str) -> str:
        """
        Get the address from the public key.

        :param public_key: the public key
        :return: str
        """
        public_key_bytes = bytes.fromhex(public_key)
        s = hashlib.new("sha256", public_key_bytes).digest()
        r = hashlib.new("ripemd160", s).digest()
        five_bit_r = convertbits(r, 8, 5)
        if five_bit_r is None:  # pragma: nocover
            raise AEAEnforceError("Unsuccessful bech32.convertbits call")
        address = bech32_encode(cls.address_prefix, five_bit_r)
        return address
예제 #27
0
def auth_challenge():
    #32 byte challenge k1
    k1 = secrets.token_hex(32)
    url = "http://" + onion_address + "/signin?tag=login&k1=" + k1
    #add k1 to challenges
    challenges.append(k1)

    #bech32 encode string
    bech32_data = convertbits(url.encode("utf-8"), 8, 5, True)
    bech_32_url = bech32_encode("lnurl", bech32_data)

    #save as url code and send
    qr = pyqrcode.create(bech_32_url)
    qr.svg("ln-auth-challenge.svg", scale=8)
    return send_file("ln-auth-challenge.svg", mimetype="image/svg+xml")
예제 #28
0
 def address(self) -> str:
     s = hashlib.new("sha256", self.public_key).digest()
     r = hashlib.new("ripemd160", s).digest()
     five_bit_r = bech32.convertbits(r, 8, 5)
     assert five_bit_r is not None, "Unsuccessful bech32.convertbits call"
     return bech32.bech32_encode(self.hrp, five_bit_r)
예제 #29
0
        for i in range(args.start_idx, args.end_idx):
            path = "m/{}/{}".format(
                metamask_path if args.metamask else args.path, i)
            priv = gen.derive(path)
            keys.append(priv)
            pub = priv.get_verifying_key()
            cpub = pub.to_string(encoding="compressed")
            if args.show_private:
                print("{}.priv(raw/ETH/AVAX-X) 0x{}".format(
                    i,
                    priv.to_string().hex()))
                print("{}.priv(BTC) {}".format(i, get_privkey_btc(priv)))
            print("{}.addr(AVAX) (X/P)-{}".format(
                i,
                bech32.bech32_encode(
                    args.hrp, bech32.convertbits(ripemd160(sha256(cpub)), 8,
                                                 5))))

            path2 = "m/{}/{}".format(metamask_path, i)
            priv2 = gen.derive(path2)
            pub2 = priv2.get_verifying_key()
            if args.show_private:
                print("{}.priv(AVAX-C) 0x{}".format(i,
                                                    priv2.to_string().hex()))
            print("{}.addr(AVAX-C) 0x{}".format(i, get_eth_addr(pub2)))

            print("{}.addr(BTC) {}".format(i, get_btc_addr(pub)))
            print("{}.addr(ETH) {}".format(i, get_eth_addr(pub)))
        if args.export_mew:
            save_to_mew(keys)
        if args.save:
            save_to_keystore(args.save, words)
예제 #30
0
def get_bech(prefix: str, payload: str) -> str:
    data = convertbits(bytes.fromhex(payload), 8, 5)
    if data is None:
        raise ValueError(f"could not parse data: prefix {prefix}, payload {payload}")
    return bech32_encode(prefix, data)  # base64 -> base32