obj.py 11 KB

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