Exemplo n.º 1
0
    def run_test(self):
        node = self.nodes[0]
        node.add_p2p_connection(P2PDataStore())
        p2pGetter = node.add_p2p_connection(P2PBlockGetter())

        self.log.info("Submitting block with invalid auxpow...")
        tip = node.getbestblockhash()
        blk, blkHash = self.createBlock()
        blk = self.addAuxpow(blk, blkHash, False)
        assert_equal(node.submitblock(blk.serialize().hex()), "high-hash")
        assert_equal(node.getbestblockhash(), tip)

        self.log.info("Submitting block with valid auxpow...")
        blk = self.addAuxpow(blk, blkHash, True)
        assert_equal(node.submitblock(blk.serialize().hex()), None)
        assert_equal(node.getbestblockhash(), blkHash)

        self.log.info("Retrieving block through RPC...")
        gotHex = node.getblock(blkHash, 0)
        gotBlk = CBlock()
        gotBlk.deserialize(BytesIO(hex_str_to_bytes(gotHex)))
        gotBlk.rehash()
        assert_equal("%064x" % int(gotBlk.hash, 16), blkHash)

        self.log.info("Retrieving block through P2P...")
        gotBlk = p2pGetter.getBlock(blkHash)
        gotBlk.rehash()
        assert_equal("%064x" % int(gotBlk.hash, 16), blkHash)

        self.log.info("Sending block with invalid auxpow over P2P...")
        tip = node.getbestblockhash()
        blk, blkHash = self.createBlock()
        blk = self.addAuxpow(blk, blkHash, False)
        node.p2p.send_blocks_and_test([blk],
                                      node,
                                      force_send=True,
                                      success=False,
                                      reject_reason="high-hash")
        assert_equal(node.getbestblockhash(), tip)

        self.log.info("Sending the same block with valid auxpow...")
        blk = self.addAuxpow(blk, blkHash, True)
        node.p2p.send_blocks_and_test([blk], node, success=True)
        assert_equal(node.getbestblockhash(), blkHash)

        self.log.info("Retrieving block through RPC...")
        gotHex = node.getblock(blkHash, 0)
        gotBlk = CBlock()
        gotBlk.deserialize(BytesIO(hex_str_to_bytes(gotHex)))
        gotBlk.rehash()
        assert_equal("%064x" % int(gotBlk.hash, 16), blkHash)

        self.log.info("Retrieving block through P2P...")
        gotBlk = p2pGetter.getBlock(blkHash)
        gotBlk.rehash()
        assert_equal("%064x" % int(gotBlk.hash, 16), blkHash)
Exemplo n.º 2
0
    def _zmq_test(self):
        num_blocks = 5
        self.log.info("Generate %(n)d blocks (and %(n)d coinbase txes)" % {"n": num_blocks})
        genhashes = self.nodes[0].generatetoaddress(num_blocks, ADDRESS_BCRT1_UNSPENDABLE)
        self.sync_all()

        for x in range(num_blocks):
            # Should receive the coinbase txid.
            txid = self.hashtx.receive()

            # Should receive the coinbase raw transaction.
            hex = self.rawtx.receive()
            tx = CTransaction()
            tx.deserialize(BytesIO(hex))
            tx.calc_sha256()
            assert_equal(tx.hash, bytes_to_hex_str(txid))

            # Should receive the generated block hash.
            hash = bytes_to_hex_str(self.hashblock.receive())
            assert_equal(genhashes[x], hash)
            # The block should only have the coinbase txid.
            assert_equal([bytes_to_hex_str(txid)], self.nodes[1].getblock(hash)["tx"])

            # Should receive the generated raw block.
            raw_block = self.rawblock.receive()
            block = CBlock()
            f = BytesIO(raw_block)
            block.deserialize(f)
            block.calc_sha256()
            assert_equal(genhashes[x], block.hash)

        if self.is_wallet_compiled():
            self.log.info("Wait for tx from second node")
            payment_txid = self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 1.0)
            self.sync_all()

            # Should receive the broadcasted txid.
            txid = self.hashtx.receive()
            assert_equal(payment_txid, bytes_to_hex_str(txid))

            # Should receive the broadcasted raw transaction.
            hex = self.rawtx.receive()
            assert_equal(payment_txid, bytes_to_hex_str(hash256(hex)))


        self.log.info("Test the getzmqnotifications RPC")
        assert_equal(self.nodes[0].getzmqnotifications(), [
            {"type": "pubhashblock", "address": ADDRESS, "hwm": 1000},
            {"type": "pubhashtx", "address": ADDRESS, "hwm": 1000},
            {"type": "pubrawblock", "address": ADDRESS, "hwm": 1000},
            {"type": "pubrawtx", "address": ADDRESS, "hwm": 1000},
        ])

        assert_equal(self.nodes[1].getzmqnotifications(), [])
