Blockchain technology has become another disruptive technology with its decentralized characteristics. Python, as an object-oriented interpreted computer programming language, is often referred to as the “glue language” due to its rich and powerful library. It is simple and easy to use. It is one of the first choices for blockchain enthusiasts to quickly learn blockchain.

The author of this article, Adil Moujahid, is a DATA scientist at NTT DATA Group, one of the top 10 IT service companies in the world and one of the top 10 IT service companies in Japan. He has in-depth research on the application of Python in the direction of blockchain.

In this article, Adil Moujahid introduces the decentralized payment scheme from the double payment problem, introduces the core concepts of blockchain such as public key cryptography, Hash function and mining, and expounds in detail how to generate a new fast, how to add new fast to the blockchain and other issues. Finally, Use Python to implement basic blockchain and blockchain client.

Adil Moujahid will teach you how to implement blockchains and blockchain clients in Python. Full of dry goods!

Blockchain is arguably one of the most important and disruptive technologies since the birth of the Internet. Blockchain, the core technology behind Bitcoin and other cryptocurrencies, has gained a lot of attention in the past few years.

Blockchain is a distributed database that allows transactions between two parties to take place directly without the need for third-party rights, with big implications for institutions such as banks, governments and markets.

Any enterprise or organization that relies on a centralized database as its core competitive advantage is likely to be disrupted by blockchain technology.

This paper is divided into three parts. The first two parts introduce the core concepts of blockchain. The third part describes how to implement the blockchain and two blockchain Web applications using Python so that end users can easily interact with the blockchain on the chain.

Simple blockchain crash course

In 2008, Satoshi Nakamoto published a bitcoin white paper titled “Bitcoin: Peer-to-peer electronic cash System”, laying the foundation for blockchain.

In his original Bitcoin white paper, Satoshi Nakamoto described how to build a peer-to-peer electronic cash system that would allow online payments to be sent directly from one party to another without going through a centralized institution. The system solves an important problem in digital currencies called double payments.

What is double pay?

Let’s say Alice wants to pay Bob $1. If Alice and Bob use physical cash, Alice will no longer have $1 after executing the transaction. If Alice and Bob use digital currency, the problem becomes more complicated.

Digital money exists in digital form and can be easily copied. For example, if Alice sends Bob a $1 digital file by E-mail, Bob can’t be sure that Alice deleted her copy of the file, and if Alice still has the $1 digital file, she can choose to send the same file to Carol. This problem is called double pay.

One way to solve the double payment problem is to establish a trusted third party (such as a bank) between Alice, Bob, and other participants in the network, which is responsible for managing the centralized ledger, which tracks and validates all transactions in the network. The downside of this solution is that in order for the system to work, it needs to trust centralized third parties.

Bitcoin: A decentralized solution to the double payment problem

To solve the double payment problem, Nakamoto proposed a public ledger that would track all transactions in the network via Bitcoin’s blockchain. Bitcoin’s blockchain has the following characteristics:

Distributed: Ledgers are replicated across multiple computers rather than stored on a central server. Any computer with an Internet connection can download a full copy of the blockchain.

Encryption: Used to confirm that the sender holds the bitcoin she wants to send and to decide how to add the transaction to the blockchain.

Immutable: Transactions can only be added to the blockchain, but cannot be deleted or modified.

Proof of Work (PoW) : A special type of participant in the network called a miner competes to search for solutions to cryptography puzzles that allow them to add a transaction block to bitcoin’s blockchain, a process called proof of work that ensures system security.



The process for sending Bitcoin funds is as follows:

Create a Bitcoin wallet. Used to send or receive Bitcoin, a Bitcoin wallet stores two pieces of information: a private key and a public key. The private key is a secret number that allows the owner to send bitcoins to another user, or to spend them. The public key is the number needed to receive bitcoin. The wallet itself does not store bitcoin, and information about bitcoin balances is stored in bitcoin’s blockchain.

