obj.py 29 KB

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