def test_block_parsing_and_serialization(self): tx_in = TxIn( prev_tx=b'\x00' * 32, prev_index=0xffffffff, script_sig=Script([b'muhhh coinz']), ) sk = create_sk(100) sec = sk.verifying_key.to_sec(compressed=False) tx_out = TxOut( amount=50 * 100_000_000, script_pubkey=p2pk_script(sec), ) coinbase = Tx( version=1, tx_ins=[tx_in], tx_outs=[tx_out], locktime=0, ) block = mine( Block(version=1, prev_block=genesis.hash(), merkle_root=merkle_root([coinbase.hash()]), timestamp=int(time.time()), bits=starting_bits, nonce=b'\x00\x00\x00\x00', txns=[coinbase])) assert Block.parse(BytesIO(block.serialize())).hash() == block.hash()
def parse(cls, stream): block = Block.parse(stream) return cls(block)
def parse(cls, stream): return Block.parse(stream)
from io import BytesIO from solutions.network import PeerConnection, GetHeadersMessage, HeadersMessage, GetDataMessage, BlockMessage from solutions.block import RAW_GENESIS_BLOCK, BlockHeader, Block from lib import target_to_bits GENESIS_HEADER = BlockHeader.parse(BytesIO(RAW_GENESIS_BLOCK)) GENESIS_BLOCK = Block.parse(BytesIO(RAW_GENESIS_BLOCK)) starting_bits = target_to_bits(16**62) class BitcoinNode: def __init__(self): self.headers = [GENESIS_HEADER] self.blocks = [GENESIS_BLOCK] self.utxo_set = {} self.peer = None def connect(self, host, port): self.peer = PeerConnection(host, port) self.peer.handshake() def receive_header(self, header): # TODO: verify hash matches # TODO: check proof-of-work # append block headers received to headers array previous = self.headers[-1] if header.prev_block != previous.hash(): raise RuntimeError('discontinuous block at {}'.format( len(self.headers)))