Home > Backend Development > Python Tutorial > Introduction to Python Basics--Blockchain

Introduction to Python Basics--Blockchain

巴扎黑
Release: 2017-08-13 14:55:16
Original
1866 people have browsed it

The basic concept of blockchain is simple: a distributed database that stores an ever-lengthening list containing many ordered records. The following article mainly introduces you to the relevant information about blockchain for learning Python. The article introduces it in detail through sample code. Friends who need it can take a look below.

Preface

This article will give you a brief introduction to the relevant knowledge about blockchain (BlockChain), and use Python to make a simple implementation. Not much to say below, let’s take a look at the detailed introduction:

What is blockchain

In short, blockchain It is a permanent and irreversibly modified record generated by superimposing (chaining) encrypted data (blocks) in chronological order. Specifically, the blockchain is composed of a series of data blocks generated using cryptographic methods. Each block contains the hash value of the previous block, starting from the genesis block. Start connecting to the current block to form a block chain. Each block is guaranteed to be generated after the previous block in chronological order, otherwise the hash value of the previous block is unknown. It is an important concept in Bitcoin.

Features

The blockchain has the following characteristics:

  • Decentralization: The blockchain does not rely on a central node, but on distributed nodes.

  • No trust system required: The blockchain is based on cryptographic algorithms, and data requires approval by other users within the network, so there is no need for a third-party intermediary structure or endorsement by a trust organization.

  • Untamperable and encrypted security: The blockchain adopts a one-way hash algorithm, and each newly generated block is strictly advanced in linear order according to time. The irreversibility of time causes any Attempts to intrude and tamper with data information in the blockchain can be easily traced, leading to rejection by other nodes, which can limit related illegal activities.

#The above characteristics enable blockchain to have more and more applications in many fields such as banking, securities markets, and finance.

How blockchain works

Blockchain is a series of encrypted data blocks. These blocks consist of a block header containing metadata, followed by a long list of transactions that make up the body of the block. The block structure in Bitcoin is as follows:

Block header

The block header contains information related to other areas in the blockchain The connection information, timestamp, nonce and other information in the block are 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 block header is a number obtained by performing a secondary hash calculation on the block header using the SHA256 algorithm. The block hash value uniquely and unambiguously identifies a block, and any node can independently obtain the block hash value by simply hashing the block header. Block height refers to the position of the block in the blockchain. Block height is not a unique identifier. While a single block will always have a clear, fixed block height, the converse is not true and a block height does not always identify a single block. Two or more blocks may have the same block height and compete for the same position in the blockchain.

After understanding the above basics, let’s start using Python to implement a simple blockchain.

Python implementation of blockchain

1. Define the 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 # 产生唯一标示
  self.nonce = None     # nonce值
  self.data = data      # 区块内容
  self.previous_hash = previous_hash # 父节点哈希值
  
 def hash(self, nonce=None):
  '''
  计算区块的哈希值
  '''
  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.previous_hash).encode('utf-8'))

  return message.hexdigest()

 def hash_is_valid(self, the_hash):
  '''
  校验区块哈希值有否有效
  '''
  return the_hash.startswith('0000')

 def __repr__(self):
  return &#39;Block<Hash: {}, Nonce: {}>&#39;.format(self.hash(), self.nonce)
Copy after login

The above is a block structure. What is implemented here is a simplified version, which does not fully correspond to the blocks 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. You can see that the hash value of a block must meet certain conditions to be valid, such as starting with 0000. Next, initialize this block structure.

In [37]:


# 创建一个内容为hello world的内容块

