addr.py 6.5 KB

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