Create a Bitcoin exchange. If Alice wants to send 1 Bitcoin to Bob, Alice needs to connect to her Bitcoin wallet using her private key and create a transaction containing the number and address of bitcoins she wants to send.

Broadcast the transaction to the Bitcoin network. Once Alice creates a Bitcoin transaction, she needs to broadcast the transaction to the entire Bitcoin network.

Confirm the transaction. Miners on the receiving end of the Bitcoin network verify the transaction using Alice’s public key, confirm that There are enough Bitcoins in Alice’s wallet, and add a new record to the Bitcoin blockchain containing the transaction details.

Broadcast blockchain changes to all miners. Once the transaction is confirmed, the miner should broadcast the blockchain changes to all miners to ensure that their blockchain copies are all synchronized.

Deep research on blockchain technology

In order to further study the building blocks of blockchain technology, the author systematically introduces public key cryptography, Hash function and blockchain mining and security.

Public key cryptography

Public key cryptography or asymmetric cryptography is any encryption system that uses a key pair: a public key that can be widely disseminated, as well as a private key known only to the owner. This accomplishes two basic functions:

Authentication: The public key authenticates the owner of the paired private key that sent the message. Encryption: Only the paired private key owner can decrypt the message encrypted with the public key.

RSA and ECDSA (Elliptic Curve Digital Signature Algorithm) are the most popular public-key encryption algorithms, and THE ECDSA algorithm is used to generate bitcoin wallets.

To send or receive a BTC, the user first generates a wallet containing a pair of private and public keys.

If Alice wants to send a certain number of BTCS to Bob, she creates a transaction in which she enters her and Bob’s public keys and the number of BTCS she wants to send, and then signs the transaction using her private key.

The computer on the blockchain uses Alice’s public key to verify that the transaction is trusted and writes the transaction to the block that will be added to the blockchain.



Hash functions and mining

All Bitcoin transactions are stored in files called blocks. Bitcoin adds a new transaction block every 10 minutes, and once a new block is added to the blockchain, it is immutable, cannot be deleted or modified.

A special group of participants in the network, called miners (computers connected to the blockchain), are responsible for creating new blocks for transactions. The miner must authenticate each transaction using the sender’s public key, confirm that the sender has a sufficient balance for the requested transaction, and add the transaction to the block.

Miners are completely free to choose the transactions in the block, so senders need to include a transaction fee as an incentive for miners to add their transactions to the block.

For blocks that are subject to block links, “mining” is required. To mine the blocks, miners needed to find a solution to a very rare encryption challenge. If the block link receives a mining block, the miner will receive a bitcoin reward, which is an additional reward for transaction fees. The mining process, also known as proof of work (PoW), is the primary mechanism for making blockchain untrustworthy and secure.

Hashing and blockchain encryption challenges

A hash function is any function that can be used to map data of any size to data of a fixed size. The value returned by a Hash function is called a Hash value. Hash functions are commonly used to speed up database lookups by detecting duplicate records, and they are also widely used in cryptography.

Hash functions allow us to easily verify that some input data maps to a given hash value, but if the input data is unknown, it is difficult to reconstruct it from the stored hash value.

Bitcoin uses a cryptographic hash function called SHA-256. Sha-256 is applied to block data (Bitcoin transactions) and a combination of numbers called Nonce. By changing the block data or Nonce, we get a completely different Hash value.

For blocks that are considered valid or “mined,” the Hash value of the block and Nonce needs to meet certain conditions. For example, the four leading digits of the Hash value must be 0000. We can increase the complexity of mining by making conditions more complex, for example by increasing the number of zeros at the beginning of the Hash value.

The cryptographic conundrum miners need to solve is to find a Nonce value that will satisfy the mining condition.

Use the following application to simulate block mining.

When you enter or change the Nonce value in the “Data” text box, you’ll notice that the Hash value changes. When you click the “Mine” button, the application computes the Hash value starting from Nonce equals zero and checks if the first four bits of the Hash value equal “0000”.

