-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
130 lines (97 loc) · 3.46 KB
/
server.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
from flask import Flask, jsonify, request
import time
import json
import os
from Wallet.Wallet import Wallet
from P2pNetwork.Peer2peer import PeerToPeer
from Blockchain.Blockchain import Blockchain
import threading
lock = threading.Lock()
### API ###
app = Flask(__name__)
@app.route('/api', methods=['GET'])
def get_data():
return jsonify({'@': 'Hieu Vo'})
@app.route('/createTxs', methods=['POST'])
def createTxs():
data = request.get_json()
if not data:
return jsonify({'error': 'No data provided'}), 400
txs = wallet.createTxs(data.get('to'), data.get('tokens'))
message = json.dumps({"data": txs.getTxs(), "sig": txs.getSignature()})
# Save to mempool before broadcast
p2p.addTxs(message)
p2p.send_message(message)
return jsonify({'status': 200})
@app.route('/getBlockchain', methods=['GET'])
def getBlockchain():
return jsonify({
"Blockchain": chain.getBlockChain()
})
@app.route('/getTxsPool', methods=['GET'])
def getTxsPool():
pool = p2p.getAllTxs()
res = []
while pool:
res.append(json.loads(pool.popleft()))
return jsonify({
"txs_list": res
})
def triggerMinning(dif=4, max_txs_per_block=5):
while True:
status, txs_list = p2p.getTxsList(max_txs_per_block)
preHash = chain.getLastBlockHash()
if not status: # not enough txs
continue
for nOnce in range(0, 10**8): # Maybe larger
if preHash != chain.getLastBlockHash(): # a new block received!
break
block = wallet.createBlock(preHash, txs_list, nOnce)
hash = block.getHash()
print(hash)
if (hash[:dif] == '0'*dif): # Difficulty with 0s
print('Found')
# Save to blockchain before broadcast
block_str = json.dumps({"data": block.getBlock(), "sig": block.getSignature()})
if chain.addBlock(block_str):
print('block sent!')
p2p.send_message(block_str)
for txs in block.getTxsList():
p2p.removeTxs(txs)
break
@app.route('/getShardConfig', methods=['GET'])
def getShardConfig():
return jsonify(p2p.getShardConfig())
@app.route('/setShardConfig', methods=['POST'])
def setShardConfig():
print('Reconfiguring shards...')
data = request.get_json()
p2p.send_message(json.dumps(data))
del data['setShardConfig']
p2p.setShardConfig(data)
return jsonify({"status": 200})
@app.route('/getChainAtShardEpochX', methods=['GET'])
def getChainAtShardEpochX():
epoch = int(request.args.get('epoch'))
return jsonify(p2p.getChainAtShardEpochX(epoch))
### MAIN ###
if __name__ == "__main__":
difficulty = 4 # num of 0s
max_hosts = 3 # num of nodes
# Blockchain
chain = Blockchain(lock=lock)
# Wallet
wallet = Wallet()
node_id = os.getenv('NODE')
print(f'NODE: {node_id}')
wallet.loadKey(f'keys/{node_id}.pem')
print(f'PKey: {wallet.getPublicKey()}')
# P2p network
p2p = PeerToPeer(difficulty=difficulty, lock=lock, pkey=wallet.getPublicKey(), max_hosts=max_hosts, chain=chain, subnet='192.168.8.224/27')
time.sleep(1) # Ensure the listener is ready
p2p.connect_to_peers()
# Minning
minning_thread = threading.Thread(target=triggerMinning, args=(difficulty, 6,))
minning_thread.start()
# API server
app.run(debug=False, port=5679, host='0.0.0.0')