Beispiel #1
0
def pubkey_to_address(pubkey: bytes) -> str:
    if 'ripemd160' not in hashlib.algorithms_available:
        raise RuntimeError('missing ripemd160 hash algorithm')

    sha = hashlib.sha256(pubkey).digest()
    ripe = hashlib.new('ripemd160', sha).digest()
    return b58encode_check(b'\x00' + ripe)
Beispiel #2
0
def publickey_to_address(public_key):
    sha256_of_pubkey = hashlib.sha256(public_key.decode('hex')).digest()
    #print 'sha256 of public key -> ', sha256_of_pubkey.encode('hex')

    ripemd160 = hashlib.new('ripemd160')
    ripemd160.update(sha256_of_pubkey)
    ripemd160_of_sha256 = ripemd160.digest()
    #print 'ripemd160 of sha256 -> ', ripemd160_of_sha256.encode('hex')

    ripemd160_of_sha256_with_network = '00' + ripemd160_of_sha256.encode('hex')
    #print 'ripemd160 of sha256 with network -> ', ripemd160_of_sha256_with_network

    #double_sha256 = hashlib.sha256(hashlib.sha256(ripemd160_of_sha256_with_network.decode('hex')).digest())
    #print 'double sha256 of previous -> ', double_sha256.digest().encode('hex')

    #checksum = double_sha256.digest().encode('hex')[:8]
    #print 'checksum -> ', checksum

    #with_checksum = ripemd160_of_sha256_with_network + checksum
    #print 'with checksum -> ', with_checksum

    address = base58.b58encode_check(ripemd160_of_sha256_with_network.decode('hex'))

    #address = base58.b58encode(with_checksum.decode('hex'))
    #print 'address -> ', address
    return address
Beispiel #3
0
def run_prototype(url, number):
    try:
        # generate a blank address...
        test_address = base58.b58encode_check(b'\x00'+os.urandom(20))
        client = DownstreamClient(test_address)

        print('Connect to server')
        client.connect(url)

        print('Fetching contract')
        client.get_chunk()

        print('Answering challenge 0')
        client.answer_challenge()

        i = 1
        while number == 0 or i < number:
            client.get_challenge()
            print('Answering challenge {0}'.format(i))
            client.answer_challenge()
            i += 1

        print('Verification successful!')

    except DownstreamError as e:
        fail_exit(e.message)
def generate_new_wallet():
    ##########################
    if "--rootkey" in sys.argv:
        i = sys.argv.index("--rootkey") + 1
        root_key = sys.argv[i].decode('hex')
    else:
        root_key = bip38v2.generate_root_key(length=32) # Feel free to change this to 16 or 64
    ##########################
    if "--unencrypted" in sys.argv:
          passphrase = None
          fake_passphrase = None
    else:
        if "--passphrase" in sys.argv:
            i = sys.argv.index("--passphrase") + 1
            passphrase = sys.argv[i]
        else:
            print "Please enter your passphrase. DO NOT FORGET THIS."
            passphrase = getpass.getpass("Passphrase:") 
            passphrase_confirm = getpass.getpass("Confirm:")
            if passphrase != passphrase_confirm:
                raise Exception("Password mismatch")
        if "--no-fake-passphrase" in sys.argv:
            fake_passphrase = None
        elif "--fake-passphrase" in sys.argv:
            i = sys.argv.index("--fake-passphrase") + 1
            fake_passphrase = sys.argv[i]
        else:
            print "Please enter your second (fake) passphrase."
            print "This can be used if you are forced to decrypt the wallet."
            print "Leave this as empty if you don't want a fake passphrase."
            fake_passphrase = getpass.getpass("Fake Passphrase:") 
            if fake_passphrase is not "":
                fake_passphrase_confirm = getpass.getpass("Confirm:")
                if fake_passphrase != fake_passphrase_confirm:
                    raise Exception("Password mismatch")
            else:
                fake_passphrase = None
    ##########################
    if "--weeks" in sys.argv:
        i = sys.argv.index("--weeks") + 1
        weeks = int(sys.argv[i])
    else:
        weeks = (date.today() - date(2013, 1, 1)).days/7
    ##########################
    if "--kdf" in sys.argv:
        i = sys.argv.index("--kdf") + 1
        kdf_type = int(sys.argv[i])
    else:
        kdf_type = 0
    ##########################
    print "Generating wallet. May take quite a while!"
    encrypted_wallet = bip38v2.make_wallet(root_key, weeks, passphrase=passphrase, fake_passphrase=fake_passphrase, kdf_type=kdf_type)
    base58_text = base58.b58encode_check(encrypted_wallet)
    print "Encrypted wallet: " + base58_text
    if "--qrcode" in sys.argv:
        import qrcode
        qr_code = qrcode.make(base58_text)
        qr_code.save("wallet.png")
        print "QR code saved to wallet.png"
Beispiel #5
0
def gen_addr(prefix):
    for a in '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz':
        for b in '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz':
            res = base58.b58decode((prefix+a+b).ljust(33, "1"))
            res = base58.b58encode_check(res[0:21])
            if res.startswith(prefix):
                return res
                
    return None
