def from_string(cls, string): """TODO""" try: data = encoding.a2b_base58check(string) except encoding.InvalidEncoding as e: raise InvalidEncoding(e.message) return cls.from_bytes(data)
def test_from_invalid_wif(self): too_short = encoding.b2a_base58check('a') with raises(privkey.InvalidEncoding): PrivateKey.from_wif(too_short) too_long = encoding.b2a_base58check('a' * 30) with raises(privkey.InvalidEncoding): PrivateKey.from_wif(too_long) valid = encoding.a2b_base58check(PrivateKey.generate().to_wif()) with raises(privkey.InvalidEncoding): PrivateKey.from_wif(encoding.b2a_base58check(valid[:-1] + 'a')) with raises(privkey.InvalidEncoding): PrivateKey.from_wif(encoding.b2a_base58check('a' + valid[1:]))
def from_wif(cls, wif, backend=default_backend()): """Create a private key from its WIF encoding. The Wallet Import Format encoding is used for serializing Bitcoin private keys. For more info on this encoding, see: https://en.bitcoin.it/wiki/Wallet_import_format """ # A WIF private key is base58check encoded try: data = bytearray(encoding.a2b_base58check(wif)) except encoding.Error as e: raise InvalidEncoding(e.message) # The first byte determines the network try: prefix = data.pop(0) except IndexError: raise InvalidEncoding('Invalid WIF length') try: network_ = network.Network.get_by_field('wif_prefix', prefix) except network.UnknownNetwork as e: raise InvalidEncoding(e.message) # If the public key should be compressed-encoded, there will be an # extra 1 byte at the end key_size = tools.elliptic_curve_key_size(network_.curve) compressed = True if len(data) == key_size + 1 else False if compressed and data[-1] == 1: data.pop(-1) # What remains should be the raw private key exponent return cls.from_bytes(bytes(data), network_, compressed, backend)