Using Django to implement a functional block chain application

Source: Internet
Author: User
Tags pow install django pip install django

Block Chain Research Institute VIP best Block chain study Community

We are curious about the rise of the digital currency and want to know the technology behind it-how the block chain is achieved.

But fully understand the block chain is not easy, I like to learn in practice, by writing code to learn technology will be more firmly mastered. By building a block chain can deepen the understanding of the block chain.

Preparatory work This article requires the reader to have a basic understanding of Python, read and write basic python, and need to have a basic understanding of HTTP requests.

We know that a block chain is an immutable, orderly chain of records made up of chunks, records can be transactions, files, or any data you want, and it is important that they are linked by a hash value (hashes).

Prepare the environment for the environment, ensuring that Python3.5, Pip, Django, Requests,urllib,json,hashlib installation methods are installed:

    
    
     
     

PIP Install Django Requests

An HTTP client, such as a postman,curl or other client, is also required, and this article takes postman as an example.

Start creating a blockchain through django-admin startproject block to create a block project that creates a demo project Django-admin Startproject demo in the project, directory structure:

The blockchain class creates a blockchain class in the views, creating two lists in the constructor, one for storing block chains, and one for storing transactions.

The following is the framework for the Blockchain class:

    
    
     
     

Class Blockchain (object):

def __init__ (self):

Self.chain = []

Self.current_transactions = []

def new_block (self):

# Creates a new block and adds it to the chain

Pass

def new_transaction (self):

# Adds A new transaction to the list of transactions

Pass

@staticmethod

def hash (block):

# Hashes a block

Pass

@property

def last_block (self):

# Returns The last blocks in the chain

Pass

The blockchain class is used to manage the chain, it can store transactions, add new blocks, and so on, let's further refine these methods.

Block structure Each block contains attributes: Index, UNIX timestamp (timestamp), transaction list (transactions), work proof (explained later), and hash value of the previous block.

The following is the structure of a block:

    
    
     
     

Block = {

' Index ': 1,

' Timestamp ': 1506057125.900785,

' Transactions ': [

{

' Sender ': "8527147fe1f5426f9dd545de4b27ee00",

' Recipient ': "a77f5cdfa2934df3954a5c7c7da5df1f",

' Amount ': 5,

}

],

' Proof ': 324984774000,

' Previous_hash ': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"

}

Here, the concept of the block chain is clear, each new block contains the hash of the previous block, which is the key point, it protects the block chain is not denatured. If an attacker destroys one of the previous blocks, then the hash of all the blocks that follow will become incorrect. If you don't understand it, digest it slowly.

Join the deal next we need to add a deal to refine the New_transaction method

    
    
     
     

Class Blockchain (object):

...

def new_transaction (self, sender, recipient, amount):

"""

Generate new transaction information and information will be added to the next block to be dug

:p Aram Sender: <str> address of the sender

:p Aram Recipient: <str> address of the recipient

:p Aram Amount: <int> Amount

: return: <int> The index of the "block" hold this transaction

"""

Self.current_transactions.append ({

' Sender ': sender,

' Recipient ': Recipient,

' Amount ': Amount,

})

Return self.last_block[' index '] + 1

Method adds a transaction to the list and returns the index of the chunk to which the record will be added (the next block to be mined), which is useful when the user submits the transaction.

Create a new block

When blockchain is instantiated, we need to construct a creation block (the first block without the front block) and add a work proof to it. Each block needs to go through the work of proof, commonly known as mining, will continue to explain later.

To construct the Genesis block, we also need to refine the Newblock (), newtransaction () and hash () methods:

    
    
     
     

Class Blockchain (object):

def __init__ (self):

Self.chain = []

Self.current_transactions = []

Self.new_block (previous_hash=1, proof=100)

Self.nodes = set ()

def new_block (self,proof,previous_hash= None):

Block = {

' Index ': Len (self.chain) + 1,

' Timestamp ': Time (),

' Transactions ': Self.current_transactions,

' Proof ':p roof,

' Previous_hash ': Previous_hash or Self.hash (Self.chain[-1]),

}

Self.current_transactions = []

Self.chain.append (Block)

return block

def new_transaction (Self,sender,recipient,amount):

Self.current_transactions.append ({

' Sender ': sender,

' Recipient ': Recipient,

' Amount ': Amount,

})

Return self.last_block[' index ']+1

@staticmethod

def hash (block):

Block_string = Json.dumps (block, sort_keys=true). Encode ()

Return hashlib.sha256 (block_string). Hexdigest ()

Through the above code and comments can be intuitive understanding of the block chain, then we see how the block is dug out.

Understanding the workload proves that the new block relies on the workload proof algorithm (PoW) to construct. The goal of POW is to find a number that meets certain criteria, which is difficult to calculate, but easy to verify. This is the core idea of work proof.

For ease of understanding, for example:

Suppose the hash value of an integer x multiplied by the product of another integer y must end with 0, i.e. hash (x * y) = AC23DC ... 0. Set the variable x = 5 to find the value of Y.

Implemented in Python as follows:

    
    
     
     

From Hashlib import sha256

x = 5

y = 0

While sha256 (str (x*y). Encode ()). Hexdigest () [: 4]!= "0000":

Y + 1

Print (y,sha256 (str (x*y). Encode ()). Hexdigest () [: 4])

Print (y)

In Bitcoin, the work-proof algorithm called Hashcash is similar to the problem above. The miners scrambled to compute the results in order to scramble for the right to create blocks. In general, the calculation difficulty is proportional to the number of specific characters that the target string needs to satisfy, and the miner will receive a bitcoin reward when the result is calculated. Of course, it's very easy to verify the results on the web.

Implementation of the workload proof let's implement a similar POW algorithm, the rule is: look for a number p, so that it and the previous block proof concatenation of the string hash value with 4 0 start.

    
    
     
     

Import Hashlib

Import JSON

From time Import time

From UUID import Uuid4

Class Blockchain (object):

...

def last_block (self):

return Self.chain[-1]

def proof_of_work (self, last_proof):

Proof = 0

While Self.valid_proof (Last_proof, proof) is False:

Proof + 1

return proof

@staticmethod

def valid_proof (Last_proof, proof):

Guess = str (last_proof*proof). Encode ()

Guess_hash = hashlib.sha256 (guess). Hexdigest ()

return Guess_hash[:5] = = "00000"

The way to measure the complexity of an algorithm is to modify the number of 0 starts. Using 4 for the demo, you'll find that one more 0 will greatly increase the time it takes to calculate the results.

Now that the Blockchain class is basically complete, the next step is to use the HTTP requests to interact.

Blockchain as an API interface we will use the Python Django Framework, a lightweight Web application framework that facilitates mapping network requests to Python functions, and now let's try:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.