addrgen.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2022 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. addrgen.py: Address generation initialization code for the MMGen suite
  20. """
  21. # decorator for to_addr() and to_viewkey()
  22. def check_data(orig_func):
  23. def f(self,data):
  24. assert data.pubkey_type == self.pubkey_type, 'addrgen.py:check_data() pubkey_type mismatch'
  25. assert data.compressed == self.compressed,(
  26. f'addrgen.py:check_data() expected compressed={self.compressed} but got compressed={data.compressed}'
  27. )
  28. return orig_func(self,data)
  29. return f
  30. class addr_generator:
  31. class base:
  32. def __init__(self,proto,addr_type):
  33. self.proto = proto
  34. self.pubkey_type = addr_type.pubkey_type
  35. self.compressed = addr_type.compressed
  36. desc = f'AddrGenerator {type(self).__name__!r}'
  37. class keccak(base):
  38. def __init__(self,proto,addr_type):
  39. super().__init__(proto,addr_type)
  40. from .util import get_keccak
  41. self.keccak_256 = get_keccak()
  42. def AddrGenerator(proto,addr_type):
  43. """
  44. factory function returning an address generator for the specified address type
  45. """
  46. package_map = {
  47. 'legacy': 'btc',
  48. 'compressed': 'btc',
  49. 'segwit': 'btc',
  50. 'bech32': 'btc',
  51. 'monero': 'xmr',
  52. 'ethereum': 'eth',
  53. 'zcash_z': 'zec',
  54. }
  55. from .addr import MMGenAddrType
  56. if type(addr_type) == str:
  57. addr_type = MMGenAddrType(proto=proto,id_str=addr_type)
  58. elif type(addr_type) == MMGenAddrType:
  59. assert addr_type in proto.mmtypes, f'{addr_type}: invalid address type for coin {proto.coin}'
  60. else:
  61. raise TypeError(f'{type(addr_type)}: incorrect argument type for {cls.__name__}()')
  62. import importlib
  63. return getattr(
  64. importlib.import_module(f'mmgen.proto.{package_map[addr_type.name]}.addrgen'),
  65. addr_type.name )(proto,addr_type)