Beispiel #6
0
 def to_b58check(self, testnet=False):
     """ Generates a Base58Check encoding of this key.
     Args:
         testnet (bool): True if the key is to be used with
             testnet, False otherwise.
     Returns:
         str: A Base58Check encoded string representing the key.
     """
     b = self.testnet_bytes if testnet else bytes(self)
     return base58.b58encode_check(b)
 def _get_bitcoin_address(self):
     private_key_decode = base58.b58decode_check(self.private_key)
     if len(private_key_decode) ==33:
         private_key = private_key_decode[1:]
     elif len(private_key_decode) ==34:
         private_key = private_key_decode[1:-1]
     else:
         raise Exception
     public_key_uncompress,public_key_compress = self._get_public_key(private_key, self.NID_secp256k1)
     return base58.b58encode_check(b'\x00'+self._sha256ripemd160(public_key_uncompress)), base58.b58encode_check(b'\x00'+self._sha256ripemd160(public_key_compress))
Beispiel #8
0
 def btg_balance(self, address):
     decoded = base58.b58decode_check(address)
     if decoded[0] == 0:
         decoded = bytearray(decoded)
         decoded[0] = 38
         address_btg = base58.b58encode_check(bytes(decoded))
         r = requests.get(
             'https://btgexplorer.com/api/addr/%s/?noTxList=1' %
             address_btg)
         return 'BTG:%s' % str(r.json()['balance'])
     else:
         return 'BTG:None'
Beispiel #9
0
def fromBytes(data):
    tx = Transaction()
    buf = StringIO(data)

    tx.type, tx.timestamp = unpack("<bi", buf)
    object.__setattr__(tx, "key_one", ArkyDict(public=unpack_bytes(buf, 33)))
    rid = unpack_bytes(buf, 21).replace(b"\x00", b"")
    if rid != "": tx.recipientId = base58.b58encode_check(rid)
    vf = unpack_bytes(buf, 64).replace(b"\x00", b"").decode()
    if vf != "": tx.vendorField = vf
    tx.amount, fee = unpack("<QQ", buf)

    idx = []
    for i in range(len(data)):
        if basint(data[i]) == 0x30:
            j = i + basint(data[i + 1]) + 2
            if j <= len(data):
                try:
                    object.__setattr__(
                        tx, "signature"
                        if not hasattr(tx, "signature") else "signSignature",
                        _hexlify(checkStrictDER(data[i:j])))
                    idx.append(i)
                except:
                    pass

    start = buf.tell()
    stop = len(data) if not len(idx) else min(idx)
    asset = data[start:stop]

    if tx.type == 1:
        object.__setattr__(
            tx, "asset",
            ArkyDict(signature=ArkyDict(publicKey=_hexlify(asset))))
    elif tx.type == 2:
        object.__setattr__(
            tx, "asset",
            ArkyDict(delegate=ArkyDict(username=str(asset.decode()))))
    elif tx.type == 3:
        object.__setattr__(
            tx, "asset",
            ArkyDict(votes=[
                str(asset[i:i + 67].decode())
                for i in range(0, len(asset), 67)
            ]))
    elif tx.type == 4:
        pass

    if hasattr(tx, "signature"):
        object.__setattr__(tx, "id",
                           _hexlify(hashlib.sha256(getBytes(tx)).digest()))

    return tx
Beispiel #10
0
def b58xpub(parent_fingerprint, public_key, chain, depth, childnr):
    """ Public key b58 serialization format. """

    raw = (
            b'\x04\x88\xb2\x1e' +
            bytes(chr(depth), 'utf-8') +
            parent_fingerprint +
            childnr.to_bytes(4, byteorder='big') +
            chain +
            public_key)

    return b58encode_check(raw)
Beispiel #11
0
    def export_to_wif(self):
        """Export a key to WIF.

        See https://en.bitcoin.it/wiki/Wallet_import_format for a full
        description.
        """
        # Add the network byte, creating the "extended key"
        extended_key_hex = self.private_key.get_extended_key()
        # BIP32 wallets have a trailing \01 byte
        extended_key_bytes = unhexlify(extended_key_hex) + b'\01'
        # And return the base58-encoded result with a checksum
        return base58.b58encode_check(extended_key_bytes)
Beispiel #12
0
def publicKeyGenerator():
    sk = ecdsa.SigningKey.from_string(start[0:64].decode('hex'),
                                      curve=ecdsa.SECP256k1)
    vk = sk.verifying_key
    publicKey = ('\04' + sk.verifying_key.to_string()).encode('hex')
    ripemd160 = hashlib.new('ripemd160')
    ripemd160.update(hashlib.sha256(publicKey.decode('hex')).digest())
    address = base58.b58encode_check(chr(0) + ripemd160.digest())
    print("Public Address: " + address)
    addrFile = address[-8:]
    img2 = qrcode.make(address)
    img2.save("Address_" + addrFile + ".png")
Beispiel #13
0
    def run(cls, _input: Union[bytes, str], **kwargs) -> bool:
        if isinstance(_input, str):
            try:
                _input = _input.encode("ascii").lower()
            except:
                return False

        if (len(_input) != 64 or _input >
                b"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"
            ):
            return False

        try:
            wif = base58.b58encode_check(b"80" + _input)
        except:
            try:
                wif = base58.b58encode_check(b"ef" + _input)
            except:
                return False

        return BitcoinWifValidator.run(wif)
Beispiel #14
0
    def export_to_wif(self):
        """Export a key to WIF.

        See https://en.bitcoin.it/wiki/Wallet_import_format for a full
        description.
        """
        # Add the network byte, creating the "extended key"
        extended_key_hex = self.private_key.get_extended_key()
        # BIP32 wallets have a trailing \01 byte
        extended_key_bytes = unhexlify(extended_key_hex) + b'\01'
        # And return the base58-encoded result with a checksum
        return base58.b58encode_check(extended_key_bytes)
