-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
141 lines (107 loc) · 3.67 KB
/
app.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
130
131
132
133
134
135
136
137
138
139
140
141
from flask import Flask, render_template, jsonify, request, json
from flask_redis import Redis
from flask_socketio import SocketIO
import time
import sys
import hashlib
from uuid import uuid4
from blk import BlkWorld
app = Flask(__name__)
redis = Redis(app)
socketio = SocketIO(app)
try:
LATEST_HASH = redis.get('prev-hash').decode("utf-8")
except:
LATEST_HASH = '0000'
redis.set('prev-hash', LATEST_HASH)
print('Latest hash:', LATEST_HASH)
try:
LAST_BLOCK_ID = int(redis.get('last-block-id').decode("utf-8"))
except:
LAST_BLOCK_ID = 0
redis.set('last-block-id', LAST_BLOCK_ID)
print("last block id:" , LAST_BLOCK_ID)
thread = None
world = BlkWorld()
def background_thread():
"""Example of how to send server generated events to clients."""
while True:
world.step()
socketio.emit('blks', world.getData())
socketio.sleep(0.01)
@app.route('/')
def index():
global thread
if thread is None:
thread = socketio.start_background_task(background_thread)
nodeId = redis.get('node-id').decode("utf-8")
return render_template('./index.html', nodeId=nodeId, blockId=LAST_BLOCK_ID, prevHash = LATEST_HASH,
worldHeight = world.height, worldWidth=world.width)
@app.route('/block/latest')
def latestBlock():
#nid = redis.get('node-id').decode("utf-8")
response = {'prevHash': LATEST_HASH, 'blockId' : LAST_BLOCK_ID}
return jsonify(response), 200
@app.route('/block/verify', methods=['POST'])
def verifyBlock():
global LAST_BLOCK_ID, LATEST_HASH
try:
print(type(request.json))
#data = json.dumps(request.json)
#block = json.loads(data)
block = request.json
print('new Block:', block)
if block['blockId'] != LAST_BLOCK_ID:
raise Exception("Block id does not match")
if block['prevHash'] != LATEST_HASH:
raise Exception("Previous Hash not up to date")
hashString = (str(block['prevHash'])+str(block['userId'])+str(block['nonce'])).encode()
hashResult = hashlib.sha256(hashString).hexdigest()
print('Hash Valid: ', hashResult)
if hashResult != block['hash'] or hashResult[:4] != '0000':
raise Exception("Invalid hash for block")
# Update latest Hash and save to redis
LATEST_HASH = hashResult
redis.set('prev-hash', LATEST_HASH)
LAST_BLOCK_ID = redis.incr('last-block-id')
userBlks = redis.incr('blk:'+block['userId'])
latestBlock = { 'blockId': LAST_BLOCK_ID, 'prevHash': LATEST_HASH}
socketio.emit('block', latestBlock);
response = {'status': 'accepted', 'block': latestBlock, 'blks': userBlks};
world.createBlk(LAST_BLOCK_ID,block['userId'] )
socketio.emit('blks', world.getData())
return jsonify(response), 200
except:
print(sys.exc_info())
response = {'message': 'Error in Block'}
return jsonify(response), 406
@app.route('/node/id')
def nodeid():
nid = redis.get('node-id').decode("utf-8")
response = {'nodeId': nid}
return jsonify(response), 200
@app.route('/user/blks/<userId>', methods=['GET'])
def getUserBlks(userId):
#Generate random number to be used as userId
blks = redis.get('blk:'+str(userId)).decode()
response = {'blks': blks}
return jsonify(response), 200
@app.route('/user/new', methods=['GET'])
def newUser():
#Generate random number to be used as userId
userId = str(uuid4()).replace('-', '')
response = {'userId': userId}
return jsonify(response), 200
@app.route('/pos', methods=['POST'])
def pos():
if request.headers['Content-Type'] == 'application/json':
data = json.dumps(request.json)
print('new data:', data)
socketio.emit('pos', data);
response = {'status': 'ok'}
return jsonify(response), 200
else:
response = {'message': 'Invalid Transaction!'}
return jsonify(response), 406
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=5000, debug=True)