区块链的helloword,入门第一段代码,适合新手,非常简单,总共不到40行代码。区块链有两部分:区块内容、区块之间的连接,区块一旦连接就成了区块链,代码如下,文章末尾有『结果分析』,便于理解。
import hashlib #hash库
import datetime #时间类
class HaoBlock: #首个区块链
def __init__(self,index,pre_hash,data,timestamp): #python的构造函数
self.index = index
self.pre_hash = pre_hash
self.data = data
self.timestamp = timestamp
self.hash = self.haoBlock_hash() #函数要放在构造顺的最后一个,不知道为什么会这样;自己的hash是hash出来的,不是传进来的
def haoBlock_hash(self): #将区块内容hash
sha = hashlib.sha256()
data_str = str(self.index) + str(self.timestamp) + str(self.data)
sha.update(data_str.encode("utf-8"))
return sha.hexdigest()
def create_first_block(): #创建首个区块 -- 创世区块
first_index = 0
first_pre_hash = "0"
first_timestamp = datetime.datetime.now()
first_data = "Love HaoBlock" #数据无所谓,模拟一下而已
return HaoBlock(first_index,first_pre_hash,first_data,first_timestamp)
def create_money_block(lastblock): #创建区块
this_index = lastblock.index + 1
this_pre_hash = lastblock.hash
this_timestamp = datetime.datetime.now()
this_data = "Love all" + str(lastblock.index)
return HaoBlock(this_index,this_pre_hash,this_data,this_timestamp)
nums = 10
HaoBlocks = [create_first_block()]
head_block = HaoBlocks[0]
print(head_block.index , head_block.timestamp , head_block.pre_hash , head_block.hash , head_block.data)
for x in range(nums): #输出一个next_hash与下一个区块的hash一样的链
this_block = create_money_block(head_block)
HaoBlocks.append(this_block)
head_block = this_block
print(this_block.index , this_block.timestamp , this_block.data, this_block.pre_hash , this_block.hash)
结果分析
可以看到,输出的区块链中,hash编码首尾相连。

数据结构如下

我会持续地输出一系列区块链入门编程,有兴趣的程序员可以继续浏览后面的文章。
网友评论