From 94060e6bfd69993e7b5625ecd48b27bef4b5cab6 Mon Sep 17 00:00:00 2001 From: root Date: Sun, 24 Sep 2023 21:26:35 +0300 Subject: [PATCH] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D1=80=D1=83=D0=B7=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20=D1=84=D0=B0=D0=B9=D0=BB=D1=8B=20=D0=B2=20=C2=AB?= =?UTF-8?q?/=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- blockchainpy.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 blockchainpy.py diff --git a/blockchainpy.py b/blockchainpy.py new file mode 100644 index 0000000..62d5dc3 --- /dev/null +++ b/blockchainpy.py @@ -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 +