Python blockchain and python blockchain

Source: Internet
Author: User
Tags sha256 algorithm

Python blockchain and python blockchain

Preface

This article will give you a brief introduction to the knowledge about BlockChain and use Python for a simple implementation. Let's take a look at the details below:

What is blockchain

To put it simply, blockchain is a permanent record generated by adding encrypted data (blocks) in chronological order. Specifically, its blockchain is composed of a series of data blocks produced by cryptographic methods. Each block contains the hash value (hash) of the previous block ), connect to the current block from the founding block (genesis block) to form a blockchain. Each block is generated after the previous block in chronological order. Otherwise, the hash value of the previous block is unknown. It is an important concept of Bitcoin.

Features

Blockchain has the following features:

  • Decentralization: blockchain depends on distributed nodes instead of a central node.
  • Trust-free system: The blockchain is based on cryptographic algorithms, and data must be approved by other users in the network. Therefore, a third-party intermediary structure or trust institution endorsement is not required.
  • Non-tampering and encryption security: The blockchain adopts a one-way hash algorithm, and each newly generated block is promoted in strict chronological order, the irreversible nature of time makes any attempt to intrude or tamper with the data in the blockchain easily traceable, leading to rejection by other nodes, thus limiting related illegal behaviors.

The above features make blockchain more and more applications in banking, securities market, finance, and other fields.

How blockchain works

Blockchain chain a series of encrypted data blocks. These blocks consist of a block header containing metadata and a long string of transactions that closely follow the blockchain entity. The Block Structure in Bitcoin is as follows:

Block Header

The block header contains the connection information, timestamp, and nonce information of other blocks in the blockchain, as shown in the following code:

Block ID

The block has two identifiers: the hash value of the block header and the block height. The hash value of the block header is a number obtained by secondary hash calculation of the block header using the SHA256 algorithm. The block hash value can uniquely and clearly identify a block, and any node can obtain the block hash value independently by simply hashing the block header. The block height refers to the position of the block in the blockchain. The block height is not a unique identifier. Although a single block always has a clear and fixed block height, in turn it is not true. A block height does not always recognize a single block. Two or more blocks may have the same block height and compete for the same location in the blockchain.

After learning about the above basics, we will start to use Python to implement a simple blockchain.

Python Implementation of blockchain

1. Define the Block Structure

In [16]:

# Block. pyimport hashlibimport uuidclass Block (object): def _ init _ (self, data = None, previous_hash = None): self. identifier = uuid. uuid4 (). hex # generate unique self. nonce = None # nonce value self. data = data # block content self. previous_hash = previus_hash # hash value of the parent node def hash (self, nonce = None): ''' the hash value of the calculated block ''' message = hashlib. sha256 () message. update (self. identifier. encode ('utf-8') message. update (str (nonce ). encode ('utf-8') message. update (str (self. data ). encode ('utf-8') message. update (str (self. previus_hash ). encode ('utf-8') return message. hexdigest () def hash_is_valid (self, the_hash): ''' check whether the block hash value is valid ''' return the_hash.startswith ('123') def _ repr _ (self ): return 'block <Hash :{}, Nonce :{}> '. format (self. hash (), self. nonce)

The above is a block structure, which implements a simplified version and does not fully correspond to the block in Bitcoin. The block here contains a unique identifier, the hash value of the parent node, the nonce value, and the content field of the block. It can be seen that the hash value of a block must meet certain conditions, for example, starting with 0000. Next, initialize the block structure.

In [37]:

# Create a content block with the content "hello world" = Block ('Hello World') block

Out [37]:

Block<Hash: 238a65a101c8829d7fc406eb78a71cfc19ad702b437e2c1be8d9061ddb81e900, Nonce: None>

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

In [38]:

block.hash_is_valid(block.hash())

Out [38]:

False

Change the nonce value to get a new hash value.

In [39]:

block.hash(1)

Out [39]:

'a6431938ba10270dfcfdf7a2371312446914fedadf79632c2c0adb3b463f4838'

The hash value is updated, but it is not a valid hash value. To obtain valid hash values, it is a process of constantly updating nonce values, or mining. The following adds a mine function to obtain a proper nonce value.

In [78]:

# Block. pyimport hashlibimport uuidclass Block (object): def _ init _ (self, data = None, previous_hash = None): self. identifier = uuid. uuid4 (). hex # generate unique self. nonce = None # nonce value self. data = data # block content self. previous_hash = previus_hash # hash value of the parent node def hash (self, nonce = None): ''' the hash value of the calculated block ''' message = hashlib. sha256 () message. update (self. identifier. encode ('utf-8') message. update (str (nonce ). encode ('utf-8') message. update (str (self. data ). encode ('utf-8') message. update (str (self. previus_hash ). encode ('utf-8') return message. hexdigest () def hash_is_valid (self, the_hash): ''' check whether the block hash value is valid ''' return the_hash.startswith ('123') def _ repr _ (self ): return 'block <Hash :{}, Nonce :{}> '. format (self. hash (self. nonce), self. nonce) ''' new mining function ''' def mine (self): # initialize nonce to 0 cur_nonce = self. nonce or 0 # loop until a valid hash value is generated while True: the_hash = self. hash (nonce = cur_nonce) if self. hash_is_valid (the_hash): # If the generated hash value is valid self. nonce = cur_nonce # Keep the current nonce value break # And exit else: cur_nonce + = 1 # If the current hash value is invalid, update the nonce value and Add 1

In [75]:

Block = Block ('Hello World') # mining, looping until appropriate nonceblock. mine () # print block

Out [75]:

Block<Hash: 000087359d5264153d624556f0a0c6f25cba06e453975c1c02587862e823911b, Nonce: 64751>

So far, the first effective block generation is complete, and the blockchain is defined below.

Ii. Define the blockchain Structure

In [81]:

Class BlockChain (object): def _ init _ (self): self. head = None # point to the latest block self. blocks ={} # A dictionary containing all blocks ''' adds the Block Function ''' def add_block (self, new_block): previous_hash = self. head. hash () if self. head else None new_block.previus_hash = previus_hash self. blocks [new_block.identifier] = {'block': new_block, 'previous _ hash': previus_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)

After the blockchain structure is defined, initialize a blockchain.

In [82]:

# Initialize chain = BlockChain () # Print chain

Out [82]:

Blockchain<0 Blocks, Head: None>

In [83]:

# Add blockchain. 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 blockchain, and the validity of the blockchain will be involved later. When a block in a blockchain is changed, the hash of the block changes, which affects the block after the block, so that the blockchain is no longer valid. These will be further explored in the future.

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

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.