derive.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2025 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. derive: coin private key secret derivation for the MMGen suite
  20. """
  21. from collections import namedtuple
  22. from hashlib import sha512, sha256
  23. from .addrlist import AddrIdxList
  24. pk_bytes = namedtuple('coin_privkey_bytes', ['idx', 'pos', 'data'])
  25. def derive_coin_privkey_bytes(seed, idxs):
  26. assert isinstance(idxs, AddrIdxList), f'{type(idxs)}: idx list not of type AddrIdxList'
  27. t_keys = len(idxs)
  28. pos = 0
  29. for idx in range(1, AddrIdxList.max_len + 1): # key/addr indexes begin from one
  30. seed = sha512(seed).digest()
  31. if idx == idxs[pos]:
  32. pos += 1
  33. # secret is double sha256 of seed hash round /idx/
  34. yield pk_bytes(idx, pos, sha256(sha256(seed).digest()).digest())
  35. if pos == t_keys:
  36. break