def test_from_WIF_bad_suffix_byte(self, value): payload = pack_byte(Bitcoin.WIF_byte) + global_privkey.to_bytes() + pack_byte(value) WIF = base58_encode_check(payload) if value == 0x01: PrivateKey.from_WIF(WIF) else: with pytest.raises(ValueError): PrivateKey.from_WIF(WIF)
def to_string(self): '''Converts to a string of the given format.''' if self.kind == self.ADDR_P2PKH: verbyte = Net.ADDRTYPE_P2PKH else: verbyte = Net.ADDRTYPE_P2SH return base58_encode_check(bytes([verbyte]) + self.hash160)
def test_version_bytes(self): xprv_headers_b58 = 'tprv' xpub_headers_b58 = 'tpub' xkey_bytes = BitcoinTestnet.xprv_verbytes + bytes([0] * 74) xkey_b58 = base58_encode_check(xkey_bytes) self.assertTrue(xkey_b58.startswith(xprv_headers_b58)) xkey_bytes = BitcoinTestnet.xprv_verbytes + bytes([255] * 74) xkey_b58 = base58_encode_check(xkey_bytes) self.assertTrue(xkey_b58.startswith(xprv_headers_b58)) xkey_bytes = BitcoinTestnet.xpub_verbytes + bytes([0] * 74) xkey_b58 = base58_encode_check(xkey_bytes) self.assertTrue(xkey_b58.startswith(xpub_headers_b58)) xkey_bytes = BitcoinTestnet.xpub_verbytes + bytes([255] * 74) xkey_b58 = base58_encode_check(xkey_bytes) self.assertTrue(xkey_b58.startswith(xpub_headers_b58))
def test_bip32_key_from_string_bad(): # Tests the failure modes of from_extended_key. with pytest.raises(Base58Error): bip32_key_from_string('') with pytest.raises(ValueError): bip32_key_from_string('1Po1oWkD2LmodfkBYiAktwh76vkF93LKnh') with pytest.raises(TypeError): bip32_key_from_string(b'') with pytest.raises(Base58Error): bip32_key_from_string(bytes(78).decode()) # Invalid prefix byte raw = base58_decode_check(MXPRV) bad_string = base58_encode_check(raw[:45] + b'\1' + raw[46:]) with pytest.raises(ValueError): bip32_key_from_string(bad_string)
def from_bytes(cls, raw: bytes) -> 'XPublicKey': """ In addition to importing public keys, we also support the legacy Electrum serialisation, except for the case of addresses. """ kwargs: Dict[str, Any] = {} kind = raw[0] if kind in {0x02, 0x03, 0x04}: kwargs['pubkey_bytes'] = raw elif kind == 0xff: # 83 is 79 + 2 + 2. assert len(raw) == 83, f"got {len(raw)}" kwargs["bip32_xpub"] = base58_encode_check(raw[1:79]) kwargs["derivation_path"] = tuple(unpack_le_uint16(raw[n: n+2])[0] for n in (79, 81)) elif kind == 0xfe: assert len(raw) == 69 kwargs["old_mpk"] = raw[1:65] # The public key bytes without the 0x04 prefix kwargs["derivation_path"] = tuple(unpack_le_uint16(raw[n: n+2])[0] for n in (65, 67)) else: kwargs["extended_kind"] = hex(raw[0]) return cls(**kwargs)
def bip32_extended_key(self): assert len(self.raw) == 83 # 1 + 78 + 2 + 2 assert self.is_bip32_key() return base58_encode_check(self.raw[1:79])
def parse_xpubkey(self, pubkey): assert pubkey[0:2] == 'ff' assert len(pubkey) == 166 pk = bytes.fromhex(pubkey) xkey = base58_encode_check(pk[1:79]) return xkey, [unpack_le_uint16(pk[n:n + 2])[0] for n in (79, 81)]