-
Notifications
You must be signed in to change notification settings - Fork 17
/
pgeth.py
executable file
·364 lines (317 loc) · 10.8 KB
/
pgeth.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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2012, 2015-2016 IOPixel SAS
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
__version__ = '1.0.0'
"""
Create Private Ethereum Blockchain
by ellis2323 & regispietra
https://github.com/regispietra/CreatePrivateEthereum
This script pilots geth to provide easy functions:
* ./pgeth.py init
this function create the blockchain with an account
* ./pgeth.py start
this function starts geth daemon and mining. When it has started, you could use your Ethereun Wallet to see
contracts and tokens.
* ./pgeth.py stop
this functions stops geth
* ./pgeth.py destroy
A function to delete quickly your private blockchain.
"""
import sys
import argparse
import subprocess
import json
import os
import shutil
import logging
import platform
import re
# const in python
PIDFILE = "/tmp/geth.pid"
# alloc with 1000 ethers
GENESIS = u"""{
"config": {
"chainId": 15
},
"nonce": "0xdeadbeefdeadbeef",
"timestamp": "0x0",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"extraData": "0x00",
"gasLimit": "0x8000000",
"difficulty": "0x400",
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"coinbase": "0x0000000000000000000000000000000000000000",
"alloc": {
"0x$ADDRESS$": { "balance": "1000000000000000000000" }
}
}"""
def load_config_keys(key):
""" doc """
try:
file = open("pgeth_config.json", "r")
txt = file.read()
file.close()
d = json.loads(txt)
except:
logging.error("invalid config file")
logging.error("please use and modify the pgeth_config.json (https://github.com/regispietra/CreatePrivateEthereum)")
sys.exit(-1)
if d.has_key(key):
return d[key]
return None
def getDataDir():
"""Load datadir key and expand it"""
datadir = load_config_keys("datadir")
datadir = os.path.expanduser(datadir)
return datadir
def getIpcDir():
"""Create default ipc path"""
pl = platform.system()
ipcdir = "~/.ethereum/geth.ipc"
if pl == "Darwin":
ipcdir = "~/Library/Ethereum/geth.ipc"
elif pl == "Windows":
ipcdir = "~/AppData/Roaming/Ethereum/geth.ipc"
elif pl == "Linux":
ipcdir = "~/.ethereum/geth.ipc"
else:
logging.error('Platform unknown %s. Contact devs at iopixel dot com', platform)
sys.exit(-1)
ipcdir = os.path.expanduser(ipcdir)
return ipcdir
def checkDir(path):
"""Check the path exists and it is a directory"""
if not os.path.exists(path):
return False
if not os.path.isdir(path):
return False
return True
def checkExe(path):
"""Check the path exists and it is a file"""
if not os.path.exists(path):
return False
if not os.path.isfile(path) and os.access(path, os.X_OK):
return False
return True
def checkFile(path):
"""Check the path exists and it is a file"""
if not os.path.exists(path):
return False
if not os.path.isfile(path) and os.access(path, os.X_OK):
return False
return True
def checkGethCommand():
"""Search Geth command"""
geth = load_config_keys("geth")
if geth:
if checkExe(geth):
return geth
logging.error("invalid geth path in config file")
sys.exit(-1)
stdpaths = [ "/usr/bin/geth", "/usr/local/bin/geth", "/opt/local/bin/geth" ]
for p in stdpaths:
if checkExe(p):
return p
logging.error("no geth found in classic path. Use the geth param in the config file")
sys.exit(0)
def strCommand(cmd):
"""cmd ie list of word into a string"""
return " ".join(cmd)
def test(args):
return getAddress()
def destroyPrivateBlochain():
"""Destroy your private blockchain"""
datadir = getDataDir()
if not checkDir(datadir):
logging.error("nothing to destroy. There is no %s directory" % datadir)
sys.exit(-1)
chaindata = os.path.join(datadir, "chaindata")
keystore = os.path.join(datadir, "keystore")
dapp = os.path.join(datadir, "dapp")
nodekey = os.path.join(datadir, "nodekey")
dsstore = os.path.join(datadir, ".DS_Store")
ipcfile = os.path.join(datadir, "geth.ipc")
if checkDir(chaindata):
shutil.rmtree(chaindata)
if checkDir(keystore):
shutil.rmtree(keystore)
if checkDir(dapp):
shutil.rmtree(dapp)
if checkDir(dsstore):
shutil.rmtree(dsstore)
if checkFile(nodekey):
os.remove(nodekey)
if checkFile(ipcfile):
os.remove(ipcfile)
try:
os.rmdir(datadir)
except:
logging.error("We do not destroy %s directory because there is something not standard in it.\nRemove the directory after checks" % datadir)
sys.exit(-1)
def getAddress():
"""Get the address of the account 0"""
datadir = getDataDir()
geth = checkGethCommand()
options = [ "--datadir", datadir ]
cmdListAccounts = [ geth ] + options + ["account", "list"]
logging.debug("cmd: " + strCommand(cmdListAccounts))
res = subprocess.check_output(cmdListAccounts)
accountQty = len(res.split('\n')) - 1
if accountQty == 0:
return None
line = res.split('\n')[0]
regexp = re.search(u"{([0-9abcdefABCDEF]+)}", line)
if regexp == None:
logging.error("No address found in keystore")
sys.exit(-1)
result = regexp.group(1)
logging.debug('adress found: 0x' + result)
return result
def initAccount():
"""List accounts. Create a default one if there is none"""
datadir = getDataDir()
geth = checkGethCommand()
options = [ "--datadir", datadir ]
cmdListAccounts = [ geth ] + options + ["account", "list"]
logging.debug("cmd: " + strCommand(cmdListAccounts))
res = subprocess.check_output(cmdListAccounts)
accountQty = len(res.split('\n')) - 1
# check account qty
if accountQty > 0:
return
# create mypassword.txt
f = open("mypassword.txt", "w")
f.write(load_config_keys("password"))
f.close()
# create an account
cmdCreateAccount = [ geth ] + options + [ "--password", "mypassword.txt", "account", "new" ]
logging.debug("cmd: " + strCommand(cmdCreateAccount))
subprocess.call(cmdCreateAccount)
def checkIfGethIsRunningByGrep():
"""Check if there is a geth running"""
try:
cmd = "ps ax | grep 'geth ' | grep -v \"grep\""
logging.debug(cmd)
res = subprocess.check_output(cmd, shell=True)
processQty = len(res.split('\n')) - 1
return True
except subprocess.CalledProcessError:
return False
def checkIfGethIsRunning():
"""Check if there is a geth running"""
if checkFile(PIDFILE):
return True
return False
def importKeys():
""" """
pass
def importContracts():
""" """
pass
def init(args):
"""init command"""
# account management
initAccount()
# init needed if there is no chaindata dir
datadir = getDataDir()
if checkDir(os.path.join(datadir, 'chaindata')):
return
geth = checkGethCommand()
options = [ "--datadir", datadir, "--networkid", "100" ]
# create the json genesis
address = getAddress()
txt = GENESIS.replace("$ADDRESS$", address)
f = open("genesis.json", "w")
f.write(txt)
f.close()
# launch the blockchain with the CustomGenesis.json file
cmdInit = [ geth ] + options + [ "init", "genesis.json"]
logging.debug("cmd: " + strCommand(cmdInit))
subprocess.call(cmdInit)
def start(args):
"""start the geth daemon"""
# check if there is a PID File
if checkIfGethIsRunning():
logging.error("geth must already be running (If not remove the %s file)" % PIDFILE)
sys.exit(1)
# start geth with mining
datadir = load_config_keys("datadir")
geth = checkGethCommand()
options = [ "--datadir", datadir, "--networkid", "100", "--nodiscover", "--nat", "none", "--mine", "--minerthreads", "1", "--ipcpath", getIpcDir() ]
options += [ "--rpc", "--rpcport", "8545", "--rpcapi", "'web3,eth,debug,net,shh'", "--rpccorsdomain", "'*'" ];
cmdStart = [ geth ] + options
logging.debug("cmd: " + strCommand(cmdStart))
logfile = open("geth.logs", "w")
process = subprocess.Popen(cmdStart, stdout=logfile, stderr=logfile)
# write the the pid file
pidfile = open(PIDFILE, "w")
pidfile.write(str(process.pid))
pidfile.close()
logging.info("geth starting")
def stop(args):
"""stop the geth daemon"""
# check if there is a PID File
if not checkIfGethIsRunning():
logging.error("geth not running (because there is no %s file)" % PIDFILE)
sys.exit(1)
# read the pid file
pidfile = open(PIDFILE, "r")
text = pidfile.read()
pidfile.close()
try:
pid = int(text)
except e:
sys.stderr.write("Invalid %s file)\n" % PIDFILE)
try:
os.kill(pid, 1)
finally:
os.remove(PIDFILE)
logging.info("geth stopping")
def destroy(args):
"""destroy your private blockchain"""
destroyPrivateBlochain()
def import_(args):
"""fsdf"""
if not vars(args).has_key("type_"):
logging.error("Specify contacts or keys")
sys.exit(-1)
type_ = vars(args)['type_'][0]
if type_ == "contracts":
importContracts()
elif type_ == "keys":
importKeys()
else:
logging.error("Specify contracts or keys")
sys.exit(-1)
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S')
parser = argparse.ArgumentParser(description = 'to be completed')
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
init_parser = subparsers.add_parser('init')
init_parser.set_defaults(func = init)
start_parser = subparsers.add_parser('start')
start_parser.set_defaults(func = start)
stop_parser = subparsers.add_parser('stop')
stop_parser.set_defaults(func = stop)
destroy_parser = subparsers.add_parser('destroy')
destroy_parser.set_defaults(func = destroy)
import_parser = subparsers.add_parser('import')
import_parser.add_argument('type_', nargs=1, help='keys or contracts')
import_parser.set_defaults(func = import_)
test_parser = subparsers.add_parser('test')
test_parser.set_defaults(func = test)
args = parser.parse_args()
args.func(args) # call the default function