Exemplo n.º 3
0
    def _zmq_test(self):
        num_blocks = 5
        self.log.info("Generate %(n)d blocks (and %(n)d coinbase txes)" %
                      {"n": num_blocks})
        genhashes = self.nodes[0].generate(num_blocks,
                                           self.signblockprivkey_wif)
        self.sync_all()

        for x in range(num_blocks):
            # Should receive the coinbase txid.
            txid = self.hashtx.receive()

            # Should receive the coinbase raw transaction.
            hex = self.rawtx.receive()
            tx = CTransaction()
            tx.deserialize(BytesIO(hex))
            tx.calc_sha256()
            assert_equal(tx.hashMalFix, bytes_to_hex_str(txid))

            # Should receive the generated block hash.
            hash = bytes_to_hex_str(self.hashblock.receive())
            assert_equal(genhashes[x], hash)
            # The block should only have the coinbase txid.
            assert_equal([bytes_to_hex_str(txid)],
                         self.nodes[1].getblock(hash)["tx"])

            # Should receive the generated raw block.
            block = CBlock()
            block.deserialize(BytesIO(self.rawblock.receive()))
            block.calc_sha256()
            assert_equal(genhashes[x], block.hash)

        self.log.info("Wait for tx from second node")
        payment_txid = self.nodes[1].sendtoaddress(
            self.nodes[0].getnewaddress(), 1.0)
        self.sync_all()

        # Should receive the broadcasted txid.
        txid = self.hashtx.receive()
        assert_equal(payment_txid, bytes_to_hex_str(txid))

        # Should receive the broadcasted raw transaction.
        hex = self.rawtx.receive()
        tx = CTransaction()
        tx.deserialize(BytesIO(hex))
        tx.calc_sha256()
        assert_equal(tx.hashMalFix, bytes_to_hex_str(txid))
Exemplo n.º 4
0
 def test_chainlock_publishers(self):
     chain_lock_publishers = [
         ZMQPublisher.hash_chain_lock, ZMQPublisher.raw_chain_lock,
         ZMQPublisher.raw_chain_lock_sig
     ]
     self.log.info("Testing %d ChainLock publishers" %
                   len(chain_lock_publishers))
     # Subscribe to ChainLock messages
     self.subscribe(chain_lock_publishers)
     # Generate ChainLock
     generated_hash = self.nodes[0].generate(1)[0]
     self.wait_for_chainlocked_block_all_nodes(generated_hash)
     rpc_best_chain_lock = self.nodes[0].getbestchainlock()
     rpc_best_chain_lock_hash = rpc_best_chain_lock["blockhash"]
     rpc_best_chain_lock_sig = rpc_best_chain_lock["signature"]
     assert_equal(generated_hash, rpc_best_chain_lock_hash)
     rpc_chain_locked_block = self.nodes[0].getblock(
         rpc_best_chain_lock_hash)
     rpc_chain_lock_height = rpc_chain_locked_block["height"]
     rpc_chain_lock_hash = rpc_chain_locked_block["hash"]
     assert_equal(generated_hash, rpc_chain_lock_hash)
     # Validate hashchainlock
     zmq_chain_lock_hash = bytes_to_hex_str(
         self.receive(ZMQPublisher.hash_chain_lock).read(32))
     assert_equal(zmq_chain_lock_hash, rpc_best_chain_lock_hash)
     # Validate rawchainlock
     zmq_chain_locked_block = CBlock()
     zmq_chain_locked_block.deserialize(
         self.receive(ZMQPublisher.raw_chain_lock))
     assert (zmq_chain_locked_block.is_valid())
     assert_equal(zmq_chain_locked_block.hash, rpc_chain_lock_hash)
     # Validate rawchainlocksig
     zmq_chain_lock_sig_stream = self.receive(
         ZMQPublisher.raw_chain_lock_sig)
     zmq_chain_locked_block = CBlock()
     zmq_chain_locked_block.deserialize(zmq_chain_lock_sig_stream)
     assert (zmq_chain_locked_block.is_valid())
     zmq_chain_lock = msg_clsig()
     zmq_chain_lock.deserialize(zmq_chain_lock_sig_stream)
     assert_equal(zmq_chain_lock.height, rpc_chain_lock_height)
     assert_equal(uint256_to_string(zmq_chain_lock.blockHash),
                  rpc_chain_lock_hash)
     assert_equal(zmq_chain_locked_block.hash, rpc_chain_lock_hash)
     assert_equal(bytes_to_hex_str(zmq_chain_lock.sig),
                  rpc_best_chain_lock_sig)
     # Unsubscribe from ChainLock messages
     self.unsubscribe(chain_lock_publishers)
