The Python block chain primer, uncover Bitcoin

Source: Internet
Author: User
Tags sha256 algorithm uuid

This article will briefly introduce the block chain (blockchain) and use Python to do a simple implementation. What is a block chain

In a nutshell, a block chain is a permanent, irreversible modification of a record of encrypted data (chunks) stacked (chained) in chronological order. Specifically, the block chain is made up of a string of data blocks that are generated by a cryptographic method, each containing a hash of the previous block, starting with the Genesis block to connect to the current block and form a block chain. Each block is guaranteed to occur after the previous block in chronological order, otherwise the hash value of the previous block is unknown. It is an important concept of Bitcoin.

Characteristics

The block chain has the following characteristics: To center: The block chain does not depend on a central node, but depends on the distributed nodes. No Trust system: block chain based on cryptography algorithm, the data need to be approved by other users in the network, so do not need a set of third-party intermediary structure or trust agency endorsement. Tamper-Proofing and encryption security: Block chain adopts one-way hashing algorithm, at the same time each newly generated block is pushed forward strictly according to the time linear order, and the irreversibility of time causes any attempt to invade the data information in the chain of tampering block is easily traced, which leads to the exclusion of other nodes, so as to restrict the related illegal behavior.

The above characteristics make the block chain in the bank, the securities market and the finance and so on many fields have the more and more application. The working principle of block chain

Block-chained series of encrypted blocks of data. These blocks consist of a block header that contains metadata and a long list of transactions immediately following the constituent block body. The chunk structure in the bitcoin is as follows:


District Size

The block header contains information such as connection information, timestamp, and nonce in other blocks in the block chain, as follows:


Block identifier

The block has two identifiers, one is the hash value of the block header and the other is the block height. The hash value of the chunk header is the number obtained by the SHA256 algorithm for two hash calculations of the block head. A chunk hash value can uniquely and unambiguously identify a block, and any node can obtain the chunk hash value independently by simply hashing the chunk header. The block height refers to the position of the block in the block chain. The block height is not a unique identifier. Although a single block will always have a clear, fixed block height, but the reverse is not true, a block height does not always identify a single block. Two or more than two blocks may have the same block height, contending for the same position in the block chain.

After you know the basics, start with Python to implement a simple block chain. python implementation of block chain

I. DEFINITION of block structure

In [16]:

# block.py Import hashlib Import UUID class block (object): Def __init__ (self, Data=none, Previous_hash=none):  Self.identifier = Uuid.uuid4 (). Hex # Produces a unique mark self.nonce = None # nonce Value Self.data = Data # block Content Self.previous_hash = Previous_hash # parent node hash value def hash (self, nonce=n One): ' Hash value for computed chunks ' message = hashlib.sha256 () message.update (SELF.IDENTIFIER.E
        Ncode (' Utf-8 ')) message.update (str (nonce). Encode (' Utf-8 ')) message.update (str (self.data). Encode (' Utf-8 ')) Message.update (str (self.previous_hash). Encode (' Utf-8 ')) return Message.hexdigest () def hash_is_valid (Self, The_hash): ' Verify that the block hash value is valid ' return the_hash.startswith (' 0000 ') def __repr__
 (self): return ' Block 

The above is a block structure, where the implementation is a simplified version, there is no full corresponding to the bit currency block. The block here contains a unique identifier, a hash value for the parent node, a nonce value, and a content field for the block. You can see that a chunk's hash value must meet certain conditions to be valid, such as starting with 0000. The following is the initialization of the block structure.

In [37]:

# Create a content block

= blocks (' Hello World ') with content for Hello world

OUT[37]:

block

Although the above block is created, its hash value is not valid.

In [38]:

Block.hash_is_valid (Block.hash ())

OUT[38]:

False

A new hash value can be obtained by changing the value of the nonce.

In [39]:

Block.hash (1)

OUT[39]:

' a6431938ba10270dfcfdf7a2371312446914fedadf79632c2c0adb3b463f4838 '

The hash value has been updated, but is not a valid hash value. In order to obtain a valid hash value, it is a process of constantly updating the nonce value, or a mining (mine) process. A mine function is added below to get an appropriate nonce value.

In [78]:

# block.py Import hashlib Import UUID class block (object): Def __init__ (self, Data=none, Previous_hash=none):  Self.identifier = Uuid.uuid4 (). Hex # Produces a unique mark self.nonce = None # nonce Value Self.data = Data # block Content Self.previous_hash = Previous_hash # parent node hash value def hash (self, nonce=n One): ' Hash value for computed chunks ' message = hashlib.sha256 () message.update (SELF.IDENTIFIER.E
        Ncode (' Utf-8 ')) message.update (str (nonce). Encode (' Utf-8 ')) message.update (str (self.data). Encode (' Utf-8 ')) Message.update (str (self.previous_hash). Encode (' Utf-8 ')) return Message.hexdigest () def hash_is_valid (Self, The_hash): ' Verify that the block hash value is valid ' return the_hash.startswith (' 0000 ') def __repr__
        (self): return ' Block 

In [75]:

block = Blocks (' Hello world ')

# dig mines, cycle until you find the right nonce
block.mine ()

# print
block

OUT[75]:

BLOCK<HASH:000087359D5264153D624556F0A0C6F25CBA06E453975C1C02587862E823911B, nonce:64751>

At this point, the first valid chunk build is complete, and the block chain is defined below.

Second, the definition of block chain structure

In [81]:

Class Blockchain (object):
    def __init__ (self):
        self.head = None   # points to the newest block
        self.blocks = {}   # Contains a dictionary of all chunks ' '
        add block function
    '
    def add_block (self, new_block):
        Previous_hash = Self.head.hash ( self.head.nonce) If self.head else None
        new_block.previous_hash = Previous_hash

        self.blocks[new_ Block.identifier] = {
            ' block ': New_block,
            ' Previous_hash ': Previous_hash,
            ' previous ': Self.head,
        }
        Self.head = New_block

    def __repr__ (self):
        num_existing_blocks = Len (self.blocks) return
        ' blockchain <{} Blocks, head: {}> '. Format (
            num_existing_blocks,
            self.head.identifier if self.head else None
        )

Once you have defined the block chain structure, you begin initializing a block chain.

In [82]:

# initialize
chain = Blockchain ()

# print
chain

OUT[82]:

Blockchain<0 Blocks, head:none>

In [83]:

# Add blocks
chain.add_block (block)

# print
chain

OUT[83]:

Blockchain<1 Blocks, head:364c0cf963384ca28a2763499a140405>

In [84]:

# add more blocks for

I in range (6):
    New_block = block (i)
    new_block.mine ()
    chain.add_block (new_block)
    
# Print
Chain

OUT[84]:

Blockchain<7 Blocks, head:e7cb24ec7acd42a4aaebe7faee9e0713>

The above is a simple block chain, which will also involve the effectiveness of the block chain. When a block in the block chain is changed, the hash of the block changes, which affects the block after the block, causing the block chain to no longer be valid. These will continue to deepen in the follow-up. Author: Walker Python enthusiasts Community column author authorized original release, please do not reprint, thank you.
Source: The Python block chain primer

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.