Example #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
Example #2
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)
Example #3
0
 def _setup_node(self, node_key):
     self._btctxstore = btctxstore.BtcTxStore()
     node_key = node_key or self._btctxstore.create_key()
     is_hwif = self._btctxstore.validate_wallet(node_key)
     self._key = self._btctxstore.get_key(node_key) if is_hwif else node_key
     address = self._btctxstore.get_address(self._key)
     self._nodeid = a2b_hashed_base58(address)[1:]
Example #4
0
File: Key.py Project: wpr101/pycoin
    def from_text(class_, text, is_compressed=True):
        """
        This function will accept a BIP0032 wallet string, a WIF, or a bitcoin address.

        The "is_compressed" parameter is ignored unless a public address is passed in.
        """

        data = a2b_hashed_base58(text)
        netcode, key_type, length = netcode_and_type_for_data(data)
        data = data[1:]

        if key_type in ("pub32", "prv32"):
            # TODO: fix this... it doesn't belong here
            from pycoin.key.BIP32Node import BIP32Node
            return BIP32Node.from_wallet_key(text)

        if key_type == 'wif':
            is_compressed = (len(data) > 32)
            if is_compressed:
                data = data[:-1]
            return Key(
                secret_exponent=from_bytes_32(data),
                prefer_uncompressed=not is_compressed, netcode=netcode)
        if key_type == 'address':
            return Key(hash160=data, is_compressed=is_compressed, netcode=netcode)
        raise EncodingError("unknown text: %s" % text)
Example #5
0
File: Key.py Project: Zibbo/pycoin
    def from_text(class_, text, is_compressed=True):
        """
        This function will accept a BIP0032 wallet string, a WIF, or a bitcoin address.

        The "is_compressed" parameter is ignored unless a public address is passed in.
        """

        data = a2b_hashed_base58(text)
        netcode, key_type = netcode_and_type_for_data(data)
        data = data[1:]

        if key_type in ("pub32", "prv32"):
            # TODO: fix this... it doesn't belong here
            from pycoin.key.BIP32Node import BIP32Node
            return BIP32Node.from_wallet_key(text)

        if key_type == 'wif':
            is_compressed = (len(data) > 32)
            if is_compressed:
                data = data[:-1]
            return Key(
                secret_exponent=from_bytes_32(data),
                prefer_uncompressed=not is_compressed, netcode=netcode)
        if key_type == 'address':
            return Key(hash160=data, is_compressed=is_compressed, netcode=netcode)
        raise EncodingError("unknown text: %s" % text)
Example #6
0
    def addr_to_script(addr):
        if addr[:2] == 't3':
            scr = 'a914' + a2b_hashed_base58(addr)[2:].encode('hex') + '87'
            return scr.decode('hex')

        assert addr[:2] == 't1'
        k = Key.from_text(addr)
        enc = '76a914' + k.hash160()[1:].encode('hex') + '88ac'
        return enc.decode('hex')
Example #7
0
def test_public(sim_execfile):
    "verify contents of public 'dump' file"
    from pycoin.key.BIP32Node import BIP32Node
    from pycoin.contrib.segwit_addr import encode as sw_encode
    from pycoin.contrib.segwit_addr import decode as sw_decode
    from pycoin.encoding import a2b_hashed_base58, hash160

    pub = sim_execfile('devtest/dump_public.py')
    assert 'Error' not in pub

    #print(pub)

    pub, dev = pub.split('#DEBUG#', 1)
    assert 'pub' in pub
    assert 'prv' not in pub
    assert 'prv' in dev

    lines = [i.strip() for i in pub.split('\n')]

    for ln in lines:
        if ln[1:4] == 'pub':
            node_pub = BIP32Node.from_wallet_key(ln)
            break

    node_prv = BIP32Node.from_wallet_key(dev.strip())

    # pub and private are linked
    assert node_prv.hwif(as_private=False) == node_pub.hwif()

    # check every path we derived
    count = 0
    for ln in lines:
        if ln[0:1] == 'm' and '=>' in ln:
            subpath, result = ln.split(' => ', 1)

            sk = node_prv.subkey_for_path(subpath[2:])

            if result[0:2] in {'tp', 'xp'}:
                expect = BIP32Node.from_wallet_key(result)
                assert sk.hwif(as_private=False) == result
            elif result[0] in '1mn':
                assert result == sk.address(False)
            elif result[0:3] in {'bc1', 'tb1'}:
                h20 = sk.hash160()
                assert result == sw_encode(result[0:2], 0, h20)
            elif result[0] in '23':
                h20 = hash160(b'\x00\x14' + sk.hash160())
                assert h20 == a2b_hashed_base58(result)[1:]
            else:
                raise ValueError(result)

            count += 1
            print("OK: %s" % ln)

    assert count > 12
 def doit(addr, sk):
     if addr[0] in '1mn':
         assert addr == sk.address(False)
     elif addr[0:3] in {'bc1', 'tb1'}:
         h20 = sk.hash160()
         assert addr == sw_encode(addr[0:2], 0, h20)
     elif addr[0] in '23':
         h20 = hash160(b'\x00\x14' + sk.hash160())
         assert h20 == a2b_hashed_base58(addr)[1:]
     else:
         raise ValueError(addr)
