obj.py 25 KB

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