-
Notifications
You must be signed in to change notification settings - Fork 0
/
peers.py
48 lines (37 loc) · 1.44 KB
/
peers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from time import time
class Peers():
def __init__(self, sender):
# this is a dict of [peer_id] = timestamp
self.peers = {}
self.sender = sender
def __str__(self):
return str(self.peers)
def has_peer(self, peer_id):
return peer_id in self.peers
def add_peer(self, peer_id, last_hash, block=None):
self.peers[peer_id] = (time(), last_hash, block)
def purge_peers(self):
for peer, (timestamp, _last_hash, _block) in self.peers.items():
if time() - timestamp > 3:
del self.peers[peer]
def size(self):
return len(self.peers)
def get_consensus(self):
block_set = {}
block_count = {}
hash_count = {}
for peer, (_, last_hash, block) in self.peers.items():
if block:
_hash = block.hash()
block_set[_hash] = block
block_count[_hash] = block_count[_hash] + 1 if _hash in block_count else 1
hash_count[last_hash] = hash_count[last_hash] + 1 if last_hash in hash_count else 1
last_hash = None
block = None
for _hash, count in block_count.items():
if count > self.size()/2:
block = block_set[_hash]
for _hash, count in hash_count.items():
if count >= self.size()/2: # I think we need to let ties win in this situation.
last_hash = _hash
return last_hash, block