Create a chunk chain from scratch with Python

Source: Internet
Author: User

The main content of this article is translated from learn blockchains by building one
This article original link, reprint please indicate the source.
The author thinks that the quickest way to learn a block chain is to create one by yourself, and this article follows the author using Python to create a block chain.

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 readers 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).

If you are not very familiar with hashing, you can view this article environment preparation

Environmental readiness to ensure that python3.6+, Pip, flask, requests have been installed
Installation method:

1
Pip Install flask==0.12.2 requests==2.18.4

You also need an HTTP client, such as a postman,curl or other client.

Reference source code (the original code in my translation, unable to run, I fork a copy, fixed the error, and added a translator, thank star) began to create blockchain

Create a new file blockchain.py, all the code in this article is written in this file, you can always refer to the source code blockchain class

First, you create a blockchain class that creates two lists in the constructor, one for storing block chains, and one for storing transactions.

The following is the framework for the Blockchain class:

1 2 3 4 5 6 7 8 9-A-list 
Class Blockchain (object):
    def __init__ (self):
        self.chain = []
        self.current_transactions = []
        
    def new_ Block (self):
        # Creates a new blocks and adds it to the chain
        pass
    
    def new_transaction (self):
        # Adds a new T Ransaction to the list of transactions
        pass
    
    @staticmethod
    def hash (blocks):
        # Hashes a
        block pass

    @property
    def last_block (self):
        # Returns 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 chunk 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:

1
2
3
4 5 6 7 8
9
ten
13
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. Do not understand the words, slowly digestion, can refer to block chain accounting principle to join the transaction

Next we need to add a deal to refine the New_transaction method

1
2
3
4
5
6
7 8 9
19
Class Blockchain (object): ...
    
    def new_transaction (self, sender, recipient, amount): "" "
        generate new transaction information, information will be added to the next block to be dug
        :p Aram Sender: <str > Address the Sender
        :p Aram recipient: <str> address of the recipient
        :p Aram Amount: <int> Amoun T: return: <int> The index of the ' block '
        hold this transaction
        "" "

        SELF.CURRENT_TRANSACTIONS.A Ppend ({
            ' 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 New_block (), new_transaction () and hash () methods:

1
2
3
4
5
6
7 8 9
30 (a) (a) This is the same as
the
57 in all of the same.
66 of the same
Import hashlib Import JSON from time Import time class Blockchain (object): Def __init__ (self): Self.current_ transactions = [] Self.chain = [] # Create the Genesis Block Self.new_block (Previous_hash=1, Proo  f=100 def new_block (self, Proof, Previous_hash=none): "" To generate a new block:p Aram Proof: <int> the
        Proof given by the proof of Work algorithm:p Aram Previous_hash: (Optional) <str> Hash of previous block
            : return: <dict> New blocks "" "block = {' index ': Len (self.chain) + 1, ' Timestamp ': Time (), ' Transactions ': self.current_transactions, ' proof ': proof, ' prev
        Ious_hash ': Previous_hash or Self.hash (Self.chain[-1]),} # Reset The current list of transactions Self.current_transactions = [] self.chain.append return block def new_transaction (self, sen Der, Recipient, amount):
        "" To generate new transaction information, the information will be added to the next block to be dug:p Aram Sender: <str> address of the sender:p Aram Recip Ient: <str> address of the recipient:p Aram Amount: <int> Amount:return: <int> the Inde X of the blocks that would hold this transaction "" "Self.current_transactions.append ({' Sender ' : Sender, ' recipient ': Recipient, ' Amount ': Amount,}) return to self.last_block[' in
        Dex '] + 1 @property def last_block (self): return self.chain[-1] @staticmethod def hash (block):

        SHA-256 Hash value:p Aram block: <dict> Block:return: <str> "" "" " # We must make sure which is Ordered, or we'll have inconsistent hashes block_string = JSON.D Umps (blocks, sort_keys=true). Encode () return hashlib.sha256 (Block_strin

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.