Exemplo n.º 5
0
    def run_test(self):
        node = self.nodes[0]
        p2pStore = node.add_p2p_connection(P2PDataStore())
        p2pGetter = node.add_p2p_connection(P2PBlockGetter())

        self.log.info("Adding a block with non-zero hash in the auxpow...")
        blk, blkHash = self.createBlock()
        blk.auxpow.hashBlock = 12345678
        blkHex = blk.serialize().hex()
        assert_equal(node.submitblock(blkHex), None)
        assert_equal(node.getbestblockhash(), blkHash)

        self.log.info("Retrieving block through RPC...")
        gotHex = node.getblock(blkHash, 0)
        assert gotHex != blkHex
        gotBlk = CBlock()
        gotBlk.deserialize(BytesIO(hex_str_to_bytes(gotHex)))
        assert_equal(gotBlk.auxpow.hashBlock, 0)

        self.log.info("Retrieving block through P2P...")
        gotBlk = p2pGetter.getBlock(blkHash)
        assert_equal(gotBlk.auxpow.hashBlock, 0)

        self.log.info("Sending zero-hash auxpow through RPC...")
        blk, blkHash = self.createBlock()
        blk.auxpow.hashBlock = 0
        assert_equal(node.submitblock(blk.serialize().hex()), None)
        assert_equal(node.getbestblockhash(), blkHash)

        self.log.info("Sending zero-hash auxpow through P2P...")
        blk, blkHash = self.createBlock()
        blk.auxpow.hashBlock = 0
        p2pStore.send_blocks_and_test([blk], node, success=True)
        assert_equal(node.getbestblockhash(), blkHash)

        self.log.info("Sending non-zero nIndex auxpow through RPC...")
        blk, blkHash = self.createBlock()
        blk.auxpow.nIndex = 42
        assert_equal(node.submitblock(blk.serialize().hex()), None)
        assert_equal(node.getbestblockhash(), blkHash)

        self.log.info("Sending non-zero nIndex auxpow through P2P...")
        blk, blkHash = self.createBlock()
        blk.auxpow.nIndex = 42
        p2pStore.send_blocks_and_test([blk], node, success=True)
        assert_equal(node.getbestblockhash(), blkHash)