Beispiel #15
0
def getAddress(publicKey):
    """
	Computes ARK address from keyring.

	Argument:
	keys (ArkyDict) -- keyring returned by `getKeys`

	Return str
	"""
    ripemd160 = hashlib.new('ripemd160', unhexlify(publicKey)).digest()[:20]
    seed = unhexlify(cfg.marker) + ripemd160
    return base58.b58encode_check(seed)
Beispiel #16
0
 def derive_child_pubkey(self, child_prv, parent_pub, depth, index):
     ''' Generate a child public key '''
     # extract child private key and chain code
     child_prv, child_chain = self.extract_prv(child_prv)
     # generate and compress child public key
     child_pub = self.compress_pubkey(self.point(child_prv))
     # generate the parent fingerprint from the public key
     fingerprint = self.generate_fingerprint(self.extract_pub(parent_pub))
     # serialize the child xpub key
     child_ypub = self.pub_version + depth + fingerprint + index + child_chain + child_pub
     # return the child xpub key encoded in bas58_check
     return b58encode_check(child_ypub).decode()
Beispiel #17
0
    def from_public_key(public_key):
        """
        Create address from public key

        :param public_key: public key used to create address (string)
        :return: BPL address (string)
        """

        buffer = Buffer()
        buffer.write_byte(Network.get_version())
        buffer.write_bytes(ripemd160(unhexlify(public_key)))
        return base58.b58encode_check(buffer.to_bytes()).decode()
Beispiel #18
0
def fill_in_missing_genesis_block():
    print("\nEnsure that we have genesis_block")
    genesis_config = NETWORK_CONFIG["genesis"]
    genesis_block_placeholder = "YOUR_GENESIS_BLOCK_HASH_HERE"

    if (genesis_config.get(
            "block", genesis_block_placeholder) == genesis_block_placeholder):
        print("Deterministically generating missing genesis_block")
        seed = "foo"
        gbk = blake2b(seed.encode(), digest_size=32).digest()
        gbk_b58 = b58encode_check(b"\x01\x34" + gbk).decode("utf-8")
        genesis_config["block"] = gbk_b58
Beispiel #19
0
def getAddress(publicKey):
    """
	Computes ARK address from keyring.

	Argument:
	publicKey (str) -- public key string

	Return str
	"""
    ripemd160 = hashlib.new('ripemd160', unhexlify(publicKey)).digest()[:20]
    seed = unhexlify(cfg.marker) + ripemd160
    b58 = base58.b58encode_check(seed)
    return b58.decode('utf-8') if isinstance(b58, bytes) else b58
Beispiel #20
0
def b58xprv(parent_fingerprint, private_key, chain, depth, childnr):
    """ Private key b58 serialization format. """

    raw = (
            b'\x04\x88\xad\xe4' +
            bytes(chr(depth), 'utf-8') +
            parent_fingerprint +
            childnr.to_bytes(4, byteorder='big') +
            chain +
            b'\x00' +
            private_key)

    return b58encode_check(raw)
Beispiel #21
0
def getWIF(seed):
    """
    Compute WIF address from seed.

    Args:
        seed (bytes): a sha256 sequence bytes
    Returns:
        WIF address
    """
    if hasattr(cfg, "wif"):
        seed = unhexlify(cfg.wif) + seed[:32] + b"\x01"  # \x01 -> compressed
        b58 = base58.b58encode_check(seed)
        return str(b58.decode('utf-8') if isinstance(b58, bytes) else b58)
Beispiel #22
0
 def to_wif(self, mainnet=None):
     network = mainnet
     if mainnet is True:
         network = 'mainnet'
     if mainnet is False:
         network = 'testnet'
     if mainnet is None:
         network = net_name()
     prefix = bytearray([NETWORKS[net_name()].wif_prefixes[network]])
     decoded = prefix + self.key
     if self.public_compressed:
         decoded.append(0x01)
     return b58encode_check(bytes(decoded))
Beispiel #23
0
def _encode(bytestring: bytes, prefix: List[int], expected_length: int) -> str:
    """
    Returns the base58 encoding of the bytestring, with the given data prefix
    (which indicates type) and while ensuring the bytestring is the expected
    length.
    """
    if expected_length and len(bytestring) != expected_length:
        error_message = """unexpected_payload_length: len(bytestring) does not match expected_length.
        Ensure that the bytes are a bytestring."""
        raise XRPLAddressCodecException(error_message)
    encoded_prefix = bytes(prefix)
    payload = encoded_prefix + bytestring
    return base58.b58encode_check(payload, alphabet=XRPL_ALPHABET).decode("utf-8")
Beispiel #24
0
def getAddress(keys):
    """
Computes ARK address from keyring.

Argument:
keys (ArkyDict) -- keyring returned by `getKeys`

Returns str
"""
    network = keys.network
    ripemd160 = hashlib.new('ripemd160', keys.public).digest()[:20]
    seed = network.pubKeyHash + ripemd160
    return base58.b58encode_check(seed)
