def add_data(self, data: str) -> bool:
        """
        Adds a new Block to the Blockchain. Returns a bool indicating success or failure.

        Parameters:
        data -- the data (represented as a string) to be stored.
        """

        timestamp = time.time()

        # The previous hash is important since this is what helps us ensure
        # that our Blockchain has not lost its integrity. Each block will
        # keep track of the block before it, using its hash, thus we
        # will know that no block has been tamperered with.
        previous_hash = self.blocks[-1].generate_hash()

        block = Block()
        block.data = data
        block.timestamp = timestamp
        block.previous_hash = previous_hash
        self.blocks.append(block)

        # We validate the entire Blockchain to ensure that
        # the block we just inserted did not break our
        # Blockchain integrity.
        if not self.validate():
            self.blocks.remove(block)
            return False

        return True
    def add_chain_data(self, chain_data: list):
        """
        Takes a list of blocks, usually ingested from a JSON file, and adds them to the chain.

        Parameters:
        chain_data -- a list of dicts with "data", "previous_hash", "timestamp".
        """

        for chain_item in chain_data:
            block = Block()
            block.data = chain_item["data"]
            block.previous_hash = chain_item["previous_hash"]
            block.timestamp = chain_item["timestamp"]
            self.blocks.append(block)
Exemple #3
0
def write_default_blockchain() -> str:
    """Returns the string representation of the default Blockchain data."""

    genesis_block = Block()
    genesis_block.data = "This is the sickest Blockchain implementation ever."
    genesis_block.timestamp = time.time()
    genesis_block.previous_hash = ""

    # Create a temporary chain which we can convert to JSON.
    default_chain = Blockchain([])
    default_chain.blocks.append(genesis_block)
    save_chain(default_chain)

    return default_chain.to_json()