You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_mnemonic.py 6.0KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. ###############################################################################
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (c) 2018 Luis Teixeira
  6. # - copied & modified from https://github.com/vergl4s/ethereum-mnemonic-utils
  7. #
  8. # Permission is hereby granted, free of charge, to any person obtaining a copy
  9. # of this software and associated documentation files (the "Software"), to deal
  10. # in the Software without restriction, including without limitation the rights
  11. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. # copies of the Software, and to permit persons to whom the Software is
  13. # furnished to do so, subject to the following conditions:
  14. #
  15. # The above copyright notice and this permission notice shall be included in
  16. # all copies or substantial portions of the Software.
  17. #
  18. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. # THE SOFTWARE.
  25. #
  26. ###############################################################################
  27. import hashlib
  28. import hmac
  29. import struct
  30. from base58 import b58encode_check
  31. from ecdsa.curves import SECP256k1
  32. BIP39_PBKDF2_ROUNDS = 2048
  33. BIP39_SALT_MODIFIER = "mnemonic"
  34. BIP32_PRIVDEV = 0x80000000
  35. BIP32_CURVE = SECP256k1
  36. BIP32_SEED_MODIFIER = b'Bitcoin seed'
  37. # https://github.com/ethereum/EIPs/issues/84#issuecomment-528213145
  38. LEDGER_ETH_DERIVATION_PATH = "m/44'/60'/0'/0"
  39. def mnemonic_to_bip39seed(mnemonic, passphrase):
  40. """ BIP39 seed from a mnemonic key.
  41. Logic adapted from https://github.com/trezor/python-mnemonic. """
  42. mnemonic = bytes(mnemonic, 'utf8')
  43. salt = bytes(BIP39_SALT_MODIFIER + passphrase, 'utf8')
  44. return hashlib.pbkdf2_hmac('sha512', mnemonic, salt, BIP39_PBKDF2_ROUNDS)
  45. def bip39seed_to_bip32masternode(seed):
  46. """ BIP32 master node derivation from a bip39 seed.
  47. Logic adapted from https://github.com/satoshilabs/slips/blob/master/slip-0010/testvectors.py. """
  48. h = hmac.new(BIP32_SEED_MODIFIER, seed, hashlib.sha512).digest()
  49. key, chain_code = h[:32], h[32:]
  50. return key, chain_code
  51. def derive_public_key(private_key):
  52. """ Public key from a private key.
  53. Logic adapted from https://github.com/satoshilabs/slips/blob/master/slip-0010/testvectors.py. """
  54. Q = int.from_bytes(private_key, byteorder='big') * BIP32_CURVE.generator
  55. xstr = Q.x().to_bytes(32, byteorder='big')
  56. parity = Q.y() & 1
  57. return (2 + parity).to_bytes(1, byteorder='big') + xstr
  58. def derive_bip32childkey(parent_key, parent_chain_code, i):
  59. """ Derives a child key from an existing key, i is current derivation parameter.
  60. Logic adapted from https://github.com/satoshilabs/slips/blob/master/slip-0010/testvectors.py. """
  61. assert len(parent_key) == 32
  62. assert len(parent_chain_code) == 32
  63. k = parent_chain_code
  64. if (i & BIP32_PRIVDEV) != 0:
  65. key = b'\x00' + parent_key
  66. else:
  67. key = derive_public_key(parent_key)
  68. d = key + struct.pack('>L', i)
  69. while True:
  70. h = hmac.new(k, d, hashlib.sha512).digest()
  71. key, chain_code = h[:32], h[32:]
  72. a = int.from_bytes(key, byteorder='big')
  73. b = int.from_bytes(parent_key, byteorder='big')
  74. key = (a + b) % BIP32_CURVE.order
  75. if a < BIP32_CURVE.order and key != 0:
  76. key = key.to_bytes(32, byteorder='big')
  77. break
  78. d = b'\x01' + h[32:] + struct.pack('>L', i)
  79. return key, chain_code
  80. def fingerprint(public_key):
  81. """ BIP32 fingerprint formula, used to get b58 serialized key. """
  82. return hashlib.new('ripemd160', hashlib.sha256(public_key).digest()).digest()[:4]
  83. def b58xprv(parent_fingerprint, private_key, chain, depth, childnr):
  84. """ Private key b58 serialization format. """
  85. raw = (b'\x04\x88\xad\xe4' + bytes(chr(depth), 'utf-8') + parent_fingerprint + childnr.to_bytes(
  86. 4, byteorder='big') + chain + b'\x00' + private_key)
  87. return b58encode_check(raw)
  88. def b58xpub(parent_fingerprint, public_key, chain, depth, childnr):
  89. """ Public key b58 serialization format. """
  90. raw = (b'\x04\x88\xb2\x1e' + bytes(chr(depth), 'utf-8') + parent_fingerprint + childnr.to_bytes(
  91. 4, byteorder='big') + chain + public_key)
  92. return b58encode_check(raw)
  93. def parse_derivation_path(str_derivation_path):
  94. """ Parses a derivation path such as "m/44'/60/0'/0" and returns
  95. list of integers for each element in path. """
  96. path = []
  97. if str_derivation_path[0:2] != 'm/':
  98. raise ValueError("Can't recognize derivation path. It should look like \"m/44'/60/0'/0\".")
  99. for i in str_derivation_path.lstrip('m/').split('/'):
  100. if "'" in i:
  101. path.append(BIP32_PRIVDEV + int(i[:-1]))
  102. else:
  103. path.append(int(i))
  104. return path
  105. def mnemonic_to_private_key(mnemonic, str_derivation_path=LEDGER_ETH_DERIVATION_PATH, passphrase=""):
  106. """ Performs all convertions to get a private key from a mnemonic sentence, including:
  107. BIP39 mnemonic to seed
  108. BIP32 seed to master key
  109. BIP32 child derivation of a path provided
  110. Parameters:
  111. mnemonic -- seed wordlist, usually with 24 words, that is used for ledger wallet backup
  112. str_derivation_path -- string that directs BIP32 key derivation, defaults to path
  113. used by ledger ETH wallet
  114. """
  115. derivation_path = parse_derivation_path(str_derivation_path)
  116. bip39seed = mnemonic_to_bip39seed(mnemonic, passphrase)
  117. master_private_key, master_chain_code = bip39seed_to_bip32masternode(bip39seed)
  118. private_key, chain_code = master_private_key, master_chain_code
  119. for i in derivation_path:
  120. private_key, chain_code = derive_bip32childkey(private_key, chain_code, i)
  121. return private_key