obj.py 30 KB

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