obj.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. #
  4. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  5. # Copyright (C)2013-2018 The MMGen Project <mmgen@tuta.io>
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. """
  20. obj.py: MMGen native classes
  21. """
  22. import sys,os,unicodedata
  23. from decimal import *
  24. from mmgen.color import *
  25. from string import hexdigits,ascii_letters,digits
  26. def is_mmgen_seed_id(s): return SeedID(sid=s,on_fail='silent')
  27. def is_mmgen_idx(s): return AddrIdx(s,on_fail='silent')
  28. def is_mmgen_id(s): return MMGenID(s,on_fail='silent')
  29. def is_coin_addr(s): return CoinAddr(s,on_fail='silent')
  30. def is_addrlist_id(s): return AddrListID(s,on_fail='silent')
  31. def is_tw_label(s): return TwLabel(s,on_fail='silent')
  32. def is_wif(s): return WifKey(s,on_fail='silent')
  33. def is_viewkey(s): return ViewKey(s,on_fail='silent')
  34. def truncate_str(s,width): # width = screen width
  35. wide_count = 0
  36. for i in range(len(s)):
  37. wide_count += unicodedata.east_asian_width(s[i]) in ('F','W')
  38. if wide_count + i >= width:
  39. return s[:i] + ('',' ')[
  40. unicodedata.east_asian_width(s[i]) in ('F','W')
  41. and wide_count + i == width]
  42. else: # pad the string to width if necessary
  43. return s + ' '*(width-len(s)-wide_count)
  44. class MMGenObject(object):
  45. # Pretty-print any object subclassed from MMGenObject, recursing into sub-objects - WIP
  46. def pmsg(self): print(self.pformat())
  47. def pdie(self): print(self.pformat()); sys.exit(0)
  48. def pformat(self,lvl=0):
  49. scalars = (str,unicode,int,float,Decimal)
  50. def do_list(out,e,lvl=0,is_dict=False):
  51. out.append('\n')
  52. for i in e:
  53. el = i if not is_dict else e[i]
  54. if is_dict:
  55. out.append('{s}{:<{l}}'.format(i,s=' '*(4*lvl+8),l=10,l2=8*(lvl+1)+8))
  56. if hasattr(el,'pformat'):
  57. out.append('{:>{l}}{}'.format('',el.pformat(lvl=lvl+1),l=(lvl+1)*8))
  58. elif type(el) in scalars:
  59. if isList(e):
  60. out.append(u'{:>{l}}{:16}\n'.format('',repr(el),l=lvl*8))
  61. else:
  62. out.append(u' {}'.format(repr(el)))
  63. elif isList(el) or isDict(el):
  64. indent = 1 if is_dict else lvl*8+4
  65. out.append(u'{:>{l}}{:16}'.format('','<'+type(el).__name__+'>',l=indent))
  66. if isList(el) and type(el[0]) in scalars: out.append('\n')
  67. do_list(out,el,lvl=lvl+1,is_dict=isDict(el))
  68. else:
  69. out.append(u'{:>{l}}{:16} {}\n'.format('','<'+type(el).__name__+'>',repr(el),l=(lvl*8)+8))
  70. out.append('\n')
  71. if not e: out.append('{}\n'.format(repr(e)))
  72. from collections import OrderedDict
  73. def isDict(obj):
  74. return issubclass(type(obj),dict) or issubclass(type(obj),OrderedDict)
  75. def isList(obj):
  76. return issubclass(type(obj),list) and type(obj) != OrderedDict
  77. def isScalar(obj):
  78. return any(issubclass(type(obj),t) for t in scalars)
  79. # print type(self)
  80. # print dir(self)
  81. # print self.__dict__
  82. # print self.__dict__.keys()
  83. # print self.keys()
  84. out = [u'<{}>{}\n'.format(type(self).__name__,' '+repr(self) if isScalar(self) else '')]
  85. if isList(self) or isDict(self):
  86. do_list(out,self,lvl=lvl,is_dict=isDict(self))
  87. # print repr(self.__dict__.keys())
  88. for k in self.__dict__:
  89. if k in ('_OrderedDict__root','_OrderedDict__map'): continue # exclude these because of recursion
  90. e = getattr(self,k)
  91. if isList(e) or isDict(e):
  92. out.append(u'{:>{l}}{:<10} {:16}'.format('',k,'<'+type(e).__name__+'>',l=(lvl*8)+4))
  93. do_list(out,e,lvl=lvl,is_dict=isDict(e))
  94. elif hasattr(e,'pformat') and type(e) != type:
  95. out.append(u'{:>{l}}{:10} {}'.format('',k,e.pformat(lvl=lvl+1),l=(lvl*8)+4))
  96. else:
  97. out.append(u'{:>{l}}{:<10} {:16} {}\n'.format(
  98. '',k,'<'+type(e).__name__+'>',repr(e),l=(lvl*8)+4))
  99. import re
  100. return re.sub('\n+','\n',''.join(out))
  101. class MMGenList(list,MMGenObject): pass
  102. class MMGenDict(dict,MMGenObject): pass
  103. class AddrListList(list,MMGenObject): pass
  104. class InitErrors(object):
  105. @staticmethod
  106. def arg_chk(cls,on_fail):
  107. assert on_fail in ('die','return','silent','raise'),'arg_chk in class {}'.format(cls.__name__)
  108. @staticmethod
  109. def init_fail(m,on_fail):
  110. if os.getenv('MMGEN_TRACEBACK'): on_fail == 'raise'
  111. from mmgen.util import die,msg
  112. if on_fail == 'silent': return None # TODO: return False instead?
  113. elif on_fail == 'raise': raise ValueError,m
  114. elif on_fail == 'die': die(1,m)
  115. elif on_fail == 'return':
  116. if m: msg(m)
  117. return None # TODO: here too?
  118. class Hilite(object):
  119. color = 'red'
  120. color_always = False
  121. width = 0
  122. trunc_ok = True
  123. @classmethod
  124. # 'width' is screen width (greater than len(s) for CJK strings)
  125. # 'append_chars' and 'encl' must consist of single-width chars only
  126. def fmtc(cls,s,width=None,color=False,encl='',trunc_ok=None,
  127. center=False,nullrepl='',append_chars='',append_color=False):
  128. s = unicode(s)
  129. s_wide_count = len([1 for ch in s if unicodedata.east_asian_width(ch) in ('F','W')])
  130. assert type(encl) is str and len(encl) in (0,2),"'encl' must be 2-character str"
  131. a,b = list(encl) if encl else ('','')
  132. add_len = len(a) + len(b) + len(append_chars)
  133. if width == None: width = cls.width
  134. if trunc_ok == None: trunc_ok = cls.trunc_ok
  135. assert width >= 2 + add_len,( # 2 because CJK
  136. "'{!r}': invalid width ({}) (width must be at least 2)".format(s,width))
  137. if len(s) + s_wide_count + add_len > width:
  138. assert trunc_ok, "If 'trunc_ok' is false, 'width' must be >= screen width of string"
  139. s = truncate_str(s,width-add_len)
  140. if s == '' and nullrepl:
  141. s = nullrepl.center(width)
  142. else:
  143. s = a+s+b
  144. if center: s = s.center(width)
  145. if append_chars:
  146. return cls.colorize(s,color=color) + \
  147. cls.colorize(append_chars.ljust(width-len(s)-s_wide_count),color=append_color)
  148. else:
  149. return cls.colorize(s.ljust(width-s_wide_count),color=color)
  150. def fmt(self,*args,**kwargs):
  151. assert args == () # forbid invocation w/o keywords
  152. return self.fmtc(self,*args,**kwargs)
  153. @classmethod
  154. def hlc(cls,s,color=True):
  155. return cls.colorize(s,color=color)
  156. def hl(self,color=True):
  157. return self.colorize(self,color=color)
  158. def __str__(self):
  159. return self.colorize(self,color=False)
  160. @classmethod
  161. def colorize(cls,s,color=True):
  162. k = color if type(color) is str else cls.color # hack: override color with str value
  163. return globals()[k](s) if (color or cls.color_always) else s
  164. # For attrs that are always present in the data instance
  165. # Reassignment and deletion forbidden
  166. class MMGenImmutableAttr(object): # Descriptor
  167. def __init__(self,name,dtype,typeconv=True):
  168. self.typeconv = typeconv
  169. assert type(dtype) in (str,type)
  170. self.name = name
  171. self.dtype = dtype
  172. def __get__(self,instance,owner):
  173. return instance.__dict__[self.name]
  174. # forbid all reassignment
  175. def set_attr_ok(self,instance):
  176. return not hasattr(instance,self.name)
  177. def __set__(self,instance,value):
  178. if not self.set_attr_ok(instance):
  179. m = "Attribute '{}' of {} instance cannot be reassigned"
  180. raise AttributeError(m.format(self.name,type(instance)))
  181. if self.typeconv: # convert type
  182. instance.__dict__[self.name] = \
  183. globals()[self.dtype](value,on_fail='raise') if type(self.dtype) == str else self.dtype(value)
  184. else: # check type
  185. if type(value) != self.dtype:
  186. m = "Attribute '{}' of {} instance must of type {}"
  187. raise TypeError(m.format(self.name,type(instance),self.dtype))
  188. instance.__dict__[self.name] = value
  189. def __delete__(self,instance):
  190. m = "Atribute '{}' of {} instance cannot be deleted"
  191. raise AttributeError(m.format(self.name,type(instance)))
  192. # For attrs that might not be present in the data instance
  193. # Reassignment or deletion allowed if specified
  194. class MMGenListItemAttr(MMGenImmutableAttr): # Descriptor
  195. def __init__(self,name,dtype,typeconv=True,reassign_ok=False,delete_ok=False):
  196. self.reassign_ok = reassign_ok
  197. self.delete_ok = delete_ok
  198. MMGenImmutableAttr.__init__(self,name,dtype,typeconv=typeconv)
  199. # return None if attribute doesn't exist
  200. def __get__(self,instance,owner):
  201. try: return instance.__dict__[self.name]
  202. except: return None
  203. def set_attr_ok(self,instance):
  204. return getattr(instance,self.name) == None or self.reassign_ok
  205. def __delete__(self,instance):
  206. if self.delete_ok:
  207. if self.name in instance.__dict__:
  208. del instance.__dict__[self.name]
  209. else:
  210. MMGenImmutableAttr.__delete__(self,instance)
  211. class MMGenListItem(MMGenObject):
  212. def __init__(self,*args,**kwargs):
  213. if args:
  214. raise ValueError, 'Non-keyword args not allowed'
  215. for k in kwargs:
  216. if kwargs[k] != None:
  217. setattr(self,k,kwargs[k])
  218. # prevent setting random attributes
  219. def __setattr__(self,name,value):
  220. if name not in type(self).__dict__:
  221. m = "'{}': no such attribute in class {}"
  222. raise AttributeError(m.format(name,type(self)))
  223. return object.__setattr__(self,name,value)
  224. class AddrIdx(int,InitErrors):
  225. max_digits = 7
  226. def __new__(cls,num,on_fail='die'):
  227. cls.arg_chk(cls,on_fail)
  228. try:
  229. assert type(num) is not float,'is float'
  230. me = int.__new__(cls,num)
  231. assert len(str(me)) <= cls.max_digits,'is more than {} digits'.format(cls.max_digits)
  232. assert me > 0,'is less than one'
  233. return me
  234. except Exception as e:
  235. m = "{!r}: value cannot be converted to address index ({})"
  236. return cls.init_fail(m.format(num,e[0]),on_fail)
  237. class AddrIdxList(list,InitErrors,MMGenObject):
  238. max_len = 1000000
  239. def __init__(self,fmt_str=None,idx_list=None,on_fail='die',sep=','):
  240. self.arg_chk(type(self),on_fail)
  241. try:
  242. if idx_list:
  243. return list.__init__(self,sorted(set(AddrIdx(i,on_fail='raise') for i in idx_list)))
  244. elif fmt_str:
  245. ret = []
  246. for i in (fmt_str.split(sep)):
  247. j = i.split('-')
  248. if len(j) == 1:
  249. idx = AddrIdx(i,on_fail='raise')
  250. if not idx: break
  251. ret.append(idx)
  252. elif len(j) == 2:
  253. beg = AddrIdx(j[0],on_fail='raise')
  254. if not beg: break
  255. end = AddrIdx(j[1],on_fail='raise')
  256. if not beg: break
  257. if end < beg: break
  258. ret.extend([AddrIdx(x,on_fail='raise') for x in range(beg,end+1)])
  259. else: break
  260. else:
  261. return list.__init__(self,sorted(set(ret))) # fell off end of loop - success
  262. raise ValueError,"{!r}: invalid range".format(i)
  263. except Exception as e:
  264. m = "{!r}: value cannot be converted to AddrIdxList ({})"
  265. return type(self).init_fail(m.format(idx_list or fmt_str,e[0]),on_fail)
  266. class BTCAmt(Decimal,Hilite,InitErrors):
  267. color = 'yellow'
  268. max_prec = 8
  269. max_amt = 21000000
  270. satoshi = Decimal('0.00000001')
  271. min_coin_unit = satoshi
  272. amt_fs = '4.8'
  273. units = ('satoshi',)
  274. forbidden_types = (float,long)
  275. def __new__(cls,num,from_unit=None,on_fail='die'):
  276. if type(num) == cls: return num
  277. cls.arg_chk(cls,on_fail)
  278. try:
  279. if from_unit:
  280. assert from_unit in cls.units,(
  281. "'{}': unrecognized denomination for {}".format(from_unit,cls.__name__))
  282. assert type(num) in (int,long),'value is not an integer or long integer'
  283. me = Decimal.__new__(cls,num * getattr(cls,from_unit))
  284. else:
  285. for t in cls.forbidden_types:
  286. assert type(num) is not t,"number is of forbidden type '{}'".format(t.__name__)
  287. me = Decimal.__new__(cls,str(num))
  288. assert me.normalize().as_tuple()[-1] >= -cls.max_prec,'too many decimal places in coin amount'
  289. if cls.max_amt:
  290. assert me <= cls.max_amt,'{}: coin amount too large (>{})'.format(me,cls.max_amt)
  291. assert me >= 0,'coin amount cannot be negative'
  292. return me
  293. except Exception as e:
  294. m = "{!r}: value cannot be converted to {} ({})"
  295. return cls.init_fail(m.format(num,cls.__name__,e[0]),on_fail)
  296. def toSatoshi(self): return int(Decimal(self) / self.satoshi)
  297. @classmethod
  298. def fmtc(cls):
  299. raise NotImplementedError
  300. def fmt(self,fs=None,color=False,suf=''):
  301. if fs == None: fs = self.amt_fs
  302. s = str(int(self)) if int(self) == self else self.normalize().__format__('f')
  303. if '.' in fs:
  304. p1,p2 = map(int,fs.split('.',1))
  305. ss = s.split('.',1)
  306. if len(ss) == 2:
  307. a,b = ss
  308. ret = a.rjust(p1) + '.' + (b+suf).ljust(p2+len(suf))
  309. else:
  310. ret = s.rjust(p1) + suf + ' ' * (p2+1)
  311. else:
  312. ret = s.ljust(int(fs))
  313. return self.colorize(ret,color=color)
  314. def hl(self,color=True):
  315. return self.__str__(color=color)
  316. def __str__(self,color=False): # format simply, no exponential notation
  317. return self.colorize(
  318. str(int(self)) if int(self) == self else self.normalize().__format__('f'),
  319. color=color)
  320. def __repr__(self):
  321. return "{}('{}')".format(type(self).__name__,self.__str__())
  322. def __add__(self,other,context=None):
  323. return type(self)(Decimal.__add__(self,other,context))
  324. __radd__ = __add__
  325. def __sub__(self,other,context=None):
  326. return type(self)(Decimal.__sub__(self,other,context))
  327. def __mul__(self,other,context=None):
  328. return type(self)('{:0.8f}'.format(Decimal.__mul__(self,Decimal(other),context)))
  329. def __div__(self,other,context=None):
  330. return type(self)('{:0.8f}'.format(Decimal.__div__(self,Decimal(other),context)))
  331. def __neg__(self,other,context=None):
  332. return type(self)(Decimal.__neg__(self,other,context))
  333. class BCHAmt(BTCAmt): pass
  334. class B2XAmt(BTCAmt): pass
  335. class LTCAmt(BTCAmt): max_amt = 84000000
  336. from mmgen.altcoins.eth.obj import ETHAmt,ETHNonce
  337. class CoinAddr(str,Hilite,InitErrors,MMGenObject):
  338. color = 'cyan'
  339. hex_width = 40
  340. width = 1
  341. trunc_ok = False
  342. def __new__(cls,s,on_fail='die'):
  343. if type(s) == cls: return s
  344. cls.arg_chk(cls,on_fail)
  345. from mmgen.globalvars import g
  346. try:
  347. assert set(s) <= set(ascii_letters+digits),'contains non-alphanumeric characters'
  348. me = str.__new__(cls,s)
  349. va = g.proto.verify_addr(s,hex_width=cls.hex_width,return_dict=True)
  350. assert va,'failed verification'
  351. me.addr_fmt = va['format']
  352. me.hex = va['hex']
  353. return me
  354. except Exception as e:
  355. m = "{!r}: value cannot be converted to {} address ({})"
  356. return cls.init_fail(m.format(s,g.proto.__name__,e[0]),on_fail)
  357. @classmethod
  358. def fmtc(cls,s,**kwargs):
  359. # True -> 'cyan': use the str value override hack
  360. if 'color' in kwargs and kwargs['color'] == True:
  361. kwargs['color'] = cls.color
  362. if not 'width' in kwargs: kwargs['width'] = cls.width
  363. if kwargs['width'] < len(s):
  364. s = s[:kwargs['width']-2] + '..'
  365. return Hilite.fmtc(s,**kwargs)
  366. def is_for_chain(self,chain):
  367. from mmgen.globalvars import g
  368. if g.coin in ('ETH','ETC'):
  369. return True
  370. def pfx_ok(pfx):
  371. if type(pfx) == tuple:
  372. if self[0] in pfx: return True
  373. elif self[:len(pfx)] == pfx: return True
  374. return False
  375. proto = g.proto.get_protocol_by_chain(chain)
  376. vn = proto.addr_ver_num
  377. if self.addr_fmt == 'bech32':
  378. return self[:len(proto.bech32_hrp)] == proto.bech32_hrp
  379. elif self.addr_fmt == 'p2sh' and 'p2sh2' in vn:
  380. return pfx_ok(vn['p2sh'][1]) or pfx_ok(vn['p2sh2'][1])
  381. else:
  382. return pfx_ok(vn[self.addr_fmt][1])
  383. class ViewKey(object):
  384. def __new__(cls,s,on_fail='die'):
  385. from mmgen.globalvars import g
  386. if g.proto.name == 'zcash':
  387. return ZcashViewKey.__new__(ZcashViewKey,s,on_fail)
  388. elif g.proto.name == 'monero':
  389. return MoneroViewKey.__new__(MoneroViewKey,s,on_fail)
  390. else:
  391. raise ValueError,'{}: protocol does not support view keys'.format(g.proto.name.capitalize())
  392. class ZcashViewKey(CoinAddr): hex_width = 128
  393. class SeedID(str,Hilite,InitErrors):
  394. color = 'blue'
  395. width = 8
  396. trunc_ok = False
  397. def __new__(cls,seed=None,sid=None,on_fail='die'):
  398. if type(sid) == cls: return sid
  399. cls.arg_chk(cls,on_fail)
  400. try:
  401. if seed:
  402. from mmgen.seed import Seed
  403. assert type(seed) == Seed,'not a Seed instance'
  404. from mmgen.util import make_chksum_8
  405. return str.__new__(cls,make_chksum_8(seed.get_data()))
  406. elif sid:
  407. assert set(sid) <= set(hexdigits.upper()),'not uppercase hex digits'
  408. assert len(sid) == cls.width,'not {} characters wide'.format(cls.width)
  409. return str.__new__(cls,sid)
  410. raise ValueError,'no arguments provided'
  411. except Exception as e:
  412. m = "{!r}: value cannot be converted to SeedID ({})"
  413. return cls.init_fail(m.format(seed or sid,e[0]),on_fail)
  414. class MMGenID(str,Hilite,InitErrors,MMGenObject):
  415. color = 'orange'
  416. width = 0
  417. trunc_ok = False
  418. def __new__(cls,s,on_fail='die'):
  419. cls.arg_chk(cls,on_fail)
  420. from mmgen.globalvars import g
  421. try:
  422. ss = str(s).split(':')
  423. assert len(ss) in (2,3),'not 2 or 3 colon-separated items'
  424. t = MMGenAddrType((ss[1],g.proto.dfl_mmtype)[len(ss)==2],on_fail='raise')
  425. me = str.__new__(cls,'{}:{}:{}'.format(ss[0],t,ss[-1]))
  426. me.sid = SeedID(sid=ss[0],on_fail='raise')
  427. me.idx = AddrIdx(ss[-1],on_fail='raise')
  428. me.mmtype = t
  429. assert t in g.proto.mmtypes,'{}: invalid address type for {}'.format(t,g.proto.__name__)
  430. me.al_id = str.__new__(AddrListID,me.sid+':'+me.mmtype) # checks already done
  431. me.sort_key = '{}:{}:{:0{w}}'.format(me.sid,me.mmtype,me.idx,w=me.idx.max_digits)
  432. return me
  433. except Exception as e:
  434. m = "{}\n{!r}: value cannot be converted to MMGenID"
  435. return cls.init_fail(m.format(e[0],s),on_fail)
  436. class TwMMGenID(str,Hilite,InitErrors,MMGenObject):
  437. color = 'orange'
  438. width = 0
  439. trunc_ok = False
  440. def __new__(cls,s,on_fail='die'):
  441. if type(s) == cls: return s
  442. cls.arg_chk(cls,on_fail)
  443. ret = None
  444. try:
  445. ret = MMGenID(s,on_fail='raise')
  446. sort_key,idtype = ret.sort_key,'mmgen'
  447. except Exception as e:
  448. try:
  449. from mmgen.globalvars import g
  450. assert s.split(':',1)[0] == g.proto.base_coin.lower(),(
  451. "not a string beginning with the prefix '{}:'".format(g.proto.base_coin.lower()))
  452. assert set(s[4:]) <= set(ascii_letters+digits),'contains non-alphanumeric characters'
  453. assert len(s) > 4,'not more that four characters long'
  454. ret,sort_key,idtype = str(s),'z_'+s,'non-mmgen'
  455. except Exception as f:
  456. m = "{}\nValue is {}\n{!r}: value cannot be converted to TwMMGenID"
  457. return cls.init_fail(m.format(e[0],f[0],s),on_fail)
  458. me = str.__new__(cls,ret)
  459. me.obj = ret
  460. me.sort_key = sort_key
  461. me.type = idtype
  462. return me
  463. # contains TwMMGenID,TwComment. Not for display
  464. class TwLabel(unicode,InitErrors,MMGenObject):
  465. def __new__(cls,s,on_fail='die'):
  466. if type(s) == cls: return s
  467. cls.arg_chk(cls,on_fail)
  468. try:
  469. ss = s.split(None,1)
  470. mmid = TwMMGenID(ss[0],on_fail='raise')
  471. comment = TwComment(ss[1] if len(ss) == 2 else '',on_fail='raise')
  472. me = unicode.__new__(cls,u'{}{}'.format(mmid,u' {}'.format(comment) if comment else ''))
  473. me.mmid = mmid
  474. me.comment = comment
  475. return me
  476. except Exception as e:
  477. m = u"{}\n{!r}: value cannot be converted to TwLabel"
  478. return cls.init_fail(m.format(e[0],s),on_fail)
  479. class HexStr(str,Hilite,InitErrors):
  480. color = 'red'
  481. trunc_ok = False
  482. def __new__(cls,s,on_fail='die',case='lower'):
  483. if type(s) == cls: return s
  484. assert case in ('upper','lower')
  485. cls.arg_chk(cls,on_fail)
  486. try:
  487. assert type(s) in (str,unicode,bytes),'not a string'
  488. assert set(s) <= set(getattr(hexdigits,case)()),'not {}case hexadecimal symbols'.format(case)
  489. assert not len(s) % 2,'odd-length string'
  490. return str.__new__(cls,s)
  491. except Exception as e:
  492. m = "{!r}: value cannot be converted to {} (value is {})"
  493. return cls.init_fail(m.format(s,cls.__name__,e[0]),on_fail)
  494. class HexStrWithWidth(HexStr):
  495. color = 'nocolor'
  496. trunc_ok = False
  497. hexcase = 'lower'
  498. width = None
  499. def __new__(cls,s,on_fail='die'):
  500. cls.arg_chk(cls,on_fail)
  501. try:
  502. ret = HexStr.__new__(cls,s,case=cls.hexcase,on_fail='raise')
  503. assert len(s) == cls.width,'Value is not {} characters wide'.format(cls.width)
  504. return ret
  505. except Exception as e:
  506. m = "{}\n{!r}: value cannot be converted to {}"
  507. return cls.init_fail(m.format(e[0],s,cls.__name__),on_fail)
  508. class MMGenTxID(HexStrWithWidth): color,width,hexcase = 'red',6,'upper'
  509. class MoneroViewKey(HexStrWithWidth): color,width,hexcase = 'cyan',64,'lower'
  510. class WalletPassword(HexStrWithWidth): color,width,hexcase = 'blue',32,'lower'
  511. class CoinTxID(HexStrWithWidth): color,width,hexcase = 'purple',64,'lower'
  512. class WifKey(str,Hilite,InitErrors):
  513. width = 53
  514. color = 'blue'
  515. def __new__(cls,s,on_fail='die'):
  516. if type(s) == cls: return s
  517. cls.arg_chk(cls,on_fail)
  518. try:
  519. assert set(s) <= set(ascii_letters+digits),'not an ascii string'
  520. from mmgen.globalvars import g
  521. g.proto.wif2hex(s) # raises exception on error
  522. return str.__new__(cls,s)
  523. except Exception as e:
  524. m = '{!r}: invalid value for WIF key ({})'.format(s,e[0])
  525. return cls.init_fail(m,on_fail)
  526. class PubKey(HexStr,MMGenObject): # TODO: add some real checks
  527. def __new__(cls,s,compressed,on_fail='die'):
  528. try:
  529. assert type(compressed) == bool,"'compressed' must be of type bool"
  530. me = HexStr.__new__(cls,s,case='lower',on_fail='raise')
  531. me.compressed = compressed
  532. return me
  533. except Exception as e:
  534. m = '{!r}: invalid value for pubkey ({})'.format(s,e[0])
  535. return cls.init_fail(m,on_fail)
  536. class PrivKey(str,Hilite,InitErrors,MMGenObject):
  537. color = 'red'
  538. width = 64
  539. trunc_ok = False
  540. compressed = MMGenImmutableAttr('compressed',bool,typeconv=False)
  541. wif = MMGenImmutableAttr('wif',WifKey,typeconv=False)
  542. # initialize with (priv_bin,compressed), WIF or self
  543. def __new__(cls,s=None,compressed=None,wif=None,pubkey_type=None,on_fail='die'):
  544. from mmgen.globalvars import g
  545. if type(s) == cls: return s
  546. cls.arg_chk(cls,on_fail)
  547. if wif:
  548. try:
  549. assert s == None
  550. assert set(wif) <= set(ascii_letters+digits),'not an ascii string'
  551. w2h = g.proto.wif2hex(wif) # raises exception on error
  552. me = str.__new__(cls,w2h['hex'])
  553. me.compressed = w2h['compressed']
  554. me.pubkey_type = w2h['pubkey_type']
  555. me.wif = str.__new__(WifKey,wif) # check has been done
  556. me.orig_hex = None
  557. return me
  558. except Exception as e:
  559. fs = "Value {!r} cannot be converted to {} WIF key ({})"
  560. return cls.init_fail(fs.format(wif,g.coin,e[0]),on_fail)
  561. try:
  562. assert s and type(compressed) == bool and pubkey_type,'Incorrect args for PrivKey()'
  563. assert len(s) == cls.width / 2,'Key length must be {}'.format(cls.width/2)
  564. me = str.__new__(cls,g.proto.preprocess_key(s.encode('hex'),pubkey_type))
  565. me.orig_hex = s.encode('hex') # save the non-preprocessed key
  566. me.compressed = compressed
  567. me.pubkey_type = pubkey_type
  568. if pubkey_type != 'password': # skip WIF creation for passwds
  569. me.wif = WifKey(g.proto.hex2wif(me,pubkey_type,compressed),on_fail='raise')
  570. return me
  571. except Exception as e:
  572. fs = "Key={!r}\nCompressed={}\nValue pair cannot be converted to PrivKey\n({})"
  573. return cls.init_fail(fs.format(s,compressed,e),on_fail)
  574. class AddrListID(str,Hilite,InitErrors,MMGenObject):
  575. width = 10
  576. trunc_ok = False
  577. color = 'yellow'
  578. def __new__(cls,sid,mmtype,on_fail='die'):
  579. cls.arg_chk(cls,on_fail)
  580. try:
  581. assert type(sid) == SeedID,"{!r} not a SeedID instance".format(sid)
  582. t = MMGenAddrType,MMGenPasswordType
  583. assert type(mmtype) in t,"{!r} not an instance of {}".format(mmtype,','.join([i.__name__ for i in t]))
  584. me = str.__new__(cls,sid+':'+mmtype)
  585. me.sid = sid
  586. me.mmtype = mmtype
  587. return me
  588. except Exception as e:
  589. m = "Cannot create AddrListID ({})".format(e[0])
  590. return cls.init_fail(m,on_fail)
  591. class MMGenLabel(unicode,Hilite,InitErrors):
  592. color = 'pink'
  593. allowed = []
  594. forbidden = []
  595. max_len = 0
  596. min_len = 0
  597. desc = 'label'
  598. def __new__(cls,s,on_fail='die',msg=None):
  599. if type(s) == cls: return s
  600. cls.arg_chk(cls,on_fail)
  601. for k in cls.forbidden,cls.allowed:
  602. assert type(k) == list
  603. for ch in k: assert type(ch) == unicode and len(ch) == 1
  604. try:
  605. s = s.strip()
  606. if type(s) != unicode:
  607. s = s.decode('utf8')
  608. for ch in s:
  609. # Allow: (L)etter,(N)umber,(P)unctuation,(S)ymbol,(Z)space
  610. # Disallow: (C)ontrol,(M)combining
  611. # Combining characters create width formatting issues, so disallow them for now
  612. assert unicodedata.category(ch)[0] not in 'CM','{!r}: {} characters not allowed'.format(
  613. ch,('control','combining')[unicodedata.category(ch)[0]=='M'])
  614. assert len(s) <= cls.max_len, 'too long (>{} symbols)'.format(cls.max_len)
  615. assert len(s) >= cls.min_len, 'too short (<{} symbols)'.format(cls.min_len)
  616. assert not cls.allowed or set(list(s)).issubset(set(cls.allowed)),\
  617. u'contains non-allowed symbols: {}'.format(' '.join(set(list(s)) - set(cls.allowed)))
  618. assert not cls.forbidden or not any(ch in s for ch in cls.forbidden),\
  619. u"contains one of these forbidden symbols: '{}'".format("', '".join(cls.forbidden))
  620. return unicode.__new__(cls,s)
  621. except Exception as e:
  622. m = u"{!r}: value cannot be converted to {} ({})"
  623. return cls.init_fail(m.format(s,cls.__name__,e),on_fail)
  624. class MMGenWalletLabel(MMGenLabel):
  625. max_len = 48
  626. desc = 'wallet label'
  627. class TwComment(MMGenLabel):
  628. max_len = 40
  629. desc = 'tracking wallet comment'
  630. class MMGenTXLabel(MMGenLabel):
  631. max_len = 72
  632. desc = 'transaction label'
  633. class MMGenPWIDString(MMGenLabel):
  634. max_len = 256
  635. min_len = 1
  636. desc = 'password ID string'
  637. forbidden = list(u' :/\\')
  638. class MMGenAddrType(str,Hilite,InitErrors,MMGenObject):
  639. width = 1
  640. trunc_ok = False
  641. color = 'blue'
  642. mmtypes = { # 'name' is used to cook the seed, so it must never change!
  643. 'L': { 'name':'legacy',
  644. 'pubkey_type':'std',
  645. 'compressed':False,
  646. 'gen_method':'p2pkh',
  647. 'addr_fmt':'p2pkh',
  648. 'desc':'Legacy uncompressed address'},
  649. 'C': { 'name':'compressed',
  650. 'pubkey_type':'std',
  651. 'compressed':True,
  652. 'gen_method':'p2pkh',
  653. 'addr_fmt':'p2pkh',
  654. 'desc':'Compressed P2PKH address'},
  655. 'S': { 'name':'segwit',
  656. 'pubkey_type':'std',
  657. 'compressed':True,
  658. 'gen_method':'segwit',
  659. 'addr_fmt':'p2sh',
  660. 'desc':'Segwit P2SH-P2WPKH address' },
  661. 'B': { 'name':'bech32',
  662. 'pubkey_type':'std',
  663. 'compressed':True,
  664. 'gen_method':'bech32',
  665. 'addr_fmt':'bech32',
  666. 'desc':'Native Segwit (Bech32) address' },
  667. 'E': { 'name':'ethereum',
  668. 'pubkey_type':'std',
  669. 'compressed':False,
  670. 'gen_method':'ethereum',
  671. 'addr_fmt':'ethereum',
  672. 'wif_label':'privkey:',
  673. 'extra_attrs': ('wallet_passwd',),
  674. 'desc':'Ethereum address' },
  675. 'Z': { 'name':'zcash_z',
  676. 'pubkey_type':'zcash_z',
  677. 'compressed':False,
  678. 'gen_method':'zcash_z',
  679. 'addr_fmt':'zcash_z',
  680. 'extra_attrs': ('viewkey',),
  681. 'desc':'Zcash z-address' },
  682. 'M': { 'name':'monero',
  683. 'pubkey_type':'monero',
  684. 'compressed':False,
  685. 'gen_method':'monero',
  686. 'addr_fmt':'monero',
  687. 'wif_label':'spendkey:',
  688. 'extra_attrs': ('viewkey','wallet_passwd'),
  689. 'desc':'Monero address'}
  690. }
  691. def __new__(cls,s,on_fail='die',errmsg=None):
  692. if type(s) == cls: return s
  693. cls.arg_chk(cls,on_fail)
  694. from mmgen.globalvars import g
  695. try:
  696. for k,v in cls.mmtypes.items():
  697. if s in (k,v['name']):
  698. if s == v['name']: s = k
  699. me = str.__new__(cls,s)
  700. for k in ('name','pubkey_type','compressed','gen_method','addr_fmt','desc'):
  701. setattr(me,k,v[k])
  702. assert me in g.proto.mmtypes + ('P',), (
  703. "'{}': invalid address type for {}".format(me.name,g.proto.__name__))
  704. me.extra_attrs = v['extra_attrs'] if 'extra_attrs' in v else ()
  705. me.wif_label = v['wif_label'] if 'wif_label' in v else 'wif:'
  706. return me
  707. raise ValueError,'not found'
  708. except Exception as e:
  709. m = '{}{!r}: invalid value for {} ({})'.format(
  710. ('{!r}\n'.format(errmsg) if errmsg else ''),s,cls.__name__,e[0])
  711. return cls.init_fail(m,on_fail)
  712. @classmethod
  713. def get_names(cls):
  714. return [v['name'] for v in cls.mmtypes.values()]
  715. class MMGenPasswordType(MMGenAddrType):
  716. mmtypes = {
  717. 'P': { 'name':'password',
  718. 'pubkey_type':'password',
  719. 'compressed':False,
  720. 'gen_method':None,
  721. 'addr_fmt':None,
  722. 'desc':'Password generated from MMGen seed'}
  723. }