-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode-API.py
More file actions
95 lines (87 loc) · 2.53 KB
/
Copy pathnode-API.py
File metadata and controls
95 lines (87 loc) · 2.53 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
from flask import Flask, jsonify,session, abort, make_response
import json
import flask
import json
from blockchain import Crypto
import requests
UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT_NO = 9999
MINER_IP_ADDRESS = "127.0.0.1"
MINER_PORT_NO = 49000
crypto = None
#serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#serverSock.bind((UDP_IP_ADDRESS, UDP_PORT_NO))
app = Flask(__name__)
def get_Hash():
TXPOOL = crypto.get_TXPOOL()
block_str = f"{TXPOOL}"
data = requests.get(f'http://{MINER_IP_ADDRESS}:{MINER_PORT_NO}/mine', json = {"block_str":block_str}).text
data = json.loads(data)
Nonce = data["Nonce"]
mined_block_hash = data["mined_block_hash"]
return mined_block_hash, Nonce
@app.route("/get-blockchain", methods=["GET"])
def get_Blockchain():
try:
f = open('blockchain.json')
blockchain = json.load(f)
f.close()
return blockchain
except Exception as e:
with open('blockchain.json', "w") as f:
json.dump({})
f.close()
print(e)
return {}
@app.route("/transact", methods = ["GET"])
def transact():
TXPOOL = crypto.get_TXPOOL()
print(TXPOOL)
try:
trans_dict = flask.request.json
trans_str = str(trans_dict["trans_str"])
trans_list = trans_str.split("|")
value = trans_list[0]
sender = str(trans_list[1])
receiver = trans_list[2]
timestamp = trans_list[3]
sign = trans_list[4]
verified_val = crypto.verify_Transaction(value, sender, receiver, timestamp, sign)
if verified_val == 1:
print(f"main TXPOOL index: {crypto.tx_index}")
print(f"main Block Index: {crypto.block_Index}")
crypto.transact(value, sender, receiver, timestamp, sign)
elif verified_val == -2 :
print("Authentication Failed!")
elif verified_val == -1:
print("Not enough Balance!")
else:
print('wtf')
if crypto.tx_index == 3:
mined_block_hash, Nonce = get_Hash()
crypto.create_Block(mined_block_hash, Nonce)
return "True"
except Exception as e:
print(e)
return "False"
@app.route("/get-balance", methods = ["GET"])
def get_Balance():
try:
balance = flask.request.json
address = balance["address"]
balance = crypto.get_Balance(address)
balance = {"balance":str(balance)}
return balance
except Exception as e:
print(e)
return {"balance":0}
@app.route("/get-all-transactions", methods = ["GET"])
def get_All_transactions():
data = flask.request.json
address = data["address"]
transactions = crypto.get_All_transactions(address)
return jsonify(transactions)
if __name__ == "__main__":
crypto = Crypto()
print("Node setup successfully!")
app.run(host = '127.0.0.1', port = 9999, debug = True)