当前位置: 首页 > 产品大全 > 用不到50行的Python 2.x代码实现简单区块链

用不到50行的Python 2.x代码实现简单区块链

用不到50行的Python 2.x代码实现简单区块链

以下是一个使用Python 2.x实现的简单区块链示例代码,总计不到50行:

`python import hashlib import json import time

class Block:
def init(self, index, transactions, timestamp, previoushash):
self.index = index
self.transactions = transactions
self.timestamp = timestamp
self.previous
hash = previoushash
self.hash = self.calculate
hash()

def calculatehash(self):
block
string = json.dumps({
"index": self.index,
"transactions": self.transactions,
"timestamp": self.timestamp,
"previoushash": self.previoushash
}, sortkeys=True)
return hashlib.sha256(block
string).hexdigest()

class Blockchain:
def init(self):
self.chain = [self.creategenesisblock()]

def creategenesisblock(self):
return Block(0, "Genesis Block", time.time(), "0")

def getlatestblock(self):
return self.chain[-1]

def addblock(self, newblock):
newblock.previoushash = self.getlatestblock().hash
newblock.hash = newblock.calculatehash()
self.chain.append(new
block)

def ischainvalid(self):
for i in range(1, len(self.chain)):
currentblock = self.chain[i]
previous
block = self.chain[i-1]

if currentblock.hash != currentblock.calculatehash():
return False

if current
block.previoushash != previousblock.hash:
return False

return True

使用示例

if name == "main":
my_blockchain = Blockchain()

# 添加一些区块

myblockchain.addblock(Block(1, "Transaction Data 1", time.time(), ""))
myblockchain.addblock(Block(2, "Transaction Data 2", time.time(), ""))

# 打印区块链

for block in myblockchain.chain:
print "Block #" + str(block.index)
print "Hash: " + block.hash
print "Previous Hash: " + block.previous
hash
print "Data: " + str(block.transactions)
print "-" * 20
`

这个简单区块链实现包含以下核心功能:

  1. Block类:定义了每个区块的结构,包括索引、交易数据、时间戳、前一个区块的哈希值
  2. Blockchain类:管理整个区块链
  • 创世区块创建
  • 添加新区块
  • 验证区块链完整性

代码特点:

  • 使用SHA256哈希算法确保数据完整性
  • 每个区块都包含前一个区块的哈希值,形成链式结构
  • 提供简单的区块链验证功能

这只是一个基础实现,真实的区块链系统还需要考虑工作量证明、分布式网络、交易验证等复杂功能。

如若转载,请注明出处:http://www.w-share.com/product/236.html

更新时间:2025-10-30 20:27:20

产品大全

Top