-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathEthUtil.py
293 lines (223 loc) · 10.1 KB
/
EthUtil.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
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
from __future__ import annotations
from .EthEnum import ConsensusMechanism
from typing import Dict, List
import json
from datetime import datetime, timezone
from os import path
from .EthTemplates import GenesisFileTemplates
from sys import stderr
from time import time
class Genesis():
"""!
@brief Genesis manage class
"""
__genesis:dict
__consensusMechanism:ConsensusMechanism
def __init__(self, consensus:ConsensusMechanism):
self.__consensusMechanism = consensus
self.__genesis = json.loads(GenesisFileTemplates[self.__consensusMechanism.value])
self.__genesis["timestamp"] = hex(int((time())))
def setGenesis(self, customGenesis:str):
"""!
@brief set custom genesis
@param customGenesis genesis file contents to set.
@returns self, for chaining calls.
"""
self.__genesis = json.loads(customGenesis)
return self
def getGenesis(self) -> str:
"""!
@brief get a string format of genesis block.
returns genesis.
"""
return json.dumps(self.__genesis)
def addAccounts(self, accounts:List[AccountStructure]) -> Genesis:
"""!
@brief allocate balance to account by setting alloc field of genesis file.
@param accounts list of accounts to allocate balance.
@returns self, for chaining calls.
"""
for account in accounts:
address = account.address
balance = account.balance
assert balance >= 0, "Genesis::addAccounts: balance cannot have a negative value. Requested Balance Value : {}".format(account.getBalance())
self.__genesis["alloc"][address[2:]] = {"balance":"{}".format(balance)}
return self
def addLocalAccount(self, address:str, balance:int) -> Genesis:
"""!
@brief allocate balance to a local account by setting alloc field of genesis file.
@param address : external account's address to allocate balance
@param balance
@returns self, for chaining calls.
"""
from web3 import Web3
assert balance >= 0, "Genesis::allocateBalance: balance cannot have a negative value. Requested Balance Value : {}".format(balance)
checksum_address = Web3.toChecksumAddress(address)
self.__genesis["alloc"][checksum_address[2:]] = {"balance":"{}".format(balance)}
return self
def setSigner(self, accounts:List[AccountStructure]) -> Genesis:
"""!
@brief set initial signers by setting extraData field of genesis file.
extraData property in genesis block consists of
32bytes of vanity data, a list of initial signer addresses,
and 65bytes of vanity data.
@param accounts account lists to set as signers.
@returns self, for chaining API calls.
"""
assert self.__consensusMechanism == ConsensusMechanism.POA, 'setSigner method supported only in POA consensus.'
signerAddresses = ''
for account in accounts:
signerAddresses = signerAddresses + account.address[2:]
self.__genesis["extraData"] = GenesisFileTemplates['POA_extra_data'].format(signer_addresses=signerAddresses)
return self
def setGasLimit(self, gasLimit:int) -> Genesis:
"""!
@brief set GasLimit (the limit of gas cost per block)
@param int
@returns self, for chaining API calls
"""
self.__genesis["gasLimit"] = hex(gasLimit)
return self
def setChainId(self, chainId:int) -> Genesis:
"""!
@brief set ChainId
@param int
@returns self, for chaining API calls
"""
self.__genesis["config"]["chainId"] = chainId
return self
class AccountStructure():
address: str
keystore_content: str
keystore_filename:str
balance: int
password: str
def __init__(self, address:str, balance:int, keystore_filename:str, keystore_content:str, password:str):
self.address = address
self.keystore_content = keystore_content
self.keystore_filename = keystore_filename
self.balance = balance
self.password = password
# Make the class stateless.
LOCAL_ACCOUNT_KEY_DERIVATION_PATH = "m/44'/60'/0'/0/{index}"
ETH_ACCOUNT_KEY_DERIVATION_PATH = "m/44'/60'/{id}'/0/{index}"
class EthAccount():
"""
@brief Ethereum Local Account.
"""
@staticmethod
def importAccount(keyfilePath: str, balance:int, password = "admin"):
"""
@brief import account from keyfile
"""
from eth_account import Account
EthAccount._log('importing eth account...')
assert path.exists(keyfilePath), "EthAccount::__importAccount: keyFile does not exist. path : {}".format(keyfilePath)
f = open(keyfilePath, "r")
keyfileContent = f.read()
f.close()
account = Account.from_key(Account.decrypt(keyfile_json=keyfileContent,password=password))
keystore_content = json.dumps(EthAccount.__encryptAccount(account=account, password=password))
datastr = datetime.now(timezone.utc).isoformat().replace("+00:00", "000Z").replace(":","-")
keystore_filename = "UTC--"+datastr+"--"+account.address
return AccountStructure(account.address, balance, keystore_filename, keystore_content, password)
@staticmethod
def __encryptAccount(account, password:str):
from eth_account import Account
while True:
keystore = Account.encrypt(account.key, password=password)
if len(keystore['crypto']['cipherparams']['iv']) == 32:
return keystore
@staticmethod
def createEmulatorAccountFromMnemonic(id:int, mnemonic:str, balance:int, index:int, password:str):
from eth_account import Account
from web3 import Web3
Account.enable_unaudited_hdwallet_features()
EthAccount._log('creating node_{} emulator account {} from mnemonic...'.format(id, index))
acct = Account.from_mnemonic(mnemonic, account_path=ETH_ACCOUNT_KEY_DERIVATION_PATH.format(id=id, index=index))
address = Web3.toChecksumAddress(acct.address)
keystore_content = json.dumps(EthAccount.__encryptAccount(account=acct, password=password))
datastr = datetime.now(timezone.utc).isoformat().replace("+00:00", "000Z").replace(":","-")
keystore_filename = "UTC--"+datastr+"--"+address
return AccountStructure(address, balance, keystore_filename, keystore_content, password)
@staticmethod
def createEmulatorAccountsFromMnemonic(id:int, mnemonic:str, balance:int, total:int, password:str):
accounts = []
index = 0
for i in range(total):
accounts.append(EthAccount.createEmulatorAccountFromMnemonic(id, mnemonic, balance, index, password))
index += 1
return accounts
@staticmethod
def createLocalAccountFromMnemonic(mnemonic:str, balance:int, index:int):
from eth_account import Account
Account.enable_unaudited_hdwallet_features()
EthAccount._log('creating local account {} from mnemonic...'.format(index))
acct = Account.from_mnemonic(mnemonic, account_path=LOCAL_ACCOUNT_KEY_DERIVATION_PATH.format(index=index))
address = Web3.toChecksumAddress(acct.address)
return AccountStructure(address, balance, "", "", "")
@staticmethod
def createLocalAccountsFromMnemonic(mnemonic:str, balance:int, total:int):
accounts = []
index = 0
for i in range(total):
accounts.append(EthAccount.createLocalAccountFromMnemonic(mnemonic, balance, index))
index += 1
return accounts
@staticmethod
def _log(message: str) -> None:
"""!
@brief Log to stderr.
"""
print("==== EthAccount: {}".format(message), file=stderr)
class SmartContract():
__abi_file_name: str
__bin_file_name: str
def __init__(self, contract_file_bin, contract_file_abi):
self.__abi_file_name = contract_file_abi
self.__bin_file_name = contract_file_bin
def __getContent(self, file_name):
"""!
@brief get Content of the file_name.
@param file_name from which we want to read data.
@returns Contents of the file_name.
"""
file = open(file_name, "r")
data = file.read()
file.close()
return data.replace("\n","")
def generateSmartContractCommand(self):
"""!
@brief generates a shell command which deploys the smart Contract on the ethereum network.
@param contract_file_bin binary file of the smart Contract.
@param contract_file_abi abi file of the smart Contract.
@returns shell command in the form of string.
"""
abi = "abi = {}".format(self.__getContent(self.__abi_file_name))
byte_code = "byteCode = \"0x{}\"".format(self.__getContent(self.__bin_file_name))
unlock_account = "personal.unlockAccount(eth.accounts[0], \"{}\")".format("admin")
contract_command = "testContract = eth.contract(abi).new({ from: eth.accounts[0], data: byteCode, gas: 1000000})"
display_contract_Info = "testContract"
finalCommand = "{},{},{},{},{}".format(abi, byte_code, unlock_account, contract_command, display_contract_Info)
SmartContractCommand = "sleep 30 \n \
while true \n\
do \n\
\t balanceCommand=\"geth --exec 'eth.getBalance(eth.accounts[0])' attach\" \n\
\t balance=$(eval \"$balanceCommand\") \n\
\t minimumBalance=1000000 \n\
\t if [ $balance -lt $minimumBalance ] \n\
\t then \n \
\t \t sleep 60 \n \
\t else \n \
\t \t break \n \
\t fi \n \
done \n \
echo \"Balance ========> $balance\" \n\
gethCommand=\'{}\'\n\
finalCommand=\'geth --exec \"$gethCommand\" attach\'\n\
result=$(eval \"$finalCommand\")\n\
touch transaction.txt\n\
echo \"transaction hash $result\" \n\
echo \"$result\" >> transaction.txt\n\
".format(finalCommand)
return SmartContractCommand