block = Block(&#39;Hello World&#39;)
block
Copy after login

Out[37]:


Block<Hash: 238a65a101c8829d7fc406eb78a71cfc19ad702b437e2c1be8d9061ddb81e900, Nonce: None>
Copy after login

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

In [38]:


block.hash_is_valid(block.hash())
Copy after login

Out[38]:


False
Copy after login

Change the value of nonce to get a new hash value.

In [39]:


block.hash(1)
Copy after login

Out[39]:


&#39;a6431938ba10270dfcfdf7a2371312446914fedadf79632c2c0adb3b463f4838&#39;
Copy after login

The hash value was updated, but is not yet 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 process. Add a mine function below to get a suitable 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 # 产生唯一标示
  self.nonce = None     # nonce值
  self.data = data      # 区块内容
  self.previous_hash = previous_hash # 父节点哈希值
  
 def hash(self, nonce=None):
  &#39;&#39;&#39;
  计算区块的哈希值
  &#39;&#39;&#39;
  message = hashlib.sha256()
  message.update(self.identifier.encode(&#39;utf-8&#39;))
  message.update(str(nonce).encode(&#39;utf-8&#39;))
  message.update(str(self.data).encode(&#39;utf-8&#39;))
  message.update(str(self.previous_hash).encode(&#39;utf-8&#39;))

  return message.hexdigest()

 def hash_is_valid(self, the_hash):
  &#39;&#39;&#39;
  校验区块哈希值有否有效
  &#39;&#39;&#39;
  return the_hash.startswith(&#39;0000&#39;)

 def __repr__(self):
  return &#39;Block<Hash: {}, Nonce: {}>&#39;.format(self.hash(self.nonce), self.nonce)
 
 
 &#39;&#39;&#39;
  新增挖矿函数
 &#39;&#39;&#39;
 def mine(self):
  # 初始化nonce为0
  cur_nonce = self.nonce or 0

  # 循环直到生成一个有效的哈希值
  while True:
   the_hash = self.hash(nonce=cur_nonce)
   if self.hash_is_valid(the_hash): # 如果生成的哈希值有效
    self.nonce = cur_nonce   # 保持当前nonce值
    break       # 并退出
   else:
    cur_nonce += 1 # 若当前哈希值无效,更新nonce值,进行加1操作
Copy after login

In [75]:


block = Block(&#39;Hello World&#39;)

# 挖矿,循环直至找到合适的nonce
block.mine()

# 打印
block
Copy after login

Out[75]:


Block<Hash: 000087359d5264153d624556f0a0c6f25cba06e453975c1c02587862e823911b, Nonce: 64751>
Copy after login

至此,第一个有效的区块生成完成,下面开始定义区块链。

二、定义区块链结构

In [81]:


class BlockChain(object):
 def __init__(self):
  self.head = None # 指向最新的一个区块
  self.blocks = {} # 包含所有区块的一个字典

 &#39;&#39;&#39;
  添加区块函数
 &#39;&#39;&#39;
 def add_block(self, new_block):
  previous_hash = self.head.hash() if self.head else None
  new_block.previous_hash = previous_hash

  self.blocks[new_block.identifier] = {
   &#39;block&#39;: new_block,
   &#39;previous_hash&#39;: previous_hash,
   &#39;previous&#39;: self.head,
  }
  self.head = new_block

 def __repr__(self):
  num_existing_blocks = len(self.blocks)
  return &#39;Blockchain<{} Blocks, Head: {}>&#39;.format(
   num_existing_blocks,
   self.head.identifier if self.head else None
  )
Copy after login

定义好区块链结构后,下面就开始初始化一条区块链。

In [82]:


# 初始化
chain = BlockChain()

# 打印
chain
Copy after login

Out[82]:


Blockchain<0 Blocks, Head: None>
Copy after login

In [83]:


# 添加区块
chain.add_block(block)

# 打印
chain
Copy after login

Out[83]:


Blockchain<1 Blocks, Head: 364c0cf963384ca28a2763499a140405>
Copy after login

In [84]:


# 添加更多的区块

for i in range(6):
 new_block = Block(i)
 new_block.mine()
 chain.add_block(new_block)
 
# 打印
chain
Copy after login

Out[84]:


Blockchain<7 Blocks, Head: e7cb24ec7acd42a4aaebe7faee9e0713>
Copy after login

以上就是一个简单区块链,后面还会涉及到区块链的有效性。当区块链中一个区块被改变后,这个区块的哈希就会改变,从而影响到这块区块之后的区块,致使这个区块链不再有效。这些将在后续继续深入。

The above is the detailed content of Introduction to Python Basics--Blockchain. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template