gentest.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2020 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
  22. pn = os.path.dirname(sys.argv[0])
  23. os.chdir(os.path.join(pn,os.pardir))
  24. sys.path.__setitem__(0,os.path.abspath(os.curdir))
  25. os.environ['MMGEN_TEST_SUITE'] = '1'
  26. # Import these _after_ local path's been added to sys.path
  27. from mmgen.common import *
  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. -a, --all Test all coins supported by specified external tool
  36. -k, --use-internal-keccak-module Force use of the internal keccak module
  37. --, --longhelp Print help message for long options (common options)
  38. -q, --quiet Produce quieter output
  39. -t, --type=t Specify address type (e.g. 'compressed','segwit','zcash_z','bech32')
  40. -v, --verbose Produce more verbose output
  41. """,
  42. 'notes': """
  43. TEST TYPES:
  44. A/B: {prog} A:B [rounds] (compare key generators A and B)
  45. Speed: {prog} A [rounds] (test speed of key generator A)
  46. Compare: {prog} A <dump file> (compare generator A to wallet dump)
  47. where A and B are one of:
  48. '1' - native Python ECDSA library (slow), or
  49. '2' - bitcoincore.org's libsecp256k1 library (default);
  50. or:
  51. B is name of an external tool (see below) or 'ext'.
  52. If B is 'ext', the external tool will be chosen automatically.
  53. EXAMPLES:
  54. Compare addresses generated by native Python ECDSA library and libsecp256k1,
  55. 100 rounds:
  56. $ {prog} 1:2 100
  57. Compare mmgen-secp256k1 Segwit address generation to pycoin library for all
  58. supported coins, 100 rounds:
  59. $ {prog} --all --type=segwit 2:pycoin 100
  60. Compare mmgen-secp256k1 address generation to keyconv tool for all
  61. supported coins, 100 rounds:
  62. $ {prog} --all --type=compressed 2:keyconv 100
  63. Compare mmgen-secp256k1 XMR address generation to configured external tool,
  64. 10 rounds:
  65. $ {prog} --coin=xmr 2:ext 10
  66. Test speed of mmgen-secp256k1 address generation, 10,000 rounds:
  67. $ {prog} 2 10000
  68. Compare mmgen-secp256k1-generated bech32 addrs to {dn} wallet dump:
  69. $ {prog} --type=bech32 2 bech32wallet.dump
  70. Supported external tools:
  71. + ethkey (for ETH,ETC)
  72. https://github.com/paritytech/parity-ethereum
  73. (build with 'cargo build -p ethkey-cli --release')
  74. + zcash-mini (for Zcash Z-addresses)
  75. https://github.com/FiloSottile/zcash-mini
  76. + moneropy (for Monero addresses)
  77. https://github.com/bigreddmachine/MoneroPy
  78. + pycoin (for supported coins)
  79. https://github.com/richardkiss/pycoin
  80. + keyconv (for supported coins)
  81. https://github.com/exploitagency/vanitygen-plus
  82. ('keyconv' does not generate Segwit addresses)
  83. """
  84. },
  85. 'code': {
  86. 'notes': lambda s: s.format(
  87. prog='test/gentest.py',
  88. pnm=g.proj_name,
  89. snum=rounds,
  90. dn=g.proto.daemon_name)
  91. }
  92. }
  93. sys.argv = [sys.argv[0]] + ['--skip-cfg-file'] + sys.argv[1:]
  94. cmd_args = opts.init(opts_data,add_opts=['exact_output','use_old_ed25519'])
  95. if not 1 <= len(cmd_args) <= 2:
  96. opts.usage()
  97. from subprocess import run,PIPE,DEVNULL
  98. def get_cmd_output(cmd,input=None):
  99. return run(cmd,input=input,stdout=PIPE,stderr=DEVNULL).stdout.decode().splitlines()
  100. from collections import namedtuple
  101. gtr = namedtuple('gen_tool_result',['wif','addr','vk'])
  102. class GenTool(object):
  103. def run_tool(self,sec):
  104. vcoin = 'BTC' if g.coin == 'BCH' else g.coin
  105. return self.run(sec,vcoin)
  106. class GenToolEthkey(GenTool):
  107. desc = 'ethkey'
  108. def __init__(self):
  109. init_coin('eth')
  110. global addr_type
  111. addr_type = MMGenAddrType('E')
  112. def run(self,sec,vcoin):
  113. o = get_cmd_output(['ethkey','info',sec])
  114. return gtr(o[0].split()[1],o[-1].split()[1],None)
  115. class GenToolKeyconv(GenTool):
  116. desc = 'keyconv'
  117. def run(self,sec,vcoin):
  118. o = get_cmd_output(['keyconv','-C',vcoin,sec.wif])
  119. return gtr(o[1].split()[1],o[0].split()[1],None)
  120. class GenToolZcash_mini(GenTool):
  121. desc = 'zcash-mini'
  122. def __init__(self):
  123. init_coin('zec')
  124. global addr_type
  125. addr_type = MMGenAddrType('Z')
  126. def run(self,sec,vcoin):
  127. o = get_cmd_output(['zcash-mini','-key','-simple'],input=(sec.wif+'\n').encode())
  128. return gtr(o[1],o[0],o[-1])
  129. class GenToolPycoin(GenTool):
  130. """
  131. pycoin/networks/all.py pycoin/networks/legacy_networks.py
  132. """
  133. desc = 'pycoin'
  134. def __init__(self):
  135. m = "Unable to import pycoin.networks.registry. Is pycoin installed on your system?"
  136. try:
  137. from pycoin.networks.registry import network_for_netcode
  138. except:
  139. raise ImportError(m)
  140. self.nfnc = network_for_netcode
  141. def run(self,sec,vcoin):
  142. if g.testnet:
  143. vcoin = ci.external_tests['testnet']['pycoin'][vcoin]
  144. network = self.nfnc(vcoin)
  145. key = network.keys.private(secret_exponent=int(sec,16),is_compressed=addr_type.name != 'legacy')
  146. if key is None:
  147. die(1,"can't parse {}".format(sec))
  148. if addr_type.name in ('segwit','bech32'):
  149. hash160_c = key.hash160(is_compressed=True)
  150. if addr_type.name == 'segwit':
  151. p2sh_script = network.contract.for_p2pkh_wit(hash160_c)
  152. addr = network.address.for_p2s(p2sh_script)
  153. else:
  154. addr = network.address.for_p2pkh_wit(hash160_c)
  155. else:
  156. addr = key.address()
  157. return gtr(key.wif(),addr,None)
  158. class GenToolMoneropy(GenTool):
  159. desc = 'moneropy'
  160. def __init__(self):
  161. m = "Unable to import moneropy. Is moneropy installed on your system?"
  162. try:
  163. import moneropy.account
  164. except:
  165. raise ImportError(m)
  166. self.mpa = moneropy.account
  167. init_coin('xmr')
  168. global addr_type
  169. addr_type = MMGenAddrType('M')
  170. def run(self,sec,vcoin):
  171. sk_t,vk_t,addr_t = self.mpa.account_from_spend_key(sec) # VERY slow!
  172. return gtr(sk_t,addr_t,vk_t)
  173. def get_tool(arg):
  174. if arg not in ext_progs + ['ext']:
  175. die(1,'{!r}: unsupported tool for network {}'.format(arg,g.network))
  176. if opt.all:
  177. if arg == 'ext':
  178. die(1,"'--all' must be combined with a specific external testing tool")
  179. return arg
  180. else:
  181. tool = ci.get_test_support(
  182. g.coin,
  183. addr_type.name,
  184. g.network,
  185. verbose = not opt.quiet,
  186. tool = arg if arg in ext_progs else None )
  187. if not tool:
  188. sys.exit(2)
  189. if arg in ext_progs and arg != tool:
  190. sys.exit(3)
  191. return tool
  192. def test_equal(desc,a_val,b_val,in_bytes,sec,wif,a_desc,b_desc):
  193. if a_val != b_val:
  194. fs = """
  195. {i:{w}}: {}
  196. {s:{w}}: {}
  197. {W:{w}}: {}
  198. {a:{w}}: {}
  199. {b:{w}}: {}
  200. """
  201. die(3,
  202. red('\nERROR: {} do not match!').format(desc)
  203. + fs.format(
  204. in_bytes.hex(), sec, wif, a_val, b_val,
  205. i='input', s='sec key', W='WIF key', a=a_desc, b=b_desc,
  206. w=max(len(e) for e in (a_desc,b_desc)) + 1
  207. ).rstrip())
  208. def gentool_test(kg_a,kg_b,ag,rounds):
  209. m = "Comparing address generators '{A}' and '{B}' for {N} {c} ({n}), addrtype {a!r}"
  210. e = ci.get_entry(g.coin,g.network)
  211. qmsg(green(m.format(
  212. A = kg_a.desc,
  213. B = kg_b.desc,
  214. N = g.network,
  215. c = g.coin,
  216. n = e.name if e else '---',
  217. a = addr_type.name )))
  218. global last_t
  219. last_t = time.time()
  220. def do_compare_test(n,trounds,in_bytes):
  221. global last_t
  222. if opt.verbose or time.time() - last_t >= 0.1:
  223. qmsg_r('\rRound {}/{} '.format(i+1,trounds))
  224. last_t = time.time()
  225. sec = PrivKey(in_bytes,compressed=addr_type.compressed,pubkey_type=addr_type.pubkey_type)
  226. a_ph = kg_a.to_pubhex(sec)
  227. a_addr = ag.to_addr(a_ph)
  228. a_vk = None
  229. tinfo = (in_bytes,sec,sec.wif,kg_a.desc,kg_b.desc)
  230. if isinstance(kg_b,GenTool):
  231. b = kg_b.run_tool(sec)
  232. test_equal('WIF keys',sec.wif,b.wif,*tinfo)
  233. test_equal('addresses',a_addr,b.addr,*tinfo)
  234. if b.vk:
  235. a_vk = ag.to_viewkey(a_ph)
  236. test_equal('view keys',a_vk,b.vk,*tinfo)
  237. else:
  238. b_addr = ag.to_addr(kg_b.to_pubhex(sec))
  239. test_equal('addresses',a_addr,b_addr,*tinfo)
  240. vmsg(fs.format(b=in_bytes.hex(),k=sec.wif,v=a_vk,a=a_addr))
  241. qmsg_r('\rRound {}/{} '.format(n+1,trounds))
  242. fs = ( '\ninput: {b}\n%-9s {k}\naddr: {a}\n',
  243. '\ninput: {b}\n%-9s {k}\nviewkey: {v}\naddr: {a}\n')[
  244. 'viewkey' in addr_type.extra_attrs] % (addr_type.wif_label + ':')
  245. # test some important private key edge cases:
  246. edgecase_sks = (
  247. bytes([0x00]*31 + [0x01]), # min
  248. bytes([0xff]*32), # max
  249. bytes([0x0f] + [0xff]*31), # same key as above for zcash-z
  250. bytes([0x00]*31 + [0xff]), # monero will reduce
  251. bytes([0xff]*31 + [0x0f]), # monero will not reduce
  252. )
  253. qmsg(purple('edge cases:'))
  254. for i,in_bytes in enumerate(edgecase_sks):
  255. do_compare_test(i,len(edgecase_sks),in_bytes)
  256. qmsg(green('\rOK ' if opt.verbose else 'OK'))
  257. qmsg(purple('random input:'))
  258. for i in range(rounds):
  259. do_compare_test(i,rounds,os.urandom(32))
  260. qmsg(green('\rOK ' if opt.verbose else 'OK'))
  261. def speed_test(kg,ag,rounds):
  262. m = "Testing speed of address generator '{}' for coin {}"
  263. qmsg(green(m.format(kg.desc,g.coin)))
  264. from struct import pack,unpack
  265. seed = os.urandom(28)
  266. qmsg('Incrementing key with each round')
  267. qmsg('Starting key: {}'.format((seed + pack('I',0)).hex()))
  268. import time
  269. start = last_t = time.time()
  270. for i in range(rounds):
  271. if time.time() - last_t >= 0.1:
  272. qmsg_r('\rRound {}/{} '.format(i+1,rounds))
  273. last_t = time.time()
  274. sec = PrivKey(seed+pack('I',i),compressed=addr_type.compressed,pubkey_type=addr_type.pubkey_type)
  275. addr = ag.to_addr(kg.to_pubhex(sec))
  276. vmsg('\nkey: {}\naddr: {}\n'.format(sec.wif,addr))
  277. qmsg_r('\rRound {}/{} '.format(i+1,rounds))
  278. qmsg('\n{} addresses generated in {:.2f} seconds'.format(rounds,time.time()-start))
  279. def dump_test(kg,ag,fh):
  280. dump = [[*(e.split()[0] for e in line.split('addr='))] for line in fh.readlines() if 'addr=' in line]
  281. if not dump:
  282. die(1,'File {!r} appears not to be a wallet dump'.format(fh.name))
  283. m = 'Comparing output of address generator {!r} against wallet dump {!r}'
  284. qmsg(green(m.format(kg.desc,fh.name)))
  285. for count,(b_wif,b_addr) in enumerate(dump,1):
  286. qmsg_r('\rKey {}/{} '.format(count,len(dump)))
  287. try:
  288. b_sec = PrivKey(wif=b_wif)
  289. except:
  290. die(2,'\nInvalid {} WIF address in dump file: {}'.format(g.network,b_wif))
  291. a_addr = ag.to_addr(kg.to_pubhex(b_sec))
  292. vmsg('\nwif: {}\naddr: {}\n'.format(b_wif,b_addr))
  293. tinfo = (bytes.fromhex(b_sec),b_sec,b_wif,kg.desc,fh.name)
  294. test_equal('addresses',a_addr,b_addr,*tinfo)
  295. qmsg(green(('\n','')[bool(opt.verbose)] + 'OK'))
  296. def init_tool(tname):
  297. return globals()['GenTool'+capfirst(tname.replace('-','_'))]()
  298. def parse_arg1(arg,arg_id):
  299. m1 = 'First argument must be a numeric generator ID or two colon-separated generator IDs'
  300. m2 = 'Second part of first argument must be a numeric generator ID or one of {}'
  301. def check_gen_num(n):
  302. if not (1 <= int(n) <= len(g.key_generators)):
  303. die(1,'{}: invalid generator ID'.format(n))
  304. return int(n)
  305. if arg_id == 'a':
  306. if is_int(arg):
  307. a_num = check_gen_num(arg)
  308. return (KeyGenerator(addr_type,a_num),a_num)
  309. else:
  310. die(1,m1)
  311. elif arg_id == 'b':
  312. if is_int(arg):
  313. return KeyGenerator(addr_type,check_gen_num(arg))
  314. elif arg in ext_progs + ['ext']:
  315. return init_tool(get_tool(arg))
  316. else:
  317. die(1,m2.format(ext_progs))
  318. def parse_arg2():
  319. m = 'Second argument must be dump filename or integer rounds specification'
  320. if len(cmd_args) == 1:
  321. return None
  322. arg = cmd_args[1]
  323. if is_int(arg) and int(arg) > 0:
  324. return int(arg)
  325. try:
  326. return open(arg)
  327. except:
  328. die(1,m)
  329. # begin execution
  330. from mmgen.protocol import init_coin
  331. from mmgen.altcoin import CoinInfo as ci
  332. from mmgen.obj import MMGenAddrType,PrivKey
  333. from mmgen.addr import KeyGenerator,AddrGenerator
  334. addr_type = MMGenAddrType(opt.type or g.proto.dfl_mmtype)
  335. ext_progs = list(ci.external_tests[g.network])
  336. arg1 = cmd_args[0].split(':')
  337. if len(arg1) == 1:
  338. a,a_num = parse_arg1(arg1[0],'a')
  339. b = None
  340. elif len(arg1) == 2:
  341. a,a_num = parse_arg1(arg1[0],'a')
  342. b = parse_arg1(arg1[1],'b')
  343. else:
  344. opts.usage()
  345. if type(a) == type(b):
  346. die(1,'Address generators are the same!')
  347. arg2 = parse_arg2()
  348. ag = AddrGenerator(addr_type)
  349. if not b and type(arg2) == int:
  350. speed_test(a,ag,arg2)
  351. elif not b and hasattr(arg2,'read'):
  352. dump_test(a,ag,arg2)
  353. elif a and b and type(arg2) == int:
  354. if opt.all:
  355. from mmgen.protocol import init_genonly_altcoins,CoinProtocol
  356. init_genonly_altcoins()
  357. for coin in ci.external_tests[g.network][b.desc]:
  358. if coin.lower() not in CoinProtocol.coins:
  359. # ymsg('Coin {} not configured'.format(coin))
  360. continue
  361. init_coin(coin)
  362. if addr_type not in g.proto.mmtypes:
  363. continue
  364. # g.proto has changed, so reinit kg and ag just to be on the safe side:
  365. a = KeyGenerator(addr_type,a_num)
  366. ag = AddrGenerator(addr_type)
  367. b_chk = ci.get_test_support(g.coin,addr_type.name,g.network,tool=b.desc,verbose=not opt.quiet)
  368. if b_chk == b.desc:
  369. gentool_test(a,b,ag,arg2)
  370. else:
  371. gentool_test(a,b,ag,arg2)
  372. else:
  373. opts.usage()