Beispiel #25
0
 def to_wif(self):
     if self.compressed:
         prefix = bytes([self.wif_prefix])
         compression_flag = bytes([1])
         extended_key = prefix + unhexlify(self.to_hex()) + compression_flag
         leading_zeroes = 0
         for x in extended_key:
             if x != 0:
                 break
             leading_zeroes += 1
         wif_key = '1' * leading_zeroes + base58.b58encode_check(
             extended_key).decode('utf8')
         return wif_key
Beispiel #26
0
def getWIF(seed):
    """
	Computes WIF address from seed.

	Argument:
	seed (bytes) -- a sha256 sequence bytes

	Return str
	"""
    seed = unhexlify(
        cfg.wif) + seed[:32] + (b"\x01" if cfg.compressed else b"")
    b58 = base58.b58encode_check(seed)
    return b58.decode('utf-8') if isinstance(b58, bytes) else b58
Beispiel #27
0
 def to_address(self):
     """Create a public address from this Wallet.
     Public addresses can accept payments.
     https://en.bitcoin.it/wiki/Technical_background_of_Bitcoin_addresses
     """
     key = unhexlify(self.get_public_key_hex())
     # First get the hash160 of the key
     hash160_bytes = hash160(key)
     # Prepend the network address byte
     network_hash160_bytes = \
         chr_py2(self.network.PUBKEY_ADDRESS) + hash160_bytes
     # Return a base58 encoded address with a checksum
     return ensure_str(base58.b58encode_check(network_hash160_bytes))
Beispiel #28
0
    def ExportNEP2(self, passphrase):
        """
        Export the encrypted private key in NEP-2 format.

        Args:
            passphrase (str): The password to encrypt the private key with, as unicode string

        Returns:
            str: The NEP-2 encrypted private key

        Raises:
            ValueError: if the input `passphrase` length is < 2
        """
        if len(passphrase) < 2:
            raise ValueError("Passphrase must have a minimum of 2 characters")

        # Hash address twice, then only use the first 4 bytes
        address_hash_tmp = hashlib.sha256(
            self.GetAddress().encode("utf-8")).digest()
        address_hash_tmp2 = hashlib.sha256(address_hash_tmp).digest()
        address_hash = address_hash_tmp2[:4]

        # Normalize password and run scrypt over it with the address_hash
        pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase),
                               'utf-8')
        derived = scrypt.hash(pwd_normalized,
                              address_hash,
                              N=SCRYPT_ITERATIONS,
                              r=SCRYPT_BLOCKSIZE,
                              p=SCRYPT_PARALLEL_FACTOR,
                              buflen=SCRYPT_KEY_LEN_BYTES)

        # Split the scrypt-result into two parts
        derived1 = derived[:32]
        derived2 = derived[32:]

        # Run XOR and encrypt the derived parts with AES
        xor_ed = xor_bytes(bytes(self.PrivateKey), derived1)
        cipher = AES.new(derived2, AES.MODE_ECB)
        encrypted = cipher.encrypt(xor_ed)

        # Assemble the final result
        assembled = bytearray()
        assembled.extend(NEP_HEADER)
        assembled.extend(NEP_FLAG)
        assembled.extend(address_hash)
        assembled.extend(encrypted)

        # Finally, encode with Base58Check
        encrypted_key_nep2 = base58.b58encode_check(bytes(assembled))
        return encrypted_key_nep2.decode("utf-8")
Beispiel #29
0
def pubkey_to_address(pubkey) -> str:
    if 'ripemd160' not in hashlib.algorithms_available:
        raise RuntimeError('missing ripemd160 hash algorithm')

    def hash_pubkey(data):
        sha = hashlib.sha256(data).digest()
        ripe = hashlib.new('ripemd160', sha).digest()
        return ripe

    if isinstance(pubkey, bytes):
        address = b58encode_check(b'\x00' + hash_pubkey(pubkey))
    elif isinstance(pubkey, list):
        # make redeem script and return P2SH address
        redeem = scriptBuild.get_redeem_script(pubkey)
        address = b58encode_check(b'\x05' + hash_pubkey(redeem))
    else:
        return ''

    # print(str(b58encode_check(b'\x00' + ripe)).encode('utf-8'))
    # print(type(b58encode_check(b'\x00' + ripe)))
    address = address if isinstance(address, str) else str(address,
                                                           encoding="utf-8")
    return address
def bip32_master_prvkey_from_seed(bip32_seed, version):
    """derive the master extended private key from the seed"""
    if type(bip32_seed) == str:
        bip32_seed = bytes.fromhex(bip32_seed)
    assert version in PRIVATE, "wrong version, master key must be private"
    xmprv = version                             # version
    xmprv += b'\x00'                            # depth
    xmprv += b'\x00\x00\x00\x00'                # parent pubkey fingerprint
    xmprv += b'\x00\x00\x00\x00'                # child index
    hashValue = HMAC(b"Bitcoin seed", bip32_seed, sha512).digest()
    xmprv += hashValue[32:]                     # chain code
    mprv = int.from_bytes(hashValue[:32], 'big') % ec.order
    xmprv += b'\x00' + mprv.to_bytes(32, 'big') # private key
    return b58encode_check(xmprv)
