-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
293 lines (255 loc) · 9.88 KB
/
Copy pathapp.py
File metadata and controls
293 lines (255 loc) · 9.88 KB
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import json
from flask import Flask, render_template, send_file, request, jsonify, send_from_directory
from cryptography.fernet import Fernet
import requests
from fetchDevices import scan_all_subnets
import hashlib
import os
from threading import Thread
from DB_Constructor import construct_db
from ipfs_test import ipfs_upload, ipfs_retrieve
key = b'65A100d105i116t105i97a107k104h105iTechTiger='
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = key.decode()
app.config['JSON_SORT_KEYS'] = False
BLOCKCHAIN = []
UserNames = {}
Thread(target=os.system, args=("ipfs daemon",)).start()
# Create blocks directory if it doesn't exist
BLOCKS_DIR = "blocks"
if not os.path.exists(BLOCKS_DIR):
os.makedirs(BLOCKS_DIR)
def saveBlock(block, index):
block_path = os.path.join(BLOCKS_DIR, str(index))
encBlock = Fernet(key).encrypt(json.dumps(block).encode()).decode()
with open(block_path, "w") as f:
f.write(encBlock)
def loadBlock(index):
"""Load a single block from its file"""
block_path = os.path.join(BLOCKS_DIR, str(index))
if not os.path.exists(block_path):
return None
with open(block_path, "r") as f:
encBlock = f.read()
try:
decBlock = Fernet(key).decrypt(encBlock.encode()).decode()
return json.loads(decBlock)
except Exception as e:
print(f"Error loading block {index}: {e}")
return None
def getBlockCount():
if not os.path.exists(BLOCKS_DIR):
return 0
block_files = [f for f in os.listdir(BLOCKS_DIR) if f.isdigit()]
return len(block_files)
def loadAllBlocks():
blockchain = []
block_count = getBlockCount()
for i in range(block_count):
block = loadBlock(i)
if block:
blockchain.append(block)
return blockchain
def saveAllBlocks(blockchain):
os.makedirs(BLOCKS_DIR, exist_ok=True)
for index, block in enumerate(blockchain):
block_path = os.path.join(BLOCKS_DIR, str(index))
if not os.path.exists(block_path):
saveBlock(block, index)
def fetchMissingBlocks(device, local_count, remote_count):
missing_blocks = []
for i in range(local_count, remote_count):
try:
response = requests.get(f"http://{device}:1878/block/{i}", timeout=2)
if response.status_code == 200:
try:
block = response.json()
except:
block = json.loads(response.text.replace("'", "\""))
# print(block)
missing_blocks.append(block)
else:
print(f"Failed to fetch block {i} from {device}")
break
except Exception as e:
print(f"Error fetching block {i} from {device}: {e}")
break
return missing_blocks
def getBlockChain():
local_count = getBlockCount()
devices = scan_all_subnets(1878)
DevicesAndBlocks = []
for device in devices:
try:
response = requests.get(f"http://{device}:1878/blockcount", timeout=1)
if response.status_code == 200:
DevicesAndBlocks.append({"device": device, "blockcount": response.json().get("count", 0)})
except:
continue
if DevicesAndBlocks:
max_device = max(DevicesAndBlocks, key=lambda x: x["blockcount"])
remote_count = max_device["blockcount"]
# Only fetch if remote has more blocks
if remote_count > local_count:
print(f"Fetching {remote_count - local_count} missing blocks from {max_device['device']}")
missing_blocks = fetchMissingBlocks(max_device['device'], local_count, remote_count)
return missing_blocks
else:
print(f"Local blockchain is up to date ({local_count} blocks)")
return []
def verifyBlockChain():
global BLOCKCHAIN
BLOCKCHAIN = []
block_count = getBlockCount()
if block_count == 0:
print("No blocks found.")
return BLOCKCHAIN
for i in range(block_count):
block = loadBlock(i)
if block is None:
print(f"Failed to load block {i}")
break
# Verify block hash (except for genesis block)
if i > 0:
expected_hash = hashlib.sha256(str(BLOCKCHAIN).encode()).hexdigest()
if block.get('hash') != expected_hash:
print(f"Blockchain verification failed at block {i}!")
print(f"Expected hash: {expected_hash}")
print(f"Got hash: {block.get('hash')}")
break
BLOCKCHAIN.append(block)
if block.get('action') == 'create_acc':
UserNames[block['token']] = block['name']
print(f"Loaded {len(BLOCKCHAIN)} valid blocks")
return BLOCKCHAIN
def sync_blockchain():
global BLOCKCHAIN
missing_blocks = getBlockChain()
if missing_blocks:
# Verify and append missing blocks
temp_chain = BLOCKCHAIN.copy()
valid_blocks = 0
for block in missing_blocks:
# Verify hash
if block['action'] == 'genesis' and len(temp_chain) == 0:
temp_chain.append(block)
BLOCKCHAIN.append(block)
saveBlock(block, len(BLOCKCHAIN) - 1)
valid_blocks += 1
continue
if block['action'] == 'create_acc':
UserNames[block['token']] = block['name']
expected_hash = hashlib.sha256(str(temp_chain).encode()).hexdigest()
if block.get('hash') != expected_hash:
print(f"Invalid block hash detected, stopping sync at block {len(temp_chain)}")
break
temp_chain.append(block)
BLOCKCHAIN.append(block)
saveBlock(block, len(BLOCKCHAIN) - 1)
valid_blocks += 1
print(f"Synced {valid_blocks} new blocks")
return {"success": True, "synced": True, "blocks": len(BLOCKCHAIN), "new_blocks": valid_blocks}
return {"success": True, "synced": False, "blocks": len(BLOCKCHAIN), "new_blocks": 0}
@app.route('/block/<int:index>', methods=['GET'])
def get_block(index):
"""Get a specific block by index"""
block = loadBlock(index)
if block:
return str(block)
return jsonify({"error": "Block not found"}), 404
@app.route('/blockcount', methods=['GET'])
def get_block_count():
return jsonify({"count": len(BLOCKCHAIN)})
@app.route('/updateBlockchain', methods=['POST'])
def updateBlockchain():
"""Update the entire blockchain from external source"""
global BLOCKCHAIN
new_blockchain = request.json
if not new_blockchain:
return jsonify({"error": "No blockchain data provided"}), 400
temp_chain = []
for i, block in enumerate(new_blockchain):
if i > 0:
expected_hash = hashlib.sha256(str(temp_chain).encode()).hexdigest()
if block.get('hash') != expected_hash:
return jsonify({"error": f"Invalid blockchain at block {i}"}), 400
temp_chain.append(block)
BLOCKCHAIN = new_blockchain
saveAllBlocks(BLOCKCHAIN)
return jsonify({"success": True, "blocks": len(BLOCKCHAIN)})
@app.route('/sync', methods=['GET'])
def sync():
return sync_blockchain()
@app.route('/createPost', methods=['GET', 'POST'])
def create_post():
global uid
if request.remote_addr != request.host.split(':')[0] and not request.remote_addr=='127.0.0.1':
return "Access not allowed from external IP addresses", 403
if request.method == 'POST':
sync_blockchain()
content = request.form.get('content')
if not content:
return "Content is required", 400
ipfs_hash = ipfs_upload(content)
post_block = {
"action": "create_post",
"data": {
"cid": ipfs_hash,
"token": uid
}
}
hash_output = hashlib.sha256(str(BLOCKCHAIN).encode()).hexdigest()
post_block['hash'] = hash_output
BLOCKCHAIN.append(post_block)
saveAllBlocks(BLOCKCHAIN)
return f"Post created and block saved as: blocks/{len(BLOCKCHAIN) - 1}"
return render_template('post.html')
@app.route('/getPosts/', methods=['GET'])
def get_posts():
sync_blockchain()
posts = []
for block in reversed(BLOCKCHAIN):
if block.get('action') == 'create_post':
cid = block.get('data', {}).get('cid')
content = ipfs_retrieve(cid) if cid else None
posts.append({"cid": cid, "content": content, "name": UserNames.get(block.get('data', {}).get('token'), 'Unknown')})
return jsonify(posts)
@app.route('/viewPosts/')
def view_posts():
return render_template('view.html')
@app.route('/assets/<path:filename>')
def serve_asset(filename):
return send_from_directory('assets', filename)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
BLOCKCHAIN = loadAllBlocks()
sync_blockchain()
BLOCKCHAIN = verifyBlockChain()
print(f"Blockchain loaded with {len(BLOCKCHAIN)} blocks")
if len(BLOCKCHAIN) == 0:
BLOCKCHAIN.append({"action": "genesis","hash": "0"})
if not os.path.exists("userID"):
uid = os.urandom(16).hex()
UserName = input("Enter your name: ")
hash_output = hashlib.sha256(str(BLOCKCHAIN).encode()).hexdigest()
newBlock = {
"hash": hash_output,
"action": "create_acc",
"name": UserName,
"token": uid,
}
BLOCKCHAIN.append(newBlock)
saveAllBlocks(BLOCKCHAIN)
with open("userID", "w") as f:
f.write(uid)
print(f"Created new account: {UserName}")
else:
with open("userID", "r") as f:
uid = f.read().strip()
print(f"Welcome back! Your user ID is: {uid}")
print(BLOCKCHAIN)
os.startfile("http://localhost:1878")
app.run(host='0.0.0.0', port=1878, debug=True)