gentest.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2016 Philemon <mmgen-py@yandex.com>
  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: Bitcoin 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. from binascii import hexlify
  26. # Import these _after_ local path's been added to sys.path
  27. from mmgen.common import *
  28. from mmgen.bitcoin import hex2wif,privnum2addr
  29. start_mscolor()
  30. rounds = 100
  31. opts_data = {
  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. -q, --quiet Produce quieter output
  37. --, --testnet Run for testnet rather than mainnet
  38. -v, --verbose Produce more verbose output
  39. """,
  40. 'notes': """
  41. Tests:
  42. A/B: {prog} a:b [rounds] (compare output of two key generators)
  43. Speed: {prog} a [rounds] (test speed of one key generator)
  44. Compare: {prog} a <dump file> (compare output of a key generator against wallet dump)
  45. where a and b are one of:
  46. '1' - native Python ecdsa library (very slow)
  47. '2' - 'keyconv' utility from the 'vanitygen' package (old default)
  48. '3' - bitcoincore.org's secp256k1 library (default from v0.8.6)
  49. EXAMPLES:
  50. {prog} 2:3 1000
  51. (compare output of 'keyconv' with secp256k1 library, 1000 rounds)
  52. {prog} 3 1000
  53. (test speed of secp256k1 library address generation, 1000 rounds)
  54. {prog} 3 my.dump
  55. (compare addrs generated with secp256k1 library to bitcoind wallet dump)
  56. """.format(prog='gentest.py',pnm=g.proj_name,snum=rounds)
  57. }
  58. sys.argv = [sys.argv[0]] + ['--skip-cfg-file'] + sys.argv[1:]
  59. cmd_args = opts.init(opts_data,add_opts=['exact_output'])
  60. if not 1 <= len(cmd_args) <= 2: opts.usage()
  61. urounds,fh = None,None
  62. dump = []
  63. if len(cmd_args) == 2:
  64. try:
  65. urounds = int(cmd_args[1])
  66. assert urounds > 0
  67. except:
  68. try:
  69. fh = open(cmd_args[1])
  70. except:
  71. die(1,"Second argument must be filename or positive integer")
  72. else:
  73. for line in fh.readlines():
  74. if 'addr=' in line:
  75. x,addr = line.split('addr=')
  76. dump.append([x.split()[0],addr.split()[0]])
  77. if urounds: rounds = urounds
  78. a,b = None,None
  79. try:
  80. a,b = cmd_args[0].split(':')
  81. except:
  82. try:
  83. a = cmd_args[0]
  84. a = int(a)
  85. assert 1 <= a <= len(g.key_generators)
  86. except:
  87. die(1,"First argument must be one or two generator IDs, colon separated")
  88. else:
  89. try:
  90. a,b = int(a),int(b)
  91. for i in a,b: assert 1 <= i <= len(g.key_generators)
  92. assert a != b
  93. except:
  94. die(1,"%s: invalid generator IDs" % cmd_args[0])
  95. def match_error(sec,wif,a_addr,b_addr,a,b):
  96. m = ['','py-ecdsa','keyconv','secp256k1','dump']
  97. msg_r(red('\nERROR: Addresses do not match!'))
  98. die(3,"""
  99. sec key : {}
  100. WIF key : {}
  101. {a:10}: {}
  102. {b:10}: {}
  103. """.format(sec,wif,a_addr,b_addr,pnm=g.proj_name,a=m[a],b=m[b]).rstrip())
  104. if a and b:
  105. m = "Comparing address generators '{}' and '{}'"
  106. msg(green(m.format(g.key_generators[a-1],g.key_generators[b-1])))
  107. from mmgen.addr import get_privhex2addr_f
  108. gen_a = get_privhex2addr_f(generator=a)
  109. gen_b = get_privhex2addr_f(generator=b)
  110. compressed = False
  111. for i in range(1,rounds+1):
  112. msg_r('\rRound %s/%s ' % (i,rounds))
  113. sec = hexlify(os.urandom(32))
  114. wif = hex2wif(sec,compressed=compressed)
  115. a_addr = gen_a(sec,compressed)
  116. b_addr = gen_b(sec,compressed)
  117. vmsg('\nkey: %s\naddr: %s\n' % (wif,a_addr))
  118. if a_addr != b_addr:
  119. match_error(sec,wif,a_addr,b_addr,a,b)
  120. if a != 2 and b != 2:
  121. compressed = not compressed
  122. msg(green(('\n','')[bool(opt.verbose)] + 'OK'))
  123. elif a and not fh:
  124. m = "Testing speed of address generator '{}'"
  125. msg(green(m.format(g.key_generators[a-1])))
  126. from mmgen.addr import get_privhex2addr_f
  127. gen_a = get_privhex2addr_f(generator=a)
  128. import time
  129. start = time.time()
  130. from struct import pack,unpack
  131. seed = os.urandom(28)
  132. print 'Incrementing key with each round'
  133. print 'Starting key:', hexlify(seed+pack('I',0))
  134. compressed = False
  135. for i in range(rounds):
  136. if not opt.quiet: msg_r('\rRound %s/%s ' % (i+1,rounds))
  137. sec = hexlify(seed+pack('I',i))
  138. wif = hex2wif(sec,compressed=compressed)
  139. a_addr = gen_a(sec,compressed)
  140. vmsg('\nkey: %s\naddr: %s\n' % (wif,a_addr))
  141. if a != 2:
  142. compressed = not compressed
  143. elapsed = int(time.time() - start)
  144. if not opt.quiet: msg('')
  145. msg('%s addresses generated in %s second%s' % (rounds,elapsed,('s','')[elapsed==1]))
  146. elif a and dump:
  147. m = "Comparing output of address generator '{}' against wallet dump '{}'"
  148. msg(green(m.format(g.key_generators[a-1],cmd_args[1])))
  149. if a == 2:
  150. msg("NOTE: for compressed addresses, 'python-ecdsa' generator will be used")
  151. from mmgen.addr import get_privhex2addr_f
  152. gen_a = get_privhex2addr_f(generator=a)
  153. from mmgen.bitcoin import wif2hex
  154. for n,[wif,a_addr] in enumerate(dump,1):
  155. msg_r('\rKey %s/%s ' % (n,len(dump)))
  156. sec = wif2hex(wif)
  157. if sec == False:
  158. die(2,'\nInvalid {}net WIF address in dump file: {}'.format(('main','test')[g.testnet],wif))
  159. compressed = wif[0] != ('5','9')[g.testnet]
  160. b_addr = gen_a(sec,compressed)
  161. if a_addr != b_addr:
  162. match_error(sec,wif,a_addr,b_addr,1 if compressed and a==2 else a,4)
  163. msg(green(('\n','')[bool(opt.verbose)] + 'OK'))