addr.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2024 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. addr: MMGen address-related types
  20. """
  21. from collections import namedtuple
  22. from .objmethods import HiliteStr,InitErrors,MMGenObject
  23. from .obj import ImmutableAttr,MMGenIdx,get_obj
  24. from .seed import SeedID
  25. from . import color as color_mod
  26. ati = namedtuple('addrtype_info',
  27. ['name','pubkey_type','compressed','gen_method','addr_fmt','wif_label','extra_attrs','desc'])
  28. class MMGenAddrType(HiliteStr,InitErrors,MMGenObject):
  29. width = 1
  30. trunc_ok = False
  31. color = 'blue'
  32. name = ImmutableAttr(str)
  33. pubkey_type = ImmutableAttr(str)
  34. compressed = ImmutableAttr(bool,set_none_ok=True)
  35. gen_method = ImmutableAttr(str,set_none_ok=True)
  36. addr_fmt = ImmutableAttr(str,set_none_ok=True)
  37. wif_label = ImmutableAttr(str,set_none_ok=True)
  38. extra_attrs = ImmutableAttr(tuple,set_none_ok=True)
  39. desc = ImmutableAttr(str)
  40. pkh_fmts = ('p2pkh','bech32','ethereum')
  41. mmtypes = {
  42. 'L': ati('legacy', 'std', False,'p2pkh', 'p2pkh', 'wif', (), 'Legacy uncompressed address'),
  43. 'C': ati('compressed','std', True, 'p2pkh', 'p2pkh', 'wif', (), 'Compressed P2PKH address'),
  44. 'S': ati('segwit', 'std', True, 'segwit', 'p2sh', 'wif', (), 'Segwit P2SH-P2WPKH address'),
  45. 'B': ati('bech32', 'std', True, 'bech32', 'bech32', 'wif', (), 'Native Segwit (Bech32) address'),
  46. 'E': ati('ethereum', 'std', False,'ethereum','p2pkh', 'privkey', ('wallet_passwd',),'Ethereum address'),
  47. 'Z': ati('zcash_z','zcash_z',False,'zcash_z', 'zcash_z', 'wif', ('viewkey',), 'Zcash z-address'),
  48. 'M': ati('monero', 'monero', False,'monero', 'monero', 'spendkey',('viewkey','wallet_passwd'),'Monero address'),
  49. }
  50. def __new__(cls,proto,id_str,errmsg=None):
  51. if isinstance(id_str,cls):
  52. return id_str
  53. try:
  54. id_str = id_str.replace('-','_')
  55. for k,v in cls.mmtypes.items():
  56. if id_str in (k,v.name):
  57. if id_str == v.name:
  58. id_str = k
  59. me = str.__new__(cls,id_str)
  60. for k in v._fields:
  61. setattr(me,k,getattr(v,k))
  62. if me not in proto.mmtypes + ('P',):
  63. raise ValueError(f'{me.name!r}: invalid address type for {proto.name} protocol')
  64. me.proto = proto
  65. return me
  66. raise ValueError(f'{id_str}: unrecognized address type for protocol {proto.name}')
  67. except Exception as e:
  68. return cls.init_fail( e,
  69. f"{errmsg or ''}{id_str!r}: invalid value for {cls.__name__} ({e!s})",
  70. preformat = True )
  71. @classmethod
  72. def get_names(cls):
  73. return [v.name for v in cls.mmtypes.values()]
  74. def is_mmgen_addrtype(proto,id_str):
  75. return get_obj( MMGenAddrType, proto=proto, id_str=id_str, silent=True, return_bool=True )
  76. class MMGenPasswordType(MMGenAddrType):
  77. mmtypes = {
  78. 'P': ati('password', 'password', None, None, None, None, None, 'Password generated from MMGen seed')
  79. }
  80. class AddrIdx(MMGenIdx):
  81. max_digits = 7
  82. def is_addr_idx(s):
  83. return get_obj( AddrIdx, n=s, silent=True, return_bool=True )
  84. class AddrListID(HiliteStr,InitErrors,MMGenObject):
  85. width = 10
  86. trunc_ok = False
  87. color = 'yellow'
  88. def __new__(cls,sid=None,mmtype=None,proto=None,id_str=None):
  89. try:
  90. if id_str:
  91. a,b = id_str.split(':')
  92. sid = SeedID(sid=a)
  93. try:
  94. mmtype = MMGenAddrType( proto=proto, id_str=b )
  95. except:
  96. mmtype = MMGenPasswordType( proto=proto, id_str=b )
  97. else:
  98. assert isinstance(sid,SeedID), f'{sid!r} not a SeedID instance'
  99. if not isinstance(mmtype,(MMGenAddrType,MMGenPasswordType)):
  100. raise ValueError(f'{mmtype!r}: not an instance of MMGenAddrType or MMGenPasswordType')
  101. me = str.__new__(cls,sid+':'+mmtype)
  102. me.sid = sid
  103. me.mmtype = mmtype
  104. return me
  105. except Exception as e:
  106. return cls.init_fail(e, f'sid={sid}, mmtype={mmtype}')
  107. def is_addrlist_id(proto,s):
  108. return get_obj( AddrListID, proto=proto, id_str=s, silent=False, return_bool=True )
  109. class MMGenID(HiliteStr,InitErrors,MMGenObject):
  110. color = 'orange'
  111. width = 0
  112. trunc_ok = False
  113. def __new__(cls,proto,id_str):
  114. try:
  115. ss = str(id_str).split(':')
  116. assert len(ss) in (2,3),'not 2 or 3 colon-separated items'
  117. t = proto.addr_type((ss[1],proto.dfl_mmtype)[len(ss)==2])
  118. me = str.__new__(cls,f'{ss[0]}:{t}:{ss[-1]}')
  119. me.sid = SeedID(sid=ss[0])
  120. me.idx = AddrIdx(ss[-1])
  121. me.mmtype = t
  122. assert t in proto.mmtypes, f'{t}: invalid address type for {proto.cls_name}'
  123. me.al_id = str.__new__(AddrListID,me.sid+':'+me.mmtype) # checks already done
  124. me.sort_key = f'{me.sid}:{me.mmtype}:{me.idx:0{me.idx.max_digits}}'
  125. me.proto = proto
  126. return me
  127. except Exception as e:
  128. return cls.init_fail(e,id_str)
  129. def is_mmgen_id(proto,s):
  130. return get_obj( MMGenID, proto=proto, id_str=s, silent=True, return_bool=True )
  131. class CoinAddr(HiliteStr, InitErrors, MMGenObject):
  132. color = 'cyan'
  133. hex_width = 40
  134. width = 1
  135. trunc_ok = False
  136. def __new__(cls, proto, addr):
  137. if isinstance(addr,cls):
  138. return addr
  139. try:
  140. ap = proto.decode_addr(addr)
  141. assert ap, f'coin address {addr!r} could not be parsed'
  142. if hasattr(ap, 'addr'):
  143. me = str.__new__(cls, ap.addr)
  144. me.views = ap.views
  145. me.view_pref = ap.view_pref
  146. else:
  147. me = str.__new__(cls, addr)
  148. me.views = [addr]
  149. me.view_pref = 0
  150. me.addr_fmt = ap.fmt
  151. me.bytes = ap.bytes
  152. me.ver_bytes = ap.ver_bytes
  153. me.proto = proto
  154. return me
  155. except Exception as e:
  156. return cls.init_fail(e,addr,objname=f'{proto.cls_name} address')
  157. @property
  158. def parsed(self):
  159. if not hasattr(self,'_parsed'):
  160. self._parsed = self.proto.parse_addr(self.ver_bytes,self.bytes,self.addr_fmt)
  161. return self._parsed
  162. # reimplement some HiliteStr methods:
  163. @classmethod
  164. def fmtc(cls,s,width,color=False):
  165. return super().fmtc( s=s[:width-2]+'..' if len(s) > width else s, width=width, color=color )
  166. def fmt(self, view_pref, width, color=False):
  167. s = self.views[view_pref]
  168. return super().fmtc(f'{s[:width-2]}..' if len(s) > width else s, width=width, color=color)
  169. def hl(self, view_pref, color=True):
  170. return getattr(color_mod, self.color)(self.views[view_pref]) if color else self.views[view_pref]
  171. def is_coin_addr(proto,s):
  172. return get_obj( CoinAddr, proto=proto, addr=s, silent=True, return_bool=True )
  173. class TokenAddr(CoinAddr):
  174. color = 'blue'
  175. def ViewKey(proto,viewkey_str):
  176. return proto.viewkey(viewkey_str)