Implement blockchain with about 60 lines

Introduction

I understood the contents of the blockchain roughly in the course of Udemy, so I implemented it. We implement it by ourselves based on the content of the course. Jun Sakai, an active engineer in Silicon Valley, teaches this course, and by taking this course, you will be able to create the following programs without looking at anything. Wallet and proof_of_work, which are not implemented in this post, are also implemented, so if you are interested, please take this course. I also recommend Jun Sakai's basic Python course.

Blockchain elements

The elements in each block are as follows.

--Block --previous_hash: Hash value of the previous block --nonce: Value found by mining --transaction: Transaction processed in the block --Timestamp: Time when the block was created

Blockchain.PNG

All blocks on the chain are connected by previous_hash, so if you want to tamper with a block in the middle of the chain, you have to recalculate all the hash values after that to prevent tampering.

Operation until a block is added to the chain

The operation until a new block is added to the chain is as follows.

  1. Create a transaction based on the sender, recipient, and amount
  2. Temporarily register (pool) the created transaction
  3. Mining pooled transactions (finding nonce values)
  4. Create a block based on the hash value, nonce, transaction, and timestamp of the previous block
  5. Add the created block to the chain

I will actually make it

class BlockChain(object):

    #Create the first block
    def __init__(self):
        self.chain = []
        self.transaction_pool = []
        self.create_block(previous_hash='Initialize')

    #Returns a hash value
    def hash(self, block):
        json_block = json.dumps(block)
        return hashlib.sha256(json_block.encode()).hexdigest()
    
    #Create a block based on the received value
    def create_block(self, previous_hash=None, nonce=0, transaction=None, timestamp=time.time()):
        block = {
            'previous_hash': previous_hash,
            'nonce': nonce,
            'transaction': transaction,
            'timestamp': timestamp
          }
        self.add_block_to_chain(block)
    
    #Add blocks to the chain
    def add_block_to_chain(self, block):
        self.chain.append(block)

    #Find the nonce value
    def mining(self):
        previous_hash = self.hash(self.chain[-1])
        nonce = 0
        transaction = self.transaction_pool
        self.transaction_pool = []
        timestamp = time.time()
        self.create_block(previous_hash, nonce, transaction, timestamp)

    #Pool transactions
    def add_transaction(self, sender_name, reciever_name, value):
        transaction = {
            'Sender_name': sender_name,
            'Reciever_name': reciever_name,
            'Value': value
        }
        self.transaction_pool.append(transaction)

    #Output the chain in an easy-to-read format
    def print_chain(self):
        for chain_index, block in enumerate(self.chain):
            print(f'{"="*40}Block {chain_index:3}')
            if block['transaction'] is None:
                print('Initialize')
                continue
            else:
                for key, value in block.items():
                    if key == 'transaction':
                        for transaction in value:
                            print(f'{"transaction":15}:')
                            for kk, vv in transaction.items():
                                print(f'\t{kk:15}:{vv}')
                    else:
                        print(f'{key:15}:{value}')


if __name__ == '__main__':
    print('='*30 + 'Start' + '='*30)
    #Create a BlockChain instance
    blockchain = BlockChain()
    #Register a transaction
    blockchain.add_transaction(sender_name='Alice', reciever_name='Bob', value=100)
    #Register a transaction
    blockchain.add_transaction(sender_name='Alice', reciever_name='Chris', value=1)
    #Perform mining (search for nonce)
    blockchain.mining()
    #Add a transaction
    blockchain.add_transaction(sender_name='Bob', reciever_name='Dave', value=100)
    #Perform mining (search for nonce)
    blockchain.mining()
    #Display the created blockchain
    blockchain.print_chain()

Execution result

========================================Block   0
Initialize
========================================Block   1
previous_hash  :54c72dc7390c09a6d2c00037c381057a7bd069e8d9c427585ce31bed16dfd0d8
nonce          :0
transaction    :
        Sender_name    :Alice
        Reciever_name  :Bob
        Value          :100
transaction    :
        Sender_name    :Alice
        Reciever_name  :Chris
        Value          :1
timestamp      :1578989130.9111161
========================================Block   2
previous_hash  :d4bb210d2e3ad304db53756e87a7513b2fca8672c6e757bef6db3fff8ff26bb1
nonce          :0
transaction    :
        Sender_name    :Bob
        Reciever_name  :Dave
        Value          :100
timestamp      :1578989132.9128711

Finally

It is a blockchain that has not been heard much since it became popular a while ago, but there are still more use cases such as Sony using it for copyright management and Microsoft using it for personal ID, so study it. I think there is no loss. In the future, we plan to implement the one linked with Flask.

Recommended Posts

Implement blockchain with about 60 lines
I tried to implement a blockchain that actually works with about 170 lines
Notes about with
Implement FReLU with tf.keras
Experience blockchain with BigchainDB
Implement login function with django-allauth
Implement subcommands with Python's argparse
About learning with google colab
Implement UnionFind (equivalent) in 10 lines
Implement PyTorch + GPU with Docker
[Python3] Dijkstra's algorithm with 14 lines
[QtDesigner] Implement WebView with PyQt5
Blockchain tampering detection with Python
Think about dropouts with MNIST
Easily implement subcommands with python click
Comment out multiple lines with csh
Implement "Data Visualization Design # 2" with matplotlib