#!/usr/bin/env python3 # Copyright (c) 2010 ArtForz -- public domain half-a-node # Copyright (c) 2012 Jeff Garzik # Copyright (c) 2010-2017 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 strcutures 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. """ from codecs import encode import copy import hashlib from io import BytesIO import random import socket import struct import time from .siphash import siphash256 from .util import hex_str_to_bytes, bytes_to_hex_str MIN_VERSION_SUPPORTED = 60001 MY_VERSION = 70925 MY_SUBVERSION = "/python-mininode-tester:0.0.3/" MY_RELAY = 1 # from version 70001 onwards, fRelay should be appended to version messages (BIP37) MAX_INV_SZ = 50000 MAX_BLOCK_BASE_SIZE = 2000000 CURRENT_BLK_VERSION = 11 COIN = 100000000 # 1 PIV in satoshis NODE_NETWORK = (1 << 0) # NODE_GETUTXO = (1 << 1) NODE_BLOOM = (1 << 2) MSG_TX = 1 MSG_BLOCK = 2 MSG_TYPE_MASK = 0xffffffff >> 2 # Serialization/deserialization tools def sha256(s): return hashlib.new('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 ser_uint64(u): rs = b"" for i in range(2): rs += 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 i 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 i 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 # Deserialize from bytes def FromBytes(obj, tx_bytes): obj.deserialize(BytesIO(tx_bytes)) return obj # Deserialize from a hex string representation (eg from RPC) def FromHex(obj, hex_string): obj.deserialize(BytesIO(hex_str_to_bytes(hex_string))) return obj # Convert a binary-serializable object to hex (eg for submission via RPC) def ToHex(obj): return bytes_to_hex_str(obj.serialize()) # Objects that map to pivxd 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 ADDRV2_NET_NAME = { NET_IPV4: "IPv4" } ADDRV2_ADDRESS_LENGTH = { NET_IPV4: 4 } def __init__(self): self.time = 0 self.nServices = 1 self.net = self.NET_IPV4 self.ip = "0.0.0.0" self.port = 0 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 == self.NET_IPV4 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: typemap = { 0: "MSG_ERROR", 1: "MSG_TX", 2: "MSG_BLOCK", 3: "MSG_FILTERED_BLOCK", 4: "MSG_TXLOCK_REQUEST", 5: "MSG_TXLOCK_VOTE", 6: "MSG_SPORK", 7: "MSG_MASTERNODE_WINNER", 8: "MSG_MASTERNODE_SCANNING_ERROR", 9: "MSG_BUDGET_VOTE", 10: "MSG_BUDGET_PROPOSAL", 11: "MSG_BUDGET_FINALIZED", 12: "MSG_BUDGET_FINALIZED_VOTE", 13: "MSG_MASTERNODE_QUORUM", 15: "MSG_MASTERNODE_ANNOUNCE", 16: "MSG_MASTERNODE_PING", 17: "MSG_DSTX" } def __init__(self, t=0, h=0): self.type = t self.hash = h def deserialize(self, f): self.type = struct.unpack("= 3: self.sapData = SaplingTxData() self.sapData.deserialize(f) if self.nType != 0: self.extraData = deser_string(f) self.sha256 = None self.hash = None def serialize_without_witness(self): r = b"" r += struct.pack("= 3: r += self.sapData.serialize() if self.nType != 0: r += ser_string(self.extraData) return r # Regular serialization is with witness -- must explicitly # call serialize_without_witness to exclude witness data. def serialize(self): return self.serialize_without_witness() # Recalculate the txid (transaction hash without witness) def rehash(self): self.sha256 = None self.calc_sha256() # We will only cache the serialization without witness in # self.sha256 and self.hash -- those are expected to be the txid. def calc_sha256(self, with_witness=False): if self.sha256 is None: self.sha256 = uint256_from_str(hash256(self.serialize_without_witness())) self.hash = encode(hash256(self.serialize_without_witness())[::-1], 'hex_codec').decode('ascii') 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 def is_coinbase(self): return ( len(self.vin) == 1 and self.vin[0].prevout == NullOutPoint and (not self.vin[0].is_zerocoinspend()) ) def is_coinstake(self): return ( len(self.vin) == 1 and len(self.vout) >= 2 and self.vout[0] == CTxOut() ) def from_hex(self, hexstring): f = BytesIO(hex_str_to_bytes(hexstring)) self.deserialize(f) def spends(self, outpoint): return len([x for x in self.vin if x.prevout.hash == outpoint.hash and x.prevout.n == outpoint.n]) > 0 def __repr__(self): return "CTransaction(nVersion=%i nType=%i vin=%s vout=%s nLockTime=%i)" \ % (self.nVersion, self.nType, repr(self.vin), repr(self.vout), self.nLockTime) class CBlockHeader: def __init__(self, header=None): if header is None: self.set_null() else: self.nVersion = header.nVersion self.hashPrevBlock = header.hashPrevBlock self.hashMerkleRoot = header.hashMerkleRoot self.nTime = header.nTime self.nBits = header.nBits self.nNonce = header.nNonce self.hashFinalSaplingRoot = header.hashFinalSaplingRoot self.sha256 = header.sha256 self.hash = header.hash self.calc_sha256() def set_null(self): self.nVersion = CURRENT_BLK_VERSION self.hashPrevBlock = 0 self.hashMerkleRoot = 0 self.nTime = 0 self.nBits = 0 self.nNonce = 0 self.hashFinalSaplingRoot = 0 self.sha256 = None self.hash = None def deserialize(self, f): self.nVersion = struct.unpack("= 8: self.hashFinalSaplingRoot = deser_uint256(f) self.sha256 = None self.hash = None def serialize(self): r = b"" r += struct.pack("= 8: r += ser_uint256(self.hashFinalSaplingRoot) return r def calc_sha256(self): if self.sha256 is None: r = b"" r += struct.pack("= 8: r += ser_uint256(self.hashFinalSaplingRoot) self.sha256 = uint256_from_str(hash256(r)) self.hash = encode(hash256(r)[::-1], 'hex_codec').decode('ascii') def rehash(self): self.sha256 = None self.calc_sha256() return self.sha256 # PIVX def solve_stake(self, stakeInputs, prevModifier): target0 = uint256_from_compact(self.nBits) loop = True while loop: for uniqueness in stakeInputs: nvalue, _, prevTime = stakeInputs[uniqueness] target = int(target0 * nvalue / 100) % 2**256 data = b"" # always modifier V2 (256 bits) on regtest data += ser_uint256(prevModifier) data += struct.pack(" 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): # For witness root purposes, the hash of the # coinbase, with witness, is defined to be 0...0 hashes = [ser_uint256(0)] for tx in self.vtx[1:]: # Calculate the hashes with witness data hashes.append(ser_uint256(tx.calc_sha256(True))) return self.get_merkle_root(hashes) def is_valid(self): self.calc_sha256() 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() def sign_block(self, key, low_s=True): data = b"" data += struct.pack("= 8: data += ser_uint256(self.hashFinalSaplingRoot) sha256NoSig = hash256(data) self.vchBlockSig = key.sign(sha256NoSig, low_s=low_s) self.sig_key = key self.low_s = low_s def re_sign_block(self): if self.sig_key is None: raise Exception("Unable to re-sign block. Key Not present, use 'sign_block' first.") return self.sign_block(self.sig_key, self.low_s) def __repr__(self): return "CBlock(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nBits=%08x nNonce=%08x vtx=%s)" \ % (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot, time.ctime(self.nTime), self.nBits, self.nNonce, repr(self.vtx)) class PrefilledTransaction: 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: 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("= 106: self.addrFrom = CAddress() self.addrFrom.deserialize(f, with_time=False) self.nNonce = struct.unpack("= 209: self.nStartingHeight = struct.unpack("= 70001: # Relay field is optional for version 70001 onwards try: self.nRelay = struct.unpack("= 70925: try: self.mn_auth_challenge = deser_uint256(f) except: self.mn_auth_challenge = 0 def serialize(self): r = b"" r += struct.pack(" class msg_headers: command = b"headers" def __init__(self, headers=None): self.headers = headers if headers is not None else [] def deserialize(self, f): # comment in pivxd 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_feefilter: command = b"feefilter" def __init__(self, feerate=0): self.feerate = feerate def deserialize(self, f): self.feerate = struct.unpack("