|
4 | 4 | # file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
5 | 5 | """Utilities for manipulating blocks and transactions."""
|
6 | 6 |
|
| 7 | +from binascii import a2b_hex |
| 8 | +import io |
| 9 | +import struct |
| 10 | +import time |
7 | 11 | import unittest
|
8 | 12 |
|
9 | 13 | from .address import (
|
|
51 | 55 | # From BIP141
|
52 | 56 | WITNESS_COMMITMENT_HEADER = b"\xaa\x21\xa9\xed"
|
53 | 57 |
|
| 58 | +NORMAL_GBT_REQUEST_PARAMS = {"rules": ["segwit"]} |
54 | 59 |
|
55 |
| -def create_block(hashprev, coinbase, ntime=None, *, version=1): |
| 60 | + |
| 61 | +def create_block(hashprev=None, coinbase=None, ntime=None, *, version=None, tmpl=None, txlist=None): |
56 | 62 | """Create a block (with regtest difficulty)."""
|
57 | 63 | block = CBlock()
|
58 |
| - block.nVersion = version |
59 |
| - if ntime is None: |
60 |
| - import time |
61 |
| - block.nTime = int(time.time() + 600) |
| 64 | + if tmpl is None: |
| 65 | + tmpl = {} |
| 66 | + block.nVersion = version or tmpl.get('version') or 1 |
| 67 | + block.nTime = ntime or tmpl.get('curtime') or int(time.time() + 600) |
| 68 | + block.hashPrevBlock = hashprev or int(tmpl['previousblockhash'], 0x10) |
| 69 | + if tmpl and not tmpl.get('bits') is None: |
| 70 | + block.nBits = struct.unpack('>I', a2b_hex(tmpl['bits']))[0] |
62 | 71 | else:
|
63 |
| - block.nTime = ntime |
64 |
| - block.hashPrevBlock = hashprev |
65 |
| - block.nBits = 0x207fffff # difficulty retargeting is disabled in REGTEST chainparams |
| 72 | + block.nBits = 0x207fffff # difficulty retargeting is disabled in REGTEST chainparams |
| 73 | + if coinbase is None: |
| 74 | + coinbase = create_coinbase(height=tmpl['height']) |
66 | 75 | block.vtx.append(coinbase)
|
| 76 | + if txlist: |
| 77 | + for tx in txlist: |
| 78 | + if not hasattr(tx, 'calc_sha256'): |
| 79 | + txo = CTransaction() |
| 80 | + txo.deserialize(io.BytesIO(tx)) |
| 81 | + tx = txo |
| 82 | + block.vtx.append(tx) |
67 | 83 | block.hashMerkleRoot = block.calc_merkle_root()
|
68 | 84 | block.calc_sha256()
|
69 | 85 | return block
|
|
0 commit comments