node.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import utils
  2. from block import Block
  3. from blockchain import Blockchain
  4. class Node:
  5. ''' This class represents a protocol node.
  6. Each node is numbered and has a secret-public keys pair, to sign messages.
  7. Nodes hold a set of Blockchains(some of which are not notarized)
  8. and a set of unconfirmed pending transactions.
  9. All nodes have syncronized clocks, using GST approach.'''
  10. def __init__(self, id, clock, password, init_block):
  11. self.id = id
  12. self.clock = clock # Clock syncronization to be implemented.
  13. self.password = password
  14. self.private_key, self.public_key = utils.generate_keys(self.password)
  15. self.blockchain = Blockchain(init_block)
  16. self.unconfirmed_transactions = []
  17. def __repr__(self):
  18. return "Node=[id={0}, clock={1}, password={2}, private_key={3}, public_key={4}, blockchain={5}, unconfirmed_transactions={6}".format(self.id, self.clock, self.password, self.private_key, self.public_key, self.blockchain, self.unconfirmed_transactions)
  19. def receive_transaction(self, transaction):
  20. # Additional validity rules must be defined by the protocol for its blockchain data structure.
  21. self.unconfirmed_transactions.append(transaction)
  22. def output(self):
  23. return self.blockchain
  24. def broadcast(self, nodes, transaction):
  25. for node in nodes:
  26. node.receive_transaction(transaction)
  27. def finalize_block(self, epoch):
  28. block = Block(hash(self.blockchain.blocks[-1]), epoch, str(self.unconfirmed_transactions))
  29. self.blockchain.add_block(block) # Block is appended to nodes blockchain
  30. self.unconfirmed_transactions = []