genesis.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. import hashlib, binascii, struct, array, os, time, sys, optparse
  2. import scrypt
  3. from construct import *
  4. def main():
  5. options = get_args()
  6. algorithm = get_algorithm(options)
  7. input_script = create_input_script(options.timestamp)
  8. output_script = create_output_script(options.pubkey)
  9. # hash merkle root is the double sha256 hash of the transaction(s)
  10. tx = create_transaction(input_script, output_script,options)
  11. hash_merkle_root = hashlib.sha256(hashlib.sha256(tx).digest()).digest()
  12. print_block_info(options, hash_merkle_root)
  13. block_header = create_block_header(hash_merkle_root, options.time, options.bits, options.nonce)
  14. genesis_hash, nonce = generate_hash(block_header, algorithm, options.nonce, options.bits)
  15. announce_found_genesis(genesis_hash, nonce)
  16. def get_args():
  17. parser = optparse.OptionParser()
  18. parser.add_option("-t", "--time", dest="time", default=int(time.time()),
  19. type="int", help="the (unix) time when the genesisblock is created")
  20. parser.add_option("-z", "--timestamp", dest="timestamp", default="The Times 03/Jan/2009 Chancellor on brink of second bailout for banks",
  21. type="string", help="the pszTimestamp found in the coinbase of the genesisblock")
  22. parser.add_option("-n", "--nonce", dest="nonce", default=0,
  23. type="int", help="the first value of the nonce that will be incremented when searching the genesis hash")
  24. parser.add_option("-a", "--algorithm", dest="algorithm", default="SHA256",
  25. help="the PoW algorithm: [SHA256|scrypt|X11|X13|X15]")
  26. parser.add_option("-p", "--pubkey", dest="pubkey", default="04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f",
  27. type="string", help="the pubkey found in the output script")
  28. parser.add_option("-v", "--value", dest="value", default=5000000000,
  29. type="int", help="the value in coins for the output, full value (exp. in bitcoin 5000000000 - To get other coins value: Block Value * 100000000)")
  30. parser.add_option("-b", "--bits", dest="bits",
  31. type="int", help="the target in compact representation, associated to a difficulty of 1")
  32. (options, args) = parser.parse_args()
  33. if not options.bits:
  34. if options.algorithm == "scrypt" or options.algorithm == "X11" or options.algorithm == "X13" or options.algorithm == "X15":
  35. options.bits = 0x1e0ffff0
  36. else:
  37. options.bits = 0x1d00ffff
  38. return options
  39. def get_algorithm(options):
  40. supported_algorithms = ["SHA256", "scrypt", "X11", "X13", "X15"]
  41. if options.algorithm in supported_algorithms:
  42. return options.algorithm
  43. else:
  44. sys.exit("Error: Given algorithm must be one of: " + str(supported_algorithms))
  45. def create_input_script(psz_timestamp):
  46. psz_prefix = ""
  47. #use OP_PUSHDATA1 if required
  48. if len(psz_timestamp) > 76: psz_prefix = '4c'
  49. script_prefix = '04ffff001d0104' + psz_prefix + chr(len(psz_timestamp)).encode('hex')
  50. print (script_prefix + psz_timestamp.encode('hex'))
  51. return (script_prefix + psz_timestamp.encode('hex')).decode('hex')
  52. def create_output_script(pubkey):
  53. script_len = '41'
  54. OP_CHECKSIG = 'ac'
  55. return (script_len + pubkey + OP_CHECKSIG).decode('hex')
  56. def create_transaction(input_script, output_script,options):
  57. transaction = Struct("transaction",
  58. Bytes("version", 4),
  59. Byte("num_inputs"),
  60. StaticField("prev_output", 32),
  61. UBInt32('prev_out_idx'),
  62. Byte('input_script_len'),
  63. Bytes('input_script', len(input_script)),
  64. UBInt32('sequence'),
  65. Byte('num_outputs'),
  66. Bytes('out_value', 8),
  67. Byte('output_script_len'),
  68. Bytes('output_script', 0x43),
  69. UBInt32('locktime'))
  70. tx = transaction.parse('\x00'*(127 + len(input_script)))
  71. tx.version = struct.pack('<I', 1)
  72. tx.num_inputs = 1
  73. tx.prev_output = struct.pack('<qqqq', 0,0,0,0)
  74. tx.prev_out_idx = 0xFFFFFFFF
  75. tx.input_script_len = len(input_script)
  76. tx.input_script = input_script
  77. tx.sequence = 0xFFFFFFFF
  78. tx.num_outputs = 1
  79. tx.out_value = struct.pack('<q' ,options.value)#0x000005f5e100)#012a05f200) #50 coins
  80. #tx.out_value = struct.pack('<q' ,0x000000012a05f200) #50 coins
  81. tx.output_script_len = 0x43
  82. tx.output_script = output_script
  83. tx.locktime = 0
  84. return transaction.build(tx)
  85. def create_block_header(hash_merkle_root, time, bits, nonce):
  86. block_header = Struct("block_header",
  87. Bytes("version",4),
  88. Bytes("hash_prev_block", 32),
  89. Bytes("hash_merkle_root", 32),
  90. Bytes("time", 4),
  91. Bytes("bits", 4),
  92. Bytes("nonce", 4))
  93. genesisblock = block_header.parse('\x00'*80)
  94. genesisblock.version = struct.pack('<I', 1)
  95. genesisblock.hash_prev_block = struct.pack('<qqqq', 0,0,0,0)
  96. genesisblock.hash_merkle_root = hash_merkle_root
  97. genesisblock.time = struct.pack('<I', time)
  98. genesisblock.bits = struct.pack('<I', bits)
  99. genesisblock.nonce = struct.pack('<I', nonce)
  100. return block_header.build(genesisblock)
  101. # https://en.bitcoin.it/wiki/Block_hashing_algorithm
  102. def generate_hash(data_block, algorithm, start_nonce, bits):
  103. print 'Searching for genesis hash..'
  104. nonce = start_nonce
  105. last_updated = time.time()
  106. # https://en.bitcoin.it/wiki/Difficulty
  107. target = (bits & 0xffffff) * 2**(8*((bits >> 24) - 3))
  108. while True:
  109. sha256_hash, header_hash = generate_hashes_from_block(data_block, algorithm)
  110. last_updated = calculate_hashrate(nonce, last_updated)
  111. if is_genesis_hash(header_hash, target):
  112. if algorithm == "X11" or algorithm == "X13" or algorithm == "X15":
  113. return (header_hash, nonce)
  114. return (sha256_hash, nonce)
  115. else:
  116. nonce = nonce + 1
  117. data_block = data_block[0:len(data_block) - 4] + struct.pack('<I', nonce)
  118. def generate_hashes_from_block(data_block, algorithm):
  119. sha256_hash = hashlib.sha256(hashlib.sha256(data_block).digest()).digest()[::-1]
  120. header_hash = ""
  121. if algorithm == 'scrypt':
  122. header_hash = scrypt.hash(data_block,data_block,1024,1,1,32)[::-1]
  123. elif algorithm == 'SHA256':
  124. header_hash = sha256_hash
  125. elif algorithm == 'X11':
  126. try:
  127. exec('import %s' % "xcoin_hash")
  128. except ImportError:
  129. sys.exit("Cannot run X11 algorithm: module xcoin_hash not found")
  130. header_hash = xcoin_hash.getPoWHash(data_block)[::-1]
  131. elif algorithm == 'X13':
  132. try:
  133. exec('import %s' % "x13_hash")
  134. except ImportError:
  135. sys.exit("Cannot run X13 algorithm: module x13_hash not found")
  136. header_hash = x13_hash.getPoWHash(data_block)[::-1]
  137. elif algorithm == 'X15':
  138. try:
  139. exec('import %s' % "x15_hash")
  140. except ImportError:
  141. sys.exit("Cannot run X15 algorithm: module x15_hash not found")
  142. header_hash = x15_hash.getPoWHash(data_block)[::-1]
  143. return sha256_hash, header_hash
  144. def is_genesis_hash(header_hash, target):
  145. return int(header_hash.encode('hex_codec'), 16) < target
  146. def calculate_hashrate(nonce, last_updated):
  147. if nonce % 1000000 == 999999:
  148. now = time.time()
  149. hashrate = round(1000000/(now - last_updated))
  150. generation_time = round(pow(2, 32) / hashrate / 3600, 1)
  151. sys.stdout.write("\r%s hash/s, estimate: %s h"%(str(hashrate), str(generation_time)))
  152. sys.stdout.flush()
  153. return now
  154. else:
  155. return last_updated
  156. def print_block_info(options, hash_merkle_root):
  157. print "algorithm: " + (options.algorithm)
  158. print "merkle hash: " + hash_merkle_root[::-1].encode('hex_codec')
  159. print "pszTimestamp: " + options.timestamp
  160. print "pubkey: " + options.pubkey
  161. print "time: " + str(options.time)
  162. print "bits: " + str(hex(options.bits))
  163. def announce_found_genesis(genesis_hash, nonce):
  164. print "genesis hash found!"
  165. print "nonce: " + str(nonce)
  166. print "genesis hash: " + genesis_hash.encode('hex_codec')
  167. # GOGOGO!
  168. main()