obj.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  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. assert me <= cls.max_amt,'coin amount too large (>{})'.format(cls.max_amt)
  290. assert me >= 0,'coin amount cannot be negative'
  291. return me
  292. except Exception as e:
  293. m = "{!r}: value cannot be converted to {} ({})"
  294. return cls.init_fail(m.format(num,cls.__name__,e[0]),on_fail)
  295. def toSatoshi(self): return int(Decimal(self) / self.satoshi)
  296. @classmethod
  297. def fmtc(cls):
  298. raise NotImplementedError
  299. def fmt(self,fs=None,color=False,suf=''):
  300. if fs == None: fs = self.amt_fs
  301. s = str(int(self)) if int(self) == self else self.normalize().__format__('f')
  302. if '.' in fs:
  303. p1,p2 = map(int,fs.split('.',1))
  304. ss = s.split('.',1)
  305. if len(ss) == 2:
  306. a,b = ss
  307. ret = a.rjust(p1) + '.' + (b+suf).ljust(p2+len(suf))
  308. else:
  309. ret = s.rjust(p1) + suf + ' ' * (p2+1)
  310. else:
  311. ret = s.ljust(int(fs))
  312. return self.colorize(ret,color=color)
  313. def hl(self,color=True):
  314. return self.__str__(color=color)
  315. def __str__(self,color=False): # format simply, no exponential notation
  316. return self.colorize(
  317. str(int(self)) if int(self) == self else self.normalize().__format__('f'),
  318. color=color)
  319. def __repr__(self):
  320. return "{}('{}')".format(type(self).__name__,self.__str__())
  321. def __add__(self,other,context=None):
  322. return type(self)(Decimal.__add__(self,other,context))
  323. __radd__ = __add__
  324. def __sub__(self,other,context=None):
  325. return type(self)(Decimal.__sub__(self,other,context))
  326. def __mul__(self,other,context=None):
  327. return type(self)('{:0.8f}'.format(Decimal.__mul__(self,Decimal(other),context)))
  328. def __div__(self,other,context=None):
  329. return type(self)('{:0.8f}'.format(Decimal.__div__(self,Decimal(other),context)))
  330. def __neg__(self,other,context=None):
  331. return type(self)(Decimal.__neg__(self,other,context))
  332. class BCHAmt(BTCAmt): pass
  333. class B2XAmt(BTCAmt): pass
  334. class LTCAmt(BTCAmt): max_amt = 84000000
  335. from mmgen.altcoins.eth.obj import ETHAmt,ETHNonce
  336. class CoinAddr(str,Hilite,InitErrors,MMGenObject):
  337. color = 'cyan'
  338. hex_width = 40
  339. width = 1
  340. trunc_ok = False
  341. def __new__(cls,s,on_fail='die'):
  342. if type(s) == cls: return s
  343. cls.arg_chk(cls,on_fail)
  344. from mmgen.globalvars import g
  345. try:
  346. assert set(s) <= set(ascii_letters+digits),'contains non-alphanumeric characters'
  347. me = str.__new__(cls,s)
  348. va = g.proto.verify_addr(s,hex_width=cls.hex_width,return_dict=True)
  349. assert va,'failed verification'
  350. me.addr_fmt = va['format']
  351. me.hex = va['hex']
  352. return me
  353. except Exception as e:
  354. m = "{!r}: value cannot be converted to {} address ({})"
  355. return cls.init_fail(m.format(s,g.proto.__name__,e[0]),on_fail)
  356. @classmethod
  357. def fmtc(cls,s,**kwargs):
  358. # True -> 'cyan': use the str value override hack
  359. if 'color' in kwargs and kwargs['color'] == True:
  360. kwargs['color'] = cls.color
  361. if not 'width' in kwargs: kwargs['width'] = cls.width
  362. if kwargs['width'] < len(s):
  363. s = s[:kwargs['width']-2] + '..'
  364. return Hilite.fmtc(s,**kwargs)
  365. def is_for_chain(self,chain):
  366. from mmgen.globalvars import g
  367. if g.coin in ('ETH','ETC'):
  368. return True
  369. def pfx_ok(pfx):
  370. if type(pfx) == tuple:
  371. if self[0] in pfx: return True
  372. elif self[:len(pfx)] == pfx: return True
  373. return False
  374. proto = g.proto.get_protocol_by_chain(chain)
  375. vn = proto.addr_ver_num
  376. if self.addr_fmt == 'bech32':
  377. return self[:len(proto.bech32_hrp)] == proto.bech32_hrp
  378. elif self.addr_fmt == 'p2sh' and 'p2sh2' in vn:
  379. return pfx_ok(vn['p2sh'][1]) or pfx_ok(vn['p2sh2'][1])
  380. else:
  381. return pfx_ok(vn[self.addr_fmt][1])
  382. def is_in_tracking_wallet(self):
  383. from mmgen.globalvars import g
  384. if g.coin in ('ETH','ETC'):
  385. from mmgen.altcoins.eth.tw import EthereumTrackingWallet
  386. return self in EthereumTrackingWallet().data.keys()
  387. from mmgen.rpc import rpc_init
  388. d = rpc_init().validateaddress(self)
  389. return d['iswatchonly'] and 'account' in d
  390. class ViewKey(object):
  391. def __new__(cls,s,on_fail='die'):
  392. from mmgen.globalvars import g
  393. if g.proto.name == 'zcash':
  394. return ZcashViewKey.__new__(ZcashViewKey,s,on_fail)
  395. elif g.proto.name == 'monero':
  396. return MoneroViewKey.__new__(MoneroViewKey,s,on_fail)
  397. else:
  398. raise ValueError,'{}: protocol does not support view keys'.format(g.proto.name.capitalize())
  399. class ZcashViewKey(CoinAddr): hex_width = 128
  400. class SeedID(str,Hilite,InitErrors):
  401. color = 'blue'
  402. width = 8
  403. trunc_ok = False
  404. def __new__(cls,seed=None,sid=None,on_fail='die'):
  405. if type(sid) == cls: return sid
  406. cls.arg_chk(cls,on_fail)
  407. try:
  408. if seed:
  409. from mmgen.seed import Seed
  410. assert type(seed) == Seed,'not a Seed instance'
  411. from mmgen.util import make_chksum_8
  412. return str.__new__(cls,make_chksum_8(seed.get_data()))
  413. elif sid:
  414. assert set(sid) <= set(hexdigits.upper()),'not uppercase hex digits'
  415. assert len(sid) == cls.width,'not {} characters wide'.format(cls.width)
  416. return str.__new__(cls,sid)
  417. raise ValueError,'no arguments provided'
  418. except Exception as e:
  419. m = "{!r}: value cannot be converted to SeedID ({})"
  420. return cls.init_fail(m.format(seed or sid,e[0]),on_fail)
  421. class MMGenID(str,Hilite,InitErrors,MMGenObject):
  422. color = 'orange'
  423. width = 0
  424. trunc_ok = False
  425. def __new__(cls,s,on_fail='die'):
  426. cls.arg_chk(cls,on_fail)
  427. from mmgen.globalvars import g
  428. try:
  429. ss = str(s).split(':')
  430. assert len(ss) in (2,3),'not 2 or 3 colon-separated items'
  431. t = MMGenAddrType((ss[1],g.proto.dfl_mmtype)[len(ss)==2],on_fail='raise')
  432. me = str.__new__(cls,'{}:{}:{}'.format(ss[0],t,ss[-1]))
  433. me.sid = SeedID(sid=ss[0],on_fail='raise')
  434. me.idx = AddrIdx(ss[-1],on_fail='raise')
  435. me.mmtype = t
  436. assert t in g.proto.mmtypes,'{}: invalid address type for {}'.format(t,g.proto.__name__)
  437. me.al_id = str.__new__(AddrListID,me.sid+':'+me.mmtype) # checks already done
  438. me.sort_key = '{}:{}:{:0{w}}'.format(me.sid,me.mmtype,me.idx,w=me.idx.max_digits)
  439. return me
  440. except Exception as e:
  441. m = "{}\n{!r}: value cannot be converted to MMGenID"
  442. return cls.init_fail(m.format(e[0],s),on_fail)
  443. class TwMMGenID(str,Hilite,InitErrors,MMGenObject):
  444. color = 'orange'
  445. width = 0
  446. trunc_ok = False
  447. def __new__(cls,s,on_fail='die'):
  448. if type(s) == cls: return s
  449. cls.arg_chk(cls,on_fail)
  450. ret = None
  451. try:
  452. ret = MMGenID(s,on_fail='raise')
  453. sort_key,idtype = ret.sort_key,'mmgen'
  454. except Exception as e:
  455. try:
  456. from mmgen.globalvars import g
  457. assert s.split(':',1)[0] == g.proto.base_coin.lower(),(
  458. "not a string beginning with the prefix '{}:'".format(g.proto.base_coin.lower()))
  459. assert set(s[4:]) <= set(ascii_letters+digits),'contains non-alphanumeric characters'
  460. assert len(s) > 4,'not more that four characters long'
  461. ret,sort_key,idtype = str(s),'z_'+s,'non-mmgen'
  462. except Exception as f:
  463. m = "{}\nValue is {}\n{!r}: value cannot be converted to TwMMGenID"
  464. return cls.init_fail(m.format(e[0],f[0],s),on_fail)
  465. me = str.__new__(cls,ret)
  466. me.obj = ret
  467. me.sort_key = sort_key
  468. me.type = idtype
  469. return me
  470. # contains TwMMGenID,TwComment. Not for display
  471. class TwLabel(unicode,InitErrors,MMGenObject):
  472. def __new__(cls,s,on_fail='die'):
  473. if type(s) == cls: return s
  474. cls.arg_chk(cls,on_fail)
  475. try:
  476. ss = s.split(None,1)
  477. mmid = TwMMGenID(ss[0],on_fail='raise')
  478. comment = TwComment(ss[1] if len(ss) == 2 else '',on_fail='raise')
  479. me = unicode.__new__(cls,u'{}{}'.format(mmid,u' {}'.format(comment) if comment else ''))
  480. me.mmid = mmid
  481. me.comment = comment
  482. return me
  483. except Exception as e:
  484. m = u"{}\n{!r}: value cannot be converted to TwLabel"
  485. return cls.init_fail(m.format(e[0],s),on_fail)
  486. class HexStr(str,Hilite,InitErrors):
  487. color = 'red'
  488. trunc_ok = False
  489. def __new__(cls,s,on_fail='die',case='lower'):
  490. if type(s) == cls: return s
  491. assert case in ('upper','lower')
  492. cls.arg_chk(cls,on_fail)
  493. try:
  494. assert type(s) in (str,unicode,bytes),'not a string'
  495. assert set(s) <= set(getattr(hexdigits,case)()),'not {}case hexadecimal symbols'.format(case)
  496. assert not len(s) % 2,'odd-length string'
  497. return str.__new__(cls,s)
  498. except Exception as e:
  499. m = "{!r}: value cannot be converted to {} (value is {})"
  500. return cls.init_fail(m.format(s,cls.__name__,e[0]),on_fail)
  501. class HexStrWithWidth(HexStr):
  502. color = 'nocolor'
  503. trunc_ok = False
  504. hexcase = 'lower'
  505. width = None
  506. def __new__(cls,s,on_fail='die'):
  507. cls.arg_chk(cls,on_fail)
  508. try:
  509. ret = HexStr.__new__(cls,s,case=cls.hexcase,on_fail='raise')
  510. assert len(s) == cls.width,'Value is not {} characters wide'.format(cls.width)
  511. return ret
  512. except Exception as e:
  513. m = "{}\n{!r}: value cannot be converted to {}"
  514. return cls.init_fail(m.format(e[0],s,cls.__name__),on_fail)
  515. class MMGenTxID(HexStrWithWidth): color,width,hexcase = 'red',6,'upper'
  516. class MoneroViewKey(HexStrWithWidth): color,width,hexcase = 'cyan',64,'lower'
  517. class WalletPassword(HexStrWithWidth): color,width,hexcase = 'blue',32,'lower'
  518. class CoinTxID(HexStrWithWidth): color,width,hexcase = 'purple',64,'lower'
  519. class WifKey(str,Hilite,InitErrors):
  520. width = 53
  521. color = 'blue'
  522. def __new__(cls,s,on_fail='die'):
  523. if type(s) == cls: return s
  524. cls.arg_chk(cls,on_fail)
  525. try:
  526. assert set(s) <= set(ascii_letters+digits),'not an ascii string'
  527. from mmgen.globalvars import g
  528. g.proto.wif2hex(s) # raises exception on error
  529. return str.__new__(cls,s)
  530. except Exception as e:
  531. m = '{!r}: invalid value for WIF key ({})'.format(s,e[0])
  532. return cls.init_fail(m,on_fail)
  533. class PubKey(HexStr,MMGenObject): # TODO: add some real checks
  534. def __new__(cls,s,compressed,on_fail='die'):
  535. try:
  536. assert type(compressed) == bool,"'compressed' must be of type bool"
  537. me = HexStr.__new__(cls,s,case='lower',on_fail='raise')
  538. me.compressed = compressed
  539. return me
  540. except Exception as e:
  541. m = '{!r}: invalid value for pubkey ({})'.format(s,e[0])
  542. return cls.init_fail(m,on_fail)
  543. class PrivKey(str,Hilite,InitErrors,MMGenObject):
  544. color = 'red'
  545. width = 64
  546. trunc_ok = False
  547. compressed = MMGenImmutableAttr('compressed',bool,typeconv=False)
  548. wif = MMGenImmutableAttr('wif',WifKey,typeconv=False)
  549. # initialize with (priv_bin,compressed), WIF or self
  550. def __new__(cls,s=None,compressed=None,wif=None,pubkey_type=None,on_fail='die'):
  551. from mmgen.globalvars import g
  552. if type(s) == cls: return s
  553. cls.arg_chk(cls,on_fail)
  554. if wif:
  555. try:
  556. assert s == None
  557. assert set(wif) <= set(ascii_letters+digits),'not an ascii string'
  558. w2h = g.proto.wif2hex(wif) # raises exception on error
  559. me = str.__new__(cls,w2h['hex'])
  560. me.compressed = w2h['compressed']
  561. me.pubkey_type = w2h['pubkey_type']
  562. me.wif = str.__new__(WifKey,wif) # check has been done
  563. me.orig_hex = None
  564. return me
  565. except Exception as e:
  566. fs = "Value {!r} cannot be converted to {} WIF key ({})"
  567. return cls.init_fail(fs.format(wif,g.coin,e[0]),on_fail)
  568. try:
  569. assert s and type(compressed) == bool and pubkey_type,'Incorrect args for PrivKey()'
  570. assert len(s) == cls.width / 2,'Key length must be {}'.format(cls.width/2)
  571. me = str.__new__(cls,g.proto.preprocess_key(s.encode('hex'),pubkey_type))
  572. me.orig_hex = s.encode('hex') # save the non-preprocessed key
  573. me.compressed = compressed
  574. me.pubkey_type = pubkey_type
  575. if pubkey_type != 'password': # skip WIF creation for passwds
  576. me.wif = WifKey(g.proto.hex2wif(me,pubkey_type,compressed),on_fail='raise')
  577. return me
  578. except Exception as e:
  579. fs = "Key={!r}\nCompressed={}\nValue pair cannot be converted to PrivKey\n({})"
  580. return cls.init_fail(fs.format(s,compressed,e),on_fail)
  581. class AddrListID(str,Hilite,InitErrors,MMGenObject):
  582. width = 10
  583. trunc_ok = False
  584. color = 'yellow'
  585. def __new__(cls,sid,mmtype,on_fail='die'):
  586. cls.arg_chk(cls,on_fail)
  587. try:
  588. assert type(sid) == SeedID,"{!r} not a SeedID instance".format(sid)
  589. t = MMGenAddrType,MMGenPasswordType
  590. assert type(mmtype) in t,"{!r} not an instance of {}".format(mmtype,','.join([i.__name__ for i in t]))
  591. me = str.__new__(cls,sid+':'+mmtype)
  592. me.sid = sid
  593. me.mmtype = mmtype
  594. return me
  595. except Exception as e:
  596. m = "Cannot create AddrListID ({})".format(e[0])
  597. return cls.init_fail(m,on_fail)
  598. class MMGenLabel(unicode,Hilite,InitErrors):
  599. color = 'pink'
  600. allowed = []
  601. forbidden = []
  602. max_len = 0
  603. min_len = 0
  604. desc = 'label'
  605. def __new__(cls,s,on_fail='die',msg=None):
  606. if type(s) == cls: return s
  607. cls.arg_chk(cls,on_fail)
  608. for k in cls.forbidden,cls.allowed:
  609. assert type(k) == list
  610. for ch in k: assert type(ch) == unicode and len(ch) == 1
  611. try:
  612. s = s.strip()
  613. if type(s) != unicode:
  614. s = s.decode('utf8')
  615. for ch in s:
  616. # Allow: (L)etter,(N)umber,(P)unctuation,(S)ymbol,(Z)space
  617. # Disallow: (C)ontrol,(M)combining
  618. # Combining characters create width formatting issues, so disallow them for now
  619. assert unicodedata.category(ch)[0] not in 'CM','{!r}: {} characters not allowed'.format(
  620. ch,('control','combining')[unicodedata.category(ch)[0]=='M'])
  621. assert len(s) <= cls.max_len, 'too long (>{} symbols)'.format(cls.max_len)
  622. assert len(s) >= cls.min_len, 'too short (<{} symbols)'.format(cls.min_len)
  623. assert not cls.allowed or set(list(s)).issubset(set(cls.allowed)),\
  624. u'contains non-allowed symbols: {}'.format(' '.join(set(list(s)) - set(cls.allowed)))
  625. assert not cls.forbidden or not any(ch in s for ch in cls.forbidden),\
  626. u"contains one of these forbidden symbols: '{}'".format("', '".join(cls.forbidden))
  627. return unicode.__new__(cls,s)
  628. except Exception as e:
  629. m = u"{!r}: value cannot be converted to {} ({})"
  630. return cls.init_fail(m.format(s,cls.__name__,e),on_fail)
  631. class MMGenWalletLabel(MMGenLabel):
  632. max_len = 48
  633. desc = 'wallet label'
  634. class TwComment(MMGenLabel):
  635. max_len = 40
  636. desc = 'tracking wallet comment'
  637. class MMGenTXLabel(MMGenLabel):
  638. max_len = 72
  639. desc = 'transaction label'
  640. class MMGenPWIDString(MMGenLabel):
  641. max_len = 256
  642. min_len = 1
  643. desc = 'password ID string'
  644. forbidden = list(u' :/\\')
  645. class MMGenAddrType(str,Hilite,InitErrors,MMGenObject):
  646. width = 1
  647. trunc_ok = False
  648. color = 'blue'
  649. mmtypes = { # 'name' is used to cook the seed, so it must never change!
  650. 'L': { 'name':'legacy',
  651. 'pubkey_type':'std',
  652. 'compressed':False,
  653. 'gen_method':'p2pkh',
  654. 'addr_fmt':'p2pkh',
  655. 'desc':'Legacy uncompressed address'},
  656. 'C': { 'name':'compressed',
  657. 'pubkey_type':'std',
  658. 'compressed':True,
  659. 'gen_method':'p2pkh',
  660. 'addr_fmt':'p2pkh',
  661. 'desc':'Compressed P2PKH address'},
  662. 'S': { 'name':'segwit',
  663. 'pubkey_type':'std',
  664. 'compressed':True,
  665. 'gen_method':'segwit',
  666. 'addr_fmt':'p2sh',
  667. 'desc':'Segwit P2SH-P2WPKH address' },
  668. 'B': { 'name':'bech32',
  669. 'pubkey_type':'std',
  670. 'compressed':True,
  671. 'gen_method':'bech32',
  672. 'addr_fmt':'bech32',
  673. 'desc':'Native Segwit (Bech32) address' },
  674. 'E': { 'name':'ethereum',
  675. 'pubkey_type':'std',
  676. 'compressed':False,
  677. 'gen_method':'ethereum',
  678. 'addr_fmt':'ethereum',
  679. 'wif_label':'privkey:',
  680. 'extra_attrs': ('wallet_passwd',),
  681. 'desc':'Ethereum address' },
  682. 'Z': { 'name':'zcash_z',
  683. 'pubkey_type':'zcash_z',
  684. 'compressed':False,
  685. 'gen_method':'zcash_z',
  686. 'addr_fmt':'zcash_z',
  687. 'extra_attrs': ('viewkey',),
  688. 'desc':'Zcash z-address' },
  689. 'M': { 'name':'monero',
  690. 'pubkey_type':'monero',
  691. 'compressed':False,
  692. 'gen_method':'monero',
  693. 'addr_fmt':'monero',
  694. 'wif_label':'spendkey:',
  695. 'extra_attrs': ('viewkey','wallet_passwd'),
  696. 'desc':'Monero address'}
  697. }
  698. def __new__(cls,s,on_fail='die',errmsg=None):
  699. if type(s) == cls: return s
  700. cls.arg_chk(cls,on_fail)
  701. from mmgen.globalvars import g
  702. try:
  703. for k,v in cls.mmtypes.items():
  704. if s in (k,v['name']):
  705. if s == v['name']: s = k
  706. me = str.__new__(cls,s)
  707. for k in ('name','pubkey_type','compressed','gen_method','addr_fmt','desc'):
  708. setattr(me,k,v[k])
  709. assert me in g.proto.mmtypes + ('P',), (
  710. "'{}': invalid address type for {}".format(me.name,g.proto.__name__))
  711. me.extra_attrs = v['extra_attrs'] if 'extra_attrs' in v else ()
  712. me.wif_label = v['wif_label'] if 'wif_label' in v else 'wif:'
  713. return me
  714. raise ValueError,'not found'
  715. except Exception as e:
  716. m = '{}{!r}: invalid value for {} ({})'.format(
  717. ('{!r}\n'.format(errmsg) if errmsg else ''),s,cls.__name__,e[0])
  718. return cls.init_fail(m,on_fail)
  719. @classmethod
  720. def get_names(cls):
  721. return [v['name'] for v in cls.mmtypes.values()]
  722. class MMGenPasswordType(MMGenAddrType):
  723. mmtypes = {
  724. 'P': { 'name':'password',
  725. 'pubkey_type':'password',
  726. 'compressed':False,
  727. 'gen_method':None,
  728. 'addr_fmt':None,
  729. 'desc':'Password generated from MMGen seed'}
  730. }