gentest.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #!/usr/bin/env python
  2. # Chdir to repo root.
  3. # Since script is not in repo root, fix sys.path so that modules are
  4. # imported from repo, not system.
  5. import sys,os
  6. pn = os.path.dirname(sys.argv[0])
  7. os.chdir(os.path.join(pn,os.pardir))
  8. sys.path.__setitem__(0,os.path.abspath(os.curdir))
  9. from binascii import hexlify
  10. import mmgen.opt as opt
  11. import mmgen.globalvars as g
  12. from mmgen.util import msg,msg_r,mmsg,mdie,red,green,vmsg,start_mscolor
  13. from mmgen.bitcoin import hextowif,privnum2addr
  14. start_mscolor()
  15. rounds = 100
  16. opts_data = {
  17. 'desc': "Test addresses generated by {} against output of 'keyconv'".format(g.proj_name),
  18. 'usage':"[options] [rounds]",
  19. 'options': """
  20. -h, --help Print this help message
  21. -s, --system Test scripts and modules installed on system rather than
  22. those in the repo root
  23. -v, --verbose Produce more verbose output
  24. """,
  25. 'notes': """
  26. 'keyconv' is the address generation utility from the well-known vanitygen
  27. package. If it's installed on your system, {pnm} will use it by default to
  28. generate Bitcoin addresses. Otherwise, it falls back on its own internal
  29. routines, which use the Python ecdsa library.
  30. rounds is {} by default.
  31. """.format(rounds,pnm=g.proj_name)
  32. }
  33. cmd_args = opt.opts.init(opts_data,add_opts=["exact_output"])
  34. if len(cmd_args) == 1:
  35. try:
  36. rounds = int(cmd_args[0])
  37. assert rounds > 0
  38. except:
  39. msg("'rounds' must be a positive integer")
  40. sys.exit(1)
  41. elif len(cmd_args) > 1:
  42. opt.opts.usage(opts_data)
  43. if opt.system: sys.path.pop(0)
  44. from mmgen.addr import test_for_keyconv
  45. if not test_for_keyconv(silent=True):
  46. msg(
  47. "To run this test, you must install 'keyconv' from the vanitygen package.")
  48. sys.exit(1)
  49. msg(green("Comparing {}'s internally generated addresses against output of 'keyconv'").format(g.proj_name))
  50. from subprocess import check_output
  51. for i in range(1,rounds+1):
  52. msg_r("\rRound %s/%s " % (i,rounds))
  53. sec = hexlify(os.urandom(32))
  54. wif = hextowif(sec)
  55. a = privnum2addr(int(sec,16))
  56. vmsg("\nkey: %s\naddr: %s\n" % (wif,a))
  57. b = check_output(["keyconv", wif]).split()[1]
  58. if a != b:
  59. msg_r(red("\nERROR: Addresses do not match!"))
  60. msg("""
  61. sec key: {}
  62. WIF key: {}
  63. {pnm}: {}
  64. keyconv: {}
  65. """.format(sec,wif,a,b,pnm=g.proj_name).rstrip())
  66. sys.exit(3)
  67. msg(green("%sOK" % ("" if opt.verbose else "\n")))