コード例 #1
0
    def call(self, inputparams):
        if len(inputparams) == 0:
            sols = list_files(contracts_dir + "/*.sol")
            for sol in sols:
                print(sol + ".sol")
            return
        common.check_param_num(inputparams, 3)
        paramsname = ["contractname", "address", "func"]
        params = fill_params(inputparams, paramsname)
        contractname = params["contractname"]
        address = params["address"]
        if address == "last" or address == "latest":
            address = ContractNote.get_last(contractname)
            if address is None:
                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>> client info: {}".format(tx_client.getinfo()))
        print("INFO >> call {} , address: {}, func: {}, args:{}".format(
            contractname, address, fn_name, fn_args))
        try:
            result = tx_client.call_and_decode(fn_name, fn_args)

            common.print_tx_result(result)

        except Exception as e:
            common.print_error_msg("call", e)
コード例 #2
0
ファイル: precompile.py プロジェクト: FISCO-BCOS/hackathon
 def call_crud_precompile(self):
     """
     createTable
     """
     try:
         if self._cmd not in self.functions["crud"]:
             return
         self.crud_serivce = CRUDService(self._contract_path)
         # create table
         if self._cmd == self.functions["crud"][0]:
             self.check_param_num(3)
             table = Table(self._args[0], self._args[1],
                           ','.join(self._args[2:]))
             result = self.crud_serivce.create_table(table)
             self.print_succ_msg(result)
         # desc table
         if self._cmd == self.functions["crud"][1]:
             self.check_param_num(1)
             result = self.crud_serivce.desc(self._args[0])
             if result is None:
                 common.print_info(
                     "WARN", "non-exist table {}".format(self._args[0]))
     except ArgumentsError as e:
         common.print_error_msg(self._cmd, e)
         self.print_crud_usage()
コード例 #3
0
def check_cmd(cmd, validcmds):
    if cmd not in validcmds:
        common.print_error_msg(
            ("console cmd  [{}]  not implement yet," " see the usage\n").format(cmd), ""
        )
        return False
    return True
コード例 #4
0
ファイル: precompile.py プロジェクト: FISCO-BCOS/hackathon
 def call_sysconfig_precompile(self):
     """
     call sysconfig precompile
     function setSystemConfigByKey(string key, string value) public returns(int256)
     """
     if self._cmd not in self.functions["sysconfig"]:
         return
     self.config_precompile = ConfigPrecompile(self._contract_path)
     try:
         result = None
         # setSystemConfigByKey
         if self._cmd == self.functions["sysconfig"][0]:
             self.check_param_num(2, True)
             result = self.config_precompile.setValueByKey(
                 self._args[0], self._args[1])
             self.print_succ_msg(result)
     except TransactionException as e:
         self.print_transaction_exception(e)
     except PrecompileError as e:
         self.print_error_msg(e)
     except BcosError as e:
         self.print_error_msg(e)
     except CompileError as e:
         self.print_error_msg(e)
     except ArgumentsError as e:
         common.print_error_msg(self._cmd, e)
         self.print_sysconfig_usage()
コード例 #5
0
ファイル: precompile.py プロジェクト: FISCO-BCOS/hackathon
 def call_cns(self):
     """
     call cns service
     register name, version, address, abi
     queryCNSByName name
     queryCnsByNameAndVersion name version
     """
     if self._cmd not in self.functions["cns"]:
         return
     self.cns_service = CnsService(self._contract_path)
     try:
         # register cns contract
         # registerCNS
         if self._cmd == self.functions["cns"][0]:
             self.check_param_num(3, True)
             contract_name = self._args[0]
             contract_address = self._args[1]
             contract_version = self._args[2]
             contract_abi_path = contracts_dir + "/" + contract_name + ".abi"
             contract_abi = Precompile.load_abi(contract_name,
                                                contracts_dir,
                                                contract_abi_path)
             try:
                 result = self.cns_service.register_cns(
                     contract_name, contract_version, contract_address,
                     contract_abi)
                 self.print_succ_msg(result)
             except TransactionException as e:
                 self.print_transaction_exception(e)
             except PrecompileError as e:
                 self.print_error_msg(e)
             except BcosError as e:
                 self.print_error_msg(e)
             except CompileError as e:
                 self.print_error_msg(e)
             return
         # query cns information by name
         # queryCNSByName
         if self._cmd == self.functions["cns"][1]:
             self.check_param_num(1, True)
             result = self.cns_service.query_cns_by_name(self._args[0])
             Precompile.print_cns_info(result)
             return
         # query cns information by name and version
         # queryCNSByNameAndVersions
         if self._cmd == self.functions["cns"][2]:
             self.check_param_num(2, True)
             result = self.cns_service.query_cns_by_nameAndVersion(
                 self._args[0], self._args[1])
             Precompile.print_cns_info(result)
             return
     except ArgumentsError as e:
         common.print_error_msg(self._cmd, e)
         self.print_cns_usage()
