Загрузить файлы в «/»
This commit is contained in:
parent
3788bfa3a9
commit
94060e6bfd
45
blockchainpy.py
Normal file
45
blockchainpy.py
Normal file
@ -0,0 +1,45 @@
|
||||
import json
|
||||
from hashlib import sha256
|
||||
|
||||
class BlockchainError(Exception): pass
|
||||
|
||||
class blockchain:
|
||||
def __init__(self):
|
||||
self.blockchain=[]
|
||||
self.transactionbyffer=[]
|
||||
def newgenesis(self, data):
|
||||
if len(self.blockchain)==0:
|
||||
temp={"id":0, "data":data, "transactions":[], "roothash":0}
|
||||
temp0=json.dumps(temp)
|
||||
temp0=sha256(temp0.encode()).hexdigest()
|
||||
temp["hash"]=temp0
|
||||
self.blockchain.append(temp)
|
||||
else:
|
||||
raise BlockchainError()
|
||||
def setbc(self, bc):
|
||||
self.blockchain=bc
|
||||
def addtx(self, data):
|
||||
self.transactionbyffer.append(data)
|
||||
def newblock(self, data):
|
||||
temp0={"id":len(self.blockchain), "data":data, "transactions":json.dumps(self.transactionbyffer), "roothash":self.blockchain[len(self.blockchain)-1]["hash"]}
|
||||
temp1=json.dumps(temp0)
|
||||
temp1=sha256(temp1.encode()).hexdigest()
|
||||
temp0["hash"]=temp1
|
||||
self.blockchain.append(temp0)
|
||||
self.transactionbyffer=[]
|
||||
def checkblocks(self):
|
||||
correct=1
|
||||
index=0
|
||||
for block in self.blockchain:
|
||||
temp0=json.dumps({"id":block["id"], "data":block["data"], "transactions":block["transactions"], "roothash":block["roothash"]})
|
||||
temp0=sha256(temp0.encode()).hexdigest()
|
||||
if block["id"]!=self.blockchain[block["id"]]["id"]:
|
||||
correct=0
|
||||
if block["id"]!=0:
|
||||
if self.blockchain[block["id"]-1]["hash"]!=block["roothash"]:
|
||||
correct=0
|
||||
if block["hash"]!=temp0:
|
||||
correct=0
|
||||
index=index+1
|
||||
return correct
|
||||
|
Loading…
Reference in New Issue
Block a user