If the first four digits do not equal “0000”, the Nonce is incremented by one and the whole process is repeated until a Nonce value that satisfies the condition is found. If the block is mined, the background color changes to green.



From block to blockchain

Transactions are grouped by blocks, which are attached to the blockchain.

To create a chain of blocks, each new block uses the Hash value of the previous block as part of its data. To create a new block, the miner selects a set of transactions and adds the Hash value of the previous block to start the block mining.

Any changes made to any block data will affect the Hash values of all subsequent blocks and they will become invalid, which is the immutability of a blockchain.



Use the following application to simulate a blockchain with three blocks.

When you enter or change the Nonce value in the “Data” text box, you can notice changes in the Hash value of the current block and the “Prev” value (the previous Hash value) of the next block.

You can simulate the mining process by clicking the “Mine” button on each block. After mining 3 blocks, try to change the data in block 1 or 2 and you will notice that all subsequent blocks become invalid.







Add a block to the blockchain

All miners in the Bitcoin network compete with each other to find a valid block that will be added to the blockchain and receive rewards from the network.

Although the probability of finding the validation block Nonce is very low, due to the large number of miners, the probability of the validation block in the network is very high. The first miner to submit a valid block adds his block to the blockchain and receives a reward of Bitcoin.

What happens if two or more miners submit at the same time?

Resolve the conflict

If 2 miners resolve a block almost simultaneously, then we will have 2 different blockchains in the network and we need to wait for the next block to resolve the conflict. Some miners chose to dig at the top of blockchain 1, others chose to dig at the top of blockchain 2.

The conflict is resolved when a miner finds a new block.

If a new block is mined at the top of blockchain 1, blockchain 2 becomes invalid, the rewards from the previous block are awarded to miners via blockchain 1, and the blockchain 2 portion and transactions not added to the blockchain are returned to the trading pool and added to the next block.

In short, if there is a conflict between blockchains, then the longest chain wins.



Blockchain and double payments

Next, details the common forms of double payment attacks on blockchain and the steps users should take to prevent damage.

Race attack: Attackers quickly send the same coin to two different addresses. To prevent such attacks, it is recommended to wait for at least one block confirmation before accepting payment.

Finney attack: Attackers use transactions to pre-mine blocks and spend the same coin in a second transaction before releasing the block. In this case, the second transaction will not be validated. To prevent such attacks, it is recommended to wait at least 6 block confirmations before accepting payment.

51% attack: In this type of attack, the attacker has 51% of the network’s computing power. The attacker first broadcasts the transaction to the entire network, then mines a private blockchain, where it doubles the coins from the last transaction.

Since the attacker has most of the computing power, it is guaranteed that at some point he will have a longer chain than normal. He can then publish a longer blockchain, replace the normal one and cancel the original transaction.

Such an attack is highly unlikely because it is very expensive in a blockchain network like Bitcoin.

Blockchain implementation in Python

In this section, we will implement the basic blockchain and blockchain client using Python.

Blockchain will have the following functions:

Add multiple nodes to the blockchain

Proof of Work (PoW)

Simple conflict resolution between nodes

The blockchain client will have the following functions:

Generate a wallet using public/private key encryption (based on RSA algorithm)

Generate transactions using RSA encryption

Two display pages will also be implemented:

A ‘blockchain front end’ for miners

A “blockchain client” for users to generate wallets and send digital currency

The blockchain implementation of this article mainly refers to the GitHub project below, where the author made some modifications to the original code to add RSA encryption for transactions.

Use Jupyter Notebook to generate electronic wallet, encrypt transaction, use HTML/CSS/JS2 to complete 2 display pages.

Blockchain client

Switch to the blockchain_client folder and enter Python Blockchain_client. py on the terminal to start the blockchain client. In your browser, go to http:// localhost: 8080 and you will see the following page displayed.







