Uh oh!
There was an error while loading. Please reload this page.
forked from FISCO-BCOS/python-sdk
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsole.py
More file actions
Latest commit
executable file
·523 lines (464 loc) · 21.1 KB
/
Copy pathconsole.py
File metadata and controls
executable file
·523 lines (464 loc) · 21.1 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
515
516
517
518
519
520
521
522
523
#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
# -*- coding: utf-8 -*-
'''
bcosliteclientpy is a python client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/)
bcosliteclientpy is free software: you can redistribute it and/or modify it under the
terms of the MIT License as published by the Free Software Foundation. This project is
distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Thanks for
authors and contributors of eth-abi, eth-account, eth-hash,eth-keys, eth-typing, eth-utils,
rlp, eth-rlp , hexbytes ... and relative projects
@author: kentzhang
@date: 2019-06
'''
importargparse
importsys
importglob
fromclient.stattoolimportStatTool
fromclient_configimportclient_config
frometh_account.accountimport (
Account
)
frometh_utils.hexadecimalimportencode_hex
fromclient.contractnoteimportContractNote
importjson
importos
fromclient.datatype_parserimportDatatypeParser
frometh_utilsimportto_checksum_address
fromconsole_utils.precompileimportPrecompile
fromconsole_utils.rpc_consoleimportRPCConsole
fromclient.commonimporttransaction_common
fromclient.commonimportcommon
fromclient.bcoserrorimportBcosError, CompileError, PrecompileError, ArgumentsError, BcosException
fromclient.common.transaction_exceptionimportTransactionException
importargcomplete
# --------------------------------------------------------------------------------------------
# useful functions
# --------------------------------------------------------------------------------------------
defdefault_abi_file(contractname):
abi_file=contractname
ifnotabi_file.endswith(".abi"): # default from contracts/xxxx.abi,if only input a name
abi_file=contracts_dir+"/"+contractname+".abi"
returnabi_file
deffill_params(params, paramsname):
index=0
result=dict()
fornameinparamsname:
result[name] =params[index]
index+=1
returnresult
defprint_receipt_logs_and_txoutput(client, receipt, contractname, parser=None):
print("\nINFO >> receipt logs : ")
# 解析receipt里的log
ifparserisNoneandlen(contractname) >0:
parser=DatatypeParser(default_abi_file(contractname))
logresult=parser.parse_event_logs(receipt["logs"])
i=0
forloginlogresult:
if'eventname'inlog:
i=i+1
print("{}): log name: {} , data: {}".format(i, log['eventname'], log['eventdata']))
txhash=receipt["transactionHash"]
txresponse=client.getTransactionByHash(txhash)
inputdetail=print_parse_transaction(txresponse, "", parser)
# 解析该交易在receipt里输出的output,即交易调用的方法的return值
outputresult=parser.parse_receipt_output(inputdetail['name'], receipt['output'])
print("receipt output :", outputresult)
defprint_parse_transaction(tx, contractname, parser=None):
ifparserisNone:
parser=DatatypeParser(default_abi_file(contractname))
inputdata=tx["input"]
inputdetail=parser.parse_transaction_input(inputdata)
print("INFO >> transaction hash : ", tx["hash"])
print("tx input data detail:\n {}".format(inputdetail))
return (inputdetail)
defcheck_result(result):
"""
check result
"""
ifisinstance(result, dict) and'error'inresult.keys():
returnTrue
returnFalse
defget_validcmds():
"""
get valid cmds
"""
validcmds= ["showaccount", "newaccount", "deploy", "call",
"sendtx", "list", "txinput", "checkaddr", "usage"]
returnvalidcmds
defcheck_cmd(cmd, validcmds):
ifcmdnotinvalidcmds:
common.print_error_msg(("console cmd [{}] not implement yet,"
" see the usage\n").format(cmd), "")
returnFalse
returnTrue
defprintusage(usagemsg, precompile=None):
"""
print usage
"""
print("FISCO BCOS 2.0 @python-SDK Usage:")
index=0
formsginusagemsg:
index+=1
print("{}\n".format(msg))
ifprecompileisNone:
return
precompile.print_cns_usage(True)
precompile.print_consensus_usage(True)
precompile.print_sysconfig_usage(True)
precompile.print_all_permission_usage()
RPCConsole.print_rpc_usage()
defusage(client_config):
"""
generate usage list
"""
usagemsg= []
usagemsg.append(('''newaccount [name] [password] [save]
创建一个新帐户,参数为帐户名(如alice,bob)和密码
结果加密保存在配置文件指定的帐户目录 *如同目录下已经有同名帐户文件,旧文件会复制一个备份
如输入了"save"参数在最后,则不做询问直接备份和写入
create a new account ,save to :[{}] (default) ,
the path in client_config.py:[account_keyfile_path]
if account file has exist ,then old file will save to a backup
if "save" arg follows,then backup file and write new without ask
the account len should be limitted to 240''')
.format(client_config.account_keyfile_path))
usagemsg.append('''showaccount [name] [password]
指定帐户名字(不带后缀)和密码,打开配置文件里默认账户文件路径下的[name].keystore文件,打印公私钥和地址
''')
usagemsg.append('''deploy [contract_name] [save]:
部署合约, 如给出'save'参数,新地址会写入本地记录文件,
eg: deploy SimpleInfo''')
usagemsg.append('''call [contractname] [address] [func] [args...]
call合约的一个只读接口,解析返回值
call a constant function of contract and get the returns
eg: call SimpleInfo 0xF2c07c98a6829aE61F3cB40c69f6b2f035dD63FC getbalance1 11
if address is "last" ,then load last address from :{}
eg: call SimpleInfo last getall
'''.format(client_config.contract_info_file))
usagemsg.append('''sendtx [contractname] [address] [func] [args...]
发送交易调用指定合约的接口,交易如成功,结果会写入区块和状态
send transaction,will commit to blockchain if success
eg: sendtx SimpleInfo 0xF2c07c98a6829aE61F3cB40c69f6b2f035dD63FC
set alice 100 0xF2c07c98a6829aE61F3cB40c69f6b2f035dD63FC
if address is "last" ,then load last address from :{}
eg: sendtx SimpleInfo last set 'test' 100 '0xF2c07c98a6829aE61F3cB40c69f6b2f035dD63FC'
'''.format(client_config.contract_info_file))
usagemsg.append('''list
列出所有支持的get接口名和参数
list: list all getcmds has implemented
(getBlock...getTransaction...getReceipt..getOthers)''')
usagemsg.append('''txinput [contractname] [inputdata(in hex string)]
复制一段来自transaction的inputdata(十六进制字符串),指定合约名,则可以自动解析(合约的abi文件应存在指定目录下)
parse the transaction input data by contractname,eg: txinput SimpleInfo [txinputdata]''')
usagemsg.append('''checkaddr [address]
将普通地址转为自校验地址,自校验地址使用时不容易出错
change address to checksum address according EIP55''')
returnusagemsg
defget_functions_by_contract(contract_name):
"""
get functions according to contract_name
"""
data_parser=DatatypeParser(default_abi_file(contract_name))
return [*data_parser.func_abi_map_by_name.keys()]
deflist_address(contract_name):
"""
get address according to contract_name
"""
returnContractNote.get_contract_addresses(contract_name)
deflist_api(file_pattern):
"""
return list according to file_pattern
"""
file_list= [fforfinglob.glob(file_pattern)]
targets= []
forfileinfile_list:
targets.append(os.path.basename(file).split(".")[0])
returntargets
deflist_contracts():
"""
list all contractname for call
"""
returnlist_api(contracts_dir+"/*.sol")
deflist_accounts():
"""
list all accounts
"""
returnlist_api("bin/accounts/*.keystore")
# get supported command
Precompile.define_functions()
RPCConsole.define_commands()
validcmds=get_validcmds() +RPCConsole.get_all_cmd() \
+Precompile.get_all_cmd()
contracts_dir="contracts"
defcompletion(prefix, parsed_args, **kwargs):
"""
complete the shell
"""
ifparsed_args.cmdisNone:
returnvalidcmds
# deploy contract
ifparsed_args.cmd[0] =="deploy":
returnlist_contracts()
# call and sendtx
# warn(parsed_args)
ifparsed_args.cmd[0] =="call"orparsed_args.cmd[0] =="sendtx":
# only list the contract name
iflen(parsed_args.cmd) ==1:
returnlist_contracts()
# list the contract address
iflen(parsed_args.cmd) ==2:
returnlist_address(parsed_args.cmd[1])
# list functions
iflen(parsed_args.cmd) ==3:
returnget_functions_by_contract(parsed_args.cmd[1])
# call showaccount
ifparsed_args.cmd[0] =="showaccount":
returnlist_accounts()
# registerCNS [contract_name] [contract_address] [contract_version]
ifparsed_args.cmd[0] =="registerCNS":
# list contract name
iflen(parsed_args.cmd) ==1:
returnlist_contracts()
# list contract address
iflen(parsed_args.cmd) ==2:
returnlist_address(parsed_args.cmd[1])
# queryCNSByName [contract_name]
ifparsed_args.cmd[0] =="queryCNSByName":
# list contract name
iflen(parsed_args.cmd) ==1:
returnlist_contracts()
# queryCNSByNameAndVersion [contract_name] [contract_version]
ifparsed_args.cmd[0] =="queryCNSByNameAndVersion":
iflen(parsed_args.cmd) ==1:
returnlist_contracts()
# sysconfig
ifparsed_args.cmd[0] =="setSystemConfigByKey"orparsed_args.cmd[0] =="getSystemConfigByKey":
return ["tx_count_limit", "tx_gas_limit"]
return []
defparse_commands(argv):
"""
parse the input command
"""
# 首先创建一个ArgumentParser对象
parser=argparse.ArgumentParser(description='FISCO BCOS 2.0 lite client @python')
parsed_args=argparse.Namespace()
cmd=parser.add_argument('cmd', nargs="+", # 添加参数
help='the command for console')
cmd.completer=completion
argcomplete.autocomplete(parser)
args=parser.parse_args()
print("\nINFO >> user input : {}\n".format(args.cmd))
cmd=args.cmd[0]
inputparams=args.cmd[1:]
returncmd, inputparams
defmain(argv):
try:
usagemsg=usage(client_config)
cmd, inputparams=parse_commands(argv)
precompile=Precompile(cmd, inputparams, contracts_dir+"/precompile")
# check cmd
valid=check_cmd(cmd, validcmds)
ifvalidisFalse:
printusage(usagemsg, precompile)
return
# try to callback cns precompile
precompile.call_cns()
# try to callback consensus precompile
precompile.call_consensus()
# try to callback config precompile
precompile.call_sysconfig_precompile()
# try to callback permission precompile
precompile.call_permission_precompile()
# try to callback crud precompile
precompile.call_crud_precompile()
# try to callback rpc functions
rpcConsole=RPCConsole(cmd, inputparams, contracts_dir)
rpcConsole.executeRpcCommand()
ifcmd=='showaccount':
# must be 2 params
common.check_param_num(inputparams, 2, True)
name=inputparams[0]
password=inputparams[1]
keyfile="{}/{}.keystore".format(client_config.account_keyfile_path, name)
# the account doesn't exists
ifos.path.exists(keyfile) isFalse:
raiseBcosException("account {} doesn't exists".format(name))
print("show account : {}, keyfile:{} ,password {} ".format(name, keyfile, password))
try:
withopen(keyfile, "r") asdump_f:
keytext=json.load(dump_f)
stat=StatTool.begin()
privkey=Account.decrypt(keytext, password)
stat.done()
print("decrypt use time : %.3f s"% (stat.time_used))
ac2=Account.from_key(privkey)
print("address:\t", ac2.address)
print("privkey:\t", encode_hex(ac2.key))
print("pubkey :\t", ac2.publickey)
print("\naccount store in file: [{}]".format(keyfile))
print("\n**** please remember your password !!! *****")
exceptExceptionase:
raiseBcosException(("load account info for [{}] failed,"
" error info: {}!").format(name, e))
ifcmd=='newaccount':
common.check_param_num(inputparams, 2, True)
name=inputparams[0]
max_account_len=240
iflen(name) >max_account_len:
common.print_info("WARNING", "account name should no more than {}"
.format(max_account_len))
sys.exit(1)
password=inputparams[1]
print("starting : {} {} ".format(name, password))
ac=Account.create(password)
print("new address :\t", ac.address)
print("new privkey :\t", encode_hex(ac.key))
print("new pubkey :\t", ac.publickey)
stat=StatTool.begin()
kf=Account.encrypt(ac.privateKey, password)
stat.done()
print("encrypt use time : %.3f s"% (stat.time_used))
keyfile="{}/{}.keystore".format(client_config.account_keyfile_path, name)
print("save to file : [{}]".format(keyfile))
forcewrite=False
ifnotos.access(keyfile, os.F_OK):
forcewrite=True
else:
# old file exist,move to backup file first
if(len(inputparams) ==3andinputparams[2] =="save"):
forcewrite=True
else:
forcewrite=common.backup_file(keyfile)
ifforcewrite:
withopen(keyfile, "w") asdump_f:
json.dump(kf, dump_f)
dump_f.close()
print(">>-------------------------------------------------------")
print(
"INFO >> read [{}] again after new account,address & keys in file:".format(keyfile))
withopen(keyfile, "r") asdump_f:
keytext=json.load(dump_f)
stat=StatTool.begin()
privkey=Account.decrypt(keytext, password)
stat.done()
print("decrypt use time : %.3f s"% (stat.time_used))
ac2=Account.from_key(privkey)
print("address:\t", ac2.address)
print("privkey:\t", encode_hex(ac2.key))
print("pubkey :\t", ac2.publickey)
print("\naccount store in file: [{}]".format(keyfile))
print("\n**** please remember your password !!! *****")
dump_f.close()
# --------------------------------------------------------------------------------------------
# console cmd entity
# --------------------------------------------------------------------------------------------
ifcmd=="deploy":
'''deploy abi bin file'''
# must be at least 2 params
common.check_param_num(inputparams, 1)
contractname=inputparams[0].strip()
gasPrice=30000000
# need save address whether or not
needSaveAddress=False
args_len=len(inputparams)
ifinputparams[-1] =="save":
needSaveAddress=True
args_len=len(inputparams) -1
# get the args
fn_args=inputparams[1:args_len]
trans_client=transaction_common.TransactionCommon("", contracts_dir, contractname)
result=trans_client.send_transaction_getReceipt(None, fn_args, gasPrice, True)[0]
print("deploy result for [{}] is:\n {}".format(
contractname, json.dumps(result, indent=4)))
name=contractname
address=result['contractAddress']
blocknum=int(result["blockNumber"], 16)
ContractNote.save_contract_address(name, address)
print("on block : {},address: {} ".format(blocknum, address))
ifneedSaveAddressisTrue:
ContractNote.save_address(name, address, blocknum)
print("address save to file: ", client_config.contract_info_file)
else:
print(
'''\nNOTE : if want to save new address as last
address for (call/sendtx)\nadd 'save' to cmdline and run again''')
# --------------------------------------------------------------------------------------------
# console cmd entity
# --------------------------------------------------------------------------------------------
ifcmd=="call"orcmd=="sendtx":
common.check_param_num(inputparams, 3)
paramsname= ["contractname", "address", "func"]
params=fill_params(inputparams, paramsname)
contractname=params["contractname"]
address=params["address"]
ifaddress=="last":
address=ContractNote.get_last(contractname)
ifaddressisNone:
sys.exit("can not get last address for [{}],break;".format(contractname))
tx_client=transaction_common.TransactionCommon(
address, contracts_dir, contractname)
fn_name=params["func"]
fn_args=inputparams[3:]
print("INFO >> {} {} , address: {}, func: {}, args:{}"
.format(cmd, contractname, address, fn_name, fn_args))
ifcmd=="call":
result=tx_client.call_and_decode(fn_name, fn_args)
print("INFO >> {} result: {}".format(cmd, result))
ifcmd=="sendtx":
receipt=tx_client.send_transaction_getReceipt(fn_name, fn_args)[0]
data_parser=DatatypeParser(default_abi_file(contractname))
# 解析receipt里的log 和 相关的tx ,output
print_receipt_logs_and_txoutput(tx_client, receipt, "", data_parser)
# --------------------------------------------------------------------------------------------
# console cmd entity
# --------------------------------------------------------------------------------------------
ifcmd=="list":
RPCConsole.print_rpc_usage()
print("--------------------------------------------------------------------")
# --------------------------------------------------------------------------------------------
# console cmd entity
# --------------------------------------------------------------------------------------------
ifcmd=="txinput":
contractname=inputparams[0]
inputdata=inputparams[1]
abi_path=default_abi_file(contractname)
ifos.path.isfile(abi_path) isFalse:
raiseBcosException("execute {} failed for {} doesn't exist"
.format(cmd, abi_path))
try:
dataParser=DatatypeParser(abi_path)
# print(dataParser.func_abi_map_by_selector)
result=dataParser.parse_transaction_input(inputdata)
print("\nabifile : ", default_abi_file(contractname))
print("parse result: {}".format(result))
exceptExceptionase:
raiseBcosException("execute {} failed for reason: {}"
.format(cmd, e))
# --------------------------------------------------------------------------------------------
# console cmd entity
# --------------------------------------------------------------------------------------------
ifcmd=="checkaddr":
address=inputparams[0]
result=to_checksum_address(address)
print("{} -->\n{}".format(address, result))
# --------------------------------------------------------------------------------------------
# console cmd entity
# --------------------------------------------------------------------------------------------
ifcmd=="usage":
printusage(usagemsg, precompile)
exceptTransactionExceptionase:
common.print_error_msg(cmd, e)
exceptPrecompileErrorase:
common.print_error_msg(cmd, e)
exceptBcosErrorase:
common.print_error_msg(cmd, e)
exceptCompileErrorase:
common.print_error_msg(cmd, e)
exceptArgumentsErrorase:
common.print_error_msg(cmd, e)
exceptBcosExceptionase:
common.print_error_msg(cmd, e)
if__name__=="__main__":
main(sys.argv[1:])