def get_address_from_pk(pubkey) -> str:
    if 'ripemd160' not in hashlib.algorithms_available:
        raise RuntimeError('missing ripemd160 hash algorithm')

    def hash_pubkey(data):
        sha = hashlib.sha256(data).digest()
        ripe = hashlib.new('ripemd160', sha).digest()
        return ripe

    if isinstance(pubkey, bytes):
        address = b58encode_check(b'\x00' + hash_pubkey(pubkey))
    elif isinstance(pubkey, list):
        # make redeem script and return P2SH address
        redeem = get_redeem_script(pubkey)
        address = b58encode_check(b'\x05' + hash_pubkey(redeem))
    else:
        raise Exception(f"[wallet] get the wrong pubkey in generating address")

    # print(str(b58encode_check(b'\x00' + ripe)).encode('utf-8'))
    # print(type(b58encode_check(b'\x00' + ripe)))
    address = address if isinstance(address, str) else str(address,
                                                           encoding="utf-8")
    return address
Beispiel #32
0
def base58_encode(v: bytes, prefix: bytes) -> bytes:
    """ Encode data using Base58 with checksum and add an according binary prefix in the end.

    :param v: Array of bytes
    :param prefix: Human-readable prefix (use b'') e.g. b'tz', b'KT', etc
    :returns: bytes (use string.decode())
    """
    try:
        encoding = next(encoding for encoding in base58_encodings
                        if len(v) == encoding[3] and prefix == encoding[0])
    except StopIteration as e:
        raise ValueError('Invalid encoding, prefix or length mismatch.') from e

    return base58.b58encode_check(encoding[2] + v)
Beispiel #33
0
    def address(self, b58=True):
        # public address calculation: ripemd160(sha256(vk))
        sha256 = hashlib.new('sha256')
        ripemd160 = hashlib.new('ripemd160')

        sha256.update(self.pubkey())
        ripemd160.update(sha256.digest())

        addr = ripemd160.digest()

        if b58:
            addr = base58.b58encode_check(b'\x00' + addr)

        return addr
Beispiel #34
0
def getWIF(seed, network):
    """
Computes WIF address from seed.

Argument:
seed (bytes)     -- a sha256 sequence bytes
network (object) -- a python object

Returns str
"""
    # network = network
    compressed = network.get("compressed", True)
    seed = network.wif + seed[:32] + (b"\x01" if compressed else b"")
    return base58.b58encode_check(seed)
Beispiel #35
0
    def _multisig_scriptconfig(
        self,
        threshold: int,
        origin_infos: Mapping[bytes, KeyOriginInfo],
        script_type: bitbox02.btc.BTCScriptConfig.Multisig.ScriptType,
    ) -> Tuple[bytes, bitbox02.btc.BTCScriptConfigWithKeypath]:
        """
        From a threshold, {xpub: KeyOriginInfo} mapping and multisig script type,
        return our xpub and the BitBox02 multisig script config.
        """
        # Figure out which of the cosigners is us.
        device_fingerprint = self.get_master_fingerprint()
        our_xpub_index = None
        our_account_keypath = None

        xpubs: List[bytes] = []
        for i, (xpub, keyinfo) in builtins.enumerate(origin_infos.items()):
            xpubs.append(xpub)
            if device_fingerprint == keyinfo.fingerprint and keyinfo.path:
                if _xpubs_equal_ignoring_version(
                        base58.b58decode_check(self._get_xpub(keyinfo.path)),
                        xpub):
                    our_xpub_index = i
                    our_account_keypath = keyinfo.path

        if our_xpub_index is None:
            raise BadArgumentError("This BitBox02 is not one of the cosigners")
        assert our_account_keypath

        if len(xpubs) != len(set(xpubs)):
            raise BadArgumentError("Duplicate xpubs not supported")

        return (
            xpubs[our_xpub_index],
            bitbox02.btc.BTCScriptConfigWithKeypath(
                script_config=bitbox02.btc.BTCScriptConfig(
                    multisig=bitbox02.btc.BTCScriptConfig.Multisig(
                        threshold=threshold,
                        xpubs=[
                            util.parse_xpub(
                                base58.b58encode_check(xpub).decode())
                            for xpub in xpubs
                        ],
                        our_xpub_index=our_xpub_index,
                        script_type=script_type,
                    )),
                keypath=our_account_keypath,
            ),
        )
Beispiel #36
0
    def to_wif(self):
        """
        Exports the private key as WIF (Wallet Import Format)

        :return: string corresponding to the private Key as WIF
        """
        # WIF = base58check encode ([version byte][private key][checksum])
        if self.__privkey_buf is None:
            raise RuntimeError("No private key")
        buffer = b''
        buffer += self.network.wif
        buffer += self.privkey_buffer
        if self.__compressed:
            buffer += b'\x01'
        return base58.b58encode_check(buffer).decode()
Beispiel #37
0
    def test_base58_check_encode(self):
        import base58
        path = self.get_contract_path('Base58CheckEncode.py')
        engine = TestEngine()
        expected_result = base58.b58encode_check('unit test'.encode('utf-8'))
        result = self.run_smart_contract(engine,
                                         path,
                                         'main',
                                         'unit test',
                                         expected_result_type=bytes)
        self.assertEqual(expected_result, result)

        expected_result = base58.b58encode_check(''.encode('utf-8'))
        result = self.run_smart_contract(engine,
                                         path,
                                         'main',
                                         '',
                                         expected_result_type=bytes)
        self.assertEqual(expected_result, result)

        long_string = (
            'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam accumsan magna eu massa '
            'vulputate bibendum. Aliquam commodo euismod tristique. Sed purus erat, pretium ut interdum '
            'et, aliquet sed mauris. Curabitur vitae turpis euismod, hendrerit mi a, rhoncus justo. Mauris '
            'sollicitudin, nisl sit amet feugiat pharetra, odio ligula congue tellus, vel pellentesque '
            'libero leo id dui. Morbi vel risus vehicula, consectetur mauris eget, gravida ligula. '
            'Maecenas aliquam velit sit amet nisi ultricies, ac sollicitudin nisi mollis. Lorem ipsum '
            'dolor sit amet, consectetur adipiscing elit. Ut tincidunt, nisi in ullamcorper ornare, '
            'est enim dictum massa, id aliquet justo magna in purus.')
        expected_result = base58.b58encode_check(long_string.encode('utf-8'))
        result = self.run_smart_contract(engine,
                                         path,
                                         'main',
                                         long_string,
                                         expected_result_type=bytes)
        self.assertEqual(expected_result, result)
