Advertisement
Guest User

Untitled

a guest
Aug 21st, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. import hashlib
  3. import json
  4. import time
  5.  
  6.  
  7. class Blockchain(object):
  8.  
  9. def __init__(self):
  10. self.chain = []
  11. self.memPool = []
  12. self.createGenesisBlock()
  13.  
  14. def createGenesisBlock(self):
  15. self.createBlock()
  16.  
  17. def createBlock(self, nonce=0, previousHash=0):
  18. # Lembre que o hash do bloco anterior é o hash na verdade do CABEÇALHO do bloco anterior.
  19.  
  20.  
  21. if(len(self.chain)==0):
  22. Block = dict(
  23. index=0,
  24. timestamp=(int(time.time())),
  25. nonce=0,
  26. merkleRoot=0,
  27. previousHash=0,
  28. transactions=self.memPool)
  29. else:
  30. header = self.chain[-1].copy()
  31. header.pop("transactions")
  32.  
  33. Block = dict(
  34. index=(len(self.chain))+1,
  35. timestamp=(int(time.time())),
  36. nonce=0,
  37. merkleRoot=0,
  38. previousHash=self.generateHash(header),
  39. transactions=self.memPool)
  40.  
  41. self.chain.append(Block)
  42.  
  43.  
  44.  
  45. @staticmethod
  46. def generateHash(data):
  47. blkSerial = json.dumps(data, sort_keys=True).encode()
  48. return hashlib.sha256(blkSerial).hexdigest()
  49.  
  50. def printChain(self):
  51. for i in self.chain:
  52. header = self.chain[-1].copy()
  53. header.pop("transactions")
  54. print(header["previousHash"])
  55. print(json.dumps(i, sort_keys=True).encode())
  56.  
  57.  
  58. blockchain = Blockchain()
  59. for x in range(1, 4):
  60. blockchain.createBlock()
  61. blockchain.printChain()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement