-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathappfuncs.py
202 lines (163 loc) · 5.63 KB
/
appfuncs.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
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Project File: Python 2.x or 3.x
# DESCRIPTION
"""appfuncs.py is the access to
databases and the blockchain.
"""
__author__ = "Adam Dabdoub"
__copyright__ = "Copyright 2021, Dabdoub"
__credits__ = ["Adam Dabdoub"]
__developers__ = ["adamdabdoub "]
__license__ = "GPL"
__version__ = "1.0."
__maintainer__ = "Adam Dabdoub"
__email__ = "[email protected]"
__status__ = "Production"
#IMPORTS
try: from app import mysql, session
except ImportError as e: print(e)
from blockchain import Block, Blockchain, updatehash
try:
import httplib
except Exception:
import http.client as httplib
#check if the user is connected to the internet
def internet_connected():
conn = httplib.HTTPConnection("www.google.com", timeout=5)
try:
conn.request("HEAD", "/"); conn.close()
return True
except Exception:
conn.close()
return False
#create ab object of a mysql table for easy access
class Table():
#specify table name on instance
def __init__(self,table_name):
self.table = table_name
#returns a dictionary of all data in the table
def getall(self):
cur = mysql.connection.cursor()
result = cur.execute("SELECT * FROM %s" %self.table)
data = cur.fetchall(); return data
#gets a value from the table
def getone(self,search,value):
data = {}; cur = mysql.connection.cursor()
result = cur.execute(
"SELECT * FROM %s WHERE %s = \"%s\"" %(self.table,search,value)
)
if result > 0: data = cur.fetchone()
cur.close(); return data
#deletes a value from the table
def deleteone(self,search,value):
cur = mysql.connection.cursor()
cur.execute("DELETE from %s where %s = \"%s\"" %(self.table,search,value))
mysql.connection.commit(); cur.close()
#deletes the table from the database
def drop(self):
cur = mysql.connection.cursor()
cur.execute("DROP TABLE %s" %self.table)
cur.close()
#simplify execution of sql code
def sql_raw(execution):
cur = mysql.connection.cursor()
cur.execute(execution)
mysql.connection.commit()
cur.close()
#check if a table is new to the database
def isnewtable(tableName):
cur = mysql.connection.cursor()
try:
result = cur.execute("SELECT * FROM %s" %tableName)
cur.close()
except:
return True
else:
return False
#get the last copy of the blockchain
def getLastBlockchain():
blockchain = Table("blockchain")
unsorted = list(blockchain.getall())
sorted = []
for block in unsorted:
if block.get('number') is not None:
sorted.insert(int(block.get('number'))-1,block)
return sorted
#add a transaction to the blockchain
def addTransaction(sender,receiver,amount,bought=False):
last_blockchain = getLastBlockchain()
blockchain = Blockchain(last_blockchain)
num = len(last_blockchain) + 1
if bought: data = "%s OBTAINED %s" %(receiver,amount)
else: data = "%s --> %s (%s)" %(sender,receiver,amount)
blockchain.mine(Block(data, num))
last = blockchain.chain[-1]
sql_raw(
"INSERT INTO blockchain(number,hash,previous,data,nonce)" +
"VALUES(\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")" %(
last.get('number'),
last.get('hash'),
last.get('previous'),
last.get('data'),
last.get('nonce')
)
)
#verify if the blockchain is not corrupt
def verifyBlockchain():
blockchain = getLastBlockchain()#; print(blockchain)
for n in range(len(blockchain)):
block_hash = updatehash(
blockchain[n].get('previous'),
blockchain[n].get('number'),
blockchain[n].get('data'),
blockchain[n].get('nonce')
)
if block_hash != blockchain[n].get('hash'):
return False
elif block_hash[:4] != "0000":
return False
if n < len(blockchain)-1:
if block_hash != blockchain[n+1].get('previous'):
return False
return True
#check if username is not taken upon registration
def isnewuser(username):
users = Table("users")
data = users.getall()
usernames = [user.get('username') for user in data]
return False if username in usernames else True
#send money to a user
def send_money(username,amount,bought=False):
balances = getbalances()
if bought:
if amount == 0: session['balance'] = amount
else: session['balance'] += amount
else:
session['balance'] -= amount
receiver_balance = balances.get(username) + amount
if bought: addTransaction("ADMIN",username,amount,bought)
else: addTransaction(session.get('username'),username,amount,bought)
#get a dicitionary of balances of each user
def getbalances():
blockchain = Table("blockchain")
blockchain = blockchain.getall()
transactions = [block.get('data') for block in blockchain]
balances = {}
for transaction in transactions:
if "OBTAINED" in transaction:
username, amount = transaction.split(" OBTAINED ")
if balances.get(username) is None:
balances[username] = int(amount)
else:
balances[username] += int(amount)
elif "-->" in transaction:
sender,receiver_data = transaction.split(" --> ")
receiver,amount = receiver_data.split(" (")
amount = int(amount.replace(")",""))
balances[sender] -= int(amount)
if balances.get(receiver) is None:
balances[receiver] = int(amount)
else:
balances[receiver] += int(amount)
return balances