obj.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2019 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,unicodedata
  22. from decimal import *
  23. from string import hexdigits,ascii_letters,digits
  24. if os.getenv('MMGEN_DEBUG') or os.getenv('MMGEN_TEST_SUITE') or os.getenv('MMGEN_TRACEBACK'):
  25. from mmgen.devtools import *
  26. else:
  27. class MMGenObject(object): pass
  28. from mmgen.color import *
  29. from mmgen.exception import *
  30. def is_mmgen_seed_id(s): return SeedID(sid=s,on_fail='silent')
  31. def is_mmgen_idx(s): return AddrIdx(s,on_fail='silent')
  32. def is_mmgen_id(s): return MMGenID(s,on_fail='silent')
  33. def is_coin_addr(s): return CoinAddr(s,on_fail='silent')
  34. def is_addrlist_id(s): return AddrListID(s,on_fail='silent')
  35. def is_tw_label(s): return TwLabel(s,on_fail='silent')
  36. def is_wif(s): return WifKey(s,on_fail='silent')
  37. def is_viewkey(s): return ViewKey(s,on_fail='silent')
  38. def is_seed_split_specifier(s): return SeedSplitSpecifier(s,on_fail='silent')
  39. def truncate_str(s,width): # width = screen width
  40. wide_count = 0
  41. for i in range(len(s)):
  42. wide_count += unicodedata.east_asian_width(s[i]) in ('F','W')
  43. if wide_count + i >= width:
  44. return s[:i] + ('',' ')[
  45. unicodedata.east_asian_width(s[i]) in ('F','W')
  46. and wide_count + i == width]
  47. else: # pad the string to width if necessary
  48. return s + ' '*(width-len(s)-wide_count)
  49. # dict that keeps a list of keys for efficient lookup by index
  50. class IndexedDict(dict):
  51. def __init__(self,*args,**kwargs):
  52. if args or kwargs:
  53. self.die('initializing values via constructor')
  54. self.__keylist = []
  55. return dict.__init__(self,*args,**kwargs)
  56. def __setitem__(self,key,value):
  57. if key in self:
  58. self.die('reassignment to existing key')
  59. self.__keylist.append(key)
  60. return dict.__setitem__(self,key,value)
  61. @property
  62. def keys(self):
  63. return self.__keylist
  64. def key(self,idx):
  65. return self.__keylist[idx]
  66. def __delitem__(self,*args): self.die('item deletion')
  67. def move_to_end(self,*args): self.die('item moving')
  68. def clear(self,*args): self.die('clearing')
  69. def update(self,*args): self.die('updating')
  70. def die(self,desc):
  71. raise NotImplementedError('{} not implemented for type {}'.format(desc,type(self).__name__))
  72. class MMGenList(list,MMGenObject): pass
  73. class MMGenDict(dict,MMGenObject): pass
  74. class AddrListList(list,MMGenObject): pass
  75. class InitErrors(object):
  76. on_fail='die'
  77. @classmethod
  78. def arg_chk(cls,on_fail):
  79. cls.on_fail = on_fail
  80. assert on_fail in ('die','return','silent','raise'),(
  81. "'{}': invalid value for 'on_fail' in class {}".format(on_fail,cls.__name__) )
  82. @classmethod
  83. def init_fail(cls,e,m,e2=None,m2=None,objname=None,preformat=False):
  84. if preformat:
  85. errmsg = m
  86. else:
  87. fs = "{!r}: value cannot be converted to {} {}({})"
  88. e2_fmt = '({}) '.format(e2.args[0]) if e2 else ''
  89. errmsg = fs.format(m,objname or cls.__name__,e2_fmt,e.args[0])
  90. if m2: errmsg = '{!r}\n{}'.format(m2,errmsg)
  91. from mmgen.globalvars import g
  92. from mmgen.util import die,msg
  93. if cls.on_fail == 'silent':
  94. return None # TODO: return False instead?
  95. elif cls.on_fail == 'return':
  96. if errmsg: msg(errmsg)
  97. return None # TODO: return False instead?
  98. elif g.traceback or cls.on_fail == 'raise':
  99. if hasattr(cls,'exc'):
  100. raise cls.exc(errmsg)
  101. else:
  102. raise
  103. elif cls.on_fail == 'die':
  104. die(1,errmsg)
  105. class Hilite(object):
  106. color = 'red'
  107. color_always = False
  108. width = 0
  109. trunc_ok = True
  110. dtype = str
  111. @classmethod
  112. # 'width' is screen width (greater than len(s) for CJK strings)
  113. # 'append_chars' and 'encl' must consist of single-width chars only
  114. def fmtc(cls,s,width=None,color=False,encl='',trunc_ok=None,
  115. center=False,nullrepl='',append_chars='',append_color=False):
  116. if cls.dtype == bytes: s = s.decode()
  117. s_wide_count = len([1 for ch in s if unicodedata.east_asian_width(ch) in ('F','W')])
  118. assert isinstance(encl,str) and len(encl) in (0,2),"'encl' must be 2-character str"
  119. a,b = list(encl) if encl else ('','')
  120. add_len = len(a) + len(b) + len(append_chars)
  121. if width == None: width = cls.width
  122. if trunc_ok == None: trunc_ok = cls.trunc_ok
  123. assert width >= 2 + add_len,( # 2 because CJK
  124. "'{!r}': invalid width ({}) (width must be at least 2)".format(s,width))
  125. if len(s) + s_wide_count + add_len > width:
  126. assert trunc_ok, "If 'trunc_ok' is false, 'width' must be >= screen width of string"
  127. s = truncate_str(s,width-add_len)
  128. if s == '' and nullrepl:
  129. s = nullrepl.center(width)
  130. else:
  131. s = a+s+b
  132. if center: s = s.center(width)
  133. if append_chars:
  134. return cls.colorize(s,color=color) + \
  135. cls.colorize(append_chars.ljust(width-len(s)-s_wide_count),color=append_color)
  136. else:
  137. return cls.colorize(s.ljust(width-s_wide_count),color=color)
  138. @classmethod
  139. def colorize(cls,s,color=True):
  140. if cls.dtype == bytes: s = s.decode()
  141. k = color if type(color) is str else cls.color # hack: override color with str value
  142. return globals()[k](s) if (color or cls.color_always) else s
  143. def fmt(self,*args,**kwargs):
  144. assert args == () # forbid invocation w/o keywords
  145. return self.fmtc(self,*args,**kwargs)
  146. @classmethod
  147. def hlc(cls,s,color=True,encl=''):
  148. if encl:
  149. assert isinstance(encl,str) and len(encl) == 2, "'encl' must be 2-character str"
  150. s = encl[0] + s + encl[1]
  151. return cls.colorize(s,color=color)
  152. def hl(self,*args,**kwargs):
  153. assert args == () # forbid invocation w/o keywords
  154. return self.hlc(self,*args,**kwargs)
  155. def __str__(self):
  156. return self.colorize(self,color=False)
  157. class Str(str,Hilite): pass
  158. class Int(int,Hilite): pass
  159. # For attrs that are always present in the data instance
  160. # Reassignment and deletion forbidden
  161. class MMGenImmutableAttr(object): # Descriptor
  162. def __init__(self,name,dtype,typeconv=True,no_type_check=False):
  163. self.typeconv = typeconv
  164. self.no_type_check = no_type_check
  165. assert isinstance(dtype,(str,type,type(None))),'{!r}: invalid dtype arg'.format(dtype)
  166. self.name = name
  167. self.dtype = dtype
  168. def __get__(self,instance,owner):
  169. return instance.__dict__[self.name]
  170. # forbid all reassignment
  171. def set_attr_ok(self,instance):
  172. return not self.name in instance.__dict__
  173. # return not hasattr(instance,self.name)
  174. def __set__(self,instance,value):
  175. if not self.set_attr_ok(instance):
  176. m = "Attribute '{}' of {} instance cannot be reassigned"
  177. raise AttributeError(m.format(self.name,type(instance)))
  178. if self.typeconv: # convert type
  179. instance.__dict__[self.name] = \
  180. globals()[self.dtype](value,on_fail='raise') if type(self.dtype) == str else self.dtype(value)
  181. else: # check type
  182. if type(value) == self.dtype or self.no_type_check:
  183. instance.__dict__[self.name] = value
  184. else:
  185. m = "Attribute '{}' of {} instance must of type {}"
  186. raise TypeError(m.format(self.name,type(instance),self.dtype))
  187. def __delete__(self,instance):
  188. m = "Atribute '{}' of {} instance cannot be deleted"
  189. raise AttributeError(m.format(self.name,type(instance)))
  190. # For attrs that might not be present in the data instance
  191. # Reassignment or deletion allowed if specified
  192. class MMGenListItemAttr(MMGenImmutableAttr): # Descriptor
  193. def __init__(self,name,dtype,typeconv=True,reassign_ok=False,delete_ok=False):
  194. self.reassign_ok = reassign_ok
  195. self.delete_ok = delete_ok
  196. MMGenImmutableAttr.__init__(self,name,dtype,typeconv=typeconv)
  197. # return None if attribute doesn't exist
  198. def __get__(self,instance,owner):
  199. try: return instance.__dict__[self.name]
  200. except: return None
  201. def set_attr_ok(self,instance):
  202. return getattr(instance,self.name) == None or self.reassign_ok
  203. def __delete__(self,instance):
  204. if self.delete_ok:
  205. if self.name in instance.__dict__:
  206. del instance.__dict__[self.name]
  207. else:
  208. MMGenImmutableAttr.__delete__(self,instance)
  209. class MMGenListItem(MMGenObject):
  210. valid_attrs = None
  211. valid_attrs_extra = set()
  212. def __init__(self,*args,**kwargs):
  213. if self.valid_attrs == None:
  214. type(self).valid_attrs = (
  215. ( {e for e in dir(self) if e[:2] != '__'} | self.valid_attrs_extra ) -
  216. {'pfmt','pmsg','pdie','valid_attrs','valid_attrs_extra'} )
  217. if args:
  218. raise ValueError('Non-keyword args not allowed')
  219. for k in kwargs:
  220. if kwargs[k] != None:
  221. setattr(self,k,kwargs[k])
  222. # allow only valid attributes to be set
  223. def __setattr__(self,name,value):
  224. if name not in self.valid_attrs:
  225. m = "'{}': no such attribute in class {}"
  226. raise AttributeError(m.format(name,type(self)))
  227. return object.__setattr__(self,name,value)
  228. class MMGenIdx(int,InitErrors):
  229. min_val = 1
  230. max_val = None
  231. max_digits = None
  232. def __new__(cls,num,on_fail='die'):
  233. cls.arg_chk(on_fail)
  234. try:
  235. assert type(num) is not float,'is float'
  236. me = int.__new__(cls,num)
  237. if cls.max_digits:
  238. assert len(str(me)) <= cls.max_digits,'has more than {} digits'.format(cls.max_digits)
  239. if cls.max_val:
  240. assert me <= cls.max_val,'is greater than {}'.format(cls.max_val)
  241. assert me >= cls.min_val,'is less than {}'.format(cls.min_val)
  242. return me
  243. except Exception as e:
  244. return cls.init_fail(e,num)
  245. class SeedShareIdx(MMGenIdx): max_val = 1024
  246. class SeedShareCount(SeedShareIdx): min_val = 2
  247. class MasterShareIdx(MMGenIdx): max_val = 1024
  248. class AddrIdx(MMGenIdx): max_digits = 7
  249. class AddrIdxList(list,InitErrors,MMGenObject):
  250. max_len = 1000000
  251. def __init__(self,fmt_str=None,idx_list=None,on_fail='die',sep=','):
  252. type(self).arg_chk(on_fail)
  253. try:
  254. if idx_list:
  255. return list.__init__(self,sorted({AddrIdx(i,on_fail='raise') for i in idx_list}))
  256. elif fmt_str:
  257. ret = []
  258. for i in (fmt_str.split(sep)):
  259. j = i.split('-')
  260. if len(j) == 1:
  261. idx = AddrIdx(i,on_fail='raise')
  262. if not idx: break
  263. ret.append(idx)
  264. elif len(j) == 2:
  265. beg = AddrIdx(j[0],on_fail='raise')
  266. if not beg: break
  267. end = AddrIdx(j[1],on_fail='raise')
  268. if not beg: break
  269. if end < beg: break
  270. ret.extend([AddrIdx(x,on_fail='raise') for x in range(beg,end+1)])
  271. else: break
  272. else:
  273. return list.__init__(self,sorted(set(ret))) # fell off end of loop - success
  274. raise ValueError("{!r}: invalid range".format(i))
  275. except Exception as e:
  276. return type(self).init_fail(e,idx_list or fmt_str)
  277. class MMGenRange(tuple,InitErrors,MMGenObject):
  278. min_idx = None
  279. max_idx = None
  280. def __new__(cls,*args,on_fail='die'):
  281. cls.arg_chk(on_fail)
  282. try:
  283. if len(args) == 1:
  284. s = args[0]
  285. if type(s) == cls: return s
  286. assert isinstance(s,str),'not a string or string subclass'
  287. ss = s.split('-',1)
  288. first = int(ss[0])
  289. last = int(ss.pop())
  290. else:
  291. s = repr(args) # needed if exception occurs
  292. assert len(args) == 2,'one format string arg or two start,stop args required'
  293. first,last = args
  294. assert first <= last, 'start of range greater than end of range'
  295. if cls.min_idx is not None:
  296. assert first >= cls.min_idx, 'start of range < {:,}'.format(cls.min_idx)
  297. if cls.max_idx is not None:
  298. assert last <= cls.max_idx, 'end of range > {:,}'.format(cls.max_idx)
  299. return tuple.__new__(cls,(first,last))
  300. except Exception as e:
  301. return cls.init_fail(e,s)
  302. @property
  303. def first(self):
  304. return self[0]
  305. @property
  306. def last(self):
  307. return self[1]
  308. def iterate(self):
  309. return range(self[0],self[1]+1)
  310. @property
  311. def items(self):
  312. return list(self.iterate())
  313. class SubSeedIdxRange(MMGenRange):
  314. min_idx = 1
  315. max_idx = 1000000
  316. class UnknownCoinAmt(Decimal): pass
  317. class BTCAmt(Decimal,Hilite,InitErrors):
  318. color = 'yellow'
  319. max_prec = 8
  320. max_amt = 21000000
  321. satoshi = Decimal('0.00000001')
  322. min_coin_unit = satoshi
  323. amt_fs = '4.8'
  324. units = ('satoshi',)
  325. forbidden_types = (float,int)
  326. # NB: 'from_decimal' rounds down to precision of 'min_coin_unit'
  327. def __new__(cls,num,from_unit=None,from_decimal=False,on_fail='die'):
  328. if type(num) == cls: return num
  329. cls.arg_chk(on_fail)
  330. try:
  331. if from_unit:
  332. assert from_unit in cls.units,(
  333. "'{}': unrecognized denomination for {}".format(from_unit,cls.__name__))
  334. assert type(num) == int,'value is not an integer'
  335. me = Decimal.__new__(cls,num * getattr(cls,from_unit))
  336. elif from_decimal:
  337. assert type(num) == Decimal,(
  338. "number is not of type Decimal (type is {!r})".format(type(num).__name__))
  339. me = Decimal.__new__(cls,num).quantize(cls.min_coin_unit)
  340. else:
  341. for t in cls.forbidden_types:
  342. assert type(num) is not t,"number is of forbidden type '{}'".format(t.__name__)
  343. me = Decimal.__new__(cls,str(num))
  344. assert me.normalize().as_tuple()[-1] >= -cls.max_prec,'too many decimal places in coin amount'
  345. if cls.max_amt:
  346. assert me <= cls.max_amt,'{}: coin amount too large (>{})'.format(me,cls.max_amt)
  347. assert me >= 0,'coin amount cannot be negative'
  348. return me
  349. except Exception as e:
  350. return cls.init_fail(e,num)
  351. def toSatoshi(self):
  352. return int(Decimal(self) // self.satoshi)
  353. def to_unit(self,unit,show_decimal=False):
  354. ret = Decimal(self) // getattr(self,unit)
  355. if show_decimal and ret < 1:
  356. return '{:.8f}'.format(ret).rstrip('0')
  357. return int(ret)
  358. @classmethod
  359. def fmtc(cls):
  360. raise NotImplementedError
  361. def fmt(self,fs=None,color=False,suf='',prec=1000):
  362. if fs == None: fs = self.amt_fs
  363. s = str(int(self)) if int(self) == self else self.normalize().__format__('f')
  364. if '.' in fs:
  365. p1,p2 = list(map(int,fs.split('.',1)))
  366. ss = s.split('.',1)
  367. if len(ss) == 2:
  368. a,b = ss
  369. ret = a.rjust(p1) + '.' + ((b+suf).ljust(p2+len(suf)))[:prec]
  370. else:
  371. ret = s.rjust(p1) + suf + (' ' * (p2+1))[:prec+1-len(suf)]
  372. else:
  373. ret = s.ljust(int(fs))
  374. return self.colorize(ret,color=color)
  375. def hl(self,color=True):
  376. return self.__str__(color=color)
  377. def __str__(self,color=False): # format simply, no exponential notation
  378. return self.colorize(
  379. str(int(self)) if int(self) == self else
  380. self.normalize().__format__('f'),
  381. color=color)
  382. def __repr__(self):
  383. return "{}('{}')".format(type(self).__name__,self.__str__())
  384. def __add__(self,other):
  385. return type(self)(Decimal.__add__(self,other))
  386. __radd__ = __add__
  387. def __sub__(self,other):
  388. return type(self)(Decimal.__sub__(self,other))
  389. def __mul__(self,other):
  390. return type(self)('{:0.8f}'.format(Decimal.__mul__(self,Decimal(other))))
  391. def __div__(self,other):
  392. return type(self)('{:0.8f}'.format(Decimal.__div__(self,Decimal(other))))
  393. def __neg__(self,other):
  394. return type(self)(Decimal.__neg__(self,other))
  395. class BCHAmt(BTCAmt): pass
  396. class B2XAmt(BTCAmt): pass
  397. class LTCAmt(BTCAmt): max_amt = 84000000
  398. class XMRAmt(BTCAmt): min_coin_unit = Decimal('0.000000000001')
  399. from mmgen.altcoins.eth.obj import ETHAmt,ETHNonce
  400. class CoinAddr(str,Hilite,InitErrors,MMGenObject):
  401. color = 'cyan'
  402. hex_width = 40
  403. width = 1
  404. trunc_ok = False
  405. def __new__(cls,s,on_fail='die'):
  406. if type(s) == cls: return s
  407. cls.arg_chk(on_fail)
  408. from mmgen.globalvars import g
  409. try:
  410. assert set(s) <= set(ascii_letters+digits),'contains non-alphanumeric characters'
  411. me = str.__new__(cls,s)
  412. va = g.proto.verify_addr(s,hex_width=cls.hex_width,return_dict=True)
  413. assert va,'failed verification'
  414. me.addr_fmt = va['format']
  415. me.hex = va['hex']
  416. return me
  417. except Exception as e:
  418. return cls.init_fail(e,s,objname='{} address'.format(g.proto.__name__))
  419. @classmethod
  420. def fmtc(cls,s,**kwargs):
  421. # True -> 'cyan': use the str value override hack
  422. if 'color' in kwargs and kwargs['color'] == True:
  423. kwargs['color'] = cls.color
  424. if not 'width' in kwargs: kwargs['width'] = cls.width
  425. if kwargs['width'] < len(s):
  426. s = s[:kwargs['width']-2] + '..'
  427. return Hilite.fmtc(s,**kwargs)
  428. def is_for_chain(self,chain):
  429. from mmgen.globalvars import g
  430. if g.proto.__name__[:8] == 'Ethereum':
  431. return True
  432. def pfx_ok(pfx):
  433. if type(pfx) == tuple:
  434. if self[0] in pfx: return True
  435. elif self[:len(pfx)] == pfx: return True
  436. return False
  437. proto = g.proto.get_protocol_by_chain(chain)
  438. vn = proto.addr_ver_num
  439. if self.addr_fmt == 'bech32':
  440. return self[:len(proto.bech32_hrp)] == proto.bech32_hrp
  441. elif self.addr_fmt == 'p2sh' and 'p2sh2' in vn:
  442. return pfx_ok(vn['p2sh'][1]) or pfx_ok(vn['p2sh2'][1])
  443. else:
  444. return pfx_ok(vn[self.addr_fmt][1])
  445. class TokenAddr(CoinAddr):
  446. color = 'blue'
  447. class ViewKey(object):
  448. def __new__(cls,s,on_fail='die'):
  449. from mmgen.globalvars import g
  450. if g.proto.name == 'zcash':
  451. return ZcashViewKey.__new__(ZcashViewKey,s,on_fail)
  452. elif g.proto.name == 'monero':
  453. return MoneroViewKey.__new__(MoneroViewKey,s,on_fail)
  454. else:
  455. raise ValueError('{}: protocol does not support view keys'.format(g.proto.name.capitalize()))
  456. class ZcashViewKey(CoinAddr): hex_width = 128
  457. class SeedID(str,Hilite,InitErrors):
  458. color = 'blue'
  459. width = 8
  460. trunc_ok = False
  461. def __new__(cls,seed=None,sid=None,on_fail='die'):
  462. if type(sid) == cls: return sid
  463. cls.arg_chk(on_fail)
  464. try:
  465. if seed:
  466. from mmgen.seed import SeedBase
  467. assert isinstance(seed,SeedBase),'not a subclass of SeedBase'
  468. from mmgen.util import make_chksum_8
  469. return str.__new__(cls,make_chksum_8(seed.data))
  470. elif sid:
  471. assert set(sid) <= set(hexdigits.upper()),'not uppercase hex digits'
  472. assert len(sid) == cls.width,'not {} characters wide'.format(cls.width)
  473. return str.__new__(cls,sid)
  474. raise ValueError('no arguments provided')
  475. except Exception as e:
  476. return cls.init_fail(e,seed or sid)
  477. class SubSeedIdx(str,Hilite,InitErrors):
  478. color = 'red'
  479. trunc_ok = False
  480. def __new__(cls,s,on_fail='die'):
  481. if type(s) == cls: return s
  482. cls.arg_chk(on_fail)
  483. try:
  484. assert isinstance(s,str),'not a string or string subclass'
  485. idx = s[:-1] if s[-1] in 'SsLl' else s
  486. from mmgen.util import is_int
  487. assert is_int(idx),"valid format: an integer, plus optional letter 'S','s','L' or 'l'"
  488. idx = int(idx)
  489. assert idx >= SubSeedIdxRange.min_idx, 'subseed index < {:,}'.format(SubSeedIdxRange.min_idx)
  490. assert idx <= SubSeedIdxRange.max_idx, 'subseed index > {:,}'.format(SubSeedIdxRange.max_idx)
  491. sstype,ltr = ('short','S') if s[-1] in 'Ss' else ('long','L')
  492. me = str.__new__(cls,str(idx)+ltr)
  493. me.idx = idx
  494. me.type = sstype
  495. return me
  496. except Exception as e:
  497. return cls.init_fail(e,s)
  498. class MMGenID(str,Hilite,InitErrors,MMGenObject):
  499. color = 'orange'
  500. width = 0
  501. trunc_ok = False
  502. def __new__(cls,s,on_fail='die'):
  503. cls.arg_chk(on_fail)
  504. from mmgen.globalvars import g
  505. try:
  506. ss = str(s).split(':')
  507. assert len(ss) in (2,3),'not 2 or 3 colon-separated items'
  508. t = MMGenAddrType((ss[1],g.proto.dfl_mmtype)[len(ss)==2],on_fail='raise')
  509. me = str.__new__(cls,'{}:{}:{}'.format(ss[0],t,ss[-1]))
  510. me.sid = SeedID(sid=ss[0],on_fail='raise')
  511. me.idx = AddrIdx(ss[-1],on_fail='raise')
  512. me.mmtype = t
  513. assert t in g.proto.mmtypes,'{}: invalid address type for {}'.format(t,g.proto.__name__)
  514. me.al_id = str.__new__(AddrListID,me.sid+':'+me.mmtype) # checks already done
  515. me.sort_key = '{}:{}:{:0{w}}'.format(me.sid,me.mmtype,me.idx,w=me.idx.max_digits)
  516. return me
  517. except Exception as e:
  518. return cls.init_fail(e,s)
  519. class TwMMGenID(str,Hilite,InitErrors,MMGenObject):
  520. color = 'orange'
  521. width = 0
  522. trunc_ok = False
  523. def __new__(cls,s,on_fail='die'):
  524. if type(s) == cls: return s
  525. cls.arg_chk(on_fail)
  526. ret = None
  527. try:
  528. ret = MMGenID(s,on_fail='raise')
  529. sort_key,idtype = ret.sort_key,'mmgen'
  530. except Exception as e:
  531. try:
  532. from mmgen.globalvars import g
  533. assert s.split(':',1)[0] == g.proto.base_coin.lower(),(
  534. "not a string beginning with the prefix '{}:'".format(g.proto.base_coin.lower()))
  535. assert set(s[4:]) <= set(ascii_letters+digits),'contains non-alphanumeric characters'
  536. assert len(s) > 4,'not more that four characters long'
  537. ret,sort_key,idtype = str(s),'z_'+s,'non-mmgen'
  538. except Exception as e2:
  539. return cls.init_fail(e,s,e2=e2)
  540. me = str.__new__(cls,ret)
  541. me.obj = ret
  542. me.sort_key = sort_key
  543. me.type = idtype
  544. return me
  545. # non-displaying container for TwMMGenID,TwComment
  546. class TwLabel(str,InitErrors,MMGenObject):
  547. def __new__(cls,s,on_fail='die'):
  548. if type(s) == cls: return s
  549. cls.arg_chk(on_fail)
  550. try:
  551. ss = s.split(None,1)
  552. mmid = TwMMGenID(ss[0],on_fail='raise')
  553. comment = TwComment(ss[1] if len(ss) == 2 else '',on_fail='raise')
  554. me = str.__new__(cls,'{}{}'.format(mmid,' {}'.format(comment) if comment else ''))
  555. me.mmid = mmid
  556. me.comment = comment
  557. return me
  558. except Exception as e:
  559. return cls.init_fail(e,s)
  560. class HexStr(str,Hilite,InitErrors):
  561. color = 'red'
  562. width = None
  563. hexcase = 'lower'
  564. trunc_ok = False
  565. dtype = str
  566. def __new__(cls,s,on_fail='die',case=None):
  567. if type(s) == cls: return s
  568. cls.arg_chk(on_fail)
  569. if case == None: case = cls.hexcase
  570. try:
  571. assert isinstance(s,str),'not a string or string subclass'
  572. assert case in ('upper','lower'),"'{}' incorrect case specifier".format(case)
  573. assert set(s) <= set(getattr(hexdigits,case)()),'not {}case hexadecimal symbols'.format(case)
  574. assert not len(s) % 2,'odd-length string'
  575. if cls.width:
  576. assert len(s) == cls.width,'Value is not {} characters wide'.format(cls.width)
  577. return cls.dtype.__new__(cls,s)
  578. except Exception as e:
  579. return cls.init_fail(e,s)
  580. class CoinTxID(HexStr): color,width,hexcase = 'purple',64,'lower'
  581. class WalletPassword(HexStr): color,width,hexcase = 'blue',32,'lower'
  582. class MoneroViewKey(HexStr): color,width,hexcase = 'cyan',64,'lower'
  583. class MMGenTxID(HexStr): color,width,hexcase = 'red',6,'upper'
  584. class WifKey(str,Hilite,InitErrors):
  585. width = 53
  586. color = 'blue'
  587. def __new__(cls,s,on_fail='die'):
  588. if type(s) == cls: return s
  589. cls.arg_chk(on_fail)
  590. try:
  591. assert set(s) <= set(ascii_letters+digits),'not an ascii alphanumeric string'
  592. from mmgen.globalvars import g
  593. g.proto.wif2hex(s) # raises exception on error
  594. return str.__new__(cls,s)
  595. except Exception as e:
  596. return cls.init_fail(e,s)
  597. class PubKey(HexStr,MMGenObject): # TODO: add some real checks
  598. def __new__(cls,s,compressed,on_fail='die'):
  599. try:
  600. assert type(compressed) == bool,"'compressed' must be of type bool"
  601. except Exception as e:
  602. return cls.init_fail(e,s)
  603. me = HexStr.__new__(cls,s,case='lower',on_fail=on_fail)
  604. if me:
  605. me.compressed = compressed
  606. return me
  607. class PrivKey(str,Hilite,InitErrors,MMGenObject):
  608. color = 'red'
  609. width = 64
  610. trunc_ok = False
  611. compressed = MMGenImmutableAttr('compressed',bool,typeconv=False)
  612. wif = MMGenImmutableAttr('wif',WifKey,typeconv=False)
  613. # initialize with (priv_bin,compressed), WIF or self
  614. def __new__(cls,s=None,compressed=None,wif=None,pubkey_type=None,on_fail='die'):
  615. from mmgen.globalvars import g
  616. if type(s) == cls: return s
  617. cls.arg_chk(on_fail)
  618. if wif:
  619. try:
  620. assert s == None,"'wif' and key hex args are mutually exclusive"
  621. assert set(wif) <= set(ascii_letters+digits),'not an ascii alphanumeric string'
  622. w2h = g.proto.wif2hex(wif) # raises exception on error
  623. me = str.__new__(cls,w2h['hex'])
  624. me.compressed = w2h['compressed']
  625. me.pubkey_type = w2h['pubkey_type']
  626. me.wif = str.__new__(WifKey,wif) # check has been done
  627. me.orig_hex = None
  628. return me
  629. except Exception as e:
  630. return cls.init_fail(e,s,objname='{} WIF key'.format(g.coin))
  631. else:
  632. try:
  633. assert s,'private key hex data missing'
  634. assert compressed is not None, "'compressed' arg missing"
  635. assert pubkey_type is not None,"'pubkey_type' arg missing"
  636. assert type(compressed) == bool,"{!r}: 'compressed' not of type 'bool'".format(compressed)
  637. assert len(s) == cls.width // 2,'key length must be {}'.format(cls.width // 2)
  638. if pubkey_type == 'password': # skip WIF creation and pre-processing for passwds
  639. me = str.__new__(cls,s.hex())
  640. else:
  641. me = str.__new__(cls,g.proto.preprocess_key(s.hex(),pubkey_type))
  642. me.wif = WifKey(g.proto.hex2wif(me,pubkey_type,compressed),on_fail='raise')
  643. me.compressed = compressed
  644. me.pubkey_type = pubkey_type
  645. me.orig_hex = s.hex() # save the non-preprocessed key
  646. return me
  647. except Exception as e:
  648. return cls.init_fail(e,s)
  649. class AddrListID(str,Hilite,InitErrors,MMGenObject):
  650. width = 10
  651. trunc_ok = False
  652. color = 'yellow'
  653. def __new__(cls,sid,mmtype,on_fail='die'):
  654. cls.arg_chk(on_fail)
  655. try:
  656. assert type(sid) == SeedID,"{!r} not a SeedID instance".format(sid)
  657. if not isinstance(mmtype,(MMGenAddrType,MMGenPasswordType)):
  658. m = '{!r}: not an instance of MMGenAddrType or MMGenPasswordType'.format(mmtype)
  659. raise ValueError(m.format(mmtype))
  660. me = str.__new__(cls,sid+':'+mmtype)
  661. me.sid = sid
  662. me.mmtype = mmtype
  663. return me
  664. except Exception as e:
  665. return cls.init_fail(e,'sid={}, mmtype={}'.format(sid,mmtype))
  666. class MMGenLabel(str,Hilite,InitErrors):
  667. color = 'pink'
  668. allowed = []
  669. forbidden = []
  670. max_len = 0
  671. min_len = 0
  672. max_screen_width = 0 # if != 0, overrides max_len
  673. desc = 'label'
  674. def __new__(cls,s,on_fail='die',msg=None):
  675. if type(s) == cls: return s
  676. cls.arg_chk(on_fail)
  677. for k in cls.forbidden,cls.allowed:
  678. assert type(k) == list
  679. for ch in k: assert type(ch) == str and len(ch) == 1
  680. try:
  681. s = s.strip()
  682. for ch in s:
  683. # Allow: (L)etter,(N)umber,(P)unctuation,(S)ymbol,(Z)space
  684. # Disallow: (C)ontrol,(M)combining
  685. # Combining characters create width formatting issues, so disallow them for now
  686. if unicodedata.category(ch)[0] in 'CM':
  687. t = { 'C':'control', 'M':'combining' }[unicodedata.category(ch)[0]]
  688. raise ValueError('{}: {} characters not allowed'.format(ascii(ch),t))
  689. me = str.__new__(cls,s)
  690. if cls.max_screen_width:
  691. me.screen_width = len(s) + len([1 for ch in s if unicodedata.east_asian_width(ch) in ('F','W')])
  692. assert me.screen_width <= cls.max_screen_width,(
  693. 'too wide (>{} screen width)'.format(cls.max_screen_width))
  694. else:
  695. assert len(s) <= cls.max_len, 'too long (>{} symbols)'.format(cls.max_len)
  696. assert len(s) >= cls.min_len, 'too short (<{} symbols)'.format(cls.min_len)
  697. assert not cls.allowed or set(list(s)).issubset(set(cls.allowed)),\
  698. 'contains non-allowed symbols: {}'.format(' '.join(set(list(s)) - set(cls.allowed)))
  699. assert not cls.forbidden or not any(ch in s for ch in cls.forbidden),\
  700. "contains one of these forbidden symbols: '{}'".format("', '".join(cls.forbidden))
  701. return me
  702. except Exception as e:
  703. return cls.init_fail(e,s)
  704. class MMGenWalletLabel(MMGenLabel):
  705. max_len = 48
  706. desc = 'wallet label'
  707. class TwComment(MMGenLabel):
  708. max_screen_width = 80
  709. desc = 'tracking wallet comment'
  710. exc = BadTwComment
  711. class MMGenTXLabel(MMGenLabel):
  712. max_len = 72
  713. desc = 'transaction label'
  714. class MMGenPWIDString(MMGenLabel):
  715. max_len = 256
  716. min_len = 1
  717. desc = 'password ID string'
  718. forbidden = list(' :/\\')
  719. trunc_ok = False
  720. class SeedSplitSpecifier(str,Hilite,InitErrors,MMGenObject):
  721. color = 'red'
  722. def __new__(cls,s,on_fail='raise'):
  723. if type(s) == cls: return s
  724. cls.arg_chk(on_fail)
  725. try:
  726. arr = s.split(':')
  727. assert len(arr) in (2,3), 'cannot be parsed'
  728. a,b,c = arr if len(arr) == 3 else ['default'] + arr
  729. me = str.__new__(cls,s)
  730. me.id = SeedSplitIDString(a,on_fail=on_fail)
  731. me.idx = SeedShareIdx(b,on_fail=on_fail)
  732. me.count = SeedShareCount(c,on_fail=on_fail)
  733. assert me.idx <= me.count, 'share index greater than share count'
  734. return me
  735. except Exception as e:
  736. return cls.init_fail(e,s)
  737. class SeedSplitIDString(MMGenPWIDString):
  738. desc = 'seed split ID string'
  739. from collections import namedtuple
  740. ati = namedtuple('addrtype_info',
  741. ['name','pubkey_type','compressed','gen_method','addr_fmt','wif_label','extra_attrs','desc'])
  742. class MMGenAddrType(str,Hilite,InitErrors,MMGenObject):
  743. width = 1
  744. trunc_ok = False
  745. color = 'blue'
  746. name = MMGenImmutableAttr('name',str)
  747. pubkey_type = MMGenImmutableAttr('pubkey_type',str)
  748. compressed = MMGenImmutableAttr('compressed',bool)
  749. gen_method = MMGenImmutableAttr('gen_method',str)
  750. addr_fmt = MMGenImmutableAttr('addr_fmt',str)
  751. wif_label = MMGenImmutableAttr('wif_label',str)
  752. extra_attrs = MMGenImmutableAttr('extra_attrs',tuple)
  753. desc = MMGenImmutableAttr('desc',str)
  754. mmtypes = {
  755. 'L': ati('legacy', 'std', False,'p2pkh', 'p2pkh', 'wif', (), 'Legacy uncompressed address'),
  756. 'C': ati('compressed','std', True, 'p2pkh', 'p2pkh', 'wif', (), 'Compressed P2PKH address'),
  757. 'S': ati('segwit', 'std', True, 'segwit', 'p2sh', 'wif', (), 'Segwit P2SH-P2WPKH address'),
  758. 'B': ati('bech32', 'std', True, 'bech32', 'bech32', 'wif', (), 'Native Segwit (Bech32) address'),
  759. 'E': ati('ethereum', 'std', False,'ethereum','ethereum','privkey', ('wallet_passwd',),'Ethereum address'),
  760. 'Z': ati('zcash_z','zcash_z',False,'zcash_z', 'zcash_z', 'wif', ('viewkey',), 'Zcash z-address'),
  761. 'M': ati('monero', 'monero', False,'monero', 'monero', 'spendkey',('viewkey','wallet_passwd'),'Monero address'),
  762. }
  763. def __new__(cls,s,on_fail='die',errmsg=None):
  764. if type(s) == cls: return s
  765. cls.arg_chk(on_fail)
  766. from mmgen.globalvars import g
  767. try:
  768. for k,v in list(cls.mmtypes.items()):
  769. if s in (k,v.name):
  770. if s == v.name: s = k
  771. me = str.__new__(cls,s)
  772. for k in v._fields:
  773. setattr(me,k,getattr(v,k))
  774. assert me in g.proto.mmtypes + ('P',), (
  775. "'{}': invalid address type for {}".format(me.name,g.proto.__name__))
  776. return me
  777. raise ValueError('unrecognized address type')
  778. except Exception as e:
  779. emsg = '{!r}\n'.format(errmsg) if errmsg else ''
  780. m = '{}{!r}: invalid value for {} ({})'.format(emsg,s,cls.__name__,e.args[0])
  781. return cls.init_fail(e,m,preformat=True)
  782. @classmethod
  783. def get_names(cls):
  784. return [v.name for v in cls.mmtypes.values()]
  785. class MMGenPasswordType(MMGenAddrType):
  786. mmtypes = {
  787. 'P': ati('password', 'password', False, None, None, None, (), 'Password generated from MMGen seed')
  788. }