1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
|
import hashlib
import hmac
import base58
from .utils import (
HARDENED_INDEX,
_deriv_path_str_to_list,
_get_curve_by_name,
_hardened_index_in_path,
_pubkey_to_fingerprint,
_serialize_extended_key,
_unserialize_extended_key,
)
class PrivateDerivationError(ValueError):
"""
Tried to use a derivation requiring private keys, without private keys.
"""
pass
class InvalidInputError(ValueError):
def __init__(self, message):
self.message = message
class ParsingError(ValueError):
def __init__(self, message):
self.message = message
class SerializationError(ValueError):
def __init__(self, message):
self.message = message
class SLIP10:
def __init__(
self,
chaincode,
privkey=None,
pubkey=None,
fingerprint=bytes(4),
depth=0,
index=0,
network="main",
curve_name="secp256k1",
):
"""
:param chaincode: The master chaincode, used to derive keys. As bytes.
:param privkey: The master private key for this index (default 0).
Can be None for pubkey-only derivation.
As bytes.
:param pubkey: The master public key for this index (default 0).
Can be None if private key is specified.
Compressed format. As bytes.
:param fingeprint: If we are instanciated from an xpub/xpriv, we need
to remember the parent's pubkey fingerprint to
reserialize !
:param depth: If we are instanciated from an existing extended key, we
need this for serialization.
:param index: If we are instanciated from an existing extended key, we
need this for serialization.
:param network: Either "main" or "test".
:param curve_name: Either "secp256k1", "secp256r1", "ed25519" or "curve25519".
"""
try:
curve = _get_curve_by_name(curve_name)
except ValueError as e:
raise InvalidInputError(e) from None
if network not in ["main", "test"]:
raise InvalidInputError("'network' must be one of 'main' or 'test'")
if not isinstance(chaincode, bytes):
raise InvalidInputError("'chaincode' must be bytes")
if privkey is None and pubkey is None:
raise InvalidInputError("Need at least a 'pubkey' or a 'privkey'")
if privkey is not None:
if not isinstance(privkey, bytes):
raise InvalidInputError("'privkey' must be bytes")
if not curve.privkey_is_valid(privkey):
raise InvalidInputError("Invalid private key")
if pubkey is not None:
if not isinstance(pubkey, bytes):
raise InvalidInputError("'pubkey' must be bytes")
if not curve.pubkey_is_valid(pubkey):
raise InvalidInputError("Invalid public key")
if privkey is not None and pubkey != curve.privkey_to_pubkey(privkey):
raise InvalidInputError("Public key does not match private key")
else:
pubkey = curve.privkey_to_pubkey(privkey)
if depth == 0:
if fingerprint != bytes(4):
raise InvalidInputError(
"Fingerprint must be 0 if depth is 0 (master xpub)"
)
if index != 0:
raise InvalidInputError("Index must be 0 if depth is 0 (master xpub)")
if network not in ["main", "test"]:
raise InvalidInputError("Unknown network")
self.chaincode = chaincode
self.privkey = privkey
self.pubkey = pubkey
self.parent_fingerprint = fingerprint
self.depth = depth
self.index = index
self.network = network
self.curve = curve
def get_child_from_path(self, path):
"""Get an child node from a derivation path.
:param path: A list of integers (index of each depth) or a string with
m/x/x'/x notation. (e.g. m/0'/1/2'/2 or m/0H/1/2H/2).
:return: SLIP10 object
"""
if isinstance(path, str):
path = _deriv_path_str_to_list(path)
if len(path) == 0:
return self
if _hardened_index_in_path(path) and self.privkey is None:
raise PrivateDerivationError
chaincode = self.chaincode
privkey = self.privkey
if privkey is not None:
pubkey = None
for index in path:
parent_privkey = privkey
privkey, chaincode = self.curve.derive_private_child(
privkey, chaincode, index
)
parent_pubkey = self.curve.privkey_to_pubkey(parent_privkey)
else:
pubkey = self.pubkey
for index in path:
parent_pubkey = pubkey
pubkey, chaincode = self.curve.derive_public_child(
pubkey, chaincode, index
)
return SLIP10(
chaincode,
privkey,
pubkey,
_pubkey_to_fingerprint(parent_pubkey),
depth=self.depth + len(path),
index=path[-1],
network=self.network,
curve_name=self.curve.name,
)
def get_extended_privkey_from_path(self, path):
"""Get an extended privkey from a derivation path.
:param path: A list of integers (index of each depth) or a string with
m/x/x'/x notation. (e.g. m/0'/1/2'/2 or m/0H/1/2H/2).
:return: chaincode (bytes), privkey (bytes)
"""
if self.privkey is None:
raise PrivateDerivationError
if isinstance(path, str):
path = _deriv_path_str_to_list(path)
chaincode, privkey = self.chaincode, self.privkey
for index in path:
privkey, chaincode = self.curve.derive_private_child(
privkey, chaincode, index
)
return chaincode, privkey
def get_privkey_from_path(self, path):
"""Get a privkey from a derivation path.
:param path: A list of integers (index of each depth) or a string with
m/x/x'/x notation. (e.g. m/0'/1/2'/2 or m/0H/1/2H/2).
:return: privkey (bytes)
"""
if self.privkey is None:
raise PrivateDerivationError
return self.get_extended_privkey_from_path(path)[1]
def get_extended_pubkey_from_path(self, path):
"""Get an extended pubkey from a derivation path.
:param path: A list of integers (index of each depth) or a string with
m/x/x'/x notation. (e.g. m/0'/1/2'/2 or m/0H/1/2H/2).
:return: chaincode (bytes), pubkey (bytes)
"""
if isinstance(path, str):
path = _deriv_path_str_to_list(path)
if _hardened_index_in_path(path) and self.privkey is None:
raise PrivateDerivationError
chaincode, key = self.chaincode, self.privkey
pubkey = self.pubkey
# We'll need the private key at some point anyway, so let's derive
# everything from private keys.
if _hardened_index_in_path(path):
for index in path:
key, chaincode = self.curve.derive_private_child(key, chaincode, index)
pubkey = self.curve.privkey_to_pubkey(key)
# We won't need private keys for the whole path, so let's only use
# public key derivation.
else:
for index in path:
pubkey, chaincode = self.curve.derive_public_child(
pubkey, chaincode, index
)
return chaincode, pubkey
def get_pubkey_from_path(self, path):
"""Get a pubkey from a derivation path.
:param path: A list of integers (index of each depth) or a string with
m/x/x'/x notation. (e.g. m/0'/1/2'/2 or m/0H/1/2H/2).
:return: privkey (bytes)
"""
return self.get_extended_pubkey_from_path(path)[1]
def get_xpriv_from_path(self, path):
"""Get an encoded extended privkey from a derivation path.
:param path: A list of integers (index of each depth) or a string with
m/x/x'/x notation. (e.g. m/0'/1/2'/2 or m/0H/1/2H/2).
:return: The encoded extended pubkey as str.
"""
if self.curve.name != "secp256k1":
raise SerializationError(
"xpriv serialization is supported only for secp256k1"
)
if self.privkey is None:
raise PrivateDerivationError
if isinstance(path, str):
path = _deriv_path_str_to_list(path)
if len(path) == 0:
return self.get_xpriv()
elif len(path) == 1:
parent_pubkey = self.pubkey
else:
parent_pubkey = self.get_pubkey_from_path(path[:-1])
chaincode, privkey = self.get_extended_privkey_from_path(path)
extended_key = _serialize_extended_key(
privkey,
self.depth + len(path),
parent_pubkey,
path[-1],
chaincode,
self.network,
)
return base58.b58encode_check(extended_key).decode()
def get_xpub_from_path(self, path):
"""Get an encoded extended pubkey from a derivation path.
:param path: A list of integers (index of each depth) or a string with
m/x/x'/x notation. (e.g. m/0'/1/2'/2 or m/0H/1/2H/2).
:return: The encoded extended pubkey as str.
"""
if self.curve.name != "secp256k1":
raise SerializationError(
"xpub serialization is supported only for secp256k1"
)
if isinstance(path, str):
path = _deriv_path_str_to_list(path)
if _hardened_index_in_path(path) and self.privkey is None:
raise PrivateDerivationError
if len(path) == 0:
return self.get_xpub()
elif len(path) == 1:
parent_pubkey = self.pubkey
else:
parent_pubkey = self.get_pubkey_from_path(path[:-1])
chaincode, pubkey = self.get_extended_pubkey_from_path(path)
extended_key = _serialize_extended_key(
pubkey,
self.depth + len(path),
parent_pubkey,
path[-1],
chaincode,
self.network,
)
return base58.b58encode_check(extended_key).decode()
def get_xpriv(self):
"""Get the base58 encoded extended private key."""
return base58.b58encode_check(self.get_xpriv_bytes()).decode()
def get_xpriv_bytes(self):
"""Get the encoded extended private key."""
if self.curve.name != "secp256k1":
raise SerializationError(
"xpriv serialization is supported only for secp256k1"
)
if self.privkey is None:
raise PrivateDerivationError
return _serialize_extended_key(
self.privkey,
self.depth,
self.parent_fingerprint,
self.index,
self.chaincode,
self.network,
)
def get_xpub(self):
"""Get the encoded extended public key."""
return base58.b58encode_check(self.get_xpub_bytes()).decode()
def get_xpub_bytes(self):
"""Get the encoded extended public key."""
if self.curve.name != "secp256k1":
raise SerializationError(
"xpub serialization is supported only for secp256k1"
)
return _serialize_extended_key(
self.pubkey,
self.depth,
self.parent_fingerprint,
self.index,
self.chaincode,
self.network,
)
@classmethod
def from_xpriv(cls, xpriv):
"""Get a SLIP10 "wallet" out of this xpriv
:param xpriv: (str) The encoded serialized extended private key.
"""
if not isinstance(xpriv, str):
raise InvalidInputError("'xpriv' must be a string")
extended_key = base58.b58decode_check(xpriv)
(
network,
depth,
fingerprint,
index,
chaincode,
key,
) = _unserialize_extended_key(extended_key)
if key[0] != 0:
raise ParsingError("Invalid xpriv: private key prefix must be 0")
try:
# We need to remove the trailing `0` before the actual private key !!
return SLIP10(chaincode, key[1:], None, fingerprint, depth, index, network)
except InvalidInputError as e:
raise ParsingError(f"Invalid xpriv: '{e}'")
@classmethod
def from_xpub(cls, xpub):
"""Get a SLIP10 "wallet" out of this xpub
:param xpub: (str) The encoded serialized extended public key.
"""
if not isinstance(xpub, str):
raise InvalidInputError("'xpub' must be a string")
extended_key = base58.b58decode_check(xpub)
(
network,
depth,
fingerprint,
index,
chaincode,
key,
) = _unserialize_extended_key(extended_key)
try:
return SLIP10(chaincode, None, key, fingerprint, depth, index, network)
except InvalidInputError as e:
raise ParsingError(f"Invalid xpub: '{e}'")
@classmethod
def from_seed(cls, seed, network="main", curve_name="secp256k1"):
"""Get a SLIP10 "wallet" out of this seed seed byte sequence, which can be a BIP39
binary seed or a SLIP39 master secret.
:param seed: The seed as bytes.
"""
try:
curve = _get_curve_by_name(curve_name)
except ValueError as e:
raise InvalidInputError(e) from None
privkey, chaincode = curve.generate_master(seed)
return SLIP10(chaincode, privkey, network=network, curve_name=curve_name)
|