Example #9
0
    def __init__(self, **kwargs):
        """Create a LooseAddressRecord for a given wallet <model>,
        color <color_set> and address <address_data>. Also let the constructor
        know whether it's on <testnet> (optional).
        <address_data> is the privKey in base58 format
        """
        super(LooseAddressRecord, self).__init__(**kwargs)

        bin_privkey = a2b_hashed_base58(kwargs['address_data'])
        key_type = bin_privkey[0]
        if key_type != self.prefix:
            raise InvalidAddressError
                
        self.rawPrivKey = from_bytes_32(bin_privkey[1:])
        self.publicPoint = BasePoint * self.rawPrivKey
        self.address = public_pair_to_bitcoin_address(
            self.publicPoint.pair(), compressed=False, is_test=self.testnet)
Example #10
0
    def __init__(self, **kwargs):
        """Create a LooseAddressRecord for a given wallet <model>,
        color <color_set> and address <address_data>. Also let the constructor
        know whether it's on <testnet> (optional).
        <address_data> is the privKey in base58 format
        """
        super(LooseAddressRecord, self).__init__(**kwargs)

        bin_privkey = a2b_hashed_base58(kwargs['address_data'])
        key_type = bin_privkey[0]
        if key_type != self.prefix:
            raise InvalidAddressError

        self.rawPrivKey = from_bytes_32(bin_privkey[1:])
        self.publicPoint = BasePoint * self.rawPrivKey
        self.address = public_pair_to_bitcoin_address(self.publicPoint.pair(),
                                                      compressed=False,
                                                      is_test=self.testnet)
Example #11
0
def slip132undo(orig):
    # take a SLIP-132 xpub/ypub/z/U/?pub/prv and convert into BIP-32 style
    # - preserve testnet vs. mainnet
    # - return addr fmt info
    from pycoin.encoding import a2b_hashed_base58, b2a_hashed_base58
    from ckcc_protocol.constants import AF_P2WPKH_P2SH, AF_P2SH, AF_P2WSH, AF_P2WSH_P2SH
    from ckcc_protocol.constants import AF_P2WPKH

    assert orig[0] not in 'xt', "already legit bip32"

    xpub = a2b_hex('0488B21E')
    tpub = a2b_hex('043587cf')
    xprv = a2b_hex('0488ADE4')
    tprv = a2b_hex('04358394')

    variants = [
        (False, AF_P2WPKH_P2SH, '049d7cb2', '049d7878', 'y'),
        (False, AF_P2WPKH, '04b24746', '04b2430c', 'z'),
        (False, AF_P2WSH_P2SH, '0295b43f', '0295b005', 'Y'),
        (False, AF_P2WSH, '02aa7ed3', '02aa7a99', 'Z'),
        (True, AF_P2WPKH_P2SH, '044a5262', '044a4e28', 'u'),
        (True, AF_P2WPKH, '045f1cf6', '045f18bc', 'v'),
        (True, AF_P2WSH_P2SH, '024289ef', '024285b5', 'U'),
        (True, AF_P2WSH, '02575483', '02575048', 'V'),
    ]

    raw = a2b_hashed_base58(orig)

    for testnet, addr_fmt, pub, priv, hint in variants:

        if raw[0:4] == a2b_hex(pub):
            return b2a_hashed_base58((tpub if testnet else xpub) + raw[4:]), \
                        testnet, addr_fmt, False

        if raw[0:4] == a2b_hex(priv):
            return b2a_hashed_base58((tprv if testnet else xprv) + raw[4:]), \
                        testnet, addr_fmt, True

    raise RuntimeError("unknown prefix")
Example #12
0
def address_to_node_id(address):
    """Convert a bitcoin address to a node id."""
    return a2b_hashed_base58(address)[1:]
Example #13
0
def validate(address, magic_bytes):
    try:
        return a2b_hashed_base58(address)[:1] in bytes(
            map(int, magic_bytes.split(',')))
    except EncodingError:
        return False
Example #14
0
 def test_raw_to_address(self):
     privkey = from_bytes_32(a2b_hashed_base58(self.address)[1:])
     pubkey = BasePoint * privkey
     raw = public_pair_to_hash160_sec(pubkey.pair(), False)
     addr = self.ccc.raw_to_address(raw)
     self.assertEqual(addr,'1CC3X2gu58d6wXUWMffpuzN9JAfTUWu4Kj')
