util.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. util: Frequently-used variables, classes and utility functions for the MMGen suite
  20. """
  21. import sys,os,time,re
  22. from .color import red,yellow,green,blue,purple
  23. from .cfg import gv,gc
  24. ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
  25. hexdigits = '0123456789abcdefABCDEF'
  26. hexdigits_uc = '0123456789ABCDEF'
  27. hexdigits_lc = '0123456789abcdef'
  28. def noop(*args,**kwargs):
  29. pass
  30. class Util:
  31. def __init__(self,cfg):
  32. self.cfg = cfg
  33. if cfg.quiet:
  34. self.qmsg = self.qmsg_r = noop
  35. else:
  36. self.qmsg = msg
  37. self.qmsg_r = msg_r
  38. if cfg.verbose:
  39. self.vmsg = msg
  40. self.vmsg_r = msg_r
  41. self.Vmsg = Msg
  42. self.Vmsg_r = Msg_r
  43. else:
  44. self.vmsg = self.vmsg_r = self.Vmsg = self.Vmsg_r = noop
  45. self.dmsg = msg if cfg.debug else noop
  46. if cfg.pager:
  47. from .ui import do_pager
  48. self.stdout_or_pager = do_pager
  49. else:
  50. self.stdout_or_pager = Msg_r
  51. def compare_chksums(
  52. self,
  53. chk1,
  54. desc1,
  55. chk2,
  56. desc2,
  57. hdr = '',
  58. die_on_fail = False,
  59. verbose = False):
  60. if not chk1 == chk2:
  61. fs = "{} ERROR: {} checksum ({}) doesn't match {} checksum ({})"
  62. m = fs.format((hdr+':\n ' if hdr else 'CHECKSUM'),desc2,chk2,desc1,chk1)
  63. if die_on_fail:
  64. die(3,m)
  65. else:
  66. if verbose or self.cfg.verbose:
  67. msg(m)
  68. return False
  69. if self.cfg.verbose:
  70. msg(f'{capfirst(desc1)} checksum OK ({chk1})')
  71. return True
  72. def compare_or_die(self, val1, desc1, val2, desc2, e='Error'):
  73. if val1 != val2:
  74. die(3,f"{e}: {desc2} ({val2}) doesn't match {desc1} ({val1})")
  75. if self.cfg.debug:
  76. msg(f'{capfirst(desc2)} OK ({val2})')
  77. return True
  78. if gc.platform == 'win':
  79. def msg_r(s):
  80. try:
  81. gv.stderr.write(s)
  82. gv.stderr.flush()
  83. except:
  84. os.write(2,s.encode())
  85. def msg(s):
  86. msg_r(s + '\n')
  87. def Msg_r(s):
  88. try:
  89. gv.stdout.write(s)
  90. gv.stdout.flush()
  91. except:
  92. os.write(1,s.encode())
  93. def Msg(s):
  94. Msg_r(s + '\n')
  95. else:
  96. def msg(s):
  97. gv.stderr.write(s + '\n')
  98. def msg_r(s):
  99. gv.stderr.write(s)
  100. gv.stderr.flush()
  101. def Msg(s):
  102. gv.stdout.write(s + '\n')
  103. def Msg_r(s):
  104. gv.stdout.write(s)
  105. gv.stdout.flush()
  106. def rmsg(s):
  107. msg(red(s))
  108. def ymsg(s):
  109. msg(yellow(s))
  110. def gmsg(s):
  111. msg(green(s))
  112. def gmsg_r(s):
  113. msg_r(green(s))
  114. def bmsg(s):
  115. msg(blue(s))
  116. def pumsg(s):
  117. msg(purple(s))
  118. def mmsg(*args):
  119. for d in args:
  120. Msg(repr(d))
  121. def mdie(*args):
  122. mmsg(*args)
  123. sys.exit(0)
  124. def die(ev,s='',stdout=False):
  125. if isinstance(ev,int):
  126. from .exception import MMGenSystemExit,MMGenError
  127. if ev <= 2:
  128. raise MMGenSystemExit(ev,s,stdout)
  129. else:
  130. raise MMGenError(ev,s,stdout)
  131. elif isinstance(ev,str):
  132. import mmgen.exception
  133. raise getattr(mmgen.exception,ev)(s)
  134. else:
  135. raise ValueError(f'{ev}: exit value must be string or int instance')
  136. def Die(ev=0,s=''):
  137. die(ev=ev,s=s,stdout=True)
  138. def pp_fmt(d):
  139. import pprint
  140. return pprint.PrettyPrinter(indent=4,compact=False).pformat(d)
  141. def pp_msg(d):
  142. msg(pp_fmt(d))
  143. def fmt(s,indent='',strip_char=None,append='\n'):
  144. "de-indent multiple lines of text, or indent with specified string"
  145. return indent + ('\n'+indent).join([l.strip(strip_char) for l in s.strip().splitlines()]) + append
  146. def fmt_list(iterable,fmt='dfl',indent='',conv=None):
  147. "pretty-format a list"
  148. _conv,sep,lq,rq = {
  149. 'dfl': ( str, ", ", "'", "'"),
  150. 'utf8': ( str, ", ", "“", "”"),
  151. 'bare': ( repr, " ", "", ""),
  152. 'no_quotes': ( str, ", ", "", ""),
  153. 'no_spc': ( str, ",", "'", "'"),
  154. 'min': ( str, ",", "", ""),
  155. 'repr': ( repr, ", ", "", ""),
  156. 'csv': ( repr, ",", "", ""),
  157. 'col': ( str, "\n", "", ""),
  158. }[fmt]
  159. conv = conv or _conv
  160. return indent + (sep+indent).join(lq+conv(e)+rq for e in iterable)
  161. def fmt_dict(mapping,fmt='dfl',kconv=None,vconv=None):
  162. "pretty-format a dict"
  163. kc,vc,sep,fs = {
  164. 'dfl': ( str, str, ", ", "'{}' ({})" ),
  165. 'square': ( str, str, ", ", "'{}' [{}]" ),
  166. 'equal': ( str, str, ", ", "'{}'={}" ),
  167. 'equal_spaced': ( str, str, ", ", "'{}' = {}" ),
  168. 'kwargs': ( str, repr, ", ", "{}={}" ),
  169. 'colon': ( str, repr, ", ", "{}:{}" ),
  170. }[fmt]
  171. kconv = kconv or kc
  172. vconv = vconv or vc
  173. return sep.join(fs.format(kconv(k),vconv(v)) for k,v in mapping.items())
  174. def list_gen(*data):
  175. """
  176. Generate a list from an arg tuple of sublists
  177. - The last element of each sublist is a condition. If it evaluates to true, the preceding
  178. elements of the sublist are included in the result. Otherwise the sublist is skipped.
  179. - If a sublist contains only one element, the condition defaults to true.
  180. """
  181. assert type(data) in (list,tuple), f'{type(data).__name__} not in (list,tuple)'
  182. def gen():
  183. for d in data:
  184. assert isinstance(d,list), f'{type(d).__name__} != list'
  185. if len(d) == 1:
  186. yield d[0]
  187. elif d[-1]:
  188. for idx in range(len(d)-1):
  189. yield d[idx]
  190. return list(gen())
  191. def remove_dups(iterable,edesc='element',desc='list',quiet=False,hide=False):
  192. """
  193. Remove duplicate occurrences of iterable elements, preserving first occurrence
  194. If iterable is a generator, return a list, else type(iterable)
  195. """
  196. ret = []
  197. for e in iterable:
  198. if e in ret:
  199. if not quiet:
  200. ymsg(f'Warning: removing duplicate {edesc} {"(hidden)" if hide else e} in {desc}')
  201. else:
  202. ret.append(e)
  203. return ret if type(iterable).__name__ == 'generator' else type(iterable)(ret)
  204. def contains_any(target_list,source_list):
  205. return any(map(target_list.count,source_list))
  206. def suf(arg,suf_type='s',verb='none'):
  207. suf_types = {
  208. 'none': {
  209. 's': ('s', ''),
  210. 'es': ('es', ''),
  211. 'ies': ('ies','y'),
  212. },
  213. 'is': {
  214. 's': ('s are', ' is'),
  215. 'es': ('es are', ' is'),
  216. 'ies': ('ies are','y is'),
  217. },
  218. 'has': {
  219. 's': ('s have', ' has'),
  220. 'es': ('es have', ' has'),
  221. 'ies': ('ies have','y has'),
  222. },
  223. }
  224. if isinstance(arg,int):
  225. n = arg
  226. elif isinstance(arg,(list,tuple,set,dict)):
  227. n = len(arg)
  228. else:
  229. die(2,f'{arg}: invalid parameter for suf()')
  230. return suf_types[verb][suf_type][n == 1]
  231. def get_extension(fn):
  232. return os.path.splitext(fn)[1][1:]
  233. def remove_extension(fn,ext):
  234. a,b = os.path.splitext(fn)
  235. return a if b[1:] == ext else fn
  236. def make_chksum_N(s,nchars,sep=False,rounds=2,upper=True):
  237. if isinstance(s,str):
  238. s = s.encode()
  239. from hashlib import sha256
  240. for i in range(rounds):
  241. s = sha256(s).digest()
  242. ret = s.hex()[:nchars]
  243. if sep:
  244. assert 4 <= nchars <= 64 and (not nchars % 4), 'illegal ‘nchars’ value'
  245. ret = ' '.join( ret[i:i+4] for i in range(0,nchars,4) )
  246. else:
  247. assert 4 <= nchars <= 64, 'illegal ‘nchars’ value'
  248. return ret.upper() if upper else ret
  249. def make_chksum_8(s,sep=False):
  250. from .obj import HexStr
  251. from hashlib import sha256
  252. s = HexStr(sha256(sha256(s).digest()).hexdigest()[:8].upper(),case='upper')
  253. return '{} {}'.format(s[:4],s[4:]) if sep else s
  254. def make_chksum_6(s):
  255. from .obj import HexStr
  256. from hashlib import sha256
  257. if isinstance(s,str):
  258. s = s.encode()
  259. return HexStr(sha256(s).hexdigest()[:6])
  260. def is_chksum_6(s):
  261. return len(s) == 6 and set(s) <= set(hexdigits_lc)
  262. def split_into_cols(col_wid,s):
  263. return ' '.join([s[col_wid*i:col_wid*(i+1)] for i in range(len(s)//col_wid+1)]).rstrip()
  264. def capfirst(s): # different from str.capitalize() - doesn't downcase any uc in string
  265. return s if len(s) == 0 else s[0].upper() + s[1:]
  266. def decode_timestamp(s):
  267. # tz_save = open('/etc/timezone').read().rstrip()
  268. os.environ['TZ'] = 'UTC'
  269. # os.environ['TZ'] = tz_save
  270. return int(time.mktime( time.strptime(s,'%Y%m%d_%H%M%S') ))
  271. def make_timestamp(secs=None):
  272. return '{:04d}{:02d}{:02d}_{:02d}{:02d}{:02d}'.format(*time.gmtime(
  273. int(secs) if secs is not None else time.time() )[:6])
  274. def make_timestr(secs=None):
  275. return '{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}'.format(*time.gmtime(
  276. int(secs) if secs is not None else time.time() )[:6])
  277. def secs_to_dhms(secs):
  278. hrs = secs // 3600
  279. return '{}{:02d}:{:02d}:{:02d} h/m/s'.format(
  280. ('{} day{}, '.format(hrs//24,suf(hrs//24)) if hrs > 24 else ''),
  281. hrs % 24,
  282. (secs // 60) % 60,
  283. secs % 60
  284. )
  285. def secs_to_hms(secs):
  286. return '{:02d}:{:02d}:{:02d}'.format(secs//3600, (secs//60) % 60, secs % 60)
  287. def secs_to_ms(secs):
  288. return '{:02d}:{:02d}'.format(secs//60, secs % 60)
  289. def is_int(s):
  290. try:
  291. int(str(s))
  292. return True
  293. except:
  294. return False
  295. def check_int_between(val,imin,imax,desc):
  296. if not imin <= int(val) <= imax:
  297. die(1,f'{val}: invalid value for {desc} (must be between {imin} and {imax})')
  298. return int(val)
  299. def is_hex_str(s):
  300. return set(s) <= set(hexdigits)
  301. def is_hex_str_lc(s):
  302. return set(s) <= set(hexdigits_lc)
  303. def is_utf8(s):
  304. try:
  305. s.decode('utf8')
  306. except:
  307. return False
  308. else:
  309. return True
  310. def remove_whitespace(s,ws='\t\r\n '):
  311. return s.translate(dict((ord(e),None) for e in ws))
  312. def strip_comment(line):
  313. return re.sub('#.*','',line).rstrip()
  314. def strip_comments(lines):
  315. pat = re.compile('#.*')
  316. return [m for m in [pat.sub('',l).rstrip() for l in lines] if m != '']
  317. def make_full_path(outdir,outfile):
  318. return os.path.normpath(os.path.join(outdir, os.path.basename(outfile)))
  319. class oneshot_warning:
  320. color = 'nocolor'
  321. def __init__(self,div=None,fmt_args=[],reverse=False):
  322. self.do(type(self),div,fmt_args,reverse)
  323. def do(self,wcls,div,fmt_args,reverse):
  324. def do_warning():
  325. import mmgen.color
  326. message = getattr(wcls,'message')
  327. color = getattr( mmgen.color, getattr(wcls,'color') )
  328. msg(color('WARNING: ' + message.format(*fmt_args)))
  329. if not hasattr(wcls,'data'):
  330. setattr(wcls,'data',[])
  331. data = getattr(wcls,'data')
  332. condition = (div in data) if reverse else (not div in data)
  333. if not div in data:
  334. data.append(div)
  335. if condition:
  336. do_warning()
  337. self.warning_shown = True
  338. else:
  339. self.warning_shown = False
  340. class oneshot_warning_group(oneshot_warning):
  341. def __init__(self,wcls,div=None,fmt_args=[],reverse=False):
  342. self.do(getattr(self,wcls),div,fmt_args,reverse)
  343. def get_subclasses(cls,names=False):
  344. def gen(cls):
  345. for i in cls.__subclasses__():
  346. yield i
  347. for j in gen(i):
  348. yield j
  349. return tuple((c.__name__ for c in gen(cls)) if names else gen(cls))
  350. def async_run(coro):
  351. import asyncio
  352. return asyncio.run(coro)
  353. def load_cryptodomex(called=[]):
  354. if not called:
  355. try:
  356. import Cryptodome
  357. except ImportError:
  358. import Crypto
  359. sys.modules['Cryptodome'] = sys.modules['Crypto']
  360. called.append(True)
  361. def wrap_ripemd160(called=[]):
  362. if not called:
  363. try:
  364. import hashlib
  365. hashlib.new('ripemd160')
  366. except ValueError:
  367. def hashlib_new_wrapper(name,*args,**kwargs):
  368. if name == 'ripemd160':
  369. return ripemd160(*args,**kwargs)
  370. else:
  371. return hashlib_new(name,*args,**kwargs)
  372. from .contrib.ripemd160 import ripemd160
  373. hashlib_new = hashlib.new
  374. hashlib.new = hashlib_new_wrapper
  375. called.append(True)
  376. def exit_if_mswin(feature):
  377. if gc.platform == 'win':
  378. die(2, capfirst(feature) + ' not supported on the MSWin / MSYS2 platform' )