-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
514 lines (416 loc) · 16.6 KB
/
main.py
File metadata and controls
514 lines (416 loc) · 16.6 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
from flask import Flask, request
import requests
import json
import psycopg2
from mnemonic import Mnemonic
import os
from werkzeug.wrappers import Request, Response
from werkzeug.serving import run_simple
from dotenv import load_dotenv, find_dotenv
# Load enviroment variables
load_dotenv(find_dotenv())
NODE_URL = os.getenv('NODE_URL')
NODE_USER = os.getenv('NODE_USER')
NODE_PASSWORD = os.getenv('NODE_PASSWORD')
DB_HOST = os.getenv('DB_HOST')
DB_PORT = os.getenv('DB_PORT')
DB_USER = os.getenv('DB_USER')
DB_PASSWORD = os.getenv('DB_PASSWORD')
app = Flask('application')
## PRIVATE FUNCTIONS - NOT PUBLICLY ACCESSIBLE
# Basic function to make rpc calls
def rpc(method, params=[], path=NODE_URL):
payload = json.dumps({
"jsonrpc": "2.0",
"id": "minebet",
"method": method,
"params": params
})
return requests.post(path, auth=(NODE_USER, NODE_PASSWORD), data=payload).json()['result']
def generate_mnemonic():
mnemo = Mnemonic("english")
words = mnemo.generate(strength=128)
words = words.split()
return words
def save_error(error_message):
with open("errors.txt", "a") as errorfile:
errorfile.write(error_message)
def log_in(username, password):
'''
@param username - STRING - user's set username
@param password - STRING - user's set password
'''
if type(username) != str:
return type_error('username', 'string')
if type(password) != str:
return type_error('password', 'string')
# Initialize new postgres connection
# Keeping one connection raises an error where it refuses to insert valid queries if it has failed another query
# To avoid this we just create a new transaction block
conn = psycopg2.connect(host=DB_HOST,
port="5432",
user="postgres",
password="BasharHafezAlAssad")
cursor = conn.cursor()
select_user_query = "select * from rpc_users where username = %s"
cursor.execute(select_user_query, (username,))
user = cursor.fetchall()
for user_details in user:
if password == user_details[3]:
message = "Successfully logged in"
return True, message, user_details
else:
message = "Incorrect login credentials"
return False, message
cursor.close()
conn.close()
def auth_error():
# This function is a template for an incorrect error auth message.
# Mostly because I already use a true/false system
# The code could be refactored to include this directly in the log_in function
return {
"status": "error",
"message": "incorrect login credentials"
}
def parameter_error(key):
'''
@param key - STRING - name of the missing parameter
'''
message = "incomplete parameters. please pass in the " + key + " parameter."
return {
"status": "error",
"message": message
}
def type_error(key, correct_type):
'''
@param key - STRING - The parameter with the incorrect type
'''
message = "Please pass in the " + key + " parameter as a " + correct_type
return {
"status": "error",
"message": message
}
## PUBLIC FUNCTIONS - USER CAN ACCESS
@app.route('/create_account', methods=['POST'])
def create_account():
'''
@param username - STRING - the username the user wants. Must be unique
@param password - STRING - the password the user wants
'''
# Initialize new postgres connection
# Keeping one connection raises an error where it refuses to insert valid queries if it has failed another query
# To avoid this we just create a new transaction block
conn = psycopg2.connect(host=DB_HOST,
port=DB_PORT,
user=DB_USER,
password=DB_PASSWORD)
cursor = conn.cursor()
# Get parameters
data = request.get_json()
try:
username = data["username"]
password = data["password"]
if type(username) != str:
return type_error('username', 'string')
if type(password) != str:
return type_error('password', 'string')
except KeyError as error:
# tell user what parameter they are missing
return parameter_error(error.args[0])
try:
cursor.execute("INSERT INTO rpc_users (username, password) VALUES(%s, %s)", (username, password))
conn.commit()
message = "Thanks for creating your account, " + username + "!"
return {
"status": "success",
"message": message
}
except Exception as error:
# The most common error is that the username exists. If so, we can replace the postgres error with something nicer
username_taken_error = 'duplicate key value violates unique constraint \"rpc_users_pkey\"\nDETAIL: Key (username)=(' + username + ') already exists.\n'
if str(error) == username_taken_error:
return {
"status": "error",
"message": "username taken"
}
else:
return {
"status": "error",
"message": str(error)
}
cursor.close()
conn.close()
@app.route('/get_transaction', methods=['POST'])
def get_transaction():
'''
@param txn_number - STRING - The transaction number, as a hash
@param full - BOOL - whether you want the full transaction details or an overview of the transaction
'''
# Get parameters
data = request.get_json()
try:
txn_number = data["txn_number"]
full = data["full"]
if type(txn_number) != str:
return type_error('txn_number', 'string')
if type(full) != bool:
return type_error('full', 'boolean')
except KeyError as error:
# tell user what parameter they are missing
return parameter_error(error.args[0])
try:
result = rpc("getrawtransaction", params = [txn_number, True])
if result == None:
return "No transaction found"
else:
if full:
return result
else:
# Process result, and provide key details (e.g. transaction fee and total amt)
time = result["time"]
confirmations = result["confirmations"]
inputs = result["vin"]
outputs = result["vout"]
transaction_id = result["txid"]
tx_hash = result["hash"]
# Initialize values to calculate
total_outputs = []
transaction_value = 0
output_values = []
for output_item in outputs:
# calculate total output
value = output_item["value"]
address = output_item["scriptPubKey"]["address"]
details = {
"value": value,
"address": address,
}
total_outputs.append(details)
transaction_value += value
output_values.append(value)
# this assumes that the transaction fee is the lowest vout
transaction_fee = min(output_values)
total_received = transaction_value - transaction_fee
payload = {
"time": time,
"confirmations": confirmations,
"transaction value": transaction_value,
"total recieved": total_received,
"transaction fee": transaction_fee,
"recepient details": total_outputs
}
return {
"status": "success",
"transaction_details": payload,
}
except Exception as error:
return error
# return "Connection error occured. Please try again later"
@app.route('/create_wallet', methods=['POST'])
def create_wallet():
'''
@param name - STRING - name of the wallet in question
@param username - STRING - user's set username
@param password - STRING - user's set password
'''
# Initialize new postgres connection
# Keeping one connection raises an error where it refuses to insert valid queries if it has failed another query
# To avoid this we just create a new transaction block
conn = psycopg2.connect(host=DB_HOST,
port=DB_PORT,
user=DB_USER,
password=DB_PASSWORD)
cursor = conn.cursor()
# Get parameters
data = request.get_json()
try:
username = data["username"]
password = data["password"]
name = data["name"]
except KeyError as error:
# tell user what parameter they are missing
return parameter_error(error.args[0])
auth = log_in(username, password)
if auth[0]:
# GENERATE RANDOM MNUMONIC
mnemonic = generate_mnemonic()
# We gotta convert he list to words to return to the user
mnemonic_words = ' '.join(mnemonic)
try:
# convert wallet name to a unique name with their id
user_id = auth[2][0]
username = auth[2][2]
wallet_name = user_id + '_' + str(name)
result = rpc("createwallet", params = [wallet_name])
if result == None:
status = "error"
message = "Looks like you already have a wallet with this name."
mnemonic_words = None
else:
if result["warning"] != '':
message = "Wallet created successfully, with a warning: " + result["warning"] + ". Your mneumonic is " + mnemonic_words + ". Please keep this phrase safe, as you'll need it to access your wallet."
status = "success"
try:
cursor.execute("INSERT INTO wallets (name, user, user_id, mnemonic) VALUES(%s, %s, %s, %s)", (wallet_name, username, user_id, mnemonic))
conn.commit()
except:
message = "Internal error. Please contact hobbleabbas@gmail.com"
else:
status = "success"
try:
cursor.execute("INSERT INTO wallets (wallet_name, user_id, username, mnemonic) VALUES(%s, %s, %s, %s)", (wallet_name, user_id, username, json.dumps(mnemonic)))
# cursor.execute("INSERT INTO wallets (name, user, user_id, mnemonic) VALUES(%s, %s, %s, %s)", (wallet_name, username, user_id, mnemonic))
conn.commit()
message = "Wallet '" + name + "' created successfully. Your mneumonic is " + mnemonic_words + ". Please keep this phrase safe, as you'll need it to access your wallet."
except Exception as error:
status = "error"
mnemonic = None
message = "Internal error. Please contact hobbleabbas@gmail.com"
message = str(error)
return {
"status": status,
"message": message,
"mnemonic": mnemonic_words,
}
except:
return "Connection error occured. Please try again later"
else:
return auth[1]
cursor.close()
conn.close()
@app.route('/retrieve_wallet', methods=['POST'])
def retrieve_wallet():
'''
@param name - STRING - wallet's name
@param username - STRING - user's set username
@param password - STRING - user's set password
@param export - BOOL - whether you want all details including privatekey
@param mnemonic - STRING - To get full export you must provide your mnemonic
'''
# Get parameters
data = request.get_json()
try:
username = data["username"]
password = data["password"]
name = data["name"]
except KeyError as error:
# tell user what parameter they are missing
return parameter_error(error.args[0])
auth = log_in(username, password)
if auth[0]:
try:
# convert wallet name to a unique name with their id
user_id = auth[2][0]
username = auth[2][2]
wallet_name = user_id + '_' + str(name)
# build a path with the specific wallet
path = NODE_URL + "/wallet/" + wallet_name
result = rpc("getwalletinfo", path = path)
return {
"status":"success",
"wallet_details": result
}
except:
return {
"status": "error",
"message": "Connection error occured. Please try again later"
}
else:
return auth[1]
@app.route('/list_wallets', methods=['POST'])
def list_wallets():
'''
@param username - STRING - user's set username
@param password - STRING - user's set password
'''
data = request.get_json()
try:
username = data["username"]
password = data["password"]
except KeyError as error:
# tell user what parameter they are missing
return parameter_error(error.args[0])
auth = log_in(username, password)
if auth[0]:
try:
result = rpc("listwallets")
user_wallets = []
for wallet in result:
wallet_uuid = wallet[0:36]
if wallet_uuid == auth[2][0]:
user_wallets.append(wallet[37:])
if len(user_wallets) == 0:
message = "You don't have any wallets. Create one with the create_wallet command."
else:
# Put together a message with the names of the wallets
wallets_string = ""
for wallet in user_wallets:
wallets_string += " '" + wallet + "' "
message = "You have " + str(len(user_wallets)) + " wallet(s) in your account. Your wallets: " + wallets_string
return {
"status": "success",
"message": message,
"number_of_wallets": len(user_wallets)
}
except Exception as error_message:
save_error(error_message)
error = "Connection error occured. Please try again later"
return error
else:
return auth_error()
@app.route('/send_coins', methods=['POST'])
def send_coins():
'''
@param username - STRING - user's set username
@param password - STRING - user's set password
@param wallet - STRING - the wallet to send from
@param amount - STRING - how much btc to send
@param recipient_address - STRING - where to send the btc
@param fees - BOOL - whether you want to pay fees or not
'''
data = request.get_json()
try:
username = data["username"]
password = data["password"]
wallet = data["wallet"]
amount = float(data["amount"])
recipient_address = data["recipient_address"]
fees = data["fees"]
if type(fees) != bool:
return type_error('fees', 'boolean')
if type(wallet) != str:
return type_error('wallet', 'string')
if type(recipient_address) != str:
return type_error('recipient_address', 'string')
except KeyError as error:
# tell user what parameter they are missing
return parameter_error(error.args[0])
auth = log_in(username, password)
if auth[0]:
try:
# convert wallet name to a unique name with their id
user_id = auth[2][0]
username = auth[2][2]
wallet_name = user_id + '_' + wallet
# build a path with the specific wallet
path = NODE_URL + "/wallet/" + wallet_name
result = rpc("sendtoaddress", params = [recipient_address, amount, "Transacted with the Bank of Bapu API", " ", fees, False], path=path)
# Returning insufficient funds is bad practice, but handling parameter types means this is the most likely case
# Send to address via rpc doesn't return an error it seems, though the cli does
if result:
return {
"status": "success",
"transaction_id": result
}
else:
return {
"status": "error",
"message": "You likely have insufficient funds or passed in a mainnet address. To check your balance use the retrieve_wallet call"
}
except:
error = "Connection error occured. Please try again later"
return error
else:
return auth[1]
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)