gentest.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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 = {
  31. 'text': {
  32. 'desc': 'Test address generation in various ways',
  33. 'usage':'[options] [spec] [rounds | dump file]',
  34. 'options': """
  35. -h, --help Print this help message
  36. -a, --all Test all supported coins for external generator 'ext'
  37. -k, --use-internal-keccak-module Force use of the internal keccak module
  38. --, --longhelp Print help message for long options (common options)
  39. -q, --quiet Produce quieter output
  40. -t, --type=t Specify address type (valid options: 'compressed','segwit','zcash_z')
  41. -v, --verbose Produce more verbose output
  42. """,
  43. 'notes': """
  44. Tests:
  45. A/B: {prog} a:b [rounds] (compare output of two key generators)
  46. Speed: {prog} a [rounds] (test speed of one key generator)
  47. Compare: {prog} a <dump file> (compare output of a key generator against wallet dump)
  48. where a and b are one of:
  49. '1' - native Python ecdsa library (very slow)
  50. '2' - bitcoincore.org's secp256k1 library (default from v0.8.6)
  51. EXAMPLES:
  52. {prog} 1:2 100
  53. (compare output of native Python ECDSA with secp256k1 library, 100 rounds)
  54. {prog} 2:ext 100
  55. (compare output of secp256k1 library with external library (see below), 100 rounds)
  56. {prog} 2 1000
  57. (test speed of secp256k1 library address generation, 1000 rounds)
  58. {prog} 2 my.dump
  59. (compare addrs generated with secp256k1 library to {dn} wallet dump)
  60. External libraries required for the 'ext' generator:
  61. + ethkey (for ETH,ETC) https://github.com/paritytech/parity-ethereum
  62. + zcash-mini (for zcash_z addresses) https://github.com/FiloSottile/zcash-mini
  63. + moneropy (for Monero addresses) https://github.com/bigreddmachine/MoneroPy
  64. + pycoin (for supported coins) https://github.com/richardkiss/pycoin
  65. + keyconv (for all other coins) https://github.com/exploitagency/vanitygen-plus
  66. ('keyconv' generates uncompressed addresses only)
  67. """
  68. },
  69. 'code': {
  70. 'notes': lambda s: s.format(
  71. prog='gentest.py',
  72. pnm=g.proj_name,
  73. snum=rounds,
  74. dn=g.proto.daemon_name)
  75. }
  76. }
  77. sys.argv = [sys.argv[0]] + ['--skip-cfg-file'] + sys.argv[1:]
  78. cmd_args = opts.init(opts_data,add_opts=['exact_output','use_old_ed25519'])
  79. if not 1 <= len(cmd_args) <= 2: opts.usage()
  80. addr_type = MMGenAddrType(opt.type or g.proto.dfl_mmtype)
  81. from collections import namedtuple
  82. ep = namedtuple('external_prog_output',['wif','addr','vk'])
  83. from subprocess import run,PIPE,DEVNULL
  84. def get_cmd_output(cmd,input=None):
  85. return run(cmd,input=input,stdout=PIPE,stderr=DEVNULL).stdout.decode().splitlines()
  86. def ethkey_sec2addr(sec):
  87. o = get_cmd_output(['ethkey','info',sec])
  88. return ep(o[0].split()[1],o[-1].split()[1],None)
  89. def keyconv_sec2addr(sec):
  90. o = get_cmd_output(['keyconv','-C',g.coin,sec.wif])
  91. return ep(o[1].split()[1],o[0].split()[1],None)
  92. def zcash_mini_sec2addr(sec):
  93. o = get_cmd_output(['zcash-mini','-key','-simple'],input=(sec.wif+'\n').encode())
  94. return ep(o[1],o[0],o[-1])
  95. def pycoin_sec2addr(sec):
  96. coin = ci.external_tests['testnet']['pycoin'][g.coin] if g.testnet else g.coin
  97. network = network_for_netcode(coin)
  98. key = network.keys.private(secret_exponent=int(sec,16),is_compressed=addr_type.name != 'legacy')
  99. if key is None:
  100. die(1,"can't parse {}".format(sec))
  101. if addr_type.name in ('segwit','bech32'):
  102. hash160_c = key.hash160(is_compressed=True)
  103. if addr_type.name == 'segwit':
  104. p2sh_script = network.contract.for_p2pkh_wit(hash160_c)
  105. addr = network.address.for_p2s(p2sh_script)
  106. else:
  107. addr = network.address.for_p2pkh_wit(hash160_c)
  108. else:
  109. addr = key.address()
  110. return ep(key.wif(),addr,None)
  111. def moneropy_sec2addr(sec):
  112. sk_t,vk_t,addr_t = mp_acc.account_from_spend_key(sec) # VERY slow!
  113. return ep(sk_t,addr_t,vk_t)
  114. # pycoin/networks/all.py pycoin/networks/legacy_networks.py
  115. def init_external_prog():
  116. global b,b_desc,ext_prog,ext_sec2addr,eth,addr_type
  117. def test_support(k):
  118. if b == k: return True
  119. if b != 'ext' and b != k: return False
  120. if g.coin in ci.external_tests['mainnet'][k] and not g.testnet: return True
  121. if g.coin in ci.external_tests['testnet'][k]: return True
  122. return False
  123. if b == 'zcash_mini' or addr_type.name == 'zcash_z':
  124. ext_sec2addr = zcash_mini_sec2addr
  125. ext_prog = 'zcash_mini'
  126. init_coin('zec')
  127. addr_type = MMGenAddrType('Z')
  128. elif test_support('ethkey'): # build with 'cargo build -p ethkey-cli --release'
  129. ext_sec2addr = ethkey_sec2addr
  130. ext_prog = 'ethkey'
  131. elif test_support('pycoin'):
  132. global network_for_netcode
  133. try:
  134. from pycoin.networks.registry import network_for_netcode
  135. except:
  136. raise ImportError("Unable to import pycoin.networks.registry. Is pycoin installed on your system?")
  137. ext_sec2addr = pycoin_sec2addr
  138. ext_prog = 'pycoin'
  139. elif test_support('moneropy'):
  140. global mp_acc
  141. try:
  142. import moneropy.account as mp_acc
  143. except:
  144. raise ImportError("Unable to import moneropy. Is moneropy installed on your system?")
  145. ext_sec2addr = moneropy_sec2addr
  146. init_coin('xmr')
  147. ext_prog = 'moneropy'
  148. addr_type = MMGenAddrType('M')
  149. elif test_support('keyconv'):
  150. ext_sec2addr = keyconv_sec2addr
  151. ext_prog = 'keyconv'
  152. else:
  153. m = '{}: coin supported by MMGen but unsupported by gentest.py for {}'
  154. raise ValueError(m.format(g.coin,('mainnet','testnet')[g.testnet]))
  155. b_desc = ext_prog
  156. b = 'ext'
  157. def test_equal(a_addr,b_addr,in_bytes,sec,wif,a,b):
  158. if a_addr != b_addr:
  159. fs = """
  160. {i:{w}}: {}
  161. {s:{w}}: {}
  162. {W:{w}}: {}
  163. {a:{w}}: {}
  164. {b:{w}}: {}
  165. """
  166. die(3,
  167. red('\nERROR: Values do not match!')
  168. + fs.format(
  169. in_bytes.hex(), sec, wif, a_addr, b_addr,
  170. i='input', s='sec key', W='WIF key', a=kg_a.desc, b=b_desc,
  171. w=max(len(e) for e in (kg_a.desc,b_desc)) + 1
  172. ).rstrip())
  173. def compare_test():
  174. for k in ('segwit','compressed'):
  175. if b == 'ext' and addr_type.name == k and g.coin not in ci.external_tests_segwit_compressed[k]:
  176. m = 'skipping - external program does not support {} for coin {}'
  177. msg(m.format(addr_type.name.capitalize(),g.coin))
  178. return
  179. if 'ext_prog' in globals():
  180. if g.coin not in ci.external_tests[('mainnet','testnet')[g.testnet]][ext_prog]:
  181. msg("Coin '{}' incompatible with external generator '{}'".format(g.coin,ext_prog))
  182. return
  183. global last_t
  184. last_t = time.time()
  185. A = kg_a.desc
  186. B = b_desc
  187. if A == B:
  188. msg('skipping - generation methods A and B are the same ({})'.format(A))
  189. return
  190. m = "Comparing address generators '{}' and '{}' for coin {}, addrtype {!r}"
  191. qmsg(green(m.format(A,B,g.coin,addr_type.name)))
  192. def do_compare_test(n,trounds,in_bytes):
  193. global last_t
  194. if opt.verbose or time.time() - last_t >= 0.1:
  195. qmsg_r('\rRound {}/{} '.format(i+1,trounds))
  196. last_t = time.time()
  197. sec = PrivKey(in_bytes,compressed=addr_type.compressed,pubkey_type=addr_type.pubkey_type)
  198. a_ph = kg_a.to_pubhex(sec)
  199. a_addr = ag.to_addr(a_ph)
  200. a_vk = None
  201. if b == 'ext':
  202. ret = ext_sec2addr(sec)
  203. tinfo = (in_bytes,sec,sec.wif,a,ext_prog)
  204. test_equal(sec.wif,ret.wif,*tinfo)
  205. test_equal(a_addr,ret.addr,*tinfo)
  206. if ret.vk:
  207. a_vk = ag.to_viewkey(a_ph)
  208. test_equal(a_vk,ret.vk,*tinfo)
  209. else:
  210. b_addr = ag.to_addr(kg_b.to_pubhex(sec))
  211. tinfo = (in_bytes,sec,sec.wif,a,b)
  212. test_equal(a_addr,b_addr,*tinfo)
  213. vmsg(ct_fs.format(b=in_bytes.hex(),k=sec.wif,v=a_vk,a=a_addr))
  214. qmsg_r('\rRound {}/{} '.format(n+1,trounds))
  215. ct_fs = ( '\ninput: {b}\n%-9s {k}\naddr: {a}\n',
  216. '\ninput: {b}\n%-9s {k}\nviewkey: {v}\naddr: {a}\n')[
  217. 'viewkey' in addr_type.extra_attrs] % (addr_type.wif_label + ':')
  218. # test some important private key edge cases:
  219. edgecase_sks = (
  220. bytes([0x00]*31 + [0x01]), # min
  221. bytes([0xff]*32), # max
  222. bytes([0x0f] + [0xff]*31), # same key as above for zcash-z
  223. bytes([0x00]*31 + [0xff]), # monero will reduce
  224. bytes([0xff]*31 + [0x0f]), # monero will not reduce
  225. )
  226. qmsg(purple('edge cases:'))
  227. for i,in_bytes in enumerate(edgecase_sks):
  228. do_compare_test(i,len(edgecase_sks),in_bytes)
  229. qmsg(green('\rOK ' if opt.verbose else 'OK'))
  230. qmsg(purple('random input:'))
  231. for i in range(rounds):
  232. do_compare_test(i,rounds,os.urandom(32))
  233. qmsg(green('\rOK ' if opt.verbose else 'OK'))
  234. def speed_test():
  235. m = "Testing speed of address generator '{}' for coin {}"
  236. qmsg(green(m.format(kg_a.desc,g.coin)))
  237. from struct import pack,unpack
  238. seed = os.urandom(28)
  239. qmsg('Incrementing key with each round')
  240. qmsg('Starting key: {}'.format((seed + pack('I',0)).hex()))
  241. import time
  242. start = last_t = time.time()
  243. for i in range(rounds):
  244. if time.time() - last_t >= 0.1:
  245. qmsg_r('\rRound {}/{} '.format(i+1,rounds))
  246. last_t = time.time()
  247. sec = PrivKey(seed+pack('I',i),compressed=addr_type.compressed,pubkey_type=addr_type.pubkey_type)
  248. a_addr = ag.to_addr(kg_a.to_pubhex(sec))
  249. vmsg('\nkey: {}\naddr: {}\n'.format(sec.wif,a_addr))
  250. qmsg_r('\rRound {}/{} '.format(i+1,rounds))
  251. qmsg('\n{} addresses generated in {:.2f} seconds'.format(rounds,time.time()-start))
  252. def dump_test():
  253. m = "Comparing output of address generator '{}' against wallet dump '{}'"
  254. qmsg(green(m.format(kg_a.desc,cmd_args[1])))
  255. for n,[wif,a_addr] in enumerate(dump,1):
  256. qmsg_r('\rKey {}/{} '.format(n,len(dump)))
  257. try:
  258. sec = PrivKey(wif=wif)
  259. except:
  260. die(2,'\nInvalid {}net WIF address in dump file: {}'.format(('main','test')[g.testnet],wif))
  261. b_addr = ag.to_addr(kg_a.to_pubhex(sec))
  262. vmsg('\nwif: {}\naddr: {}\n'.format(wif,b_addr))
  263. tinfo = (bytes.fromhex(sec),sec,wif,3,a)
  264. test_equal(a_addr,b_addr,*tinfo)
  265. qmsg(green(('\n','')[bool(opt.verbose)] + 'OK'))
  266. # begin execution
  267. from mmgen.protocol import init_coin
  268. from mmgen.altcoin import CoinInfo as ci
  269. urounds,fh = None,None
  270. dump = []
  271. if len(cmd_args) == 2:
  272. try:
  273. urounds = int(cmd_args[1])
  274. assert urounds > 0
  275. except:
  276. try:
  277. fh = open(cmd_args[1])
  278. except:
  279. die(1,'Second argument must be filename or positive integer')
  280. else:
  281. for line in fh.readlines():
  282. if 'addr=' in line:
  283. x,addr = line.split('addr=')
  284. dump.append([x.split()[0],addr.split()[0]])
  285. if urounds: rounds = urounds
  286. a,b = None,None
  287. b_desc = 'unknown'
  288. try:
  289. a,b = cmd_args[0].split(':')
  290. except:
  291. try:
  292. a = cmd_args[0]
  293. a = int(a)
  294. assert 1 <= a <= len(g.key_generators)
  295. except:
  296. die(1,'First argument must be one or two generator IDs, colon separated')
  297. else:
  298. try:
  299. a = int(a)
  300. assert 1 <= a <= len(g.key_generators),'{}: invalid key generator'.format(a)
  301. if b in ('ext','ethkey','pycoin','keyconv','zcash_mini','moneropy'):
  302. init_external_prog()
  303. else:
  304. b = int(b)
  305. assert 1 <= b <= len(g.key_generators),'{}: invalid key generator'.format(b)
  306. assert a != b,'Key generators are the same!'
  307. except Exception as e:
  308. die(1,'{}\n{}: invalid generator argument'.format(e.args[0],cmd_args[0]))
  309. from mmgen.addr import KeyGenerator,AddrGenerator
  310. from mmgen.obj import PrivKey
  311. kg_a = KeyGenerator(addr_type,a)
  312. ag = AddrGenerator(addr_type)
  313. if a and b:
  314. if opt.all:
  315. from mmgen.protocol import init_genonly_altcoins,CoinProtocol
  316. init_genonly_altcoins('btc',trust_level=0)
  317. mmgen_supported = CoinProtocol.get_valid_coins(upcase=True)
  318. for coin in ci.external_tests[('mainnet','testnet')[g.testnet]][ext_prog]:
  319. if coin not in mmgen_supported: continue
  320. init_coin(coin)
  321. if addr_type not in g.proto.mmtypes:
  322. addr_type = MMGenAddrType(g.proto.dfl_mmtype)
  323. kg_a = KeyGenerator(addr_type,a)
  324. ag = AddrGenerator(addr_type)
  325. compare_test()
  326. else:
  327. if b != 'ext':
  328. kg_b = KeyGenerator(addr_type,b)
  329. b_desc = kg_b.desc
  330. compare_test()
  331. elif a and not fh:
  332. speed_test()
  333. elif a and dump:
  334. b_desc = 'dump'
  335. dump_test()
  336. else:
  337. die(2,'Illegal invocation')