Beispiel #38
0
 def calculate_name_hash(cls, name):
     if isinstance(name, str):
         name = name.encode('ascii')
     # see:
     # https://github.com/aeternity/protocol/blob/master/AENS.md#hashing
     # and also:
     # https://github.com/ethereum/EIPs/blob/master/EIPS/eip-137.md#namehash-algorithm
     labels = name.split(b'.')
     hash_func = lambda data: blake2b(data, digest_size=32).digest()
     hashed = b'\x00' * 32
     while labels:
         hashed = hash_func(hashed + hash_func(labels[0]))
         labels = labels[1:]
     b58hash = base58.b58encode_check(hashed)
     return f'nm${b58hash}'
Beispiel #39
0
def prv_hex_to_wif():
    parser = ArgumentParser(description="from private key in hex to with format")
    parser.add_argument("hex_str", help="private key, in hex", type=str)
    parser.add_argument("-p", "--prv_version", help="version prefix for private key in hex, in [0x00, 0xff]",
                        type=str, default=version_prefix_prv["mainnet"].hex())
    parser.add_argument("-u", "--uncompressed", help="obtain an uncompressed key, default is compressed",
                        action="store_true")
    args = parser.parse_args()
    if not is_hex(args.hex_str):
        raise TypeError("expected hex string")
    prv = str_to_1bytes(args.prv_version) + int(args.hex_str, 16).to_bytes(32, "big") + \
        (b'' if args.uncompressed else b'\x01')
    #  fixme: use class PrivateKey instead

    print(b58encode_check(prv))
Beispiel #40
0
 def setUp(self):
     self.server_url = 'https://test.url/'
     self.address = base58.b58encode_check(b'\x00'+os.urandom(20))
     self.client = DownstreamClient(self.address)
     self.test_contract = Contract(MockValues.get_chunk_response['file_hash'],
                                   MockValues.get_chunk_response['seed'],
                                   MockValues.get_chunk_response['size'],
                                   Heartbeat.challenge_type().fromdict(
                                     MockValues.get_chunk_response['challenge']),
                                   datetime.strptime(
                                     MockValues.get_chunk_response['expiration'],
                                     '%Y-%m-%dT%H:%M:%S'),
                                   Heartbeat.tag_type().fromdict(
                                     MockValues.get_chunk_response['tag']))
     self.test_heartbeat = Heartbeat.fromdict(MockValues.connect_response['heartbeat'])
Beispiel #41
0
    def to_address(self):
        """Create a public address from this Wallet.

        Public addresses can accept payments.

        https://en.bitcoin.it/wiki/Technical_background_of_Bitcoin_addresses
        """
        key = unhexlify(self.get_public_key_hex())
        # First get the hash160 of the key
        hash160_bytes = hash160(key)
        # Prepend the network address byte
        network_hash160_bytes = \
            chr_py2(self.network.PUBKEY_ADDRESS) + hash160_bytes
        # Return a base58 encoded address with a checksum
        return ensure_str(base58.b58encode_check(network_hash160_bytes))
Beispiel #42
0
    def address(self, testnet=False):
        """ Returns the Base58Check encoded version of the HASH160.

        Args:
            testnet (bool): Whether or not the key is intended for testnet
               usage. False indicates mainnet usage.

        Returns:
            bytes: Base58Check encoded string
        """
        rv = ""
        prefix = bytes([self.P2SH_TESTNET_VERSION if testnet else self.P2SH_MAINNET_VERSION])
        rv = base58.b58encode_check(prefix + self.hash160())

        return rv
 def setUp(self):
     self.server_url = 'https://test.url/'
     self.api_path = '/api/downstream/v1'
     self.size = 100
     self.address = base58.b58encode_check(b'\x00' + os.urandom(20))
     self.token = binascii.hexlify(os.urandom(16)).decode('ascii')
     self.msg = ''
     self.sig = ''
     self.thread_manager = ShellApplication()
     self.contract_thread = ManagedThread()
     self.chunk_dir = os.path.join('data', 'chunks')
     self.client = DownstreamClient(self.server_url,
                                    self.token,
                                    self.address,
                                    self.size,
                                    self.msg,
                                    self.sig,
                                    self.thread_manager,
                                    self.chunk_dir)
     self.client.session = mock.MagicMock()
     self.test_contract = \
         DownstreamContract(self.client,
                            MockValues.get_chunks_response[
                                'chunks'][0]['file_hash'],
                            MockValues.get_chunks_response[
                                'chunks'][0]['seed'],
                            MockValues.get_chunks_response[
                                'chunks'][0]['size'],
                            Heartbeat.challenge_type().fromdict(
                                MockValues
                                .get_chunks_response
                                ['chunks'][0]['challenge']),
                            datetime.utcnow() + timedelta(
                                seconds=int(
                                    MockValues
                                    .get_chunks_response
                                    ['chunks'][0]['due'])),
                            Heartbeat.tag_type().fromdict(
                                MockValues
                                .get_chunks_response
                                ['chunks'][0]['tag']),
                            self.thread_manager,
                            self.chunk_dir)
     self.test_heartbeat = Heartbeat.fromdict(
         MockValues.connect_response['heartbeat'])