Wallet Generator: Generate a Wallet (public/private key pair) using RSA encryption algorithm

Make Transaction: Generates a Transaction and sends it to a blockchain node

View Transasctions: View transactions on the blockchain

To create or view transactions, you need to run at least one blockchain node.

The important parts of the Blockchain_client.py code are explained below.

Define a Python class named Transaction that has sender_address, sender_private_key, recipient_address, and value. These are the four pieces of information the sender needs to create an exchange.

Use the to_dict () method to return the transaction information in Python dictionary format (without the sender’s private key).

Obtain the transaction information (without the sender’s private key) by using the sign_transaction () method and sign it with the sender’s private key.



Start a Python Flask application and use it to create different apis that interact with the blockchain and its clients.



Here we define three Flask HTML page return paths, each tag connecting to an HTML page.



Then, define an API (private/public key pair) to generate a wallet.





Let’s define an API that takes sender_address, sender_private_key, recipient_address, and value as input and returns the transaction (without the private key) and the signature.





Block chain

Go to the blockchain folder and start the blockchain node from the terminal, then type Python Blockchain_client. py or Python Blockchain_client.py -p. If no port number is specified, the default port number is 5000. In your browser, go to http:// localhost: to see the blockchain front end display page.



The display page under the navigation bar has 2 tabs:

Mine: Used for viewing transaction and blockchain data, as well as mining new transaction blocks.

Configure: Used to Configure connections between different blockchain nodes.

Next, the important parts of the blockchain.py code are explained.

Start by defining a Blockchain class with the following properties:

Transactions: List of transactions to be added to the next block.

Chain: a blockchain consisting of a series of blocks.

Nodes: a collection of node urls. The blockchain uses these nodes to retrieve blockchain data from other nodes and update their blockchain if they are out of sync.

Node_id: random string used to identify blockchain nodes.

The Blockchain class also implements the following methods:

Register_node (node_URL) : Adds a new blockchain node to the node list.

Verify_transaction_signature (sender_address, signature, transaction) : Checks whether the signature provided corresponds to a transaction signed by a public key (sender_address).

Socmit_transaction (sender_address, recipient_address, value, signature) : If the signature is validated, add the transaction to the transaction list.

Create_block (Nonce, previous_hash) : Adds a block containing transaction information to the blockchain.

Hash (block) : Creates a sha-256 hash value for a block.

“Proof_of_work () : Proof of work. Search for the Nonce that meets the mining conditions.

Valid_proof (transactions, last_hash, Nonce, difficulty = MINING_DIFFICULTY) : Checks whether the Hash value meets the mining criteria. This function is used in the proof_of_work function.

Valid_chain (chain) : checks whether the blockchain is valid.

Resolution_conflicts () : Resolves conflicts between blockchain nodes by replacing the chain with the longest chain in the network.





Start a Python Flask application and use it to create different apis to interact with the blockchain.



Next, start the Blockchain instance.



Define 2 Flask paths that return the front-end HTML pages of the blockchain.

The Flask API is defined to manage transactions and mine the blockchain.

‘/ transactions/new’ : This API is used to enter ‘sender_address’, ‘recipient_address’, ‘amount’, and ‘signature’, and add transactions to the list of transactions with valid signatures that can be added to the next block.

‘/ Transactions/get’ : This API returns all transactions that can be added to the next block.

‘/ chain’ : This API returns all blockchain data.

‘/ mine’ : This API runs proof-of-work algorithms and adds new blocks of transactions to the blockchain.





The Flask API is defined to manage the blockchain nodes.

‘/ Nodes/register’ : This API takes a list of node urls as input and adds them to the node list.

‘/ Nodes/resolve’ : This API resolves conflicts between blockchain nodes by replacing the local chain with the longest chain available in the network.

‘/ Nodes/get’ : This API returns a list of nodes.





This article is from “CDA Data Analyst”, a partner of the cloud community. For more information, you can follow “CDA Data Analyst”.