#!/usr/bin/env python3 # Copyright (c) 2010 ArtForz -- public domain half-a-node # Copyright (c) 2012 Jeff Garzik # Copyright (c) 2010-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Bitcoin test framework primitive and message structures CBlock, CTransaction, CBlockHeader, CTxIn, CTxOut, etc....: data structures that should map to corresponding structures in bitcoin/primitives msg_block, msg_tx, msg_headers, etc.: data structures that represent network messages ser_*, deser_*: functions that handle serialization/deserialization. Classes use __slots__ to ensure extraneous attributes aren't accidentally added by tests, compromising their intended effect. """ from base64 import b32decode, b32encode import copy import hashlib from io import BytesIO import math import random import socket import struct import time from test_framework.siphash import siphash256 from test_framework.util import calcfastmerkleroot, BITCOIN_ASSET_OUT, assert_equal MAX_LOCATOR_SZ = 101 MAX_BLOCK_WEIGHT = 4000000 MAX_BLOOM_FILTER_SIZE = 36000 MAX_BLOOM_HASH_FUNCS = 50 COIN = 100000000 # 1 btc in satoshis MAX_MONEY = 21000000 * COIN BIP125_SEQUENCE_NUMBER = 0xfffffffd # Sequence number that is rbf-opt-in (BIP 125) and csv-opt-out (BIP 68) SEQUENCE_FINAL = 0xffffffff # Sequence number that disables nLockTime if set for every input of a tx MAX_PROTOCOL_MESSAGE_LENGTH = 16 * 1000 * 1000 # Maximum length of incoming protocol messages MAX_HEADERS_RESULTS = 2000 # Number of headers sent in one getheaders result MAX_INV_SIZE = 50000 # Maximum number of entries in an 'inv' protocol message NODE_NETWORK = (1 << 0) NODE_BLOOM = (1 << 2) NODE_WITNESS = (1 << 3) NODE_COMPACT_FILTERS = (1 << 6) NODE_NETWORK_LIMITED = (1 << 10) MSG_TX = 1 MSG_BLOCK = 2 MSG_FILTERED_BLOCK = 3 MSG_CMPCT_BLOCK = 4 MSG_WTX = 5 MSG_WITNESS_FLAG = 1 << 30 MSG_TYPE_MASK = 0xffffffff >> 2 MSG_WITNESS_TX = MSG_TX | MSG_WITNESS_FLAG FILTER_TYPE_BASIC = 0 WITNESS_SCALE_FACTOR = 4 def sha256(s): return hashlib.sha256(s).digest() def hash256(s): return sha256(sha256(s)) def ser_compact_size(l): r = b"" if l < 253: r = struct.pack("B", l) elif l < 0x10000: r = struct.pack(">= 32 return rs def uint256_from_str(s): r = 0 t = struct.unpack("> 24) & 0xFF v = (c & 0xFFFFFF) << (8 * (nbytes - 3)) return v # deser_function_name: Allow for an alternate deserialization function on the # entries in the vector. def deser_vector(f, c, deser_function_name=None): nit = deser_compact_size(f) r = [] for _ in range(nit): t = c() if deser_function_name: getattr(t, deser_function_name)(f) else: t.deserialize(f) r.append(t) return r # ser_function_name: Allow for an alternate serialization function on the # entries in the vector (we use this for serializing the vector of transactions # for a witness block). def ser_vector(l, ser_function_name=None): r = ser_compact_size(len(l)) for i in l: if ser_function_name: r += getattr(i, ser_function_name)() else: r += i.serialize() return r def deser_uint256_vector(f): nit = deser_compact_size(f) r = [] for _ in range(nit): t = deser_uint256(f) r.append(t) return r def ser_uint256_vector(l): r = ser_compact_size(len(l)) for i in l: r += ser_uint256(i) return r def deser_string_vector(f): nit = deser_compact_size(f) r = [] for _ in range(nit): t = deser_string(f) r.append(t) return r def ser_string_vector(l): r = ser_compact_size(len(l)) for sv in l: r += ser_string(sv) return r def from_hex(obj, hex_string): """Deserialize from a hex string representation (e.g. from RPC) Note that there is no complementary helper like e.g. `to_hex` for the inverse operation. To serialize a message object to a hex string, simply use obj.serialize().hex()""" obj.deserialize(BytesIO(bytes.fromhex(hex_string))) return obj def tx_from_hex(hex_string): """Deserialize from hex string to a transaction object""" return from_hex(CTransaction(), hex_string) # Objects that map to bitcoind objects, which can be serialized/deserialized class CAddress: __slots__ = ("net", "ip", "nServices", "port", "time") # see https://github.com/bitcoin/bips/blob/master/bip-0155.mediawiki NET_IPV4 = 1 NET_I2P = 5 ADDRV2_NET_NAME = { NET_IPV4: "IPv4", NET_I2P: "I2P" } ADDRV2_ADDRESS_LENGTH = { NET_IPV4: 4, NET_I2P: 32 } I2P_PAD = "====" def __init__(self): self.time = 0 self.nServices = 1 self.net = self.NET_IPV4 self.ip = "0.0.0.0" self.port = 0 def __eq__(self, other): return self.net == other.net and self.ip == other.ip and self.nServices == other.nServices and self.port == other.port and self.time == other.time def deserialize(self, f, *, with_time=True): """Deserialize from addrv1 format (pre-BIP155)""" if with_time: # VERSION messages serialize CAddress objects without time self.time = struct.unpack("H", f.read(2))[0] def serialize(self, *, with_time=True): """Serialize in addrv1 format (pre-BIP155)""" assert self.net == self.NET_IPV4 r = b"" if with_time: # VERSION messages serialize CAddress objects without time r += struct.pack("H", self.port) return r def deserialize_v2(self, f): """Deserialize from addrv2 format (BIP155)""" self.time = struct.unpack("H", f.read(2))[0] def serialize_v2(self): """Serialize in addrv2 format (BIP155)""" assert self.net in (self.NET_IPV4, self.NET_I2P) r = b"" r += struct.pack("H", self.port) return r def __repr__(self): return ("CAddress(nServices=%i net=%s addr=%s port=%i)" % (self.nServices, self.ADDRV2_NET_NAME[self.net], self.ip, self.port)) class CInv: __slots__ = ("hash", "type") typemap = { 0: "Error", MSG_TX: "TX", MSG_BLOCK: "Block", MSG_TX | MSG_WITNESS_FLAG: "WitnessTx", MSG_BLOCK | MSG_WITNESS_FLAG: "WitnessBlock", MSG_FILTERED_BLOCK: "filtered Block", MSG_CMPCT_BLOCK: "CompactBlock", MSG_WTX: "WTX", } def __init__(self, t=0, h=0): self.type = t self.hash = h def deserialize(self, f): self.type = struct.unpack(" 0: has_asset_issuance = True if self.prevout.n & OUTPOINT_PEGIN_FLAG > 0: self.m_is_pegin = True self.prevout.n = self.prevout.n & OUTPOINT_INDEX_MASK self.scriptSig = deser_string(f) self.nSequence = struct.unpack("> (i*8)) & 0xff) self.vchCommitment = bytes(commit) else: if len(amount) != 8: raise 'invalid explicit amount (expected 8 bytes)' self.vchCommitment = b'\x01' + amount[::-1] def getAmount(self): if self.vchCommitment[0] != 1: raise ValueError('getAmount() called on non-explicit CTxOutValue') ret = 0 for i in range(8): #8 bytes ret <<= 8 ret |= self.vchCommitment[i+1] return ret def __repr__(self): return "CTxOutValue(vchCommitment=%s)" % self.vchCommitment class CTxOutNonce: __slots__ = ("vchCommitment") def __init__(self, vchCommitment=b"\x00"): self.vchCommitment = vchCommitment def setNull(self): self.vchCommitment = b'\x00' def deserialize(self, f): version = ord(f.read(1)) if version == 0: self.vchCommitment = b'\x00' elif version == 1: self.vchCommitment = b'\x01' + f.read(32) elif version == 0xff: self.vchCommitment = b'\xff' + f.read(32) elif version == 2 or version == 3: self.vchCommitment = bytes([version]) + f.read(32) else: raise ValueError('invalid CTxOutNonce in deserialize') def serialize(self): r = b"" r += self.vchCommitment return r def __repr__(self): return "CTxOutNonce(vchCommitment=%s)" % self.vchCommitment class CTxOut(): __slots__ = ("nValue", "scriptPubKey", "nAsset", "nNonce") def __init__(self, nValue=CTxOutValue(), scriptPubKey=b'', nAsset=CTxOutAsset(BITCOIN_ASSET_OUT), nNonce=CTxOutNonce()): self.nAsset = nAsset if type(nValue) is int: self.nValue = CTxOutValue(nValue) else: self.nValue = nValue self.nNonce = nNonce self.scriptPubKey = scriptPubKey def setNull(self): self.nAsset.setNull() self.nValue.setNull() self.nNonce.setNull() self.scriptPubKey = b'' def is_fee(self): return len(self.scriptPubKey) == 0 def deserialize(self, f): self.nAsset = CTxOutAsset() self.nAsset.deserialize(f) self.nValue = CTxOutValue() self.nValue.deserialize(f) self.nNonce = CTxOutNonce() self.nNonce.deserialize(f) self.scriptPubKey = deser_string(f) def serialize(self): r = b"" r += self.nAsset.serialize() r += self.nValue.serialize() r += self.nNonce.serialize() r += ser_string(self.scriptPubKey) return r def from_pegin_witness_data(self, peg_witness): self.nAsset = CTxOutAsset() self.nAsset.setToAsset(peg_witness.stack[1]) self.nValue = CTxOutValue() self.nValue.setToAmount(peg_witness.stack[0]) self.scriptPubKey = peg_witness.stack[3] def __repr__(self): return "CTxOut(nAsset=%s nValue=%s nNonce=%s scriptPubKey=%s)" \ % (self.nAsset, self.nValue, self.nNonce, self.scriptPubKey.hex()) class CScriptWitness: __slots__ = ("stack",) def __init__(self): # stack is a vector of strings self.stack = [] def __repr__(self): return "CScriptWitness(%s)" % \ (",".join([x.hex() for x in self.stack])) def is_null(self): if self.stack: return False return True class CTxInWitness: __slots__ = ("scriptWitness", "vchIssuanceAmountRangeproof", "vchInflationKeysRangeproof", "peginWitness") def __init__(self): self.vchIssuanceAmountRangeproof = b'' self.vchInflationKeysRangeproof = b'' self.scriptWitness = CScriptWitness() self.peginWitness = CScriptWitness() def deserialize(self, f): self.vchIssuanceAmountRangeproof = deser_string(f) self.vchInflationKeysRangeproof = deser_string(f) self.scriptWitness.stack = deser_string_vector(f) self.peginWitness.stack = deser_string_vector(f) def serialize(self): r = b'' r += ser_string(self.vchIssuanceAmountRangeproof) r += ser_string(self.vchInflationKeysRangeproof) r += ser_string_vector(self.scriptWitness.stack) r += ser_string_vector(self.peginWitness.stack) return r # Used in taproot sighash calculation def serialize_issuance_proofs(self): r = b'' r += ser_string(self.vchIssuanceAmountRangeproof) r += ser_string(self.vchInflationKeysRangeproof) return r def calc_witness_hash(self): leaves = [ hash256(ser_string(self.vchIssuanceAmountRangeproof))[::-1].hex(), hash256(ser_string(self.vchInflationKeysRangeproof))[::-1].hex(), hash256(ser_string_vector(self.scriptWitness.stack))[::-1].hex(), hash256(ser_string_vector(self.peginWitness.stack))[::-1].hex() ] return calcfastmerkleroot(leaves) def __repr__(self): return "CTxInWitness (%s, %s, %s %s)" % (self.vchIssuanceAmountRangeproof, self.vchInflationKeysRangeproof, self.scriptWitness, self.peginWitness) def is_null(self): return len(self.vchIssuanceAmountRangeproof) == 0 \ and len(self.vchInflationKeysRangeproof) == 0 \ and self.peginWitness.is_null() \ and self.scriptWitness.is_null() class CTxOutWitness: __slots__ = ("vchSurjectionproof", "vchRangeproof") def __init__(self): self.vchSurjectionproof = b'' self.vchRangeproof = b'' def deserialize(self, f): self.vchSurjectionproof = deser_string(f) self.vchRangeproof = deser_string(f) def serialize(self): r = b'' r += ser_string(self.vchSurjectionproof) r += ser_string(self.vchRangeproof) return r def calc_witness_hash(self): leaves = [ hash256(ser_string(self.vchSurjectionproof))[::-1].hex(), hash256(ser_string(self.vchRangeproof))[::-1].hex() ] return calcfastmerkleroot(leaves) def __repr__(self): return "CTxOutWitness (%s, %s)" % (self.vchSurjectionproof, self.vchRangeproof) def is_null(self): return len(self.vchSurjectionproof) == 0 \ and len(self.vchRangeproof) == 0 class CTxWitness: __slots__ = ("vtxinwit", "vtxoutwit") def __init__(self): self.vtxinwit = [] self.vtxoutwit = [] def deserialize(self, f): for i in range(len(self.vtxinwit)): self.vtxinwit[i].deserialize(f) for i in range(len(self.vtxoutwit)): self.vtxoutwit[i].deserialize(f) def serialize(self): r = b"" # This is different than the usual vector serialization -- # we omit the length of the vector, which is required to be # the same length as the transaction's vin vector. for x in self.vtxinwit: r += x.serialize() for x in self.vtxoutwit: r += x.serialize() return r def __repr__(self): return "CTxWitness([%s], [%s])" % \ (';'.join([repr(x) for x in self.vtxinwit]), ';'.join([repr(x) for x in self.vtxoutwit])) def is_null(self): for x in self.vtxinwit: if not x.is_null(): return False for x in self.vtxoutwit: if not x.is_null(): return False return True class CTransaction: __slots__ = ("hash", "nLockTime", "nVersion", "sha256", "vin", "vout", "wit") def __init__(self, tx=None): if tx is None: self.nVersion = 2 self.vin = [] self.vout = [] self.wit = CTxWitness() self.nLockTime = 0 self.sha256 = None self.hash = None else: self.nVersion = tx.nVersion self.vin = copy.deepcopy(tx.vin) self.vout = copy.deepcopy(tx.vout) self.nLockTime = tx.nLockTime self.sha256 = tx.sha256 self.hash = tx.hash self.wit = copy.deepcopy(tx.wit) def deserialize(self, f): self.nVersion = struct.unpack(" 0: self.wit.vtxinwit = [CTxInWitness() for _ in range(len(self.vin))] self.wit.vtxoutwit = [CTxOutWitness() for _ in range(len(self.vout))] self.wit.deserialize(f) else: self.wit = CTxWitness() if flags > 1: raise TypeError('Extra witness flags:' + str(flags)) self.sha256 = None self.hash = None # Only applicable for non-CT, non-segwit transactions def serialize_without_witness(self): r = b"" r += struct.pack("= len(self.wit.vtxinwit) or self.vin[i].prevout.isNull(): wit = CTxInWitness() else: wit = self.wit.vtxinwit[i] leaves.append(wit.calc_witness_hash()) inwitroot = calcfastmerkleroot(leaves) leaves = [] for i in range(len(self.vout)): wit = self.wit.vtxoutwit[i] if i < len(self.wit.vtxoutwit) else CTxOutWitness() leaves.append(wit.calc_witness_hash()) outwitroot = calcfastmerkleroot(leaves) # returns bitcoin hash print style string return calcfastmerkleroot([inwitroot, outwitroot]) def is_valid(self): self.calc_sha256() for tout in self.vout: if tout.nValue < 0 or tout.nValue > 21000000 * COIN: return False return True # Calculate the transaction weight using witness and non-witness # serialization size (does NOT use sigops). def get_weight(self): with_witness_size = len(self.serialize_with_witness()) without_witness_size = len(self.serialize_without_witness()) return (WITNESS_SCALE_FACTOR - 1) * without_witness_size + with_witness_size def get_vsize(self): return math.ceil(self.get_weight() / WITNESS_SCALE_FACTOR) def __repr__(self): return "CTransaction(nVersion=%i vin=%s vout=%s wit=%s nLockTime=%i)" \ % (self.nVersion, repr(self.vin), repr(self.vout), repr(self.wit), self.nLockTime) class CProof: __slots__ = ("challenge", "solution") # Default allows OP_TRUE blocks def __init__(self, challenge=bytearray.fromhex('51'), solution=b""): self.challenge = challenge self.solution = solution def set_null(self): self.challenge = b"" self.solution = b"" def deserialize(self, f): self.challenge = deser_string(f) self.solution = deser_string(f) def serialize(self): r = b"" r += ser_string(self.challenge) r += ser_string(self.solution) return r def serialize_for_hash(self): r = b"" r += ser_string(self.challenge) return r def __repr__(self): return "CProof(challenge=%s solution=%s)" \ % (self.challenge, self.solution) class DynaFedParamEntry: __slots__ = ("m_serialize_type", "m_signblockscript", "m_signblock_witness_limit", "m_fedpeg_program", "m_fedpegscript", "m_extension_space", "m_elided_root") # Constructor args will define serialization type: # null = 0 # signblock-related fields = 1, required for m_current on non-epoch-starts # all fields = 2, required for epoch starts def __init__(self, m_signblockscript=b"", m_signblock_witness_limit=0, m_fedpeg_program=b"", m_fedpegscript=b"", m_extension_space=None, m_elided_root=0): if m_extension_space is None: m_extension_space = [] self.m_signblockscript = m_signblockscript self.m_signblock_witness_limit = m_signblock_witness_limit self.m_fedpeg_program = m_fedpeg_program self.m_fedpegscript = m_fedpegscript self.m_extension_space = m_extension_space if self.is_null(): self.m_serialize_type = 0 elif m_fedpegscript==b"" and m_fedpeg_program==b"" and m_extension_space == []: self.m_serialize_type = 1 # We also set the "extra root" in this case self.m_elided_root = m_elided_root else: self.m_serialize_type = 2 def set_null(self): self.m_signblockscript = b"" self.m_signblock_witness_limit = 0 self.m_fedpeg_program = b"" self.m_fedpegscript = b"" self.m_extension_space = [] self.m_serialize_type = 0 self.m_elided_root = 0 def is_null(self): return self.m_signblockscript == b"" and self.m_signblock_witness_limit == 0 and \ self.m_fedpeg_program == b"" and self.m_fedpegscript == b"" and \ self.m_extension_space == [] def serialize(self): r = b"" r += struct.pack("B", self.m_serialize_type) if self.m_serialize_type == 1: r += ser_string(self.m_signblockscript) r += struct.pack(" 2: raise Exception("Invalid serialization type for DynaFedParamEntry") return r def deserialize(self, f): self.m_serialize_type = struct.unpack("B", f.read(1))[0] if self.m_serialize_type == 1: self.m_signblockscript = deser_string(f) self.m_signblock_witness_limit = struct.unpack(" 1: newhashes = [] for i in range(0, len(hashes), 2): i2 = min(i+1, len(hashes)-1) newhashes.append(hash256(hashes[i] + hashes[i2])) hashes = newhashes return uint256_from_str(hashes[0]) def calc_merkle_root(self): hashes = [] for tx in self.vtx: tx.calc_sha256() hashes.append(ser_uint256(tx.sha256)) return self.get_merkle_root(hashes) def calc_witness_merkle_root(self): hashes = [] for tx in self.vtx: # Calculate the hashes with witness data hashes.append(tx.calc_witness_hash()) # returns bitcoin hash print order hex string return calcfastmerkleroot(hashes) def is_valid(self): self.calc_sha256() # TODO: check signatures # target = uint256_from_compact(self.nBits) # if self.sha256 > target: # return False for tx in self.vtx: if not tx.is_valid(): return False if self.calc_merkle_root() != self.hashMerkleRoot: return False return True def solve(self): self.rehash() # target = uint256_from_compact(self.nBits) # while self.sha256 > target: # self.nNonce += 1 # self.rehash() # Calculate the block weight using witness and non-witness # serialization size (does NOT use sigops). def get_weight(self): with_witness_size = len(self.serialize(with_witness=True)) without_witness_size = len(self.serialize(with_witness=False)) return (WITNESS_SCALE_FACTOR - 1) * without_witness_size + with_witness_size def __repr__(self): return "CBlock(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s vtx=%s m_dynafed_params=%s)" \ % (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot, time.ctime(self.nTime), repr(self.vtx), self.m_dynafed_params) class PrefilledTransaction: __slots__ = ("index", "tx") def __init__(self, index=0, tx = None): self.index = index self.tx = tx def deserialize(self, f): self.index = deser_compact_size(f) self.tx = CTransaction() self.tx.deserialize(f) def serialize(self, with_witness=True): r = b"" r += ser_compact_size(self.index) if with_witness: r += self.tx.serialize_with_witness() else: r += self.tx.serialize_without_witness() return r def serialize_without_witness(self): return self.serialize(with_witness=False) def serialize_with_witness(self): return self.serialize(with_witness=True) def __repr__(self): return "PrefilledTransaction(index=%d, tx=%s)" % (self.index, repr(self.tx)) # This is what we send on the wire, in a cmpctblock message. class P2PHeaderAndShortIDs: __slots__ = ("header", "nonce", "prefilled_txn", "prefilled_txn_length", "shortids", "shortids_length") def __init__(self): self.header = CBlockHeader() self.nonce = 0 self.shortids_length = 0 self.shortids = [] self.prefilled_txn_length = 0 self.prefilled_txn = [] def deserialize(self, f): self.header.deserialize(f) self.nonce = struct.unpack(" class msg_headers: __slots__ = ("headers",) msgtype = b"headers" def __init__(self, headers=None): self.headers = headers if headers is not None else [] def deserialize(self, f): # comment in bitcoind indicates these should be deserialized as blocks blocks = deser_vector(f, CBlock) for x in blocks: self.headers.append(CBlockHeader(x)) def serialize(self): blocks = [CBlock(x) for x in self.headers] return ser_vector(blocks) def __repr__(self): return "msg_headers(headers=%s)" % repr(self.headers) class msg_merkleblock: __slots__ = ("merkleblock",) msgtype = b"merkleblock" def __init__(self, merkleblock=None): if merkleblock is None: self.merkleblock = CMerkleBlock() else: self.merkleblock = merkleblock def deserialize(self, f): self.merkleblock.deserialize(f) def serialize(self): return self.merkleblock.serialize() def __repr__(self): return "msg_merkleblock(merkleblock=%s)" % (repr(self.merkleblock)) class msg_filterload: __slots__ = ("data", "nHashFuncs", "nTweak", "nFlags") msgtype = b"filterload" def __init__(self, data=b'00', nHashFuncs=0, nTweak=0, nFlags=0): self.data = data self.nHashFuncs = nHashFuncs self.nTweak = nTweak self.nFlags = nFlags def deserialize(self, f): self.data = deser_string(f) self.nHashFuncs = struct.unpack("