def simple_wallet():
    # root_key basically just needs to be a random 16/32/64 byte string.
    # It is used to derive all the addresses in the wallet.
    # This function is guaranteed to return a valid root key.
    root_key = bip38v2.generate_root_key(length=32)
    # Both real_passphrase and fake_passphrase will successfully decrypt the wallet.
    # However, each passphrase results in a different set of Bitcoin addresses.
    # The idea is that, if you are forced to decrypt your wallet by someone robbing you,
    # you just use the "fake" password. You can put a small amount of BTC in the "fake"
    # wallet, so that the person robbing you thinks it's your real wallet.
    # If the passphrase is set to None, the wallet will be unencrypted.
    real_passphrase = "ItsMyMoneyAndIWantItNow"
    fake_passphrase = "GoodLuckTakingMyMoney"
    # The "date" field tells wallet software when the wallet was created (by week)
    # so that the wallet knows when to start looking. If you don't want to reveal
    # the creation date, you can set this to zero (but it may hurt wallet performance)
    weeks = (date.today() - date(2013, 1, 1)).days/7
    # The KDF is the "Key Derivation Formula". This forumla is used to make the
    # wallet encryption/decryption take a lot longer, so it takes longer for a hacker
    # to guess the wallet password. The spec supports a number of KDFs. These are:
    # 0) Scrypt, weak. 1) Scrypt, medium. 2) Scrypt, strong. 8) PBKDF2-HMAC-SHA512, weak.  
    # 9) PBKDF2-HMAC-SHA512, strong. See crypto.py for details.
    # Scrypt is thought to be more resistant to attack by well-funded adversaries,
    # but is not as thoroughly vetted as PBKDF2-HMAC-SHA512, and also requires a lot of
    # RAM, so it's harder to run on mobile devices.
    kdf_type = 8 # Let's use PBKDF-HMAC-SHA512 with 2^16 iterations.
    # salt_entropy is called "entropy" in the spec. It's some extra random data
    # included with the wallet to make it harder for hackers to crack wallets en masse.
    # If we set entropy to None, or don't provide it as an argument, it will be randomly
    # generated. We need to provide at least 4 bytes if we choose to provide it.
    salt_entropy = os.urandom(4)

    # Now let's actually make the wallet
    wallet = bip38v2.make_wallet(root_key, weeks, passphrase=real_passphrase, fake_passphrase=fake_passphrase, kdf_type=kdf_type, salt_entropy=salt_entropy)
    # These are also valid ways to make wallets:
    if False:
        wallet2 = bip38v2.make_wallet(root_key, weeks) # unencrypted
        wallet3 = bip38v2.make_wallet(root_key, 0, passphrase = "bob") # No date, random fake password, default KDF (weaker scrypt)
        wallet4 = bip38v2.make_wallet(root_key, weeks, passphrase="hello", kdf_type=8) # Random fake password, weaker PBKDF2 as KDF

    # Now we'll encode the wallet in the format we're used to
    base58_wallet = base58.b58encode_check(wallet)

    # And display it to the user
    print base58_wallet
Beispiel #45
0
    def to_address(self, compressed=None):
        """Create a public address from this key.

        :param compressed: False if you want a normal uncompressed address
            (the most standard option). True if you want the compressed form.
            Note that most clients will not accept compressed addresses.
            Defaults to None, which in turn uses the self.compressed attribute.
        :type compressed: bool

        https://en.bitcoin.it/wiki/Technical_background_of_Bitcoin_addresses
        """
        key = unhexlify(ensure_bytes(self.get_key(compressed)))
        # First get the hash160 of the key
        hash160_bytes = hash160(key)
        # Prepend the network address byte
        network_hash160_bytes = \
            chr_py2(self.network.PUBKEY_ADDRESS) + hash160_bytes
        # Return a base58 encoded address with a checksum
        return ensure_str(base58.b58encode_check(network_hash160_bytes))
Beispiel #46
0
 def setUp(self):
     self.server_url = 'https://test.url/'
     self.api_path = '/api/downstream/v1'
     self.size = 100
     self.address = base58.b58encode_check(b'\x00' + os.urandom(20))
     self.token = binascii.hexlify(os.urandom(16)).decode('ascii')
     self.msg = ''
     self.sig = ''
     self.api = API()
     self.client = DownstreamClient(self.server_url,
                                    self.token,
                                    self.address,
                                    self.size,
                                    self.msg,
                                    self.sig,
                                    self.api)
     self.test_contract = DownstreamContract(self.client,
                                             MockValues.get_chunk_response[
                                                 'file_hash'],
                                             MockValues.get_chunk_response[
                                                 'seed'],
                                             MockValues.get_chunk_response[
                                                 'size'],
                                             Heartbeat.challenge_type()
                                             .fromdict(
                                                 MockValues.
                                                 get_chunk_response['challe'
                                                                    'nge']),
                                             datetime.utcnow() +
                                             timedelta(
                                                 seconds=int(
                                                     MockValues.
                                                     get_chunk_response['du'
                                                                        'e']
                                                 )),
                                             Heartbeat.tag_type().fromdict(
                                                 MockValues
                                                 .get_chunk_response['ta'
                                                                     'g'],
                                             ),
                                             self.api)
     self.test_heartbeat = Heartbeat.fromdict(
         MockValues.connect_response['heartbeat'])
