obj.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2022 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,re,unicodedata
  22. from .objmethods import *
  23. from .exception import BadTwComment
  24. def get_obj(objname,*args,**kwargs):
  25. """
  26. Wrapper for data objects
  27. - If the object throws an exception on instantiation, return False, otherwise return the object.
  28. - If silent is True, suppress display of the exception.
  29. - If return_bool is True, return True instead of the object.
  30. Only keyword args are accepted.
  31. """
  32. assert args == (), 'get_obj_chk1'
  33. silent,return_bool = (False,False)
  34. if 'silent' in kwargs:
  35. silent = kwargs['silent']
  36. del kwargs['silent']
  37. if 'return_bool' in kwargs:
  38. return_bool = kwargs['return_bool']
  39. del kwargs['return_bool']
  40. try:
  41. ret = objname(**kwargs)
  42. except Exception as e:
  43. if not silent:
  44. from .util import msg
  45. msg(f'{e!s}')
  46. return False
  47. else:
  48. return True if return_bool else ret
  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(f'{desc} not implemented for type {type(self).__name__}')
  72. class MMGenList(list,MMGenObject):
  73. pass
  74. class MMGenDict(dict,MMGenObject):
  75. pass
  76. class ImmutableAttr: # Descriptor
  77. """
  78. For attributes that are always present in the data instance
  79. Reassignment and deletion forbidden
  80. """
  81. ok_dtypes = (type,type(None),type(lambda:0))
  82. def __init__(self,dtype,typeconv=True,set_none_ok=False,include_proto=False):
  83. assert isinstance(dtype,self.ok_dtypes), 'ImmutableAttr_check1'
  84. if include_proto:
  85. assert typeconv, 'ImmutableAttr_check2'
  86. if set_none_ok:
  87. assert typeconv and type(dtype) != str, 'ImmutableAttr_check3'
  88. if dtype is None:
  89. 'use instance-defined conversion function for this attribute'
  90. self.conv = lambda instance,value: getattr(instance.conv_funcs,self.name)(instance,value)
  91. elif typeconv:
  92. "convert this attribute's type"
  93. if set_none_ok:
  94. self.conv = lambda instance,value: None if value is None else dtype(value)
  95. elif include_proto:
  96. self.conv = lambda instance,value: dtype(instance.proto,value)
  97. else:
  98. self.conv = lambda instance,value: dtype(value)
  99. else:
  100. "check this attribute's type"
  101. def assign_with_check(instance,value):
  102. if type(value) == dtype:
  103. return value
  104. raise TypeError('Attribute {!r} of {} instance must of type {}'.format(
  105. self.name,
  106. type(instance).__name__,
  107. dtype ))
  108. self.conv = assign_with_check
  109. def __set_name__(self,owner,name):
  110. self.name = name
  111. def __get__(self,instance,owner):
  112. return instance.__dict__[self.name]
  113. def setattr_condition(self,instance):
  114. 'forbid all reassignment'
  115. return not self.name in instance.__dict__
  116. def __set__(self,instance,value):
  117. if not self.setattr_condition(instance):
  118. raise AttributeError(f'Attribute {self.name!r} of {type(instance)} instance cannot be reassigned')
  119. instance.__dict__[self.name] = self.conv(instance,value)
  120. def __delete__(self,instance):
  121. raise AttributeError(
  122. f'Attribute {self.name!r} of {type(instance).__name__} instance cannot be deleted')
  123. class ListItemAttr(ImmutableAttr):
  124. """
  125. For attributes that might not be present in the data instance
  126. Reassignment or deletion allowed if specified
  127. """
  128. def __init__(self,dtype,typeconv=True,include_proto=False,reassign_ok=False,delete_ok=False):
  129. self.reassign_ok = reassign_ok
  130. self.delete_ok = delete_ok
  131. ImmutableAttr.__init__(self,dtype,typeconv=typeconv,include_proto=include_proto)
  132. def __get__(self,instance,owner):
  133. "return None if attribute doesn't exist"
  134. try: return instance.__dict__[self.name]
  135. except: return None
  136. def setattr_condition(self,instance):
  137. return getattr(instance,self.name) == None or self.reassign_ok
  138. def __delete__(self,instance):
  139. if self.delete_ok:
  140. if self.name in instance.__dict__:
  141. del instance.__dict__[self.name]
  142. else:
  143. ImmutableAttr.__delete__(self,instance)
  144. class MMGenListItem(MMGenObject):
  145. valid_attrs = set()
  146. valid_attrs_extra = set()
  147. invalid_attrs = {
  148. 'pfmt',
  149. 'pmsg',
  150. 'pdie',
  151. 'valid_attrs',
  152. 'valid_attrs_extra',
  153. 'invalid_attrs',
  154. 'immutable_attr_init_check',
  155. 'conv_funcs',
  156. '_asdict',
  157. }
  158. def __init__(self,*args,**kwargs):
  159. # generate valid_attrs, or use the class valid_attrs if set
  160. self.__dict__['valid_attrs'] = self.valid_attrs or (
  161. ( {e for e in dir(self) if e[:2] != '__'} | self.valid_attrs_extra )
  162. - MMGenListItem.invalid_attrs
  163. - self.invalid_attrs
  164. )
  165. if args:
  166. raise ValueError(f'Non-keyword args not allowed in {type(self).__name__!r} constructor')
  167. for k,v in kwargs.items():
  168. if v != None:
  169. setattr(self,k,v)
  170. # Require all immutables to be initialized. Check performed only when testing.
  171. self.immutable_attr_init_check()
  172. # allow only valid attributes to be set
  173. def __setattr__(self,name,value):
  174. if name not in self.valid_attrs:
  175. raise AttributeError(f'{name!r}: no such attribute in class {type(self)}')
  176. return object.__setattr__(self,name,value)
  177. def _asdict(self):
  178. return dict((k,v) for k,v in self.__dict__.items() if k in self.valid_attrs)
  179. class MMGenRange(tuple,InitErrors,MMGenObject):
  180. min_idx = None
  181. max_idx = None
  182. def __new__(cls,*args):
  183. try:
  184. if len(args) == 1:
  185. s = args[0]
  186. if type(s) == cls:
  187. return s
  188. assert isinstance(s,str),'not a string or string subclass'
  189. ss = s.split('-',1)
  190. first = int(ss[0])
  191. last = int(ss.pop())
  192. else:
  193. s = repr(args) # needed if exception occurs
  194. assert len(args) == 2,'one format string arg or two start,stop args required'
  195. first,last = args
  196. assert first <= last, 'start of range greater than end of range'
  197. if cls.min_idx is not None:
  198. assert first >= cls.min_idx, f'start of range < {cls.min_idx:,}'
  199. if cls.max_idx is not None:
  200. assert last <= cls.max_idx, f'end of range > {cls.max_idx:,}'
  201. return tuple.__new__(cls,(first,last))
  202. except Exception as e:
  203. return cls.init_fail(e,s)
  204. @property
  205. def first(self):
  206. return self[0]
  207. @property
  208. def last(self):
  209. return self[1]
  210. def iterate(self):
  211. return range(self[0],self[1]+1)
  212. @property
  213. def items(self):
  214. return list(self.iterate())
  215. class Int(int,Hilite,InitErrors):
  216. min_val = None
  217. max_val = None
  218. max_digits = None
  219. color = 'red'
  220. def __new__(cls,n,base=10):
  221. if type(n) == cls:
  222. return n
  223. try:
  224. me = int.__new__(cls,str(n),base)
  225. if cls.min_val != None:
  226. assert me >= cls.min_val, f'is less than cls.min_val ({cls.min_val})'
  227. if cls.max_val != None:
  228. assert me <= cls.max_val, f'is greater than cls.max_val ({cls.max_val})'
  229. if cls.max_digits != None:
  230. assert len(str(me)) <= cls.max_digits, f'has more than {cls.max_digits} digits'
  231. return me
  232. except Exception as e:
  233. return cls.init_fail(e,n)
  234. @classmethod
  235. def fmtc(cls,*args,**kwargs):
  236. cls.method_not_implemented()
  237. @classmethod
  238. def colorize(cls,n,color=True):
  239. return super().colorize(repr(n),color=color)
  240. class MMGenIdx(Int):
  241. min_val = 1
  242. class ETHNonce(Int):
  243. min_val = 0
  244. class Str(str,Hilite):
  245. pass
  246. class HexStr(str,Hilite,InitErrors):
  247. color = 'red'
  248. width = None
  249. hexcase = 'lower'
  250. trunc_ok = False
  251. def __new__(cls,s,case=None):
  252. if type(s) == cls:
  253. return s
  254. if case == None:
  255. case = cls.hexcase
  256. from .util import hexdigits_lc,hexdigits_uc
  257. try:
  258. assert isinstance(s,str),'not a string or string subclass'
  259. assert case in ('upper','lower'), f'{case!r} incorrect case specifier'
  260. assert set(s) <= set(hexdigits_lc if case == 'lower' else hexdigits_uc), (
  261. f'not {case}case hexadecimal symbols' )
  262. assert not len(s) % 2,'odd-length string'
  263. if cls.width:
  264. assert len(s) == cls.width, f'Value is not {cls.width} characters wide'
  265. return str.__new__(cls,s)
  266. except Exception as e:
  267. return cls.init_fail(e,s)
  268. class CoinTxID(HexStr):
  269. color,width,hexcase = ('purple',64,'lower')
  270. class WalletPassword(HexStr):
  271. color,width,hexcase = ('blue',32,'lower')
  272. class MMGenTxID(HexStr):
  273. color,width,hexcase = ('red',6,'upper')
  274. class MMGenLabel(str,Hilite,InitErrors):
  275. color = 'pink'
  276. allowed = []
  277. forbidden = []
  278. max_len = 0
  279. min_len = 0
  280. max_screen_width = 0 # if != 0, overrides max_len
  281. desc = 'label'
  282. def __new__(cls,s,msg=None):
  283. if type(s) == cls:
  284. return s
  285. for k in ( cls.forbidden, cls.allowed ):
  286. assert type(k) == list
  287. for ch in k:
  288. assert type(ch) == str and len(ch) == 1
  289. try:
  290. s = s.strip()
  291. for ch in s:
  292. # Allow: (L)etter,(N)umber,(P)unctuation,(S)ymbol,(Z)space
  293. # Disallow: (C)ontrol,(M)combining
  294. # Combining characters create width formatting issues, so disallow them for now
  295. if unicodedata.category(ch)[0] in ('C','M'):
  296. raise ValueError('{!a}: {} characters not allowed'.format(ch,
  297. { 'C':'control', 'M':'combining' }[unicodedata.category(ch)[0]] ))
  298. me = str.__new__(cls,s)
  299. if cls.max_screen_width:
  300. me.screen_width = len(s) + len([1 for ch in s if unicodedata.east_asian_width(ch) in ('F','W')])
  301. assert me.screen_width <= cls.max_screen_width, f'too wide (>{cls.max_screen_width} screen width)'
  302. else:
  303. assert len(s) <= cls.max_len, f'too long (>{cls.max_len} symbols)'
  304. assert len(s) >= cls.min_len, f'too short (<{cls.min_len} symbols)'
  305. if cls.allowed and not set(list(s)).issubset(set(cls.allowed)):
  306. raise ValueError('contains non-allowed symbols: ' + ' '.join(set(list(s)) - set(cls.allowed)) )
  307. if cls.forbidden and any(ch in s for ch in cls.forbidden):
  308. raise ValueError('contains one of these forbidden symbols: ' + ' '.join(cls.forbidden) )
  309. return me
  310. except Exception as e:
  311. return cls.init_fail(e,s)
  312. class MMGenWalletLabel(MMGenLabel):
  313. max_len = 48
  314. desc = 'wallet label'
  315. class TwComment(MMGenLabel):
  316. max_screen_width = 80
  317. desc = 'tracking wallet comment'
  318. exc = BadTwComment
  319. class MMGenTxLabel(MMGenLabel):
  320. max_len = 72
  321. desc = 'transaction label'
  322. class MMGenPWIDString(MMGenLabel):
  323. max_len = 256
  324. min_len = 1
  325. desc = 'password ID string'
  326. forbidden = list(' :/\\')
  327. trunc_ok = False