Exemplo n.º 6
0
  def run_test (self):
    node = self.nodes[0]
    p2pStore = node.add_p2p_connection (P2PDataStore ())
    p2pGetter = node.add_p2p_connection (P2PBlockGetter ())

    self.log.info ("Adding a block with non-zero hash in the auxpow...")
    blk, blkHash = self.createBlock ()
    blk.auxpow.hashBlock = 12345678
    blkHex = blk.serialize ().hex ()
    assert_equal (node.submitblock (blkHex), None)
    assert_equal (node.getbestblockhash (), blkHash)

    self.log.info ("Retrieving block through RPC...")
    gotHex = node.getblock (blkHash, 0)
    assert gotHex != blkHex
    gotBlk = CBlock ()
    gotBlk.deserialize (BytesIO (hex_str_to_bytes (gotHex)))
    assert_equal (gotBlk.auxpow.hashBlock, 0)

    self.log.info ("Retrieving block through P2P...")
    gotBlk = p2pGetter.getBlock (blkHash)
    assert_equal (gotBlk.auxpow.hashBlock, 0)

    self.log.info ("Sending zero-hash auxpow through RPC...")
    blk, blkHash = self.createBlock ()
    blk.auxpow.hashBlock = 0
    assert_equal (node.submitblock (blk.serialize ().hex ()), None)
    assert_equal (node.getbestblockhash (), blkHash)

    self.log.info ("Sending zero-hash auxpow through P2P...")
    blk, blkHash = self.createBlock ()
    blk.auxpow.hashBlock = 0
    p2pStore.send_blocks_and_test ([blk], node, success=True)
    assert_equal (node.getbestblockhash (), blkHash)

    self.log.info ("Sending non-zero nIndex auxpow through RPC...")
    blk, blkHash = self.createBlock ()
    blk.auxpow.nIndex = 42
    assert_equal (node.submitblock (blk.serialize ().hex ()), None)
    assert_equal (node.getbestblockhash (), blkHash)

    self.log.info ("Sending non-zero nIndex auxpow through P2P...")
    blk, blkHash = self.createBlock ()
    blk.auxpow.nIndex = 42
    p2pStore.send_blocks_and_test ([blk], node, success=True)
    assert_equal (node.getbestblockhash (), blkHash)
Exemplo n.º 7
0
def unidirectional_node_sync_via_rpc(node_src, node_dest):
    blocks_to_copy = []
    blockhash = node_src.getbestblockhash()
    while True:
        try:
            assert len(node_dest.getblock(blockhash, False)) > 0
            break
        except:
            blocks_to_copy.append(blockhash)
            blockhash = node_src.getblockheader(blockhash, True)['previousblockhash']

    blocks_to_copy.reverse()
    for blockhash in blocks_to_copy:
        blockdata = node_src.getblock(blockhash, False)
        block = CBlock()
        block.deserialize(BytesIO(hex_str_to_bytes(blockdata)))
        node_dest.p2p.send_message(msg_block(block))
        node_dest.p2p.sync_with_ping()
Exemplo n.º 8
0
    def test_transaction_serialization(self):
        legacy_addr = self.nodes[0].getnewaddress("", "legacy")
        p2sh_addr = self.nodes[0].getnewaddress("", "p2sh-segwit")
        bech32_addr = self.nodes[0].getnewaddress("", "bech32")
        self.unknown_addr = self.nodes[1].getnewaddress()

        # directly seed types of utxos required
        self.nodes[0].generatetoaddress(1, legacy_addr)
        self.nodes[0].generatetoaddress(1, p2sh_addr)
        self.nodes[0].generatetoaddress(1, bech32_addr)
        self.nodes[0].generatetoaddress(101, self.unknown_addr)

        # grab utxos filtering by age
        legacy_utxo = self.nodes[0].listunspent(104, 104)[0]
        p2sh_utxo = self.nodes[0].listunspent(103, 103)[0]
        bech32_utxo = self.nodes[0].listunspent(102, 102)[0]

        submitted_txids = []
        self.log.info("Testing legacy UTXO")
        submitted_txids.append(
            self.assert_tx_format_also_signed(legacy_utxo, segwit=False))
        self.log.info("Testing p2sh UTXO")
        submitted_txids.append(
            self.assert_tx_format_also_signed(p2sh_utxo, segwit=True))
        self.log.info("Testing bech32 UTXO")
        submitted_txids.append(
            self.assert_tx_format_also_signed(bech32_utxo, segwit=True))

        blockhash = self.nodes[0].generate(1)[0]
        hexblock = self.nodes[0].getblock(blockhash, 0)
        block_details = self.nodes[0].getblock(blockhash, 2)
        block = CBlock()
        block.deserialize(BytesIO(hex_str_to_bytes(hexblock)))
        assert (len(block.vtx) == len(submitted_txids) + 1)
        assert_equal(len(block_details["tx"]), len(block.vtx))
        for tx1, tx2 in zip(block.vtx[1:], block_details["tx"][1:]):
            # no tuple wildcard, just re-used tx2 on first one
            assert ((tx1.rehash(), tx2["wtxid"]) in submitted_txids)
            assert ((tx2["txid"], tx2["hash"]) in submitted_txids)
            assert ((tx2["txid"], tx2["wtxid"]) in submitted_txids)
        block.rehash()
        assert_equal(block.hash, self.nodes[0].getbestblockhash())
