obj.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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. obj.py: MMGen native classes
  20. """
  21. import sys,os,re,unicodedata
  22. from decimal import *
  23. from string import hexdigits,ascii_letters,digits
  24. from .exception import *
  25. from .globalvars import *
  26. from .color import *
  27. from .objmethods import *
  28. def get_obj(objname,*args,**kwargs):
  29. """
  30. Wrapper for data objects
  31. - If the object throws an exception on instantiation, return False, otherwise return the object.
  32. - If silent is True, suppress display of the exception.
  33. - If return_bool is True, return True instead of the object.
  34. Only keyword args are accepted.
  35. """
  36. assert args == (), 'get_obj_chk1'
  37. silent,return_bool = (False,False)
  38. if 'silent' in kwargs:
  39. silent = kwargs['silent']
  40. del kwargs['silent']
  41. if 'return_bool' in kwargs:
  42. return_bool = kwargs['return_bool']
  43. del kwargs['return_bool']
  44. try:
  45. ret = objname(**kwargs)
  46. except Exception as e:
  47. if not silent:
  48. from .util import msg
  49. msg(f'{e!s}')
  50. return False
  51. else:
  52. return True if return_bool else ret
  53. def is_addr_idx(s): return get_obj(AddrIdx, n=s, silent=True,return_bool=True)
  54. def is_addrlist_id(s): return get_obj(AddrListID, sid=s, silent=True,return_bool=True)
  55. def is_mmgen_id(proto,s): return get_obj(MMGenID, proto=proto, id_str=s, silent=True,return_bool=True)
  56. def is_coin_addr(proto,s): return get_obj(CoinAddr, proto=proto, addr=s, silent=True,return_bool=True)
  57. # dict that keeps a list of keys for efficient lookup by index
  58. class IndexedDict(dict):
  59. def __init__(self,*args,**kwargs):
  60. if args or kwargs:
  61. self.die('initializing values via constructor')
  62. self.__keylist = []
  63. return dict.__init__(self,*args,**kwargs)
  64. def __setitem__(self,key,value):
  65. if key in self:
  66. self.die('reassignment to existing key')
  67. self.__keylist.append(key)
  68. return dict.__setitem__(self,key,value)
  69. @property
  70. def keys(self):
  71. return self.__keylist
  72. def key(self,idx):
  73. return self.__keylist[idx]
  74. def __delitem__(self,*args): self.die('item deletion')
  75. def move_to_end(self,*args): self.die('item moving')
  76. def clear(self,*args): self.die('clearing')
  77. def update(self,*args): self.die('updating')
  78. def die(self,desc):
  79. raise NotImplementedError(f'{desc} not implemented for type {type(self).__name__}')
  80. class MMGenList(list,MMGenObject): pass
  81. class MMGenDict(dict,MMGenObject): pass
  82. class Str(str,Hilite): pass
  83. class Int(int,Hilite,InitErrors):
  84. min_val = None
  85. max_val = None
  86. max_digits = None
  87. color = 'red'
  88. def __new__(cls,n,base=10):
  89. if type(n) == cls:
  90. return n
  91. try:
  92. me = int.__new__(cls,str(n),base)
  93. if cls.min_val != None:
  94. assert me >= cls.min_val, f'is less than cls.min_val ({cls.min_val})'
  95. if cls.max_val != None:
  96. assert me <= cls.max_val, f'is greater than cls.max_val ({cls.max_val})'
  97. if cls.max_digits != None:
  98. assert len(str(me)) <= cls.max_digits, f'has more than {cls.max_digits} digits'
  99. return me
  100. except Exception as e:
  101. return cls.init_fail(e,n)
  102. @classmethod
  103. def fmtc(cls,*args,**kwargs):
  104. cls.method_not_implemented()
  105. @classmethod
  106. def colorize(cls,n,color=True):
  107. return super().colorize(repr(n),color=color)
  108. class ImmutableAttr: # Descriptor
  109. """
  110. For attributes that are always present in the data instance
  111. Reassignment and deletion forbidden
  112. """
  113. ok_dtypes = (str,type,type(None),type(lambda:0))
  114. def __init__(self,dtype,typeconv=True,set_none_ok=False,include_proto=False):
  115. assert isinstance(dtype,self.ok_dtypes), 'ImmutableAttr_check1'
  116. if include_proto:
  117. assert typeconv, 'ImmutableAttr_check2'
  118. if set_none_ok:
  119. assert typeconv and type(dtype) != str, 'ImmutableAttr_check3'
  120. if dtype is None:
  121. 'use instance-defined conversion function for this attribute'
  122. self.conv = lambda instance,value: getattr(instance.conv_funcs,self.name)(instance,value)
  123. elif typeconv:
  124. "convert this attribute's type"
  125. if type(dtype) == str:
  126. if include_proto:
  127. self.conv = lambda instance,value: globals()[dtype](instance.proto,value)
  128. else:
  129. self.conv = lambda instance,value: globals()[dtype](value)
  130. else:
  131. if set_none_ok:
  132. self.conv = lambda instance,value: None if value is None else dtype(value)
  133. elif include_proto:
  134. self.conv = lambda instance,value: dtype(instance.proto,value)
  135. else:
  136. self.conv = lambda instance,value: dtype(value)
  137. else:
  138. "check this attribute's type"
  139. def assign_with_check(instance,value):
  140. if type(value) == dtype:
  141. return value
  142. raise TypeError('Attribute {!r} of {} instance must of type {}'.format(
  143. self.name,
  144. type(instance).__name__,
  145. dtype ))
  146. self.conv = assign_with_check
  147. def __set_name__(self,owner,name):
  148. self.name = name
  149. def __get__(self,instance,owner):
  150. return instance.__dict__[self.name]
  151. def setattr_condition(self,instance):
  152. 'forbid all reassignment'
  153. return not self.name in instance.__dict__
  154. def __set__(self,instance,value):
  155. if not self.setattr_condition(instance):
  156. raise AttributeError(f'Attribute {self.name!r} of {type(instance)} instance cannot be reassigned')
  157. instance.__dict__[self.name] = self.conv(instance,value)
  158. def __delete__(self,instance):
  159. raise AttributeError(
  160. f'Attribute {self.name!r} of {type(instance).__name__} instance cannot be deleted')
  161. class ListItemAttr(ImmutableAttr):
  162. """
  163. For attributes that might not be present in the data instance
  164. Reassignment or deletion allowed if specified
  165. """
  166. def __init__(self,dtype,typeconv=True,include_proto=False,reassign_ok=False,delete_ok=False):
  167. self.reassign_ok = reassign_ok
  168. self.delete_ok = delete_ok
  169. ImmutableAttr.__init__(self,dtype,typeconv=typeconv,include_proto=include_proto)
  170. def __get__(self,instance,owner):
  171. "return None if attribute doesn't exist"
  172. try: return instance.__dict__[self.name]
  173. except: return None
  174. def setattr_condition(self,instance):
  175. return getattr(instance,self.name) == None or self.reassign_ok
  176. def __delete__(self,instance):
  177. if self.delete_ok:
  178. if self.name in instance.__dict__:
  179. del instance.__dict__[self.name]
  180. else:
  181. ImmutableAttr.__delete__(self,instance)
  182. class MMGenListItem(MMGenObject):
  183. valid_attrs = set()
  184. valid_attrs_extra = set()
  185. invalid_attrs = {
  186. 'pfmt',
  187. 'pmsg',
  188. 'pdie',
  189. 'valid_attrs',
  190. 'valid_attrs_extra',
  191. 'invalid_attrs',
  192. 'immutable_attr_init_check',
  193. 'conv_funcs',
  194. '_asdict',
  195. }
  196. def __init__(self,*args,**kwargs):
  197. # generate valid_attrs, or use the class valid_attrs if set
  198. self.__dict__['valid_attrs'] = self.valid_attrs or (
  199. ( {e for e in dir(self) if e[:2] != '__'} | self.valid_attrs_extra )
  200. - MMGenListItem.invalid_attrs
  201. - self.invalid_attrs
  202. )
  203. if args:
  204. raise ValueError(f'Non-keyword args not allowed in {type(self).__name__!r} constructor')
  205. for k,v in kwargs.items():
  206. if v != None:
  207. setattr(self,k,v)
  208. # Require all immutables to be initialized. Check performed only when testing.
  209. self.immutable_attr_init_check()
  210. # allow only valid attributes to be set
  211. def __setattr__(self,name,value):
  212. if name not in self.valid_attrs:
  213. raise AttributeError(f'{name!r}: no such attribute in class {type(self)}')
  214. return object.__setattr__(self,name,value)
  215. def _asdict(self):
  216. return dict((k,v) for k,v in self.__dict__.items() if k in self.valid_attrs)
  217. class MMGenIdx(Int): min_val = 1
  218. class AddrIdx(MMGenIdx): max_digits = 7
  219. class MMGenRange(tuple,InitErrors,MMGenObject):
  220. min_idx = None
  221. max_idx = None
  222. def __new__(cls,*args):
  223. try:
  224. if len(args) == 1:
  225. s = args[0]
  226. if type(s) == cls:
  227. return s
  228. assert isinstance(s,str),'not a string or string subclass'
  229. ss = s.split('-',1)
  230. first = int(ss[0])
  231. last = int(ss.pop())
  232. else:
  233. s = repr(args) # needed if exception occurs
  234. assert len(args) == 2,'one format string arg or two start,stop args required'
  235. first,last = args
  236. assert first <= last, 'start of range greater than end of range'
  237. if cls.min_idx is not None:
  238. assert first >= cls.min_idx, f'start of range < {cls.min_idx:,}'
  239. if cls.max_idx is not None:
  240. assert last <= cls.max_idx, f'end of range > {cls.max_idx:,}'
  241. return tuple.__new__(cls,(first,last))
  242. except Exception as e:
  243. return cls.init_fail(e,s)
  244. @property
  245. def first(self):
  246. return self[0]
  247. @property
  248. def last(self):
  249. return self[1]
  250. def iterate(self):
  251. return range(self[0],self[1]+1)
  252. @property
  253. def items(self):
  254. return list(self.iterate())
  255. class CoinAddr(str,Hilite,InitErrors,MMGenObject):
  256. color = 'cyan'
  257. hex_width = 40
  258. width = 1
  259. trunc_ok = False
  260. def __new__(cls,proto,addr):
  261. if type(addr) == cls:
  262. return addr
  263. try:
  264. assert set(addr) <= set(ascii_letters+digits),'contains non-alphanumeric characters'
  265. me = str.__new__(cls,addr)
  266. ap = proto.parse_addr(addr)
  267. assert ap, f'coin address {addr!r} could not be parsed'
  268. me.addr_fmt = ap.fmt
  269. me.hex = ap.bytes.hex()
  270. me.proto = proto
  271. return me
  272. except Exception as e:
  273. return cls.init_fail(e,addr,objname=f'{proto.cls_name} address')
  274. @classmethod
  275. def fmtc(cls,addr,**kwargs):
  276. w = kwargs['width'] or cls.width
  277. return super().fmtc(addr[:w-2]+'..' if w < len(addr) else addr, **kwargs)
  278. class TokenAddr(CoinAddr):
  279. color = 'blue'
  280. class ViewKey(object):
  281. def __new__(cls,proto,viewkey):
  282. if proto.name == 'Zcash':
  283. return ZcashViewKey.__new__(ZcashViewKey,proto,viewkey)
  284. elif proto.name == 'Monero':
  285. return MoneroViewKey.__new__(MoneroViewKey,viewkey)
  286. else:
  287. raise ValueError(f'{proto.name}: protocol does not support view keys')
  288. class ZcashViewKey(CoinAddr): hex_width = 128
  289. class MMGenID(str,Hilite,InitErrors,MMGenObject):
  290. color = 'orange'
  291. width = 0
  292. trunc_ok = False
  293. def __new__(cls,proto,id_str):
  294. from .seed import SeedID
  295. try:
  296. ss = str(id_str).split(':')
  297. assert len(ss) in (2,3),'not 2 or 3 colon-separated items'
  298. t = proto.addr_type((ss[1],proto.dfl_mmtype)[len(ss)==2])
  299. me = str.__new__(cls,'{}:{}:{}'.format(ss[0],t,ss[-1]))
  300. me.sid = SeedID(sid=ss[0])
  301. me.idx = AddrIdx(ss[-1])
  302. me.mmtype = t
  303. assert t in proto.mmtypes, f'{t}: invalid address type for {proto.cls_name}'
  304. me.al_id = str.__new__(AddrListID,me.sid+':'+me.mmtype) # checks already done
  305. me.sort_key = '{}:{}:{:0{w}}'.format(me.sid,me.mmtype,me.idx,w=me.idx.max_digits)
  306. me.proto = proto
  307. return me
  308. except Exception as e:
  309. return cls.init_fail(e,id_str)
  310. class TwMMGenID(str,Hilite,InitErrors,MMGenObject):
  311. color = 'orange'
  312. width = 0
  313. trunc_ok = False
  314. def __new__(cls,proto,id_str):
  315. if type(id_str) == cls:
  316. return id_str
  317. ret = None
  318. try:
  319. ret = MMGenID(proto,id_str)
  320. sort_key,idtype = ret.sort_key,'mmgen'
  321. except Exception as e:
  322. try:
  323. assert id_str.split(':',1)[0] == proto.base_coin.lower(),(
  324. f'not a string beginning with the prefix {proto.base_coin.lower()!r}:' )
  325. assert set(id_str[4:]) <= set(ascii_letters+digits),'contains non-alphanumeric characters'
  326. assert len(id_str) > 4,'not more that four characters long'
  327. ret,sort_key,idtype = str(id_str),'z_'+id_str,'non-mmgen'
  328. except Exception as e2:
  329. return cls.init_fail(e,id_str,e2=e2)
  330. me = str.__new__(cls,ret)
  331. me.obj = ret
  332. me.sort_key = sort_key
  333. me.type = idtype
  334. me.proto = proto
  335. return me
  336. # non-displaying container for TwMMGenID,TwComment
  337. class TwLabel(str,InitErrors,MMGenObject):
  338. exc = BadTwLabel
  339. passthru_excs = (BadTwComment,)
  340. def __new__(cls,proto,text):
  341. if type(text) == cls:
  342. return text
  343. try:
  344. ts = text.split(None,1)
  345. mmid = TwMMGenID(proto,ts[0])
  346. comment = TwComment(ts[1] if len(ts) == 2 else '')
  347. me = str.__new__( cls, mmid + (' ' + comment if comment else '') )
  348. me.mmid = mmid
  349. me.comment = comment
  350. me.proto = proto
  351. return me
  352. except Exception as e:
  353. return cls.init_fail(e,text)
  354. class HexStr(str,Hilite,InitErrors):
  355. color = 'red'
  356. width = None
  357. hexcase = 'lower'
  358. trunc_ok = False
  359. def __new__(cls,s,case=None):
  360. if type(s) == cls:
  361. return s
  362. if case == None:
  363. case = cls.hexcase
  364. try:
  365. assert isinstance(s,str),'not a string or string subclass'
  366. assert case in ('upper','lower'), f'{case!r} incorrect case specifier'
  367. assert set(s) <= set(getattr(hexdigits,case)()), f'not {case}case hexadecimal symbols'
  368. assert not len(s) % 2,'odd-length string'
  369. if cls.width:
  370. assert len(s) == cls.width, f'Value is not {cls.width} characters wide'
  371. return str.__new__(cls,s)
  372. except Exception as e:
  373. return cls.init_fail(e,s)
  374. class CoinTxID(HexStr): color,width,hexcase = 'purple',64,'lower'
  375. class WalletPassword(HexStr): color,width,hexcase = 'blue',32,'lower'
  376. class MoneroViewKey(HexStr): color,width,hexcase = 'cyan',64,'lower' # FIXME - no checking performed
  377. class MMGenTxID(HexStr): color,width,hexcase = 'red',6,'upper'
  378. class AddrListID(str,Hilite,InitErrors,MMGenObject):
  379. width = 10
  380. trunc_ok = False
  381. color = 'yellow'
  382. def __new__(cls,sid,mmtype):
  383. from .seed import SeedID
  384. try:
  385. assert type(sid) == SeedID, f'{sid!r} not a SeedID instance'
  386. if not isinstance(mmtype,(MMGenAddrType,MMGenPasswordType)):
  387. raise ValueError(f'{mmtype!r}: not an instance of MMGenAddrType or MMGenPasswordType')
  388. me = str.__new__(cls,sid+':'+mmtype)
  389. me.sid = sid
  390. me.mmtype = mmtype
  391. return me
  392. except Exception as e:
  393. return cls.init_fail(e, f'sid={sid}, mmtype={mmtype}')
  394. class MMGenLabel(str,Hilite,InitErrors):
  395. color = 'pink'
  396. allowed = []
  397. forbidden = []
  398. max_len = 0
  399. min_len = 0
  400. max_screen_width = 0 # if != 0, overrides max_len
  401. desc = 'label'
  402. def __new__(cls,s,msg=None):
  403. if type(s) == cls:
  404. return s
  405. for k in cls.forbidden,cls.allowed:
  406. assert type(k) == list
  407. for ch in k: assert type(ch) == str and len(ch) == 1
  408. try:
  409. s = s.strip()
  410. for ch in s:
  411. # Allow: (L)etter,(N)umber,(P)unctuation,(S)ymbol,(Z)space
  412. # Disallow: (C)ontrol,(M)combining
  413. # Combining characters create width formatting issues, so disallow them for now
  414. if unicodedata.category(ch)[0] in ('C','M'):
  415. raise ValueError('{!a}: {} characters not allowed'.format(ch,
  416. { 'C':'control', 'M':'combining' }[unicodedata.category(ch)[0]] ))
  417. me = str.__new__(cls,s)
  418. if cls.max_screen_width:
  419. me.screen_width = len(s) + len([1 for ch in s if unicodedata.east_asian_width(ch) in ('F','W')])
  420. assert me.screen_width <= cls.max_screen_width, f'too wide (>{cls.max_screen_width} screen width)'
  421. else:
  422. assert len(s) <= cls.max_len, f'too long (>{cls.max_len} symbols)'
  423. assert len(s) >= cls.min_len, f'too short (<{cls.min_len} symbols)'
  424. if cls.allowed and not set(list(s)).issubset(set(cls.allowed)):
  425. raise ValueError('contains non-allowed symbols: ' + ' '.join(set(list(s)) - set(cls.allowed)) )
  426. if cls.forbidden and any(ch in s for ch in cls.forbidden):
  427. raise ValueError('contains one of these forbidden symbols: ' + ' '.join(cls.forbidden) )
  428. return me
  429. except Exception as e:
  430. return cls.init_fail(e,s)
  431. class MMGenWalletLabel(MMGenLabel):
  432. max_len = 48
  433. desc = 'wallet label'
  434. class TwComment(MMGenLabel):
  435. max_screen_width = 80
  436. desc = 'tracking wallet comment'
  437. exc = BadTwComment
  438. class MMGenTxLabel(MMGenLabel):
  439. max_len = 72
  440. desc = 'transaction label'
  441. class MMGenPWIDString(MMGenLabel):
  442. max_len = 256
  443. min_len = 1
  444. desc = 'password ID string'
  445. forbidden = list(' :/\\')
  446. trunc_ok = False
  447. class IPPort(str,Hilite,InitErrors,MMGenObject):
  448. color = 'yellow'
  449. width = 0
  450. trunc_ok = False
  451. min_len = 9 # 0.0.0.0:0
  452. max_len = 21 # 255.255.255.255:65535
  453. def __new__(cls,s):
  454. if type(s) == cls:
  455. return s
  456. try:
  457. m = re.fullmatch(r'{q}\.{q}\.{q}\.{q}:(\d{{1,10}})'.format(q=r'([0-9]{1,3})'),s)
  458. assert m is not None, f'{s!r}: invalid IP:HOST specifier'
  459. for e in m.groups():
  460. if len(e) != 1 and e[0] == '0':
  461. raise ValueError(f'{e}: leading zeroes not permitted in dotted decimal element or port number')
  462. res = [int(e) for e in m.groups()]
  463. for e in res[:4]:
  464. assert e <= 255, f'{e}: dotted decimal element > 255'
  465. assert res[4] <= 65535, f'{res[4]}: port number > 65535'
  466. me = str.__new__(cls,s)
  467. me.ip = '{}.{}.{}.{}'.format(*res)
  468. me.ip_num = sum( res[i] * ( 2 ** (-(i-3)*8) ) for i in range(4) )
  469. me.port = res[4]
  470. return me
  471. except Exception as e:
  472. return cls.init_fail(e,s)
  473. from collections import namedtuple
  474. ati = namedtuple('addrtype_info',
  475. ['name','pubkey_type','compressed','gen_method','addr_fmt','wif_label','extra_attrs','desc'])
  476. class MMGenAddrType(str,Hilite,InitErrors,MMGenObject):
  477. width = 1
  478. trunc_ok = False
  479. color = 'blue'
  480. name = ImmutableAttr(str)
  481. pubkey_type = ImmutableAttr(str)
  482. compressed = ImmutableAttr(bool,set_none_ok=True)
  483. gen_method = ImmutableAttr(str,set_none_ok=True)
  484. addr_fmt = ImmutableAttr(str,set_none_ok=True)
  485. wif_label = ImmutableAttr(str,set_none_ok=True)
  486. extra_attrs = ImmutableAttr(tuple,set_none_ok=True)
  487. desc = ImmutableAttr(str)
  488. mmtypes = {
  489. 'L': ati('legacy', 'std', False,'p2pkh', 'p2pkh', 'wif', (), 'Legacy uncompressed address'),
  490. 'C': ati('compressed','std', True, 'p2pkh', 'p2pkh', 'wif', (), 'Compressed P2PKH address'),
  491. 'S': ati('segwit', 'std', True, 'segwit', 'p2sh', 'wif', (), 'Segwit P2SH-P2WPKH address'),
  492. 'B': ati('bech32', 'std', True, 'bech32', 'bech32', 'wif', (), 'Native Segwit (Bech32) address'),
  493. 'E': ati('ethereum', 'std', False,'ethereum','ethereum','privkey', ('wallet_passwd',),'Ethereum address'),
  494. 'Z': ati('zcash_z','zcash_z',False,'zcash_z', 'zcash_z', 'wif', ('viewkey',), 'Zcash z-address'),
  495. 'M': ati('monero', 'monero', False,'monero', 'monero', 'spendkey',('viewkey','wallet_passwd'),'Monero address'),
  496. }
  497. def __new__(cls,proto,id_str,errmsg=None):
  498. if isinstance(id_str,cls):
  499. return id_str
  500. try:
  501. for k,v in cls.mmtypes.items():
  502. if id_str in (k,v.name):
  503. if id_str == v.name:
  504. id_str = k
  505. me = str.__new__(cls,id_str)
  506. for k in v._fields:
  507. setattr(me,k,getattr(v,k))
  508. if me not in proto.mmtypes + ('P',):
  509. raise ValueError(f'{me.name!r}: invalid address type for {proto.name} protocol')
  510. me.proto = proto
  511. return me
  512. raise ValueError(f'{id_str}: unrecognized address type for protocol {proto.name}')
  513. except Exception as e:
  514. return cls.init_fail( e,
  515. f"{errmsg or ''}{id_str!r}: invalid value for {cls.__name__} ({e!s})",
  516. preformat = True )
  517. @classmethod
  518. def get_names(cls):
  519. return [v.name for v in cls.mmtypes.values()]
  520. class MMGenPasswordType(MMGenAddrType):
  521. mmtypes = {
  522. 'P': ati('password', 'password', None, None, None, None, None, 'Password generated from MMGen seed')
  523. }