コード例 #6
0
ファイル: precompile.py プロジェクト: FISCO-BCOS/hackathon
 def call_permission_precompile(self):
     """
     call permission precompile
     """
     if self._cmd not in self.functions["permission"]:
         return
     self.premisson_service = PermissionService(self._contract_path)
     try:
         result = self.exec_permission_cmd()
         self.print_succ_msg(result)
     except TransactionException as e:
         self.print_transaction_exception(e)
     except PrecompileError as e:
         self.print_error_msg(e)
     except BcosError as e:
         self.print_error_msg(e)
     except CompileError as e:
         self.print_error_msg(e)
     except ArgumentsError as e:
         common.print_error_msg(self._cmd, e)
         self.print_permission_usage()
コード例 #7
0
ファイル: precompile.py プロジェクト: FISCO-BCOS/hackathon
 def call_consensus(self):
     """
     call consensusPrecompile
     addSealer(string nodeID) public returns(int256)
     addObserver(string nodeID) public returns(int256)
     remove(string nodeID) public returns(int256)
     """
     if self._cmd not in self.functions["consensus"]:
         return
     self.consensus_precompile = ConsensusPrecompile(self._contract_path)
     try:
         self.check_param_num(1, True)
         result = None
         # addSealer
         if self._cmd == self.functions["consensus"][0]:
             # check nodeList
             Precompile.check_nodeList(self.consensus_precompile.client,
                                       self._args[0])
             result = self.consensus_precompile.addSealer(self._args[0])
         # addObserver
         elif self._cmd == self.functions["consensus"][1]:
             result = self.consensus_precompile.addObserver(self._args[0])
         # removeNode
         elif self._cmd == self.functions["consensus"][2]:
             # check node existence
             Precompile.check_sealer(self.consensus_precompile.client,
                                     self._args[0])
             result = self.consensus_precompile.removeNode(self._args[0])
         self.print_succ_msg(result)
     except TransactionException as e:
         self.print_transaction_exception(e)
     except PrecompileError as e:
         self.print_error_msg(e)
     except ArgumentsError as e:
         common.print_error_msg(self._cmd, e)
         self.print_consensus_usage()
     except BcosError as e:
         self.print_error_msg(e)
     except CompileError as e:
         self.print_error_msg(e)
コード例 #8
0
    def sendtx(self, inputparams):
        if len(inputparams) == 0:
            sols = list_files(contracts_dir + "/*.sol")
            for sol in sols:
                print(sol + ".sol")
            return
        common.check_param_num(inputparams, 3)
        paramsname = ["contractname", "address", "func"]
        params = fill_params(inputparams, paramsname)
        contractname = params["contractname"]
        address = params["address"]
        if address == "last" or address == "latest":
            address = ContractNote.get_last(contractname)
            if address is None:
                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>> client info: {}".format(tx_client.getinfo()))
        print("INFO >> sendtx {} , address: {}, func: {}, args:{}".format(
            contractname, address, fn_name, fn_args))
        try:
            from_account_signer = None
            # from_account_signer = Signer_ECDSA.from_key_file(
            #    "bin/accounts/tester.keystore", "123456")
            # print(keypair.address)
            # 不指定from账户,如需指定,参考上面的加载,或者创建一个新的account,
            # 参见国密(client.GM_Account)和非国密的account管理类LocalAccount
            (receipt, output) = tx_client.send_transaction_getReceipt(
                fn_name, fn_args, from_account_signer=from_account_signer)
            data_parser = DatatypeParser(tx_client.contract_abi_path)
            # 解析receipt里的log 和 相关的tx ,output
            print_receipt_logs_and_txoutput(tx_client, receipt, "",
                                            data_parser)
        except Exception as e:
            common.print_error_msg("sendtx", e)
