-
Notifications
You must be signed in to change notification settings - Fork 5
/
blockchain.py
81 lines (61 loc) · 2.02 KB
/
blockchain.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import json
import requests
from _sha256 import sha256
from time import time
from typing import Optional
from urllib.parse import urlparse
FORGE_TRIGGER = 1
class Blockchain:
def __init__(self):
self.authority = None
self.blocs = []
self.peers = set()
self.mempool = []
self.forge(prev_hash='genesis', curr_hash=None)
def forge(self, prev_hash: Optional[str], curr_hash: Optional[str]):
# noinspection PyDictCreation
bloc = {
'previous_hash': prev_hash or self.previous_block['current_hash'],
'current_hash': '',
'timestamp': int(time()),
'transactions': self.mempool[:]
}
bloc['current_hash'] = curr_hash or self.hash(bloc)
self.blocs.append(bloc)
def new_transaction(self, sender: str, content: dict):
if self.authority is not None:
requests.post(
f'http://{self.authority}/transaction/create',
json=content
)
return
self.mempool.append({
'sender': sender,
'content': content
})
if len(self.mempool) == FORGE_TRIGGER:
self.forge(prev_hash=None, curr_hash=None)
self.mempool.clear()
def register(self, address: str):
parsed_url = urlparse(address)
self.peers.add(parsed_url.path)
def sync(self) -> bool:
changed = False
for peer in self.peers:
r = requests.get(f'http://{peer}/')
if r.status_code != 200:
continue
chain = r.json()['chain']
if len(chain) > len(self.blocs):
self.blocs = chain
changed = True
return changed
@property
def previous_block(self) -> dict:
return self.blocs[-1]
@staticmethod
def hash(block: dict):
to_hash = json.dumps(block)
return sha256(to_hash.encode()).hexdigest()
def set_authority(self, address: str):
self.authority = address