You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

getblocktemplate_proposals.py 5.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2014-2016 The Bitcoin Core developers
  3. # Distributed under the MIT software license, see the accompanying
  4. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. """Test block proposals with getblocktemplate."""
  6. from test_framework.test_framework import BitcoinTestFramework
  7. from test_framework.util import *
  8. from binascii import a2b_hex, b2a_hex
  9. from hashlib import sha256
  10. from struct import pack
  11. def b2x(b):
  12. return b2a_hex(b).decode('ascii')
  13. # NOTE: This does not work for signed numbers (set the high bit) or zero (use b'\0')
  14. def encodeUNum(n):
  15. s = bytearray(b'\1')
  16. while n > 127:
  17. s[0] += 1
  18. s.append(n % 256)
  19. n //= 256
  20. s.append(n)
  21. return bytes(s)
  22. def varlenEncode(n):
  23. if n < 0xfd:
  24. return pack('<B', n)
  25. if n <= 0xffff:
  26. return b'\xfd' + pack('<H', n)
  27. if n <= 0xffffffff:
  28. return b'\xfe' + pack('<L', n)
  29. return b'\xff' + pack('<Q', n)
  30. def dblsha(b):
  31. return sha256(sha256(b).digest()).digest()
  32. def genmrklroot(leaflist):
  33. cur = leaflist
  34. while len(cur) > 1:
  35. n = []
  36. if len(cur) & 1:
  37. cur.append(cur[-1])
  38. for i in range(0, len(cur), 2):
  39. n.append(dblsha(cur[i] + cur[i+1]))
  40. cur = n
  41. return cur[0]
  42. def template_to_bytearray(tmpl, txlist):
  43. blkver = pack('<L', tmpl['version'])
  44. mrklroot = genmrklroot(list(dblsha(a) for a in txlist))
  45. timestamp = pack('<L', tmpl['curtime'])
  46. nonce = b'\0\0\0\0'
  47. blk = blkver + a2b_hex(tmpl['previousblockhash'])[::-1] + mrklroot + timestamp + a2b_hex(tmpl['bits'])[::-1] + nonce
  48. blk += varlenEncode(len(txlist))
  49. for tx in txlist:
  50. blk += tx
  51. return bytearray(blk)
  52. def template_to_hex(tmpl, txlist):
  53. return b2x(template_to_bytearray(tmpl, txlist))
  54. def assert_template(node, tmpl, txlist, expect):
  55. rsp = node.getblocktemplate({'data':template_to_hex(tmpl, txlist),'mode':'proposal'})
  56. if rsp != expect:
  57. raise AssertionError('unexpected: %s' % (rsp,))
  58. class GetBlockTemplateProposalTest(BitcoinTestFramework):
  59. def __init__(self):
  60. super().__init__()
  61. self.num_nodes = 2
  62. self.setup_clean_chain = False
  63. def setup_network(self):
  64. self.nodes = self.setup_nodes()
  65. connect_nodes_bi(self.nodes, 0, 1)
  66. def run_test(self):
  67. node = self.nodes[0]
  68. node.generate(1) # Mine a block to leave initial block download
  69. tmpl = node.getblocktemplate()
  70. if 'coinbasetxn' not in tmpl:
  71. rawcoinbase = encodeUNum(tmpl['height'])
  72. rawcoinbase += b'\x01-'
  73. hexcoinbase = b2x(rawcoinbase)
  74. hexoutval = b2x(pack('<Q', tmpl['coinbasevalue']))
  75. tmpl['coinbasetxn'] = {'data': '01000000' + '01' + '0000000000000000000000000000000000000000000000000000000000000000ffffffff' + ('%02x' % (len(rawcoinbase),)) + hexcoinbase + 'fffffffe' + '01' + hexoutval + '00' + '00000000'}
  76. txlist = list(bytearray(a2b_hex(a['data'])) for a in (tmpl['coinbasetxn'],) + tuple(tmpl['transactions']))
  77. # Test 0: Capability advertised
  78. assert('proposal' in tmpl['capabilities'])
  79. # NOTE: This test currently FAILS (regtest mode doesn't enforce block height in coinbase)
  80. ## Test 1: Bad height in coinbase
  81. #txlist[0][4+1+36+1+1] += 1
  82. #assert_template(node, tmpl, txlist, 'FIXME')
  83. #txlist[0][4+1+36+1+1] -= 1
  84. # Test 2: Bad input hash for gen tx
  85. txlist[0][4+1] += 1
  86. assert_template(node, tmpl, txlist, 'bad-cb-missing')
  87. txlist[0][4+1] -= 1
  88. # Test 3: Truncated final tx
  89. lastbyte = txlist[-1].pop()
  90. assert_raises_jsonrpc(-22, "Block decode failed", assert_template, node, tmpl, txlist, 'n/a')
  91. txlist[-1].append(lastbyte)
  92. # Test 4: Add an invalid tx to the end (duplicate of gen tx)
  93. txlist.append(txlist[0])
  94. assert_template(node, tmpl, txlist, 'bad-txns-duplicate')
  95. txlist.pop()
  96. # Test 5: Add an invalid tx to the end (non-duplicate)
  97. txlist.append(bytearray(txlist[0]))
  98. txlist[-1][4+1] = 0xff
  99. assert_template(node, tmpl, txlist, 'bad-txns-inputs-missingorspent')
  100. txlist.pop()
  101. # Test 6: Future tx lock time
  102. txlist[0][-4:] = b'\xff\xff\xff\xff'
  103. assert_template(node, tmpl, txlist, 'bad-txns-nonfinal')
  104. txlist[0][-4:] = b'\0\0\0\0'
  105. # Test 7: Bad tx count
  106. txlist.append(b'')
  107. assert_raises_jsonrpc(-22, 'Block decode failed', assert_template, node, tmpl, txlist, 'n/a')
  108. txlist.pop()
  109. # Test 8: Bad bits
  110. realbits = tmpl['bits']
  111. tmpl['bits'] = '1c0000ff' # impossible in the real world
  112. assert_template(node, tmpl, txlist, 'bad-diffbits')
  113. tmpl['bits'] = realbits
  114. # Test 9: Bad merkle root
  115. rawtmpl = template_to_bytearray(tmpl, txlist)
  116. rawtmpl[4+32] = (rawtmpl[4+32] + 1) % 0x100
  117. rsp = node.getblocktemplate({'data':b2x(rawtmpl),'mode':'proposal'})
  118. if rsp != 'bad-txnmrklroot':
  119. raise AssertionError('unexpected: %s' % (rsp,))
  120. # Test 10: Bad timestamps
  121. realtime = tmpl['curtime']
  122. tmpl['curtime'] = 0x7fffffff
  123. assert_template(node, tmpl, txlist, 'time-too-new')
  124. tmpl['curtime'] = 0
  125. assert_template(node, tmpl, txlist, 'time-too-old')
  126. tmpl['curtime'] = realtime
  127. # Test 11: Valid block
  128. assert_template(node, tmpl, txlist, None)
  129. # Test 12: Orphan block
  130. tmpl['previousblockhash'] = 'ff00' * 16
  131. assert_template(node, tmpl, txlist, 'inconclusive-not-best-prevblk')
  132. if __name__ == '__main__':
  133. GetBlockTemplateProposalTest().main()