The image is from Monument Valley, developed by USTWO

Recently, a foreign guru opened a blockchain teaching project.

The project is based on Python and is said to be very simple and easy to learn.

Related lovers at home and abroad have been introduced and used.

I also learned about it at the first time.

My personal assessment: This is really —

Suitable for entrants to learn to use, operational conscience open source projects.

And based on Python, it’s pretty good!

(Life is short, I use Python)

As a result, I am the action person

Wrote this detailed rehash note for the reader,

In order to help those who want to get into blockchain development

There is a preliminary exploration and perception.

Here is a tour to begin with me

I. Project introduction

Open source address:

https://github.com/adilmoujahid/blockchain-python-tutorial

Functions overview

This section describes the functions and features

The project is only for interest and teaching purposes. It implements a simple blockchain cryptocurrency transaction and billing function, which is divided into local service front-end and local client. The blockchain-related functions are implemented in Python. The server side and client side Web interaction panels are implemented in HTML/CSS/JS (the three Swordsmen of the Web) (we just need to focus and learn the Python implementation of the block chain code part).

Server functions and features:

  • Multiple nodes can be added

  • Supporting Proof of Work (PoW)

  • Encrypts transactions using the RSA algorithm

  • View transaction records and blockchain data

  • Mining new transaction blocks (get billing rights)

  • Link configuration for different nodes

  • Simple node conflict resolution

Client functions and features:

  • Generate wallets with public/private key pairs

  • Conduct cryptocurrency transactions

  • View transaction records and status

Two, environment configuration

This project is based on Python 3.6.

To avoid the hassle of installing base dependency libraries, the Anaconda integrated development environment is recommended.

Because Anaconda contains most of the science packages and dependencies needed to develop and run Python.

Since I’m using MacOS on my MAC laptop, this tutorial also downloads Anaconda for MacOS. If you use Windows or Linux, download the corresponding version and install it.

The command line operation is the same regardless of the system version.

2.1 download

Download Anaconda 5.1 for Python 3.6 for macOS, as shown in the figure below:

If the download is slow or fails, it is recommended to use tsinghua Source image to download, as shown below:

2.2 installation

Double-click the installation package you just downloaded;

Click “Next”, “Agree” and “Continue” along the way.

Use the default mode to complete the installation.

During the installation process, you should see the screen shown below

