python简单区块链模拟详解

yipeiwu_com6年前Python基础

最近学习了一点python,那就试着做一做简单的编程练习。

首先是这个编程的指导图,如下:

对的,类似一个简单区块链的模拟。

代码如下:

class DaDaBlockCoin:

 #index 索引,timestamp 时间戳,data 交易记录,self_hash交易hash,last_hash,上个hash
 def __init__(self,idex,timestamp,data,last_hash):
  self.idex = idex
  self.timestamp = timestamp
  self.data = data
  self.last_hash = last_hash
  self.self_hash=self.hash_DaDaBlockCoin()


 def hash_DaDaBlockCoin(self):
  sha = hashlib.md5()#加密算法,这里可以选择sha256,sha512,为了打印方便,所以选了md5
  #对数据整体加密
  datastr = str(self.idex)+str(self.timestamp)+str(self.data)+str(self.last_hash)
  sha.update(datastr.encode("utf-8"))
  return sha.hexdigest()

def create_first_DaDaBlock(): # 创世区块

 return DaDaBlockCoin(0, datetime.datetime.now(), "love dadacoin", "0")

# last_block,上一个区块
def create_money_DadaBlock(last_block): # 其它块
 this_idex = last_block.idex + 1 # 索引加1
 this_timestamp = datetime.datetime.now()
 this_data = "love dada" + str(this_idex) # 模拟交易数据
 this_hash = last_block.self_hash # 取得上一块的hash
 return DaDaBlockCoin(this_idex, this_timestamp, this_data, this_hash)

DaDaBlockCoins = [create_first_DaDaBlock()] # 区块链列表,只有一个创世区块
nums = 10
head_block = DaDaBlockCoins[0]
print(head_block.idex, head_block.timestamp, head_block.self_hash, head_block.last_hash)
for i in range(nums):
 dadaBlock_add = create_money_DadaBlock(head_block) # 创建一个区块链的节点
 DaDaBlockCoins.append(dadaBlock_add)
 head_block = dadaBlock_add
 print(dadaBlock_add.idex, dadaBlock_add.timestamp, dadaBlock_add.self_hash, dadaBlock_add.last_hash)

打印结果如下:

与开头的指导思路完美契合,虽然只是很简单的模拟。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python构造函数及解构函数介绍

python 有一个相应的特殊解构器(destructor)方法名为__del__()。然而,由于python具有垃圾对象回收机制(靠引用计数),这个函数要直到该实例对象所有的引用都被清...

Python中的urllib模块使用详解

urllib模块提供的上层接口,使我们可以像读取本地文件一样读取www和ftp上的数据。每当使用这个模块的时候,老是会想起公司产品的客户端,同事用C++下载Web上的图片,那种“痛苦”的...

Matplotlib scatter绘制散点图的方法实现

Matplotlib scatter绘制散点图的方法实现

前言 考虑到很多同学可能还没有安装matplotlib包,这里给大家提供我常用的安装方法。首先Win键 + R,输入命令cmd打开命令行工具,再次在命令行工具中输入pip install...

对python中UDP,socket的使用详解

对python中UDP,socket的使用详解

讲到UDP和TCP之前咱们先了解一下socket Socket socket简称套接字,是进程间通信的一种方式。与其他的方式的进程间的通讯的方式不同的是,socket是实现了主机间进程间...

下载糗事百科的内容_python版

复制代码 代码如下:#coding:utf-8 import urllib.request import xml.dom.minidom import sqlite3 import th...