forked from iammortimer/TN-ETH-Gateway
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathethChecker.py
200 lines (166 loc) · 9.59 KB
/
ethChecker.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
import os
import sqlite3 as sqlite
import time
import PyCWaves
import traceback
import sharedfunc
from web3 import Web3
from verification import verifier
class ETHChecker(object):
def __init__(self, config):
self.config = config
self.dbCon = sqlite.connect('gateway.db')
self.w3 = self.getWeb3Instance()
self.pwTN = PyCWaves.PyCWaves()
self.pwTN.setNode(node=self.config['tn']['node'], chain=self.config['tn']['network'], chain_id='L')
seed = os.getenv(self.config['tn']['seedenvname'], self.config['tn']['gatewaySeed'])
self.tnAddress = self.pwTN.Address(seed=seed)
self.tnAsset = self.pwTN.Asset(self.config['tn']['assetId'])
self.verifier = verifier(config)
cursor = self.dbCon.cursor()
self.lastScannedBlock = cursor.execute('SELECT height FROM heights WHERE chain = "ETH"').fetchall()[0][0]
def getWeb3Instance(self):
instance = None
if self.config['erc20']['node'].startswith('http'):
instance = Web3(Web3.HTTPProvider(self.config['erc20']['node']))
else:
instance = Web3()
return instance
def getCurrentBlock(self):
latestBlock = self.w3.eth.blockNumber
return latestBlock
def run(self):
# main routine to run continuesly
print('started checking tn blocks at: ' + str(self.lastScannedBlock))
self.dbCon = sqlite.connect('gateway.db')
while True:
try:
nextblock = self.getCurrentBlock() - self.config['erc20']['confirmations']
if nextblock > self.lastScannedBlock:
self.lastScannedBlock += 1
self.checkBlock(self.lastScannedBlock)
cursor = self.dbCon.cursor()
cursor.execute(
'UPDATE heights SET "height" = ' + str(self.lastScannedBlock) + ' WHERE "chain" = "ETH"')
self.dbCon.commit()
except Exception as e:
self.lastScannedBlock -= 1
print('Something went wrong during ETH block iteration: ')
print(traceback.TracebackException.from_exception(e))
time.sleep(self.config['erc20']['timeInBetweenChecks'])
def checkBlock(self, heightToCheck):
cursor = self.dbCon.cursor()
amount_tunnels = cursor.execute('SELECT * FROM tunnel').fetchall()
if len(amount_tunnels) != 0:
# check content of the block for valid transactions
block = self.w3.eth.getBlock(heightToCheck)
for transaction in block['transactions']:
txInfo = self.checkTx(transaction)
if txInfo is not None:
txContinue = False
cursor = self.dbCon.cursor()
sourceAddress = txInfo['sender']
res = cursor.execute(
'SELECT targetAddress FROM tunnel WHERE sourceAddress ="' + sourceAddress + '"').fetchall()
if len(res) == 0:
sourceAddress = str(txInfo['amount'])[-6:]
res = cursor.execute(
'SELECT targetAddress FROM tunnel WHERE sourceAddress ="' + sourceAddress + '"').fetchall()
if len(res) == 0:
self.faultHandler(txInfo, 'notunnel')
else:
txContinue = True
else:
txContinue = True
if txContinue:
targetAddress = res[0][0]
amount = txInfo['amount']
amount -= self.config['tn']['fee']
amount *= pow(10, self.config['tn']['decimals'])
amount = int(round(amount))
if amount < 0:
txInfo['recipient'] = targetAddress
self.faultHandler(txInfo, "senderror", e='under minimum amount')
cursor = self.dbCon.cursor()
cursor.execute(
'DELETE FROM tunnel WHERE sourceAddress = "' + sourceAddress + '" and targetAddress = "' + targetAddress + '"')
self.dbCon.commit()
elif self.checkReceived(transaction):
try:
addr = self.pwTN.Address(targetAddress)
if self.config['tn']['assetId'] == 'TN':
tx = self.tnAddress.sendWaves(addr, amount, 'Thanks for using our service!',
txFee=2000000)
else:
tx = self.tnAddress.sendAsset(addr, self.tnAsset, amount,
'Thanks for using our service!', txFee=2000000)
if 'error' in tx:
self.faultHandler(txInfo, "senderror", e=tx['message'])
else:
print("send tx: " + str(tx))
cursor = self.dbCon.cursor()
amount /= pow(10, self.config['tn']['decimals'])
cursor.execute(
'INSERT INTO executed ("sourceAddress", "targetAddress", "ethTxId", "tnTxId", "amount", "amountFee") VALUES ("' +
txInfo[
'sender'] + '", "' + targetAddress + '", "' + transaction.hex() + '", "' +
tx['id'] + '", "' + str(round(amount)) + '", "' + str(
self.config['tn']['fee']) + '")')
self.dbCon.commit()
print('send tokens from eth to tn!')
cursor = self.dbCon.cursor()
cursor.execute('DELETE FROM tunnel WHERE sourceAddress = "' + txInfo[
'sender'] + '" and targetAddress = "' + targetAddress + '"')
self.dbCon.commit()
self.verifier.verifyTN(tx)
except Exception as e:
self.faultHandler(txInfo, "txerror", e=e)
continue
def checkReceived(self, tx):
transactionreceipt = self.w3.eth.getTransactionReceipt(tx)
return transactionreceipt['status']
def checkTx(self, tx):
# check the transaction
result = None
transaction = self.w3.eth.getTransaction(tx)
if transaction['to'] == self.config['erc20']['gatewayAddress']:
sender = transaction['from']
recipient = transaction['to']
amount = transaction['value'] / 10 ** self.config['erc20']['decimals']
cursor = self.dbCon.cursor()
res = cursor.execute('SELECT tnTxId FROM executed WHERE ethTxId = "' + tx.hex() + '"').fetchall()
if len(res) == 0: result = {'sender': sender, 'function': 'transfer', 'recipient': recipient,
'amount': amount, 'id': tx.hex()}
return result
def faultHandler(self, tx, error, e=""):
# handle transfers to the gateway that have problems
amount = tx['amount']
timestampStr = sharedfunc.getnow()
if error == "notunnel":
cursor = self.dbCon.cursor()
cursor.execute(
'INSERT INTO errors ("sourceAddress", "targetAddress", "tnTxId", "ethTxId", "amount", "error") VALUES ("' +
tx['sender'] + '", "", "", "' + tx['id'] + '", "' + str(amount) + '", "no tunnel found for sender")')
self.dbCon.commit()
print(timestampStr + " - Error: no tunnel found for transaction from " + tx[
'sender'] + " - check errors table.")
if error == "txerror":
targetAddress = tx['recipient']
cursor = self.dbCon.cursor()
cursor.execute(
'INSERT INTO errors ("sourceAddress", "targetAddress", "tnTxId", "ethTxId", "amount", "error", "exception") VALUES ("' +
tx['sender'] + '", "' + targetAddress + '", "", "' + tx['id'] + '", "' + str(
amount) + '", "tx error, possible incorrect address", "' + str(e) + '")')
self.dbCon.commit()
print(timestampStr + " - Error: on outgoing transaction for transaction from " + tx[
'sender'] + " - check errors table.")
if error == "senderror":
targetAddress = tx['recipient']
cursor = self.dbCon.cursor()
cursor.execute(
'INSERT INTO errors ("sourceAddress", "targetAddress", "tnTxId", "ethTxId", "amount", "error", "exception") VALUES ("' +
tx['sender'] + '", "' + targetAddress + '", "", "' + tx['id'] + '", "' + str(
amount) + '", "tx error, check exception error", "' + str(e) + '")')
self.dbCon.commit()
print(timestampStr + " - Error: on outgoing transaction for transaction from " + tx[
'sender'] + " - check errors table.")