gentest.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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. test/gentest.py: Cryptocoin key/address generation tests for the MMGen suite
  20. """
  21. import sys,os,time
  22. import include.test_init
  23. # Import these _after_ local path's been added to sys.path
  24. from mmgen.cfg import gc,Config
  25. from mmgen.color import green,red,purple
  26. from mmgen.util import msg,ymsg,capfirst,is_int,die
  27. results_file = 'gentest.out.json'
  28. rounds = 100
  29. opts_data = {
  30. 'text': {
  31. 'desc': 'Test key/address generation of the MMGen suite in various ways',
  32. 'usage':'[options] <spec> <rounds | dump file>',
  33. 'options': """
  34. -h, --help Print this help message
  35. --, --longhelp Print help message for long options (common options)
  36. -a, --all-coins Test all coins supported by specified external tool
  37. -k, --use-internal-keccak-module Force use of the internal keccak module
  38. -q, --quiet Produce quieter output
  39. -s, --save-results Save output of external tool in Compare test to
  40. {rf!r}
  41. -t, --type=t Specify address type (e.g. 'compressed','segwit',
  42. 'zcash_z','bech32')
  43. -v, --verbose Produce more verbose output
  44. """,
  45. 'notes': """
  46. TEST TYPES:
  47. Compare: {prog} A:B <rounds> (compare address generators A and B)
  48. Speed: {prog} A <rounds> (test speed of generator A)
  49. Dump: {prog} A <dump file> (compare generator A to wallet dump)
  50. where:
  51. A and B are keygen backend numbers ('1' being the default); or
  52. B is the name of an external tool (see below) or 'ext'.
  53. If B is 'ext', the external tool will be chosen automatically.
  54. For the Compare test, A may be 'all' to test all backends for the current
  55. coin/address type combination.
  56. EXAMPLES:
  57. Compare addresses generated by 'libsecp256k1' and 'python-ecdsa' backends,
  58. with 100 random rounds plus private-key edge cases:
  59. $ {prog} 1:2 100
  60. Compare Segwit addresses from default 'libsecp256k1' backend to 'pycoin'
  61. library for all supported coins, 100 rounds + edge cases:
  62. $ {prog} --all-coins --type=segwit 1:pycoin 100
  63. Compare addresses from 'python-ecdsa' backend to output of 'keyconv' tool
  64. for all supported coins, 100 rounds + edge cases:
  65. $ {prog} --all-coins --type=compressed 2:keyconv 100
  66. Compare bech32 addrs from 'libsecp256k1' backend to Bitcoin Core wallet
  67. dump:
  68. $ {prog} --type=bech32 1 bech32wallet.dump
  69. Compare addresses from Monero 'ed25519ll' backend to output of default
  70. external tool, 10 rounds + edge cases:
  71. $ {prog} --coin=xmr 3:ext 10
  72. Test the speed of default Monero 'nacl' backend, 10,000 rounds:
  73. $ test/gentest.py --coin=xmr 1 10000
  74. Same for Zcash:
  75. $ test/gentest.py --coin=zec --type=zcash_z 1 10000
  76. Test all configured Monero backends against the 'monero-python' library, 3 rounds
  77. + edge cases:
  78. $ test/gentest.py --coin=xmr all:monero-python 3
  79. Test 'nacl' and 'ed25519ll_djbec' backends against each other, 10,000 rounds
  80. + edge cases:
  81. $ test/gentest.py --coin=xmr 1:2 10000
  82. SUPPORTED EXTERNAL TOOLS:
  83. + ethkey (for ETH,ETC)
  84. https://github.com/openethereum/openethereum
  85. (build with 'cargo build -p ethkey-cli --release')
  86. + zcash-mini (for Zcash-Z addresses and view keys)
  87. https://github.com/FiloSottile/zcash-mini
  88. + monero-python (for Monero addresses and view keys)
  89. https://github.com/monero-ecosystem/monero-python
  90. + pycoin (for supported coins)
  91. https://github.com/richardkiss/pycoin
  92. + keyconv (for supported coins)
  93. https://github.com/exploitagency/vanitygen-plus
  94. ('keyconv' does not generate Segwit addresses)
  95. """
  96. },
  97. 'code': {
  98. 'options': lambda s: s.format(
  99. rf=results_file,
  100. ),
  101. 'notes': lambda s: s.format(
  102. prog='test/gentest.py',
  103. pnm=gc.proj_name,
  104. snum=rounds )
  105. }
  106. }
  107. def get_cmd_output(cmd,input=None):
  108. return run(cmd,input=input,stdout=PIPE,stderr=DEVNULL).stdout.decode().splitlines()
  109. saved_results = {}
  110. class GenTool:
  111. def __init__(self,proto,addr_type):
  112. self.proto = proto
  113. self.addr_type = addr_type
  114. self.data = {}
  115. def __del__(self):
  116. if cfg.save_results:
  117. key = f'{self.proto.coin}-{self.proto.network}-{self.addr_type.name}-{self.desc}'.lower()
  118. saved_results[key] = {k.hex():v._asdict() for k,v in self.data.items()}
  119. def run_tool(self,sec,cache_data):
  120. vcoin = 'BTC' if self.proto.coin == 'BCH' else self.proto.coin
  121. key = sec.orig_bytes
  122. if key in self.data:
  123. return self.data[key]
  124. else:
  125. ret = self.run(sec,vcoin)
  126. if cache_data:
  127. self.data[key] = sd( **{'reduced':sec.hex()}, **ret._asdict() )
  128. return ret
  129. class GenToolEthkey(GenTool):
  130. desc = 'ethkey'
  131. def __init__(self,*args,**kwargs):
  132. self.cmdname = get_ethkey()
  133. return super().__init__(*args,**kwargs)
  134. def run(self,sec,vcoin):
  135. o = get_cmd_output([self.cmdname,'info',sec.hex()])
  136. return gtr(
  137. o[0].split()[1],
  138. o[-1].split()[1],
  139. None )
  140. class GenToolKeyconv(GenTool):
  141. desc = 'keyconv'
  142. def run(self,sec,vcoin):
  143. o = get_cmd_output(['keyconv','-C',vcoin,sec.wif])
  144. return gtr(
  145. o[1].split()[1],
  146. o[0].split()[1],
  147. None )
  148. class GenToolZcash_mini(GenTool):
  149. desc = 'zcash-mini'
  150. def run(self,sec,vcoin):
  151. o = get_cmd_output(['zcash-mini','-key','-simple'],input=(sec.wif+'\n').encode())
  152. return gtr( o[1], o[0], o[-1] )
  153. class GenToolPycoin(GenTool):
  154. """
  155. pycoin/networks/all.py pycoin/networks/legacy_networks.py
  156. """
  157. desc = 'pycoin'
  158. def __init__(self,*args,**kwargs):
  159. super().__init__(*args,**kwargs)
  160. try:
  161. from pycoin.networks.registry import network_for_netcode
  162. except Exception as e:
  163. raise ImportError(
  164. 'Unable to import pycoin.networks.registry. Is pycoin installed on your system?') from e
  165. self.nfnc = network_for_netcode
  166. def run(self,sec,vcoin):
  167. if self.proto.testnet:
  168. vcoin = cinfo.external_tests['testnet']['pycoin'][vcoin]
  169. network = self.nfnc(vcoin)
  170. key = network.keys.private(
  171. secret_exponent = int(sec.hex(),16),
  172. is_compressed = self.addr_type.name != 'legacy' )
  173. if key is None:
  174. die(1,f'can’t parse {sec.hex()}')
  175. if self.addr_type.name in ('segwit','bech32'):
  176. hash160_c = key.hash160(is_compressed=True)
  177. if self.addr_type.name == 'segwit':
  178. p2sh_script = network.contract.for_p2pkh_wit(hash160_c)
  179. addr = network.address.for_p2s(p2sh_script)
  180. else:
  181. addr = network.address.for_p2pkh_wit(hash160_c)
  182. else:
  183. addr = key.address()
  184. return gtr( key.wif(), addr, None )
  185. class GenToolMonero_python(GenTool):
  186. desc = 'monero-python'
  187. def __init__(self,*args,**kwargs):
  188. super().__init__(*args,**kwargs)
  189. from mmgen.util import load_cryptodomex
  190. load_cryptodomex()
  191. try:
  192. from monero.seed import Seed
  193. except Exception as e:
  194. raise ImportError(
  195. 'Unable to import monero-python. Is monero-python installed on your system?') from e
  196. self.Seed = Seed
  197. def run(self,sec,vcoin):
  198. seed = self.Seed( sec.orig_bytes.hex() )
  199. sk = seed.secret_spend_key()
  200. vk = seed.secret_view_key()
  201. addr = seed.public_address()
  202. return gtr( sk, addr, vk )
  203. def find_or_check_tool(proto,addr_type,toolname):
  204. ext_progs = list(cinfo.external_tests[proto.network])
  205. if toolname not in ext_progs + ['ext']:
  206. die(1,f'{toolname!r}: unsupported tool for network {proto.network}')
  207. if cfg.all_coins and toolname == 'ext':
  208. die(1,"'--all-coins' must be combined with a specific external testing tool")
  209. else:
  210. tool = cinfo.get_test_support(
  211. proto.coin,
  212. addr_type.name,
  213. proto.network,
  214. verbose = not cfg.quiet,
  215. toolname = toolname if toolname != 'ext' else None )
  216. if tool and toolname in ext_progs and toolname != tool:
  217. sys.exit(3)
  218. if tool is None:
  219. return None
  220. return tool
  221. def test_equal(desc,a_val,b_val,in_bytes,sec,wif,a_desc,b_desc):
  222. if a_val != b_val:
  223. fs = """
  224. {i:{w}}: {}
  225. {s:{w}}: {}
  226. {W:{w}}: {}
  227. {a:{w}}: {}
  228. {b:{w}}: {}
  229. """
  230. die(3,
  231. red('\nERROR: {} do not match!').format(desc)
  232. + fs.format(
  233. in_bytes.hex(), sec, wif, a_val, b_val,
  234. i='input', s='sec key', W='WIF key', a=a_desc, b=b_desc,
  235. w=max(len(e) for e in (a_desc,b_desc)) + 1
  236. ).rstrip())
  237. def do_ab_test(proto,scfg,addr_type,gen1,kg2,ag,tool,cache_data):
  238. def do_ab_inner(n,trounds,in_bytes):
  239. global last_t
  240. if cfg.verbose or time.time() - last_t >= 0.1:
  241. qmsg_r(f'\rRound {i+1}/{trounds} ')
  242. last_t = time.time()
  243. sec = PrivKey(proto,in_bytes,compressed=addr_type.compressed,pubkey_type=addr_type.pubkey_type)
  244. data = kg1.gen_data(sec)
  245. addr1 = ag.to_addr(data)
  246. tinfo = ( in_bytes, sec, sec.wif, type(kg1).__name__, type(kg2).__name__ if kg2 else tool.desc )
  247. def do_msg():
  248. if cfg.verbose:
  249. msg( fs.format( b=in_bytes.hex(), r=sec.hex(), k=sec.wif, v=vk2, a=addr1 ))
  250. if tool:
  251. def run_tool():
  252. o = tool.run_tool(sec,cache_data)
  253. test_equal( 'WIF keys', sec.wif, o.wif, *tinfo )
  254. test_equal( 'addresses', addr1, o.addr, *tinfo )
  255. if o.viewkey:
  256. test_equal( 'view keys', ag.to_viewkey(data), o.viewkey, *tinfo )
  257. return o.viewkey
  258. vk2 = run_tool()
  259. do_msg()
  260. else:
  261. test_equal( 'addresses', addr1, ag.to_addr(kg2.gen_data(sec)), *tinfo )
  262. vk2 = None
  263. do_msg()
  264. qmsg_r(f'\rRound {n+1}/{trounds} ')
  265. def get_randbytes():
  266. if tool and len(tool.data) > len(edgecase_sks):
  267. for privbytes in tuple(tool.data)[len(edgecase_sks):]:
  268. yield privbytes
  269. else:
  270. for _ in range(scfg.rounds):
  271. yield getrand(32)
  272. kg1 = KeyGenerator( cfg, proto, addr_type.pubkey_type, gen1 )
  273. if type(kg1) == type(kg2):
  274. die(4,'Key generators are the same!')
  275. e = cinfo.get_entry(proto.coin,proto.network)
  276. qmsg(green("Comparing address generators '{A}' and '{B}' for {N} {c} ({n}), addrtype {a!r}".format(
  277. A = type(kg1).__name__.replace('_','-'),
  278. B = type(kg2).__name__.replace('_','-') if kg2 else tool.desc,
  279. N = proto.network,
  280. c = proto.coin,
  281. n = e.name if e else '---',
  282. a = addr_type.name )))
  283. global last_t
  284. last_t = time.time()
  285. fs = (
  286. '\ninput: {b}' +
  287. '\nreduced: {r}' +
  288. '\n{:9} {{k}}'.format(addr_type.wif_label+':') +
  289. ('\nviewkey: {v}' if 'viewkey' in addr_type.extra_attrs else '') +
  290. '\naddr: {a}\n' )
  291. ge = CoinProtocol.Secp256k1.secp256k1_ge
  292. # test some important private key edge cases:
  293. edgecase_sks = (
  294. bytes([0x00]*31 + [0x01]), # min
  295. bytes([0xff]*32), # max
  296. bytes([0x0f] + [0xff]*31), # produces same key as above for zcash-z
  297. int.to_bytes(ge + 1, 32, 'big'), # bitcoin will reduce
  298. int.to_bytes(ge - 1, 32, 'big'), # bitcoin will not reduce
  299. bytes([0x00]*31 + [0xff]), # monero will reduce
  300. bytes([0xff]*31 + [0x0f]), # monero will not reduce
  301. bytes.fromhex('deadbeef'*8),
  302. )
  303. qmsg(purple('edge cases:'))
  304. for i,privbytes in enumerate(edgecase_sks):
  305. do_ab_inner(i,len(edgecase_sks),privbytes)
  306. qmsg(green('\rOK ' if cfg.verbose else 'OK'))
  307. qmsg(purple('random input:'))
  308. for i,privbytes in enumerate(get_randbytes()):
  309. do_ab_inner(i,scfg.rounds,privbytes)
  310. qmsg(green('\rOK ' if cfg.verbose else 'OK'))
  311. def init_tool(proto,addr_type,toolname):
  312. return globals()['GenTool'+capfirst(toolname.replace('-','_'))](proto,addr_type)
  313. def ab_test(proto,scfg):
  314. addr_type = MMGenAddrType( proto=proto, id_str=cfg.type or proto.dfl_mmtype )
  315. if scfg.gen2:
  316. assert scfg.gen1 != 'all', "'all' must be used only with external tool"
  317. kg2 = KeyGenerator( cfg, proto, addr_type.pubkey_type, scfg.gen2 )
  318. tool = None
  319. else:
  320. toolname = find_or_check_tool( proto, addr_type, scfg.tool )
  321. if toolname is None:
  322. ymsg(f'Warning: skipping tool {scfg.tool!r} for {proto.coin} {addr_type.name}')
  323. return
  324. tool = init_tool( proto, addr_type, toolname )
  325. kg2 = None
  326. ag = AddrGenerator( cfg, proto, addr_type )
  327. if scfg.all_backends: # check all backends against external tool
  328. for n in range(len(get_backends(addr_type.pubkey_type))):
  329. do_ab_test(
  330. proto,
  331. scfg,
  332. addr_type,
  333. gen1 = n+1,
  334. kg2 = kg2,
  335. ag = ag,
  336. tool = tool,
  337. cache_data = scfg.rounds < 1000 and not n)
  338. else: # check specific backend against external tool or another backend
  339. do_ab_test(
  340. proto,
  341. scfg,
  342. addr_type,
  343. gen1 = scfg.gen1,
  344. kg2 = kg2,
  345. ag = ag,
  346. tool = tool,
  347. cache_data = False)
  348. def speed_test(proto,kg,ag,rounds):
  349. qmsg(green('Testing speed of address generator {!r} for coin {}'.format(
  350. type(kg).__name__,
  351. proto.coin )))
  352. from struct import pack
  353. seed = getrand(28)
  354. qmsg('Incrementing key with each round')
  355. qmsg('Starting key: {}'.format( (seed + pack('I',0)).hex() ))
  356. start = last_t = time.time()
  357. for i in range(rounds):
  358. if time.time() - last_t >= 0.1:
  359. qmsg_r(f'\rRound {i+1}/{rounds} ')
  360. last_t = time.time()
  361. sec = PrivKey( proto, seed+pack('I', i), compressed=ag.compressed, pubkey_type=ag.pubkey_type )
  362. addr = ag.to_addr(kg.gen_data(sec))
  363. vmsg(f'\nkey: {sec.wif}\naddr: {addr}\n')
  364. qmsg(
  365. f'\rRound {i+1}/{rounds} ' +
  366. f'\n{rounds} addresses generated' +
  367. ('' if cfg.test_suite_deterministic else f' in {time.time()-start:.2f} seconds')
  368. )
  369. def dump_test(proto,kg,ag,filename):
  370. with open(filename) as fp:
  371. dump = [[*(e.split()[0] for e in line.split('addr='))] for line in fp.readlines() if 'addr=' in line]
  372. if not dump:
  373. die(1,f'File {filename!r} appears not to be a wallet dump')
  374. qmsg(green(
  375. "A: generator pair '{}:{}'\nB: wallet dump {!r}".format(
  376. type(kg).__name__,
  377. type(ag).__name__,
  378. filename)))
  379. for count,(b_wif,b_addr) in enumerate(dump,1):
  380. qmsg_r(f'\rKey {count}/{len(dump)} ')
  381. try:
  382. b_sec = PrivKey(proto,wif=b_wif)
  383. except:
  384. die(2,f'\nInvalid {proto.network} WIF address in dump file: {b_wif}')
  385. a_addr = ag.to_addr(kg.gen_data(b_sec))
  386. vmsg(f'\nwif: {b_wif}\naddr: {b_addr}\n')
  387. tinfo = (b_sec,b_sec.hex(),b_wif,type(kg).__name__,filename)
  388. test_equal('addresses',a_addr,b_addr,*tinfo)
  389. qmsg(green(('\n','')[bool(cfg.verbose)] + 'OK'))
  390. def get_protos(proto,addr_type,toolname):
  391. init_genonly_altcoins(testnet=proto.testnet)
  392. for coin in cinfo.external_tests[proto.network][toolname]:
  393. if coin.lower() not in CoinProtocol.coins:
  394. continue
  395. ret = init_proto( cfg, coin, testnet=proto.testnet )
  396. if addr_type not in ret.mmtypes:
  397. continue
  398. yield ret
  399. def parse_args():
  400. if len(cfg._args) != 2:
  401. cfg._opts.usage()
  402. arg1,arg2 = cfg._args
  403. gen1,gen2,rounds = (0,0,0)
  404. tool,all_backends,dumpfile = (None,None,None)
  405. if is_int(arg1) and is_int(arg2):
  406. test = 'speed'
  407. gen1 = arg1
  408. rounds = arg2
  409. elif is_int(arg1) and os.access(arg2,os.R_OK):
  410. test = 'dump'
  411. gen1 = arg1
  412. dumpfile = arg2
  413. else:
  414. test = 'ab'
  415. rounds = arg2
  416. if not is_int(arg2):
  417. die(1,'Second argument must be dump filename or integer rounds specification')
  418. try:
  419. a,b = arg1.split(':')
  420. except:
  421. die(1,'First argument must be a generator backend number or two colon-separated arguments')
  422. if is_int(a):
  423. gen1 = a
  424. else:
  425. if a == 'all':
  426. all_backends = True
  427. else:
  428. die(1,"First part of first argument must be a generator backend number or 'all'")
  429. if is_int(b):
  430. if cfg.all_coins:
  431. die(1,'--all-coins must be used with external tool only')
  432. gen2 = b
  433. else:
  434. tool = b
  435. ext_progs = list(cinfo.external_tests[cfg._proto.network]) + ['ext']
  436. if b not in ext_progs:
  437. die(1,f'Second part of first argument must be a generator backend number or one of {ext_progs}')
  438. return namedtuple('parsed_args',['test','gen1','gen2','rounds','tool','all_backends','dumpfile'])(
  439. test,
  440. int(gen1) or None,
  441. int(gen2) or None,
  442. int(rounds) or None,
  443. tool,
  444. all_backends,
  445. dumpfile )
  446. def main():
  447. scfg = parse_args()
  448. addr_type = MMGenAddrType( proto=proto, id_str=cfg.type or proto.dfl_mmtype )
  449. if scfg.test == 'ab':
  450. protos = get_protos(proto,addr_type,scfg.tool) if cfg.all_coins else [proto]
  451. for p in protos:
  452. ab_test( p, scfg )
  453. else:
  454. kg = KeyGenerator( cfg, proto, addr_type.pubkey_type, scfg.gen1 )
  455. ag = AddrGenerator( cfg, proto, addr_type )
  456. if scfg.test == 'speed':
  457. speed_test( proto, kg, ag, scfg.rounds )
  458. elif scfg.test == 'dump':
  459. dump_test( proto, kg, ag, scfg.dumpfile )
  460. if saved_results:
  461. import json
  462. with open(results_file,'w') as fp:
  463. fp.write(json.dumps( saved_results, indent=4 ))
  464. from subprocess import run,PIPE,DEVNULL
  465. from collections import namedtuple
  466. from mmgen.protocol import init_proto,CoinProtocol
  467. from mmgen.altcoin import init_genonly_altcoins
  468. from mmgen.altcoin import CoinInfo as cinfo
  469. from mmgen.key import PrivKey
  470. from mmgen.addr import MMGenAddrType
  471. from mmgen.addrgen import KeyGenerator,AddrGenerator
  472. from mmgen.keygen import get_backends
  473. from test.include.common import getrand,get_ethkey,set_globals
  474. gtr = namedtuple('gen_tool_result',['wif','addr','viewkey'])
  475. sd = namedtuple('saved_data_item',['reduced','wif','addr','viewkey'])
  476. sys.argv = [sys.argv[0]] + ['--skip-cfg-file'] + sys.argv[1:]
  477. cfg = Config(opts_data=opts_data)
  478. set_globals(cfg)
  479. qmsg = cfg._util.qmsg
  480. qmsg_r = cfg._util.qmsg_r
  481. vmsg = cfg._util.vmsg
  482. proto = cfg._proto
  483. main()