Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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. __all__ = [
  40. 'mnemonic_to_bip39seed',
  41. 'mnemonic_to_private_key',
  42. ]
  43. def mnemonic_to_bip39seed(mnemonic, passphrase):
  44. """ BIP39 seed from a mnemonic key.
  45. Logic adapted from https://github.com/trezor/python-mnemonic. """
  46. mnemonic = bytes(mnemonic, 'utf8')
  47. salt = bytes(BIP39_SALT_MODIFIER + passphrase, 'utf8')
  48. return hashlib.pbkdf2_hmac('sha512', mnemonic, salt, BIP39_PBKDF2_ROUNDS)
  49. def bip39seed_to_bip32masternode(seed):
  50. """ BIP32 master node derivation from a bip39 seed.
  51. Logic adapted from https://github.com/satoshilabs/slips/blob/master/slip-0010/testvectors.py. """
  52. h = hmac.new(BIP32_SEED_MODIFIER, seed, hashlib.sha512).digest()
  53. key, chain_code = h[:32], h[32:]
  54. return key, chain_code
  55. def derive_public_key(private_key):
  56. """ Public key from a private key.
  57. Logic adapted from https://github.com/satoshilabs/slips/blob/master/slip-0010/testvectors.py. """
  58. Q = int.from_bytes(private_key, byteorder='big') * BIP32_CURVE.generator
  59. xstr = int(Q.x()).to_bytes(32, byteorder='big')
  60. parity = Q.y() & 1
  61. return int(2 + parity).to_bytes(1, byteorder='big') + xstr
  62. def derive_bip32childkey(parent_key, parent_chain_code, i):
  63. """ Derives a child key from an existing key, i is current derivation parameter.
  64. Logic adapted from https://github.com/satoshilabs/slips/blob/master/slip-0010/testvectors.py. """
  65. assert len(parent_key) == 32
  66. assert len(parent_chain_code) == 32
  67. k = parent_chain_code
  68. if (i & BIP32_PRIVDEV) != 0:
  69. key = b'\x00' + parent_key
  70. else:
  71. key = derive_public_key(parent_key)
  72. d = key + struct.pack('>L', i)
  73. while True:
  74. h = hmac.new(k, d, hashlib.sha512).digest()
  75. key, chain_code = h[:32], h[32:]
  76. a = int.from_bytes(key, byteorder='big')
  77. b = int.from_bytes(parent_key, byteorder='big')
  78. key = (a + b) % BIP32_CURVE.order
  79. if a < BIP32_CURVE.order and key != 0:
  80. key = int(key).to_bytes(32, byteorder='big')
  81. break
  82. d = b'\x01' + h[32:] + struct.pack('>L', i)
  83. return key, chain_code
  84. def fingerprint(public_key):
  85. """ BIP32 fingerprint formula, used to get b58 serialized key. """
  86. return hashlib.new('ripemd160', hashlib.sha256(public_key).digest()).digest()[:4]
  87. def b58xprv(parent_fingerprint, private_key, chain, depth, childnr):
  88. """ Private key b58 serialization format. """
  89. raw = (b'\x04\x88\xad\xe4' + bytes(chr(depth), 'utf-8') + parent_fingerprint + int(childnr).to_bytes(
  90. 4, byteorder='big') + chain + b'\x00' + private_key)
  91. return b58encode_check(raw)
  92. def b58xpub(parent_fingerprint, public_key, chain, depth, childnr):
  93. """ Public key b58 serialization format. """
  94. raw = (b'\x04\x88\xb2\x1e' + bytes(chr(depth), 'utf-8') + parent_fingerprint + int(childnr).to_bytes(
  95. 4, byteorder='big') + chain + public_key)
  96. return b58encode_check(raw)
  97. def parse_derivation_path(str_derivation_path):
  98. """ Parses a derivation path such as "m/44'/60/0'/0" and returns
  99. list of integers for each element in path. """
  100. path = []
  101. if str_derivation_path[0:2] != 'm/':
  102. raise ValueError("Can't recognize derivation path. It should look like \"m/44'/60/0'/0\".")
  103. for i in str_derivation_path.lstrip('m/').split('/'):
  104. if "'" in i:
  105. path.append(BIP32_PRIVDEV + int(i[:-1]))
  106. else:
  107. path.append(int(i))
  108. return path
  109. def mnemonic_to_private_key(mnemonic, str_derivation_path=LEDGER_ETH_DERIVATION_PATH, passphrase=""):
  110. """ Performs all convertions to get a private key from a mnemonic sentence, including:
  111. BIP39 mnemonic to seed
  112. BIP32 seed to master key
  113. BIP32 child derivation of a path provided
  114. Parameters:
  115. mnemonic -- seed wordlist, usually with 24 words, that is used for ledger wallet backup
  116. str_derivation_path -- string that directs BIP32 key derivation, defaults to path
  117. used by ledger ETH wallet
  118. """
  119. derivation_path = parse_derivation_path(str_derivation_path)
  120. bip39seed = mnemonic_to_bip39seed(mnemonic, passphrase)
  121. master_private_key, master_chain_code = bip39seed_to_bip32masternode(bip39seed)
  122. private_key, chain_code = master_private_key, master_chain_code
  123. for i in derivation_path:
  124. private_key, chain_code = derive_bip32childkey(private_key, chain_code, i)
  125. return private_key