common.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2024 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. test.include.common: Shared routines and data for the MMGen test suites
  20. """
  21. import sys, os, re, atexit
  22. from subprocess import run, PIPE, DEVNULL
  23. from pathlib import Path
  24. from mmgen.cfg import gv
  25. from mmgen.color import yellow, green, orange
  26. from mmgen.util import msg, msg_r, Msg, Msg_r, gmsg, die, suf, fmt_list
  27. from mmgen.fileutil import write_data_to_file, get_data_from_file
  28. def noop(*args, **kwargs):
  29. pass
  30. def set_globals(cfg):
  31. """
  32. make `cfg`, `qmsg`, `vmsg`, etc. available as globals to scripts by setting
  33. the module attr
  34. """
  35. import test.include.common as this
  36. this.cfg = cfg
  37. if cfg.quiet:
  38. this.qmsg = this.qmsg_r = noop
  39. else:
  40. this.qmsg = msg
  41. this.qmsg_r = msg_r
  42. if cfg.verbose:
  43. this.vmsg = msg
  44. this.vmsg_r = msg_r
  45. this.Vmsg = Msg
  46. this.Vmsg_r = Msg_r
  47. else:
  48. this.vmsg = this.vmsg_r = this.Vmsg = this.Vmsg_r = noop
  49. this.dmsg = msg if cfg.debug else noop
  50. def strip_ansi_escapes(s):
  51. return re.sub('\x1b' + r'\[[;0-9]+?m', '', s)
  52. cmdtest_py_log_fn = 'cmdtest.py.log'
  53. cmdtest_py_error_fn = 'cmdtest.py.err'
  54. parity_dev_amt = 1606938044258990275541962092341162602522202993782792835301376
  55. ascii_uc = ''.join(map(chr, list(range(65, 91)))) # 26 chars
  56. ascii_lc = ''.join(map(chr, list(range(97, 123)))) # 26 chars
  57. lat_accent = ''.join(map(chr, list(range(192, 383)))) # 191 chars, L, S
  58. ru_uc = ''.join(map(chr, list(range(1040, 1072)))) # 32 chars
  59. gr_uc = ''.join(map(chr, list(range(913, 930)) + list(range(931, 940)))) # 26 chars (930 is ctrl char)
  60. gr_uc_w_ctrl = ''.join(map(chr, list(range(913, 940)))) # 27 chars, L, C
  61. lat_cyr_gr = lat_accent[:130:5] + ru_uc + gr_uc # 84 chars
  62. ascii_cyr_gr = ascii_uc + ru_uc + gr_uc # 84 chars
  63. utf8_text = '[α-$ample UTF-8 text-ω]' * 10 # 230 chars, L, N, P, S, Z
  64. utf8_combining = '[α-$ámple UTF-8 téxt-ω]' * 10 # L, N, P, S, Z, M
  65. utf8_ctrl = '[α-$ample\nUTF-8\ntext-ω]' * 10 # L, N, P, S, Z, C
  66. text_jp = '必要なのは、信用ではなく暗号化された証明に基づく電子取引システムであり、これにより希望する二者が信用できる第三者機関を介さずに直接取引できるよう' # 72 chars ('W'ide)
  67. text_zh = '所以,我們非常需要這樣一種電子支付系統,它基於密碼學原理而不基於信用,使得任何達成一致的雙方,能夠直接進行支付,從而不需要協力廠商仲介的參與。。' # 72 chars ('F'ull + 'W'ide)
  68. sample_text = 'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks'
  69. sample_mn = {
  70. 'mmgen': { # 'able': 0, 'youth': 1625, 'after' == 'afternoon'[:5]
  71. 'mn': 'able cast forgive master funny gaze after afternoon million paint moral youth',
  72. 'hex': '0005685ab4e94cbe3b228cf92112bc5f',
  73. },
  74. 'bip39': { # len('sun') < uniq_ss_len
  75. 'mn': 'vessel ladder alter error federal sibling chat ability sun glass valve picture',
  76. 'hex': 'f30f8c1da665478f49b001d94c5fc452',
  77. },
  78. 'xmrseed': {
  79. 'mn': 'viewpoint donuts ardent template unveil agile meant unafraid urgent athlete rustled mime azure jaded hawk baby jagged haystack baby jagged haystack ramped oncoming point template',
  80. 'hex': 'e8164dda6d42bd1e261a3406b2038dcbddadbeefdeadbeefdeadbeefdeadbe0f',
  81. },
  82. }
  83. ref_kafile_pass = 'kafile password'
  84. ref_kafile_hash_preset = '1'
  85. proto_cmds = (
  86. 'addrimport',
  87. 'autosign',
  88. 'msg',
  89. 'regtest',
  90. 'tool',
  91. 'txbump',
  92. 'txcreate',
  93. 'txdo',
  94. 'txsend',
  95. 'txsign',
  96. 'xmrwallet',
  97. )
  98. def getrand(n):
  99. if cfg.test_suite_deterministic:
  100. from mmgen.test import fake_urandom
  101. return fake_urandom(n)
  102. else:
  103. return os.urandom(n)
  104. def getrandnum(n):
  105. return int(getrand(n).hex(), 16)
  106. def getrandhex(n):
  107. return getrand(n).hex()
  108. def getrandnum_range(nbytes, rn_max):
  109. while True:
  110. rn = int(getrand(nbytes).hex(), 16)
  111. if rn < rn_max:
  112. return rn
  113. def getrandstr(num_chars, no_space=False):
  114. n, m = (94, 33) if no_space else (95, 32)
  115. return ''.join(chr(i % n + m) for i in list(getrand(num_chars)))
  116. # Windows uses non-UTF8 encodings in filesystem, so use raw bytes here
  117. def cleandir(d, do_msg=False):
  118. d_enc = d.encode()
  119. try:
  120. files = os.listdir(d_enc)
  121. except:
  122. return None
  123. if files:
  124. from shutil import rmtree
  125. if do_msg:
  126. gmsg(f'Cleaning directory {d!r}')
  127. for f in files:
  128. try:
  129. os.unlink(os.path.join(d_enc, f))
  130. except:
  131. rmtree(os.path.join(d_enc, f), ignore_errors=True)
  132. return files
  133. def mk_tmpdir(d):
  134. try:
  135. os.makedirs(d, mode=0o755, exist_ok=True)
  136. except OSError as e:
  137. if e.errno != 17:
  138. raise
  139. else:
  140. vmsg(f'Created directory {d!r}')
  141. def clean(cfgs, tmpdir_ids=None, extra_dirs=[]):
  142. def clean_tmpdirs():
  143. cfg_tmpdirs = {k:cfgs[k]['tmpdir'] for k in cfgs}
  144. for d in map(str, sorted(map(int, (tmpdir_ids or cfg_tmpdirs)))):
  145. if d in cfg_tmpdirs:
  146. if cleandir(cfg_tmpdirs[d]):
  147. yield d
  148. else:
  149. die(1, f'{d}: invalid directory number')
  150. def clean_extra_dirs():
  151. for d in extra_dirs:
  152. if os.path.exists(d):
  153. if cleandir(d):
  154. yield os.path.relpath(d)
  155. for clean_func, list_fmt in (
  156. (clean_tmpdirs, 'no_quotes'),
  157. (clean_extra_dirs, 'dfl')
  158. ):
  159. if cleaned := list(clean_func()):
  160. iqmsg(green('Cleaned director{} {}'.format(
  161. suf(cleaned, 'ies'),
  162. fmt_list(cleaned, fmt=list_fmt)
  163. )))
  164. for d in extra_dirs:
  165. if (os.path.exists(d) or os.path.islink(d)) and not os.path.isdir(d):
  166. print(f'Removing non-directory ‘{d}’')
  167. os.unlink(d)
  168. def get_tmpfile(cfg, fn):
  169. return os.path.join(cfg['tmpdir'], fn)
  170. def write_to_file(fn, data, binary=False):
  171. write_data_to_file(
  172. cfg,
  173. fn,
  174. data,
  175. quiet = True,
  176. binary = binary,
  177. ignore_opt_outdir = True)
  178. def write_to_tmpfile(cfg, fn, data, binary=False):
  179. write_to_file(os.path.join(cfg['tmpdir'], fn), data=data, binary=binary)
  180. def read_from_file(fn, binary=False):
  181. return get_data_from_file(cfg, fn, quiet=True, binary=binary)
  182. def read_from_tmpfile(cfg, fn, binary=False):
  183. return read_from_file(os.path.join(cfg['tmpdir'], fn), binary=binary)
  184. def joinpath(*args, **kwargs):
  185. return os.path.join(*args, **kwargs)
  186. def ok(text='OK'):
  187. if cfg.profile:
  188. return
  189. if cfg.verbose or cfg.exact_output:
  190. gmsg(text)
  191. else:
  192. msg(f' {text}')
  193. def cmp_or_die(s, t, desc=None):
  194. if s != t:
  195. die('TestSuiteFatalException',
  196. (f'For {desc}:\n' if desc else '') +
  197. f'ERROR: recoded data:\n{t!r}\ndiffers from original data:\n{s!r}'
  198. )
  199. def init_coverage():
  200. coverdir = os.path.join('test', 'trace')
  201. acc_file = os.path.join('test', 'trace.acc')
  202. try:
  203. os.mkdir(coverdir, 0o755)
  204. except:
  205. pass
  206. return coverdir, acc_file
  207. def silence():
  208. if not (cfg.verbose or cfg.exact_output):
  209. gv.stdout = gv.stderr = open(os.devnull, 'w')
  210. def end_silence():
  211. if not (cfg.verbose or cfg.exact_output):
  212. gv.stdout.close()
  213. gv.stdout = sys.stdout
  214. gv.stderr = sys.stderr
  215. def omsg(s):
  216. sys.stderr.write(s + '\n')
  217. def omsg_r(s):
  218. sys.stderr.write(s)
  219. sys.stderr.flush()
  220. def imsg(s):
  221. if cfg.verbose or cfg.exact_output:
  222. omsg(s)
  223. def imsg_r(s):
  224. if cfg.verbose or cfg.exact_output:
  225. omsg_r(s)
  226. def iqmsg(s):
  227. if not cfg.quiet:
  228. omsg(s)
  229. def iqmsg_r(s):
  230. if not cfg.quiet:
  231. omsg_r(s)
  232. def oqmsg(s):
  233. if not (cfg.verbose or cfg.exact_output):
  234. omsg(s)
  235. def oqmsg_r(s):
  236. if not (cfg.verbose or cfg.exact_output):
  237. omsg_r(s)
  238. def end_msg(t):
  239. omsg(green(
  240. 'All requested tests finished OK' +
  241. ('' if cfg.test_suite_deterministic else f', elapsed time: {t//60:02d}:{t%60:02d}')
  242. ))
  243. def start_test_daemons(*network_ids, remove_datadir=False):
  244. if not cfg.no_daemon_autostart:
  245. return test_daemons_ops(*network_ids, op='start', remove_datadir=remove_datadir)
  246. def stop_test_daemons(*network_ids, force=False, remove_datadir=False):
  247. if force or not cfg.no_daemon_stop:
  248. return test_daemons_ops(*network_ids, op='stop', remove_datadir=remove_datadir)
  249. def restart_test_daemons(*network_ids, remove_datadir=False):
  250. if not stop_test_daemons(*network_ids):
  251. return False
  252. return start_test_daemons(*network_ids, remove_datadir=remove_datadir)
  253. def test_daemons_ops(*network_ids, op, remove_datadir=False):
  254. if not cfg.no_daemon_autostart:
  255. from mmgen.daemon import CoinDaemon
  256. silent = not (cfg.verbose or cfg.exact_output)
  257. ret = False
  258. for network_id in network_ids:
  259. d = CoinDaemon(cfg, network_id, test_suite=True)
  260. if remove_datadir:
  261. d.wait = True
  262. d.stop(silent=True)
  263. d.remove_datadir()
  264. ret = d.cmd(op, silent=silent)
  265. return ret
  266. tested_solc_ver = '0.8.26'
  267. def check_solc_ver():
  268. cmd = 'python3 scripts/create-token.py --check-solc-version'
  269. try:
  270. cp = run(cmd.split(), check=False, stdout=PIPE)
  271. except Exception as e:
  272. die(4, f'Unable to execute {cmd!r}: {e}')
  273. res = cp.stdout.decode().strip()
  274. if cp.returncode == 0:
  275. omsg(
  276. orange(f'Found supported solc version {res}') if res == tested_solc_ver else
  277. yellow(f'WARNING: solc version ({res}) does not match tested version ({tested_solc_ver})')
  278. )
  279. return True
  280. else:
  281. omsg(yellow('Warning: Solidity compiler (solc) could not be executed or has unsupported version'))
  282. omsg(res)
  283. return False
  284. def get_ethkey():
  285. cmdnames = ('ethkey', 'openethereum-ethkey')
  286. for cmdname in cmdnames:
  287. try:
  288. run([cmdname, '--help'], stdout=PIPE)
  289. except:
  290. pass
  291. else:
  292. return cmdname
  293. die(1, f'ethkey executable not found (tried {cmdnames})')
  294. def do_run(cmd, check=True):
  295. return run(cmd, stdout=PIPE, stderr=DEVNULL, check=check)
  296. def VirtBlockDevice(img_path, size):
  297. if sys.platform == 'linux':
  298. return VirtBlockDeviceLinux(img_path, size)
  299. elif sys.platform == 'darwin':
  300. return VirtBlockDeviceMacOS(img_path, size)
  301. class VirtBlockDeviceBase:
  302. @property
  303. def dev(self):
  304. res = self._get_associations()
  305. if len(res) < 1:
  306. die(2, f'No device associated with {self.img_path}')
  307. elif len(res) > 1:
  308. die(2, f'More than one device associated with {self.img_path}')
  309. return res[0]
  310. def try_detach(self):
  311. try:
  312. dev = self.dev
  313. except:
  314. pass
  315. else:
  316. self.do_detach(dev, check=False)
  317. def create(self, silent=False):
  318. for dev in self._get_associations():
  319. if not silent:
  320. imsg(f'Detaching associated device {dev}')
  321. self.do_detach(dev)
  322. self.img_path.unlink(missing_ok=True)
  323. if not silent:
  324. imsg(f'Creating block device image file {self.img_path}')
  325. self.do_create(self.size, self.img_path)
  326. atexit.register(self.try_detach)
  327. def attach(self, dev_mode=None, silent=False):
  328. if res := self._get_associations():
  329. die(2, f'Device{suf(res)} {fmt_list(res, fmt="barest")} already associated with {self.img_path}')
  330. dev = self.get_new_dev()
  331. if dev_mode:
  332. self.dev_mode_orig = '0{:o}'.format(os.stat(dev).st_mode & 0xfff)
  333. if not silent:
  334. imsg(f'Changing permissions on device {dev} to {dev_mode!r}')
  335. do_run(['sudo', 'chmod', dev_mode, dev])
  336. if not silent:
  337. imsg(f'Attaching {dev or self.img_path!r}')
  338. self.do_attach(self.img_path, dev)
  339. def detach(self, silent=False):
  340. dev = self.dev
  341. if not silent:
  342. imsg(f'Detaching {dev!r}')
  343. self.do_detach(dev)
  344. if hasattr(self, 'dev_mode_orig'):
  345. if not silent:
  346. imsg(f'Resetting permissions on device {dev} to {self.dev_mode_orig!r}')
  347. do_run(['sudo', 'chmod', self.dev_mode_orig, dev])
  348. delattr(self, 'dev_mode_orig')
  349. def __del__(self):
  350. self.try_detach()
  351. class VirtBlockDeviceLinux(VirtBlockDeviceBase):
  352. def __init__(self, img_path, size):
  353. self.img_path = Path(img_path).resolve()
  354. self.size = size
  355. def _get_associations(self):
  356. cmd = ['/sbin/losetup', '-n', '-O', 'NAME', '-j', str(self.img_path)]
  357. return do_run(cmd).stdout.decode().splitlines()
  358. def get_new_dev(self):
  359. return do_run(['sudo', '/sbin/losetup', '-f']).stdout.decode().strip()
  360. def do_create(self, size, path):
  361. do_run(['truncate', f'--size={size}', str(path)])
  362. def do_attach(self, path, dev):
  363. do_run(['sudo', '/sbin/losetup', dev, str(path)])
  364. def do_detach(self, dev, check=True):
  365. do_run(['sudo', '/sbin/losetup', '-d', dev], check=check)
  366. class VirtBlockDeviceMacOS(VirtBlockDeviceBase):
  367. def __init__(self, img_path, size):
  368. self.img_path = Path(img_path + '.dmg').resolve()
  369. self.size = size
  370. def _get_associations(self):
  371. cp = run(['hdiutil', 'info'], stdout=PIPE, stderr=PIPE, text=True, check=False)
  372. if cp.returncode == 0:
  373. lines = cp.stdout.splitlines()
  374. out = [re.sub('.* ', '', s.strip()) for s in lines if re.match(r'image-path|/dev/', s)]
  375. def gen_pairs():
  376. for n in range(len(out) // 2):
  377. yield(out[n*2], out[(n*2)+1])
  378. return [dev for path, dev in gen_pairs() if path == str(self.img_path)]
  379. else:
  380. return []
  381. def get_new_dev(self):
  382. return None
  383. def do_create(self, size, path):
  384. do_run(['hdiutil', 'create', '-size', size, '-layout', 'NONE', str(path)])
  385. def do_attach(self, path, dev=None):
  386. do_run(['hdiutil', 'attach', '-nomount', str(path)])
  387. def do_detach(self, dev, check=True):
  388. do_run(['hdiutil', 'detach', dev], check=check)