コード例 #9
0
def main(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)
        if valid is False:
            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()
        if cmd == '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
            if os.path.exists(keyfile) is False:
                raise BcosException("account {} doesn't exists".format(name))
            print("show account : {}, keyfile:{} ,password {}  ".format(
                name, keyfile, password))
            try:
                with open(keyfile, "r") as dump_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 !!! *****")
            except Exception as e:
                raise BcosException(("load account info for [{}] failed,"
                                     " error info: {}!").format(name, e))

        if cmd == 'newaccount':
            common.check_param_num(inputparams, 2, True)
            name = inputparams[0]
            max_account_len = 240
            if len(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
            if not os.access(keyfile, os.F_OK):
                forcewrite = True
            else:
                # old file exist,move to backup file first
                if (len(inputparams) == 3 and inputparams[2] == "save"):
                    forcewrite = True
                else:
                    forcewrite = common.backup_file(keyfile)
            if forcewrite:
                with open(keyfile, "w") as dump_f:
                    json.dump(kf, dump_f)
                    dump_f.close()
            print(">>-------------------------------------------------------")
            print(
                "INFO >> read [{}] again after new account,address & keys in file:"
                .format(keyfile))
            with open(keyfile, "r") as dump_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
        # --------------------------------------------------------------------------------------------
        if cmd == "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)
            if inputparams[-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))
            if needSaveAddress is True:
                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
        # --------------------------------------------------------------------------------------------
        if cmd == "call" or cmd == "sendtx":
            common.check_param_num(inputparams, 3)
            paramsname = ["contractname", "address", "func"]
            params = fill_params(inputparams, paramsname)
            contractname = params["contractname"]
            address = params["address"]
            if address == "last":
                address = ContractNote.get_last(contractname)
                if address is None:
                    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))
            if cmd == "call":
                result = tx_client.call_and_decode(fn_name, fn_args)
                print("INFO >> {} result: {}".format(cmd, result))
            if cmd == "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
        # --------------------------------------------------------------------------------------------
        if cmd == "list":
            RPCConsole.print_rpc_usage()
            print(
                "--------------------------------------------------------------------"
            )

        # --------------------------------------------------------------------------------------------
        # console cmd entity
        # --------------------------------------------------------------------------------------------
        if cmd == "txinput":
            contractname = inputparams[0]
            inputdata = inputparams[1]
            abi_path = default_abi_file(contractname)
            if os.path.isfile(abi_path) is False:
                raise BcosException(
                    "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))
            except Exception as e:
                raise BcosException("execute {} failed for reason: {}".format(
                    cmd, e))

        # --------------------------------------------------------------------------------------------
        # console cmd entity
        # --------------------------------------------------------------------------------------------
        if cmd == "checkaddr":
            address = inputparams[0]
            result = to_checksum_address(address)
            print("{} -->\n{}".format(address, result))

        # --------------------------------------------------------------------------------------------
        # console cmd entity
        # --------------------------------------------------------------------------------------------
        if cmd == "usage":
            printusage(usagemsg, precompile)
    except TransactionException as e:
        common.print_error_msg(cmd, e)
    except PrecompileError as e:
        common.print_error_msg(cmd, e)
    except BcosError as e:
        common.print_error_msg(cmd, e)
    except CompileError as e:
        common.print_error_msg(cmd, e)
    except ArgumentsError as e:
        common.print_error_msg(cmd, e)
    except BcosException as e:
        common.print_error_msg(cmd, e)
コード例 #10
0
def main(argv):
    try:
        command_parser = CommandParser(validcmds)
        cmd, inputparams = command_parser.parse_commands(argv)
        if cmd == "list":
            RPCConsole.print_rpc_usage()
            print(
                "--------------------------------------------------------------------"
            )
            return
        # check cmd
        valid = check_cmd(cmd, validcmds)
        if valid is False:
            usage()
            return
        if cmd == "usage":
            usage(inputparams)
            return
        if cmd in cmd_mapping:
            (modulename, classname) = cmd_mapping[cmd]
            console_run_byname(modulename, classname, cmd, inputparams)
            return
        print("cmd=", cmd)
        precompile = Precompile(cmd, inputparams, contracts_dir + "/precompile")
        # 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()
    except TransactionException as e:
        common.print_error_msg(cmd, e)
    except PrecompileError as e:
        common.print_error_msg(cmd, e)
    except BcosError as e:
        common.print_error_msg(cmd, e)
    except CompileError as e:
        common.print_error_msg(cmd, e)
    except ArgumentsError as e:
        common.print_error_msg(cmd, e)
    except BcosException as e:
        common.print_error_msg(cmd, e)
    except ValueError as e:
        common.print_error_msg(cmd, e)
    except Exception as e:
        print("exception happened!")
        print(traceback.format_exc())
        exit(-1)