50 lines of Python code to build a block chain

Source: Internet
Author: User
Tags new set

Although it is thought that the block chain (blockchain) is an answer to the problem before the technology, but there is no doubt that the new technology is a computational miracle. But what is the block chain?

An open digital ledger that grows over time and records the transactions of Bitcoin or other cryptographic currencies.

In simple terms, a block chain is a public database in which new data is stored in a data structure called block, and blocks are added to an chain chain (that is, a block chain) that stores all the data that was added in the past. In bitcoin and some other encrypted currency, the data is a transaction. In practice, however, these data can be of any type.

Block-chain technology has spawned a whole new set of digital assets like Bitcoin, the Wright dollar, that are not issued or managed by any central authority. This brings new options to individuals who do not trust the existing banking system. The block chain also redefined distributed computing, with technologies like the ether square that introduced new concepts like intelligent contracts.

In this article, I'm going to build a simple block-chain prototype with less than 50 lines of Python code (the original code is Python 2, which is divided into parts that are hosted in Gist.) The translator has changed it to Python 3 and put the source on the GitHub and click here to view it. ), let's call it snakecoin.

First, define what our blocks are about. In a block chain, each block requires a timestamp (timestamp) and an optional index (indexed). In Snakecoin, we store both of these items at the same time. In order to ensure the integrity of the block chain, each block needs to have a hash that recognizes its identity. In Bitcoin, the hash of each chunk is a cryptographic hash of all the contents of the chunk index, timestamp, data, and the previous block hash. In addition, the data can be anything you want to store.

Import Hashlib as Hasher

class block:
    def __init__ (self, index, timestamp, data, Previous_hash):
        self.index = Index
        Self.timestamp = timestamp
        self.data = data
        Self.previous_hash = Previous_hash
        Self.hash = Self.hash_block ()

    def hash_block (self):
        sha = hasher.sha256 ()
        sha.update (
            bytes (
                Self.index) + str (self.timestamp) + str (self.data) + str (
                    self.previous_hash), ' Utf-8 ') return
        Sha.hexdigest ()

Well, there's already a block structure, but we're building a block chain . So, we need to add chunks to the real chain. As mentioned earlier, each block requires information from the previous block. As a result, there is a problem: how the first block in the block chain comes in. the first block, or generally called the Genesis Block, is a very special block. In many cases, it is added to the block chain by manual or some special logic.

For simplicity, we create a function that simply returns to the Genesis block. The initiator block has an index of 0, an arbitrary data value, and an arbitrary value that belongs to the previous hash parameter.

Import datetime as Date
def create_genesis_block ():
    #  manually construct a block with index 0 and arbitrary PR Evious Hash return blocks
    (0, Date.datetime.now (), "Genesis block", "0")

Now that we have created a Genesis block, next we need a function that can generate subsequent chunks in the block chain. This function takes the previous block in the block chain as a parameter, creates the data for the block to be generated, and then returns the new zone block with the data. The integrity of the block chain will be further enhanced when the block information is hashed in the new zone. If we do not hash the previous chunk information, then the third party can easily "tamper with history" and replace our chain with a chain of their own. The hash of a chunk chain is like a cryptographic proof that it guarantees that once a block is added to the block chain, the block can never be replaced or removed.

def next_block (last_block):
    this_index = last_block.index + 1
    this_timestamp = Date.datetime.now ()
    This_ data = "hey! I ' m block ' + str (this_index)
    This_hash = Last_block.hash return block
    (This_index, This_timestamp, This_data, This_hash)

This is the hardest part of the whole section. Now, you can create our block chain again. In our case, the chunk chain is actually just a list of Python. The first element of the list is a Genesis block. Of course, we need to add further blocks. Because this is just a minimalist block-chain model, we add only 20 new blocks. Can be added through a loop.

    #  Create The blockchain and add the Genesis block
    blockchain = [Create_genesis_block ()]
    Previous_block = Bloc Kchain[0]

    # How  many blocks should we add to the chain after the Genesis block
    Num_of_blocks_to_add =

    F or I in range (0, Num_of_blocks_to_add):
        block_to_add = Next_block (previous_block)
        blockchain.append (block_to _add)
        Previous_block = Block_to_add
        # tell  everyone about it!
        Print ("Block #{} has been added to" "
              blockchain!". Format (block_to_add.index))
        print ("Hash: {}\n". Format (Block_to_add.hash))

Look at the effect:

We can see that our chain is working as scheduled. If you want to see more information in the console, you can edit the source file to print the timestamp and data for each block.

This is what snakecoin can do. If you want to achieve the snakecoin of today's real block chain standards, we must also add more features, such as tracking the changes in the chain of the service layer on multiple machines, limiting the number of blocks in a given time to join the workload proof algorithm.

If you want to learn more about the technical details, you can view the original Bitcoin white paper.

This article is translated from: Let's build the tiniest blockchain

Related Article

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.