Beispiel #47
0
    def export_to_wif(self, compressed=None):
        """Export a key to WIF.

        :param compressed: False if you want a standard WIF export (the most
            standard option). True if you want the compressed form (Note that
            not all clients will accept this form). Defaults to None, which
            in turn uses the self.compressed attribute.
        :type compressed: bool
        See https://en.bitcoin.it/wiki/Wallet_import_format for a full
        description.
        """
        # Add the network byte, creating the "extended key"
        extended_key_hex = self.get_extended_key()
        extended_key_bytes = unhexlify(ensure_bytes(extended_key_hex))
        if compressed is None:
            compressed = self.compressed
        if compressed:
            extended_key_bytes += b'\01'
        # And return the base58-encoded result with a checksum
        return ensure_str(base58.b58encode_check(extended_key_bytes))
Beispiel #48
0
def key_hash_to_address(hash160, version=0x0):
    """Convert RIPEMD-160 hash to bitcoin address.

    Args:
        hash160 (bytes/str): bitcoin hash160 to decode
        version (int): The version prefix

    Returns:
        (bitcoin address): base58 encoded bitcoin address
    """
    if isinstance(hash160, str):
        # if 0x in string, strip it
        if "0x" in hash160:
            h160 = hex_str_to_bytes(hash160[2:])
        else:
            h160 = hex_str_to_bytes(hash160)
    elif isinstance(hash160, bytes):
        h160 = hash160

    address = base58.b58encode_check(bytes([version]) + h160)
    return address
Beispiel #49
0
def address(input_data_bytes):

    #Do it twice for valid address hacks.
    hasher = hashlib.sha256()
    hasher.update(input_data_bytes)
    hash = hasher.digest()

    hasher = hashlib.sha256()
    hasher.update(hash)
    hash = hasher.digest()

    hasher = hashlib.new("ripemd160")
    hasher.update(hash)
    hash = hasher.digest()

    hash = binascii.unhexlify("00") + hash

    encoded_final = base58.b58encode_check(hash)


    return encoded_final
Beispiel #50
0
def change_version_byte(address, new_version=None, new_crypto=None):
    """
    Convert the passed in address (or any base58 encoded string), and change the
    version byte to `new_version`.
    """
    if not new_version and new_crypto:
        try:
            new_version = crypto_data[new_crypto]['address_version_byte']
        except KeyError:
            raise CurrencyNotSupported("Unknown currency symbol: " + new_crypto)

        if not new_version:
            raise CurrencyNotSupported("Can't yet make %s addresses." % new_crypto)

    payload = b58decode_check(address)[1:]
    if is_py2:
        byte = chr(new_version)
    else:
        byte = bytes(chr(new_version), 'ascii')

    return b58encode_check(byte + payload)
Beispiel #51
0
 def to_wif(self):
     if self.address is None:
         return "address is not set"
     else:
         return b58encode_check(self.version + self.address)
Beispiel #52
0
def b58xprv(parent_fingerprint, private_key, chain, depth, childnr):
    raw = ('\x04\x88\xad\xe4' +
              chr(depth) + parent_fingerprint + int_to_string(childnr, 4) +
              chain + '\x00' + private_key)
    return b58encode_check(raw)
Beispiel #53
0
def b58xpub(parent_fingerprint, public_key, chain, depth, childnr):
    raw = ('\x04\x88\xb2\x1e' +
              chr(depth) + parent_fingerprint + int_to_string(childnr, 4) +
              chain + public_key)
    return b58encode_check(raw)
Beispiel #54
0
def privatekey_to_wif(key):
#    return utils.base58CheckEncode(0x80, key_hex.decode('hex'))
    x = '80' + key
    return base58.b58encode_check(x.decode('hex'))
def base58_format_shares(shares):
	shares = ["\xfb\xb3" + share for share in shares]
	return [base58.b58encode_check(share) for share in shares]
Beispiel #56
0
def new_object_id():
    """ Generates a new object ID in base58_check format.
    :return:
    """
    oid = uuid.uuid1().get_bytes()
    return base58.b58encode_check(oid)
Beispiel #57
0
 def serialize_b58(self, private=True):
     """Encode the serialized node in base58."""
     return ensure_str(
         base58.b58encode_check(unhexlify(self.serialize(private))))
Beispiel #58
0
def test_check_identity():
    data = b'hello world'
    out = b58decode_check(b58encode_check(data))
    assert_that(out, equal_to(data))
Beispiel #59
0
 def to_wif(self):
     if self.prv is None:
         return "private key is not set"
     else:
         return b58encode_check(self.version + self.prv.to_bytes(32, "big") + (b'\x01' if self.compressed else b''))
Beispiel #60
0
def make_barcode_text(num, typesym, block):
    num = base64.b32encode(bytes(ctypes.c_uint16(num)))
    newblock = num.decode('ascii').replace('=','')
    newblock += typesym
    newblock += base58.b58encode_check(block)
    return newblock