Example #15
0
def address2nodeid(address):
    """Convert a bitcoin address to a node id."""
    return binascii.hexlify(a2b_hashed_base58(address)[1:]).decode("utf-8")
 def do_test(as_text, as_bin):
     self.assertEqual(as_text, encoding.b2a_hashed_base58(as_bin))
     self.assertEqual(as_bin, encoding.a2b_hashed_base58(as_text))
     self.assertTrue(encoding.is_hashed_base58_valid(as_text))
     bogus_text = as_text[:-1] + chr(1+ord(as_text[-1]))
     self.assertFalse(encoding.is_hashed_base58_valid(bogus_text))
if __name__ == '__main__':
    prev_hash = '3f7352324c97313dfb36c7d2234aef84708ab48739aee4a38b6ffc884dcdeb76'  #TX ID
    print('Prev hash: {}'.format(prev_hash))

    prev_hash_le = hexlify(unhexlify(prev_hash)[::-1])  #LE TX ID
    print('Prev hash LE: {}'.format(prev_hash_le.decode()))

    print()

    # ADDRESS TO PUB KEY IN HEX

    address_send_to = 'mfZ18J7nP5t4L1F79Mu9jhVzMfBxDKifLk'  #Send TO ADDRESS
    print('Send to address: {}'.format(address_send_to))

    pub_key_send_to_hex = hexlify(a2b_hashed_base58(address_send_to)[1:])
    print('Send to pub key hex: {}'.format(pub_key_send_to_hex))

    address_mine = 'mo3kHhHn6ixsXy8LGcdY2zW2QkE8FmhsFH'  #MY ADDRESS
    print('My address: {}'.format(address_mine))

    pub_key_mine_hex = hexlify(a2b_hashed_base58(address_mine)[1:])
    print('My pub key hex: {}'.format(pub_key_mine_hex))

    print()

    # BUILD TX

    ver = '01000000'
    print('Ver: {}'.format(ver))
Example #18
0
def btcaddress_to_hexnodeid(address):
    return binascii.hexlify(a2b_hashed_base58(address)[1:])
Example #19
0
 def do_test(as_text, as_bin):
     self.assertEqual(as_text, encoding.b2a_hashed_base58(as_bin))
     self.assertEqual(as_bin, encoding.a2b_hashed_base58(as_text))
     self.assertTrue(encoding.is_hashed_base58_valid(as_text))
     bogus_text = as_text[:-1] + chr(1 + ord(as_text[-1]))
     self.assertFalse(encoding.is_hashed_base58_valid(bogus_text))
Example #20
0
def address_to_node_id(address):
    # e.g. address = api.get_address(wif)
    return a2b_hashed_base58(address)[1:]
Example #21
0
import settings
from pymongo import MongoClient
from pycoin.encoding import a2b_hashed_base58
from binascii import hexlify

connection = MongoClient('localhost', 27017)
collection = connection[settings.DBS_NAME][settings.FARMERS_COLLECTION]

for farmer in collection.find().distinct('farmers.btc_addr'):
    nodeid = hexlify(a2b_hashed_base58(farmer)[1:]).decode("utf-8")
    print(nodeid)
    collection.update_many({'farmers.btc_addr': farmer}, 
                           {'$set': {'farmers.$.nodeid': nodeid}, 
                            '$unset': {'farmers.$.btc_addr': ''}}) 

connection.close()
Example #22
0
def address_to_nodeid(address):
    """Convert a bitcoin address to a node id."""
    return a2b_hashed_base58(address)[1:]
Example #23
0
 def get_id(self):
     address = self._btctxstore.get_address(self.key)
     return a2b_hashed_base58(address)[1:]  # remove network prefix
Example #24
0
def netcode_from_address(address):
    """ Returns netcode for given bitcoin address. """
    data = a2b_hashed_base58(address)
    netcode, key_type, length = netcode_and_type_for_data(data)
    return netcode
Example #25
0
def b58_to_pcode(b58):
    return encoding.a2b_hashed_base58( b58 )[1:]
Example #26
0
def validate_address(address_bytes):
    _assert(type(address_bytes) == bytes, 'Address: type must be bytes')
    _assert(len(address_bytes) == 25, 'Address: len != 25')
    v_hash160 = a2b_hashed_base58(b2a_base58(address_bytes))
    _assert(v_hash160 == address_bytes[0:21], 'Address: version + hash160 does not match')
Example #27
0
def address_to_node_id(address):
    # e.g. address = api.get_address(wif)
    return a2b_hashed_base58(address)[1:]
Example #28
0
def validate(address, magic_bytes):
	try:
		return a2b_hashed_base58(address)[:1] in bytes(map(int, magic_bytes.split(',')))
	except EncodingError:
		return False
Example #29
0
 def get_id(self):
     address = self._btctxstore.get_address(self.key)
     return a2b_hashed_base58(address)[1:]  # remove network prefix