-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.py
100 lines (74 loc) · 2.03 KB
/
main.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
from argparse import ArgumentParser
import flask
from flask import Flask, request
from blockchain import Blockchain
app = Flask(__name__)
address = ''
blockchain = Blockchain()
@app.route('/')
def base():
return flask.jsonify({
'message': f'running on {address}',
'chain': blockchain.blocs
})
@app.route('/register/authority', methods=['POST'])
def set_auth():
payload = request.get_json(force=True)
if not payload['peer']:
return flask.jsonify({
'message': 'authority\'s address missing'
}), 400
blockchain.set_authority(payload['peer'])
return flask.jsonify({
'message': f"authority set at {payload['peer']}"
})
@app.route('/register/node', methods=['POST'])
def new_node():
payload = request.get_json(force=True)
if not payload['peer']:
return flask.jsonify({
'message': 'peer\'s address missing'
}), 400
blockchain.register(payload['peer'])
return flask.jsonify({
'message': f"peer at {payload['peer']} added "
f"(total: {len(blockchain.peers)})"
})
@app.route('/sync')
def sync():
changed = blockchain.sync()
return flask.jsonify({
'message': 'chain updated' if changed else 'chain up to date'
})
@app.route('/transaction/create', methods=['POST'])
def new_transaction():
payload = request.get_json(force=True)
blockchain.new_transaction(
sender=address,
content=payload
)
return flask.jsonify({
'message': 'transaction added',
'content': payload
})
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument(
'-p',
'--port',
default=5000,
type=int,
help='port to listen on'
)
parser.add_argument(
'-ht',
'--host',
default='127.0.0.1',
type=str,
help='peer\'s host'
)
args = parser.parse_args()
port = args.port
host = args.host
address = f'{host}:{port}'
app.run(host=host, port=port)