gentest.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2019 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. from mmgen.obj import MMGenAddrType
  29. rounds = 100
  30. opts_data = lambda: {
  31. 'desc': 'Test address generation in various ways',
  32. 'usage':'[options] [spec] [rounds | dump file]',
  33. 'options': """
  34. -h, --help Print this help message
  35. -a, --all Test all supported coins for external generator 'ext'
  36. --, --longhelp Print help message for long options (common options)
  37. -q, --quiet Produce quieter output
  38. -t, --type=t Specify address type (valid options: 'compressed','segwit','zcash_z')
  39. -v, --verbose Produce more verbose output
  40. """,
  41. 'notes': """
  42. Tests:
  43. A/B: {prog} a:b [rounds] (compare output of two key generators)
  44. Speed: {prog} a [rounds] (test speed of one key generator)
  45. Compare: {prog} a <dump file> (compare output of a key generator against wallet dump)
  46. where a and b are one of:
  47. '1' - native Python ecdsa library (very slow)
  48. '2' - bitcoincore.org's secp256k1 library (default from v0.8.6)
  49. EXAMPLES:
  50. {prog} 1:2 100
  51. (compare output of native Python ECDSA with secp256k1 library, 100 rounds)
  52. {prog} 2:ext 100
  53. (compare output of secp256k1 library with external library (see below), 100 rounds)
  54. {prog} 2 1000
  55. (test speed of secp256k1 library address generation, 1000 rounds)
  56. {prog} 2 my.dump
  57. (compare addrs generated with secp256k1 library to {dn} wallet dump)
  58. External libraries required for the 'ext' generator:
  59. + pyethereum (for ETH,ETC) https://github.com/ethereum/pyethereum
  60. + zcash-mini (for zcash_z addresses) https://github.com/FiloSottile/zcash-mini
  61. + pycoin (for supported coins) https://github.com/richardkiss/pycoin
  62. + keyconv (for all other coins) https://github.com/exploitagency/vanitygen-plus
  63. ('keyconv' generates uncompressed addresses only)
  64. """.format(prog='gentest.py',pnm=g.proj_name,snum=rounds,dn=g.proto.daemon_name)
  65. }
  66. sys.argv = [sys.argv[0]] + ['--skip-cfg-file'] + sys.argv[1:]
  67. cmd_args = opts.init(opts_data,add_opts=['exact_output','use_old_ed25519'])
  68. if not 1 <= len(cmd_args) <= 2: opts.usage()
  69. addr_type = MMGenAddrType(opt.type or g.proto.dfl_mmtype)
  70. def pyethereum_sec2addr(sec):
  71. return sec,eth.privtoaddr(sec).hex()
  72. def keyconv_sec2addr(sec):
  73. p = sp.Popen(['keyconv','-C',g.coin,sec.wif],stderr=sp.PIPE,stdout=sp.PIPE)
  74. o = p.stdout.read().decode().splitlines()
  75. return o[1].split()[1],o[0].split()[1]
  76. def zcash_mini_sec2addr(sec):
  77. p = sp.Popen(['zcash-mini','-key','-simple'],stderr=sp.PIPE,stdin=sp.PIPE,stdout=sp.PIPE)
  78. ret = p.communicate(sec.wif.encode()+b'\n')[0].decode().strip().split('\n')
  79. return (sec.wif,ret[0],ret[-1])
  80. def pycoin_sec2addr(sec):
  81. coin = ci.external_tests['testnet']['pycoin'][g.coin] if g.testnet else g.coin
  82. key = pcku.parse_key(sec,[network_for_netcode(coin)])[1]
  83. if key is None: die(1,"can't parse {}".format(sec))
  84. d = {
  85. 'legacy': ('wif_uncompressed','address_uncompressed'),
  86. 'compressed': ('wif','address'),
  87. 'segwit': ('wif','p2sh_segwit'),
  88. }[addr_type.name]
  89. return [pcku.create_output(sec,key,network_for_netcode(coin),d[i])[0][d[i]] for i in (0,1)]
  90. # pycoin/networks/all.py pycoin/networks/legacy_networks.py
  91. def init_external_prog():
  92. global b,b_desc,ext_lib,ext_sec2addr,sp,eth,addr_type
  93. def test_support(k):
  94. if b == k: return True
  95. if b != 'ext' and b != k: return False
  96. if g.coin in ci.external_tests['mainnet'][k] and not g.testnet: return True
  97. if g.coin in ci.external_tests['testnet'][k]: return True
  98. return False
  99. if b == 'zcash_mini' or addr_type.name == 'zcash_z':
  100. import subprocess as sp
  101. from mmgen.protocol import init_coin
  102. ext_sec2addr = zcash_mini_sec2addr
  103. ext_lib = 'zcash_mini'
  104. init_coin('zec')
  105. addr_type = MMGenAddrType('Z')
  106. elif test_support('pyethereum'):
  107. try:
  108. import ethereum.utils as eth
  109. except:
  110. raise ImportError("Unable to import 'ethereum' module. Is pyethereum installed?")
  111. ext_sec2addr = pyethereum_sec2addr
  112. ext_lib = 'pyethereum'
  113. elif test_support('pycoin'):
  114. try:
  115. global pcku,secp256k1_generator,network_for_netcode
  116. import pycoin.cmds.ku as pcku
  117. from pycoin.ecdsa.secp256k1 import secp256k1_generator
  118. from pycoin.networks.registry import network_for_netcode
  119. except:
  120. raise ImportError("Unable to import pycoin modules. Is pycoin installed and up-to-date?")
  121. ext_sec2addr = pycoin_sec2addr
  122. ext_lib = 'pycoin'
  123. elif test_support('keyconv'):
  124. import subprocess as sp
  125. ext_sec2addr = keyconv_sec2addr
  126. ext_lib = 'keyconv'
  127. else:
  128. m = '{}: coin supported by MMGen but unsupported by gentest.py for {}'
  129. raise ValueError(m.format(g.coin,('mainnet','testnet')[g.testnet]))
  130. b_desc = ext_lib
  131. b = 'ext'
  132. def match_error(sec,wif,a_addr,b_addr,a,b):
  133. qmsg_r(red('\nERROR: Values do not match!'))
  134. die(3,"""
  135. sec key : {}
  136. WIF key : {}
  137. {a:10}: {}
  138. {b:10}: {}
  139. """.format(sec,wif,a_addr,b_addr,pnm=g.proj_name,a=kg_a.desc,b=b_desc).rstrip())
  140. def compare_test():
  141. for k in ('segwit','compressed'):
  142. if addr_type.name == k and g.coin not in ci.external_tests_segwit_compressed[k]:
  143. m = 'skipping - external program does not support {} for coin {}'
  144. msg(m.format(addr_type.name.capitalize(),g.coin))
  145. return
  146. if 'ext_lib' in globals():
  147. if g.coin not in ci.external_tests[('mainnet','testnet')[g.testnet]][ext_lib]:
  148. msg("Coin '{}' incompatible with external generator '{}'".format(g.coin,ext_lib))
  149. return
  150. m = "Comparing address generators '{}' and '{}' for coin {}"
  151. last_t = time.time()
  152. qmsg(green(m.format(kg_a.desc,(ext_lib if b == 'ext' else kg_b.desc),g.coin)))
  153. for i in range(rounds):
  154. if opt.verbose or time.time() - last_t >= 0.1:
  155. qmsg_r('\rRound {}/{} '.format(i+1,rounds))
  156. last_t = time.time()
  157. sec = PrivKey(os.urandom(32),compressed=addr_type.compressed,pubkey_type=addr_type.pubkey_type)
  158. ph = kg_a.to_pubhex(sec)
  159. a_addr = ag.to_addr(ph)
  160. if addr_type.name == 'zcash_z':
  161. a_vk = ag.to_viewkey(ph)
  162. if b == 'ext':
  163. if addr_type.name == 'zcash_z':
  164. b_wif,b_addr,b_vk = ext_sec2addr(sec)
  165. vmsg_r('\nvkey: {}'.format(b_vk))
  166. if b_vk != a_vk:
  167. match_error(sec,sec.wif,a_vk,b_vk,a,b)
  168. else:
  169. b_wif,b_addr = ext_sec2addr(sec)
  170. if b_wif != sec.wif:
  171. match_error(sec,sec.wif,sec.wif,b_wif,a,b)
  172. else:
  173. b_addr = ag.to_addr(kg_b.to_pubhex(sec))
  174. vmsg('\nkey: {}\naddr: {}\n'.format(sec.wif,a_addr))
  175. if a_addr != b_addr:
  176. match_error(sec,sec.wif,a_addr,b_addr,a,ext_lib if b == 'ext' else b)
  177. qmsg_r('\rRound {}/{} '.format(i+1,rounds))
  178. qmsg(green(('\n','')[bool(opt.verbose)] + 'OK'))
  179. def speed_test():
  180. m = "Testing speed of address generator '{}' for coin {}"
  181. qmsg(green(m.format(kg_a.desc,g.coin)))
  182. from struct import pack,unpack
  183. seed = os.urandom(28)
  184. print('Incrementing key with each round')
  185. print('Starting key:', (seed + pack('I',0)).hex())
  186. import time
  187. start = last_t = time.time()
  188. for i in range(rounds):
  189. if time.time() - last_t >= 0.1:
  190. qmsg_r('\rRound {}/{} '.format(i+1,rounds))
  191. last_t = time.time()
  192. sec = PrivKey(seed+pack('I',i),compressed=addr_type.compressed,pubkey_type=addr_type.pubkey_type)
  193. a_addr = ag.to_addr(kg_a.to_pubhex(sec))
  194. vmsg('\nkey: {}\naddr: {}\n'.format(sec.wif,a_addr))
  195. qmsg_r('\rRound {}/{} '.format(i+1,rounds))
  196. qmsg('\n{} addresses generated in {:.2f} seconds'.format(rounds,time.time()-start))
  197. def dump_test():
  198. m = "Comparing output of address generator '{}' against wallet dump '{}'"
  199. qmsg(green(m.format(kg_a.desc,cmd_args[1])))
  200. for n,[wif,a_addr] in enumerate(dump,1):
  201. qmsg_r('\rKey {}/{} '.format(n,len(dump)))
  202. try:
  203. sec = PrivKey(wif=wif)
  204. except:
  205. die(2,'\nInvalid {}net WIF address in dump file: {}'.format(('main','test')[g.testnet],wif))
  206. b_addr = ag.to_addr(kg_a.to_pubhex(sec))
  207. vmsg('\nwif: {}\naddr: {}\n'.format(wif,b_addr))
  208. if a_addr != b_addr:
  209. match_error(sec,wif,a_addr,b_addr,3,a)
  210. qmsg(green(('\n','')[bool(opt.verbose)] + 'OK'))
  211. from mmgen.altcoin import CoinInfo as ci
  212. urounds,fh = None,None
  213. dump = []
  214. if len(cmd_args) == 2:
  215. try:
  216. urounds = int(cmd_args[1])
  217. assert urounds > 0
  218. except:
  219. try:
  220. fh = open(cmd_args[1])
  221. except:
  222. die(1,'Second argument must be filename or positive integer')
  223. else:
  224. for line in fh.readlines():
  225. if 'addr=' in line:
  226. x,addr = line.split('addr=')
  227. dump.append([x.split()[0],addr.split()[0]])
  228. if urounds: rounds = urounds
  229. a,b = None,None
  230. b_desc = 'unknown'
  231. try:
  232. a,b = cmd_args[0].split(':')
  233. except:
  234. try:
  235. a = cmd_args[0]
  236. a = int(a)
  237. assert 1 <= a <= len(g.key_generators)
  238. except:
  239. die(1,'First argument must be one or two generator IDs, colon separated')
  240. else:
  241. try:
  242. a = int(a)
  243. assert 1 <= a <= len(g.key_generators),'{}: invalid key generator'.format(a)
  244. if b in ('ext','pyethereum','pycoin','keyconv','zcash_mini'):
  245. init_external_prog()
  246. else:
  247. b = int(b)
  248. assert 1 <= b <= len(g.key_generators),'{}: invalid key generator'.format(b)
  249. assert a != b,'Key generators are the same!'
  250. except Exception as e:
  251. die(1,'{}\n{}: invalid generator argument'.format(e.args[0],cmd_args[0]))
  252. from mmgen.addr import KeyGenerator,AddrGenerator
  253. from mmgen.obj import PrivKey
  254. kg_a = KeyGenerator(addr_type,a)
  255. ag = AddrGenerator(addr_type)
  256. if a and b:
  257. if opt.all:
  258. from mmgen.protocol import init_coin,init_genonly_altcoins,CoinProtocol
  259. init_genonly_altcoins('btc',trust_level=0)
  260. mmgen_supported = CoinProtocol.get_valid_coins(upcase=True)
  261. for coin in ci.external_tests[('mainnet','testnet')[g.testnet]][ext_lib]:
  262. if coin not in mmgen_supported: continue
  263. init_coin(coin)
  264. tmp_addr_type = addr_type if addr_type in g.proto.mmtypes else MMGenAddrType(g.proto.dfl_mmtype)
  265. kg_a = KeyGenerator(tmp_addr_type,a)
  266. ag = AddrGenerator(tmp_addr_type)
  267. compare_test()
  268. else:
  269. if b != 'ext':
  270. kg_b = KeyGenerator(addr_type,b)
  271. b_desc = kg_b.desc
  272. compare_test()
  273. elif a and not fh:
  274. speed_test()
  275. elif a and dump:
  276. b_desc = 'dump'
  277. dump_test()
  278. else:
  279. die(2,'Illegal invocation')