Beispiel #1
0
    def add_transaction(self, transaction):
        """ Add a transaction to the blockchain. Return the hash
            of the transaction.
        """

        if not self.current_block.is_empty():
            transaction.hash_previous_transaction = hash_sha256(
                str(self.current_block.transactions[-1]).encode('utf-8'))
        else:
            transaction.hash_previous_transaction = None

        if self.current_block.is_full():
            self.add_block(self.current_block)
            self.current_block = Block(
                id=len(self.blocks),
                hash_previous_block=hash_sha256(
                    str(self.blocks[-1]).encode('utf-8')))

        transaction.id = len(self.current_block.transactions)
        if isinstance(transaction, CoinCreation):
            for index, _ in enumerate(transaction.created_coins):
                transaction.created_coins[index].id = CoinId(
                    index, transaction.id, self.current_block.id)
        else:
            for index, _ in enumerate(transaction.coins):
                transaction.coins[index].id = CoinId(index, transaction.id,
                                                     self.current_block.id)

        self.current_block.transactions.append(transaction)

        return transaction
Beispiel #2
0
 def get_hash_last_block(self):
     """ Return the hash of the last block of the
         blockchain. If there are not blocks, return
         None.
     """
     if len(self.blocks) > 0:
         return hash_sha256(self.blocks[-1])
     else:
         return None
Beispiel #3
0
    def add_block(self, block):
        """ Add a block to the blockchain. Return the hash
            of the block.
        """
        if not self.is_empty():
            block.hash_previous_block = hash_sha256(
                str(self.blocks[-1]).encode('utf-8'))
        else:
            block.hash_previous_block = None

        self.blocks.append(block)
        return block
Beispiel #4
0
    def check_blockchain(self):
        """ Check the blockchain to find inconsistencies """
        blocks = self.blocks + [self.current_block]

        # The list must have at least one block (the genesis block)
        if len(blocks) == 0:
            return False

        for ind in range(len(blocks) - 1, 0, -1):
            if blocks[ind].hash_previous_block != hash_sha256(
                    str(blocks[ind - 1]).encode('utf-8')):
                return False
        return True
Beispiel #5
0
 def __short_str__(self):
     block_hash = hash_sha256(str(self).encode('utf-8'))
     return f'Block ID:  {self.id},Block Hash: {block_hash}, Previous Block Hash: {self.hash_previous_block}'