gentest.py 13 KB

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