(the penultimate step will give you the option to install VSCode, an excellent code editing, management, and runtime software from Microsoft, which is recommended (although not used in this tutorial) :

2.3 Checking whether the environment is configured successfully

Open the terminal and enter the command “python”.

If you see something like the output below — awesome!

The operating environment is successfully installed and configured.

(After you enter Python, the terminal enters the Python command line. You can enter “exit()” after >>>.)

Three, code download

The browser into the project at https://github.com/adilmoujahid/blockchain-python-tutorial.

Download the complete project code to any local directory and unzip it.

As shown below:

If you want to go out of your way, download can go out of your way.

Download method 2: Simple and quick download through the command line.

The terminal jumps to the file you want to download by running the “CD” command.

Then enter the command:

“Git clone — recursive https://github.com/adilmoujahid/blockchain-python-tutorial.git”.

Press “Enter” to start downloading!

(You can run the ls command to view the downloaded files.)

Four, operation and use

The operation mode of this project belongs to B/S mode.

That is, the Server provides services and the client uses the Browser.

Therefore, we need to run the server code first to run the blockchain function, and then run the client code to use it.

(Both the client and server of this project are running on the local 127.0.0.1 network segment).

3.1 Running server code

Run the server code to start the blockchain service.

Go to the blockchain folder where you downloaded the file in step 3.

Enter the command “Python blockchain.py -p 5000”,

Press Enter and the page is as follows:

In the address box of the browser, enter http://127.0.0.1:5000 and press Enter.

If the following page is displayed, the front end is successfully started.

That is, a node has been successfully run on the blockchain.

To add a new node, just click the “+” sign on the upper right of the terminal,

Enter the same command to change the port number.

(This tutorial starts both nodes 5000 and 5001)

3.2 Running the client code

A new terminal page can be added in the same way as server side execution.

Go to the blockchain_client folder

Enter the command:

“Python Blockchain_client. py -p 8080”,

Click “Enter”, as shown below:

In the address box of the browser, enter http://127.0.0.1:8080 and press Enter.

The interface is shown below – Congratulations! The client is started successfully:

3.3 Simulated trading

(1) First generate a wallet (public/private key pair) on the client wallet generation page.

(2) Transaction page operation:

Send to address bar: fill in the public key;

Sender private key field: Enter the private key.

Receiving address: Fill in the receiving address (this tutorial first tests sending and receiving both enter the same address, that is, send to yourself; After the test, manually changing the receiving address to another address can also be successfully traded, you can check the part marked by red line in the last transaction record of the server);

Send quantity: you can set yourself;

Click “Generate transaction”;

The “Confirm Information” dialog box is displayed [the system automatically generates the transaction signature and can modify the address of the transaction node].

If yes, click “Ok”;

The “Transaction succeeded” prompt pops up. Click OK to complete the transaction.

(3) Then enter the transaction block chain node in the view transaction page to view the transaction information (when the transaction is not confirmed by the server, the client cannot view the transaction record temporarily)





<< Slide left and right to view client interface >>

(4) Log in to server 5000 node, click Transactions to be added to the next block button, you can see that the transaction record is successfully recorded (at this time the client can view the transaction record).

(5) Click the Mine button to simulate mining. Each time, one coin can be mined, and the billing right will be included in the block of the corresponding node, and the coin will be sent to the designated receiving address (the value here can be changed from line 42-44 in blockchain.py).

(6) Click the Transactions on the Blockchain button to synchronize all block records of the current node.

(7) List of all nodes can be added and retrieved on the configuration page. For example, I added two block chain nodes 5000 and 5001, and retrieved the data on 5001 node. You can see my transaction records on 5001 node (one point-to-point transaction record of different addresses, two mining records).





<< Scroll left and right to view the interface of using the server >>

Four, code interpretation

4.1 Blockchain server code interpretation

(1) The blockchain server code is written in the blockchain.py module, which first defines the blockchain class (47 lines) with four attributes:

  • Transactions: A list of all transactions that will be added to the next block

  • Chain: A blockchain entity that contains all blocks defined in an array

  • Nodes: A collection of urls containing all nodes that the blockchain uses to retrieve blockchain data from other nodes and update the blockchain if the data is not synchronized

  • Node_id: A random string that distinguishes different nodes of the blockchain

(2) The Blockchain class has 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 provided signature matches the transaction signature of the public key (that is, the sender’s address)

  • Submit_transaction (sender_address, recipient_address, value, signature): Adds transactions whose signatures pass to the transaction list

  • Create_block (nonce, previous_hash): adds a transaction block to the blockchain

  • Hash (block): Creates a SHA-256 hash code for a block

  • “Proof_of_work ()” : provides a proof of work algorithm for finding people who meet the mining conditions of the time

  • Valid_proof (transactions, last_hash, nonce, difficulty=MINING_DIFFICULTY): valid_proof(transactions, last_hash, nonce, difficulty=MINING_DIFFICULTY): Proof_of_work ()

  • Valid_chain (chain): verifies whether the blockchain is valid

  • Resolve_conflicts (): Resolves conflicts between blockchains by replacing the conflict chain with the longest chain in the network

Swipe up and down to browse the code and click to enlarge

After writing the functional code of the block chain above, the following calls are made to realize the corresponding functions. As the functions interact in the way of Web, the mainstream Flask Web framework is used to implement the code, that is, the core code at the bottom layer is web-based called and encapsulated by Flask.

(1) First initialize a Python Flask app to create various interfaces to interact with the blockchain (lines 222-223)

Next initialize an instance of Blockchain class Blockchain (the essence of object-oriented programming)

(3) Then define 2 Flask routes (paths), which are used to return the HTML page of the front-end panel of blockchain service (lines 228-230, corresponding to the home page of Mine; Line 232-234, Configure page)

(4) Next, define four Flask APIs to manage and Mine the blockchain (corresponding to various functions of the blockchain service front-end Mine page, lines 238-292) :

  • ‘/transactions/new’: This API acts as a gateway to ‘sender_address’, ‘recipient_address’, ‘amount’, and ‘signature’, and adds valid signed transactions to the transaction list, which is added to the next block

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

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

  • ‘/mine’: This API runs a proof of work algorithm and adds new blocks of transactions to the blockchain

(5) The next three Flask APIs are for managing blockchain nodes (corresponding to the capabilities of the Blockchain service front-end Configure page, lines 296-335) :

  • ‘/ Nodes /register’: This API takes a list of nodes’ 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 is used to return a list of nodes

(6) Finally 339-347 is the execution entry (main function) of the program, which is used to receive terminal input from the program (such as the command we typed: Python blockchain.py -p 5001) and to run the code (blockchain).

Swipe up and down to browse the code and click to enlarge

4.2 Blockchain client code interpretation

(1) The blockchain client code is written in the blockchain_client.py module, which first defines the Transaction class (32 lines) with four properties: Sender_address, sender_private_key, recipient_address, and value. These are the four pieces of information required by the sender to create an exchange (corresponding to Rule (2) of Simulated trading in Section 3.3 above).

(2) Transaction class has the following methods:

  • To_dict () : This method returns the transaction information in Python dictionary format (without the sender’s private key)

  • Sign_transaction () : This method gets the transaction information (excluding the sender’s private key) and uses the sender’s private key to sign the transaction information

Client transaction core code

As with the server-side code, you then use Flask to Web the functionality of the client.

(1) First initialize a Python Flask app to create various interfaces to interact with the blockchain and clients (line 59)

(2) Then define 3 Flask routes (paths) to return the HTML page of the blockchain client panel (lines 61-63, corresponding to the Wallet Generator home page; Lines 65-76 correspond to the Make Transaction page; Lines 69-71, corresponding to View Transactions page)

(3) Next, define 2 Flask APIs to implement wallet generation and transaction functions:

  • New_wallet () : Generate wallet(public/private key pair) (code corresponds to Section 3.3 Simulated transaction (1))

  • generate_transaction(): The Transaction method is called. It takes sender_address, sender_private_key, recipient_address, and value as inputs. And return transaction information (excluding private key) and signature (code corresponding to section 3.3 Simulated transaction (2))

Client transaction function Web code

(4) The last lines 100-108 are the execution entry (main function) of the client program, which receives terminal input from the program (as we typed: python blockchain_client.py -p 8080) and runs the code (client).

The client program executes the entry code

Five, the summary

One said, “A gentleman’s nature is not different, good false in things.”

To have such a beautiful implementation of this project,

The authors also build on other god codes.

Interested friends can study further.

[Code address based on]

https://github.com/dvf/blockchain,

https://github.com/julienr/ipynb_playground/blob/master/bitcoin/dumbcoin/dumbcoin.ipynb.

Two yue “paper come zhongjue shallow, must know this to practice.”

If you read this long passage,

Can have more intuitive feeling and understanding of blockchain programming and development,

That’s great!

But, you know what they say,

As the saying goes, “Once is better than once.”

So, small partners or quickly start to practice it 👊

At the end of the article’s welfare

The author of this project strongly recommends a new book Mastering Bitcoin: Programming the Open Blockchain in his blog post with the word excellent. I happen to have the digital original (hd color) of the O ‘Reilly print edition of the book. Mastering Bitcoin: Mastering Bitcoin 🙈, I’d like to “master Bitcoin” (Mastering Bitcoin)!

Note: original English blog address

http://adilmoujahid.com/posts/2018/03/intro-blockchain-bitcoin-python/

Finally it was time for another song,

Let me share a song I heard at dinner today,

I remember hearing this song for the first time on my way to Tibet…

The current browser does not support music or voice playback. Please play music in wechat or another browser After the later zhuang Xinyan – ten thousand reluctant

Article | look back

Edit | xiaoyuzi

Review | old cat 🐱