Exemplo n.º 9
0
    def test_transaction_serialization(self):
        legacy_addr = self.nodes[0].getnewaddress("", "legacy")
        p2sh_addr = self.nodes[0].getnewaddress("", "p2sh-segwit")
        bech32_addr = self.nodes[0].getnewaddress("", "bech32")
        self.unknown_addr = self.nodes[1].getnewaddress()

        # directly seed types of utxos required
        self.nodes[0].generatetoaddress(1, legacy_addr)
        self.nodes[0].generatetoaddress(1, p2sh_addr)
        self.nodes[0].generatetoaddress(1, bech32_addr)
        self.nodes[0].generatetoaddress(101, self.unknown_addr)

        # grab utxos filtering by age
        legacy_utxo = self.nodes[0].listunspent(104, 104)[0]
        p2sh_utxo = self.nodes[0].listunspent(103, 103)[0]
        bech32_utxo = self.nodes[0].listunspent(102, 102)[0]

        submitted_txids = []
        self.log.info("Testing legacy UTXO")
        submitted_txids.append(self.assert_tx_format_also_signed(legacy_utxo, segwit=False))
        self.log.info("Testing p2sh UTXO")
        submitted_txids.append(self.assert_tx_format_also_signed(p2sh_utxo, segwit=True))
        self.log.info("Testing bech32 UTXO")
        submitted_txids.append(self.assert_tx_format_also_signed(bech32_utxo, segwit=True))

        blockhash = self.nodes[0].generate(1)[0]
        hexblock = self.nodes[0].getblock(blockhash, 0)
        block_details = self.nodes[0].getblock(blockhash, 2)
        block = CBlock()
        block.deserialize(BytesIO(hex_str_to_bytes(hexblock)))
        assert(len(block.vtx) == len(submitted_txids) + 1)
        assert_equal(len(block_details["tx"]), len(block.vtx))
        for tx1, tx2 in zip(block.vtx[1:], block_details["tx"][1:]):
            # no tuple wildcard, just re-used tx2 on first one
            assert((tx1.rehash(), tx2["wtxid"]) in submitted_txids)
            assert((tx2["txid"], tx2["hash"]) in submitted_txids)
            assert((tx2["txid"], tx2["wtxid"]) in submitted_txids)
        block.rehash()
        assert_equal(block.hash, self.nodes[0].getbestblockhash())
