Build a blockchain with Python ① Create a class

This time, I took a course on building a blockchain with Python at Udemy, so I would like to share the contents. In this course, you can understand the concept of blockchain by actually moving your hands, and it will be a good practice in Python coding. In this article, I will introduce the touching part of this course!

I will explain the implementation of an application that sends money using blockchain in Python. The development environment used Pycharm. First of all, create a list of chains that will contain several blocks, a list of pools that describe the contents of the transaction, and an initial block.

def __init__(self):
        self.transaction_pool = []         #Contains transaction information
        self.chain = []                    #Contains blockchain information
        self.create_block(0, "init hash")  #Creating an initial block

The information contained in one block is

・ prev hash: A hash containing information related to the previous block

-Timestamp: Information on block generation time

・ Nonce: Value obtained from the calculation result of mining

・ Transactions: Information on transaction details

It will be these four. Create a block, create a block to be used next time, and empty the pool containing transaction details.

def create_block(self, nonce, previous_hash):  #Method to make a block
        block = {
            'timestamp': time.time(),              #Store timestamp
            'transactions': self.transaction_pool, #Store transaction
            'nonce': nonce,                        #Store nonce
            'previous_hash': previous_hash         #Stores the hash associated with the previous block
        }
        self.chain.append(block)    #Make a new block
        self.transaction_pool = []  #Empty the contents of the transaction pool
        return block```

 It also performs processing to make the execution result easier to see.


#### **`  #Processing to make blocks easier to see`**
```def pprint(chains)

    for i, chain in enumerate(chains):
        print(f'{"="*12} Chain {i} {"="*12}')
        for k, v in chain.items():
            print(f'{k:15}{v}')

Finally, add the process of calling the blockchain.

    if __name__ == '__main__':     #Call the blockchain
    block_chain = BlockChain()
    pprint(block_chain.chain)  #First block
    block_chain.create_block(5, 'hash 1')
    pprint(block_chain.chain)  #Second block

The following is a summary of all the descriptions so far.

import logging
import sys
import time  #To use timestamps

logging.basicConfig(level=logging.INFO, stream=sys.stdout)

class BlockChain(object):  #Blockchain class

    def __init__(self):
        self.transaction_pool = []         #Contains transaction information
        self.chain = []                    #Contains blockchain information
        self.create_block(0, "init hash")  #Creating an initial block

    def create_block(self, nonce, previous_hash):  #Method to make a block
        block = {
            'timestamp': time.time(),              #Store timestamp
            'transactions': self.transaction_pool, #Store transaction
            'nonce': nonce,                        #Store nonce
            'previous_hash': previous_hash         #Stores the hash associated with the previous block
        }
        self.chain.append(block)    #Make a new block
        self.transaction_pool = []  #Empty the contents of the transaction pool
        return block

def pprint(chains):  #Processing to make blocks easier to see
    for i, chain in enumerate(chains):
        print(f'{"="*12} Chain {i} {"="*12}')
        for k, v in chain.items():
            print(f'{k:15}{v}')

if __name__ == '__main__':     #Call the blockchain
    block_chain = BlockChain()
    pprint(block_chain.chain)  #First block
    block_chain.create_block(5, 'hash 1')
    pprint(block_chain.chain)  #Second block

Click here to continue the course "Introduction to blockchain development from scratch starting with Python taught by active Silicon Valley engineers" https://www.udemy.com/course/python-blockchain/learn/lecture/15381372#overview

Recommended Posts

Build a blockchain with Python ① Create a class
[Note] Create a one-line timezone class with python
Create a python3 build environment with Sublime Text3
Create a directory with python
Create a virtual environment with Python!
[Python] Inherit a class with class variables
Create a dummy image with Python + PIL.
[Python] Create a virtual environment with Anaconda
Let's create a free group with Python
Create a word frequency counter with Python 3.4
Build a python virtual environment with pyenv
Build a modern Python environment with Neovim
Create a Python module
Create a Python environment
Create a frame with transparent background with tkinter [Python]
Create a LINE BOT with Minette for Python
Build a python environment with ansible on centos6
Create a virtual environment with conda in Python
Create a page that loads infinitely with python
[Python] Build a Django development environment with Docker
You can easily create a GUI with Python
Create a color bar with Python + Qt (PySide)
Steps to create a Twitter bot with python
Python: Create a class that supports unpacked assignment
Create a decision tree from 0 with Python (1. Overview)
Create a new page in confluence with Python
Create a color-specified widget with Python + Qt (PySide)
Create a Photoshop format file (.psd) with python
Build a Python environment with OSX El capitan
Quickly build a Python Django environment with IntelliJ
Create a Python console application easily with Click
Build a Python machine learning environment with a container
Build a python execution environment with VS Code
Create a Wox plugin (Python)
Create a function in Python
Create a dictionary in Python
Build a python virtual environment with virtualenv and virtualenvwrapper
Create 3d gif with python3
Build a python environment for each directory with pyenv-virtualenv
[Python] Create a ValueObject with a complete constructor using dataclasses
Create a homepage with django
Why not create a stylish table easily with Python?
Create a python development environment with vagrant + ansible + fabric
Build python3 environment with ubuntu 16.04
Build python environment with direnv
Build a machine learning application development environment with Python
Create a python numpy array
Make a fortune with Python
Build a python virtual environment with virtualenv and virtualenvwrapper
Create a Layer for AWS Lambda Python with Docker
Create a heatmap with pyqtgraph
[python] Create a date array with arbitrary increments with np.arange
Build a Python environment offline
Blockchain tampering detection with Python
[Python] How to create a 2D histogram with Matplotlib
[Python] Create a Tkinter program distribution file with cx_Freeze
Let's build git-cat with Python
Create a fake Minecraft server in Python with Quarry
Create a company name extractor with python using JCLdic
Create a 2d CAD file ".dxf" with python [ezdxf]
[Python] Create a file & folder path specification screen with tkinter