Пример #1
0
    def add_block(self, block: Block) -> Tuple[bool, Optional[str]]:
        """
        When a new block is received via a broadcast, the receiving nodes must validate the
        block to make sure it is valid, and then add it to their chains.

        This also makes sure that there are not open transactions on any of the nodes
        that match a transaction in the broadcasted block.
        """
        if not Verification.valid_nonce(block.header):
            return False, "Nonce is not valid"
        if (not Verification.hash_block_header(self.last_block.header)
                == block.header.previous_hash):
            return (
                False,
                "Hash of last block does not equal previous hash in the current block",
            )
        self.add_block_to_chain(block)

        # Always work off a copy as to not disrupt the current list of open transactions
        stored_transactions = self.__open_transactions[:]
        for itx in block.transactions:
            for opentx in stored_transactions:
                if opentx.transaction_hash == itx:
                    try:
                        self.__open_transactions.remove(opentx)
                    except ValueError:
                        logger.warning("Item was already removed: %s", opentx)

        self.save_data()
        return True, "success"
Пример #2
0
def test_correct_nonce():
    timestamp = datetime.utcfromtimestamp(0)

    block_one = Block(
        index=0,
        block_hash="",
        size=0,
        header=Header(
            timestamp=timestamp,
            transaction_merkle_root="",
            nonce=100,
            previous_hash="",
            difficulty=4,
            version=1,
        ),
        transaction_count=0,
        transactions=[],
    )

    previous_hash = Verification.hash_block_header(block_one.header)

    open_transactions = [
        SignedRawTransaction(
            details=Details(
                sender="test2",
                recipient="test",
                amount=2.5,
                nonce=0,
                timestamp=timestamp,
                public_key="pub_key",
            ),
            signature="sig",
        )
    ]

    block_header = Header(
        version=1,
        difficulty=4,
        timestamp=datetime.utcfromtimestamp(1),
        transaction_merkle_root=get_merkle_root(open_transactions),
        previous_hash=previous_hash,
        nonce=0,
    )

    block_header = Verification.proof_of_work(block_header)

    block_two = Block(
        index=1,
        block_hash="",
        size=0,
        header=block_header,
        transaction_count=len(open_transactions),
        transactions=[
            Verification.hash_transaction(t) for t in open_transactions
        ],
    )

    assert Verification.valid_nonce(block_two.header)