Exemplo n.º 10
0
    def run_test(self):
        self.description = "Covers the reorg with a zc public spend in vtx"
        self.init_test()
        DENOM_TO_USE = 10  # zc denomination
        INITAL_MINED_BLOCKS = 321  # First mined blocks (rewards collected to mint)
        MORE_MINED_BLOCKS = 105  # More blocks mined before spending zerocoins

        # 1) Starting mining blocks
        self.log.info("Mining %d blocks.." % INITAL_MINED_BLOCKS)
        self.node.generate(INITAL_MINED_BLOCKS)

        # 2) Mint 2 zerocoins
        self.node.mintzerocoin(DENOM_TO_USE)
        self.node.generate(1)
        self.node.mintzerocoin(DENOM_TO_USE)
        self.node.generate(1)

        # 3) Mine additional blocks and collect the mints
        self.log.info("Mining %d blocks.." % MORE_MINED_BLOCKS)
        self.node.generate(MORE_MINED_BLOCKS)
        self.log.info("Collecting mints...")
        mints = self.node.listmintedzerocoins(True, False)
        assert len(mints) == 2, "mints list has len %d (!= 2)" % len(mints)

        # 4) Get unspent coins and chain tip
        self.unspent = self.node.listunspent()
        block_count = self.node.getblockcount()
        pastBlockHash = self.node.getblockhash(block_count)
        self.log.info(
            "Block count: %d - Current best: %s..." %
            (self.node.getblockcount(), self.node.getbestblockhash()[:5]))
        pastBlock = CBlock()
        pastBlock.deserialize(
            BytesIO(hex_str_to_bytes(self.node.getblock(pastBlockHash,
                                                        False))))
        checkpoint = pastBlock.nAccumulatorCheckpoint

        # 5) get the raw zerocoin spend txes
        self.log.info("Getting the raw zerocoin public spends...")
        public_spend_A = self.node.createrawzerocoinpublicspend(
            mints[0].get("serial hash"))
        tx_A = CTransaction()
        tx_A.deserialize(BytesIO(hex_str_to_bytes(public_spend_A)))
        tx_A.rehash()
        public_spend_B = self.node.createrawzerocoinpublicspend(
            mints[1].get("serial hash"))
        tx_B = CTransaction()
        tx_B.deserialize(BytesIO(hex_str_to_bytes(public_spend_B)))
        tx_B.rehash()
        # Spending same coins to different recipients to get different txids
        my_addy = "yAVWM5urwaTyhiuFQHP2aP47rdZsLUG5PH"
        public_spend_A2 = self.node.createrawzerocoinpublicspend(
            mints[0].get("serial hash"), my_addy)
        tx_A2 = CTransaction()
        tx_A2.deserialize(BytesIO(hex_str_to_bytes(public_spend_A2)))
        tx_A2.rehash()
        public_spend_B2 = self.node.createrawzerocoinpublicspend(
            mints[1].get("serial hash"), my_addy)
        tx_B2 = CTransaction()
        tx_B2.deserialize(BytesIO(hex_str_to_bytes(public_spend_B2)))
        tx_B2.rehash()
        self.log.info("tx_A id: %s" % str(tx_A.hash))
        self.log.info("tx_B id: %s" % str(tx_B.hash))
        self.log.info("tx_A2 id: %s" % str(tx_A2.hash))
        self.log.info("tx_B2 id: %s" % str(tx_B2.hash))

        self.test_nodes[0].handle_connect()

        # 6) create block_A --> main chain
        self.log.info("")
        self.log.info("*** block_A ***")
        self.log.info("Creating block_A [%d] with public spend tx_A in it." %
                      (block_count + 1))
        block_A = self.new_block(block_count, pastBlock, checkpoint, tx_A)
        self.log.info("Hash of block_A: %s..." % block_A.hash[:5])
        self.log.info("sending block_A...")
        var = self.node.submitblock(bytes_to_hex_str(block_A.serialize()))
        if var is not None:
            self.log.info("result: %s" % str(var))
            raise Exception("block_A not accepted")
        time.sleep(2)
        assert_equal(self.node.getblockcount(), block_count + 1)
        assert_equal(self.node.getbestblockhash(), block_A.hash)
        self.log.info("  >>  block_A connected  <<")
        self.log.info(
            "Current chain: ... --> block_0 [%d] --> block_A [%d]\n" %
            (block_count, block_count + 1))

        # 7) create block_B --> forked chain
        self.log.info("*** block_B ***")
        self.log.info("Creating block_B [%d] with public spend tx_B in it." %
                      (block_count + 1))
        block_B = self.new_block(block_count, pastBlock, checkpoint, tx_B)
        self.log.info("Hash of block_B: %s..." % block_B.hash[:5])
        self.log.info("sending block_B...")
        var = self.node.submitblock(bytes_to_hex_str(block_B.serialize()))
        self.log.info("result of block_B submission: %s" % str(var))
        time.sleep(2)
        assert_equal(self.node.getblockcount(), block_count + 1)
        assert_equal(self.node.getbestblockhash(), block_A.hash)
        # block_B is not added. Chain remains the same
        self.log.info("  >>  block_B not connected  <<")
        self.log.info(
            "Current chain: ... --> block_0 [%d] --> block_A [%d]\n" %
            (block_count, block_count + 1))

        # 8) Create new block block_C on the forked chain (block_B)
        block_count += 1
        self.log.info("*** block_C ***")
        self.log.info(
            "Creating block_C [%d] on top of block_B triggering the reorg" %
            (block_count + 1))
        block_C = self.new_block(block_count, block_B, checkpoint)
        self.log.info("Hash of block_C: %s..." % block_C.hash[:5])
        self.log.info("sending block_C...")
        var = self.node.submitblock(bytes_to_hex_str(block_C.serialize()))
        if var is not None:
            self.log.info("result: %s" % str(var))
            raise Exception("block_C not accepted")
        time.sleep(2)
        assert_equal(self.node.getblockcount(), block_count + 1)
        assert_equal(self.node.getbestblockhash(), block_C.hash)
        self.log.info(
            "  >>  block_A disconnected / block_B and block_C connected  <<")
        self.log.info(
            "Current chain: ... --> block_0 [%d] --> block_B [%d] --> block_C [%d]\n"
            % (block_count - 1, block_count, block_count + 1))

        # 7) Now create block_D which tries to spend same coin of tx_B again on the (new) main chain
        # (this block will be rejected)
        block_count += 1
        self.log.info("*** block_D ***")
        self.log.info(
            "Creating block_D [%d] trying to double spend the coin of tx_B" %
            (block_count + 1))
        block_D = self.new_block(block_count, block_C, checkpoint, tx_B2)
        self.log.info("Hash of block_D: %s..." % block_D.hash[:5])
        self.log.info("sending block_D...")
        var = self.node.submitblock(bytes_to_hex_str(block_D.serialize()))
        self.log.info("result of block_D submission: %s" % str(var))
        time.sleep(2)
        assert_equal(self.node.getblockcount(), block_count)
        assert_equal(self.node.getbestblockhash(), block_C.hash)
        # block_D is not added. Chain remains the same
        self.log.info("  >>  block_D rejected  <<")
        self.log.info(
            "Current chain: ... --> block_0 [%d] --> block_B [%d] --> block_C [%d]\n"
            % (block_count - 2, block_count - 1, block_count))

        # 8) Now create block_E which spends tx_A again on main chain
        # (this block will be accepted and connected since tx_A was spent on block_A now disconnected)
        self.log.info("*** block_E ***")
        self.log.info("Creating block_E [%d] trying spend tx_A on main chain" %
                      (block_count + 1))
        block_E = self.new_block(block_count, block_C, checkpoint, tx_A)
        self.log.info("Hash of block_E: %s..." % block_E.hash[:5])
        self.log.info("sending block_E...")
        var = self.node.submitblock(bytes_to_hex_str(block_E.serialize()))
        if var is not None:
            self.log.info("result: %s" % str(var))
            raise Exception("block_E not accepted")
        time.sleep(2)
        assert_equal(self.node.getblockcount(), block_count + 1)
        assert_equal(self.node.getbestblockhash(), block_E.hash)
        self.log.info("  >>  block_E connected <<")
        self.log.info(
            "Current chain: ... --> block_0 [%d] --> block_B [%d] --> block_C [%d] --> block_E [%d]\n"
            % (block_count - 2, block_count - 1, block_count, block_count + 1))

        # 9) Now create block_F which tries to double spend the coin in tx_A
        # # (this block will be rejected)
        block_count += 1
        self.log.info("*** block_F ***")
        self.log.info(
            "Creating block_F [%d] trying to double spend the coin in tx_A" %
            (block_count + 1))
        block_F = self.new_block(block_count, block_E, checkpoint, tx_A2)
        self.log.info("Hash of block_F: %s..." % block_F.hash[:5])
        self.log.info("sending block_F...")
        var = self.node.submitblock(bytes_to_hex_str(block_F.serialize()))
        self.log.info("result of block_F submission: %s" % str(var))
        time.sleep(2)
        assert_equal(self.node.getblockcount(), block_count)
        assert_equal(self.node.getbestblockhash(), block_E.hash)
        self.log.info("  >>  block_F rejected <<")
        self.log.info(
            "Current chain: ... --> block_0 [%d] --> block_B [%d] --> block_C [%d] --> block_E [%d]\n"
            % (block_count - 3, block_count - 2, block_count - 1, block_count))
        self.log.info("All good.")
Exemplo n.º 11
0
def blockhashstr(block_data):
    b = CBlock()
    b.deserialize(BytesIO(block_data), legacy=False)
    b.calc_sha256()
    return b.hash