예제 #1
0
        def show_ecdsa_account(name, password):

            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))
예제 #2
0
 def unlock_account(self,
                    account: str,
                    password: str,
                    duration: int = None) -> bool:
     """
     Decrypt the signing material from the key metadata file and cache it on
     the keystore instance is decryption is successful.
     """
     if not self.__signers.get(account):
         try:
             key_metadata = self.__keys[account]
         except KeyError:
             raise self.UnknownAccount(account=account)
         try:
             signing_key = Account.from_key(
                 Account.decrypt(key_metadata, password))
             self.__signers[account] = signing_key
         except TypeError:
             if not password:
                 # It is possible that password is None here passed from the above layer
                 # causing Account.decrypt to crash, expecting a value for password.
                 raise self.AuthenticationFailed(
                     'No password supplied to unlock account.')
             raise
         except ValueError as e:
             raise self.AuthenticationFailed(
                 "Invalid or incorrect ethereum account password.") from e
     return True
예제 #3
0
 def validate(self):
     name = self.line_name.text()
     password = self.line_pwd.text()
     if name == "bank" and password == "bank":
         bank_window.show()
         bank_window.set_table_content()
     else:
         keyfile = "{}/{}.keystore".format(
             client_config.account_keyfile_path, name)
         # 如果名字不存在
         if os.path.exists(keyfile) is False:
             QMessageBox.warning(self, "error",
                                 "名称 {} 不存在,请先注册。".format(name),
                                 QMessageBox.Yes)
         else:
             print("name : {}, keyfile:{} ,password {}  ".format(
                 name, keyfile, password))
             try:
                 with open(keyfile, "r") as dump_f:
                     keytext = json.load(dump_f)
                     privkey = Account.decrypt(keytext, password)
                     ac2 = Account.from_key(privkey)
                     print("address:\t", ac2.address)
                     print("privkey:\t", encode_hex(ac2.key))
                     print("pubkey :\t", ac2.publickey)
                     company_window.show()
                     company_window.set_basic_info(name)
             except Exception as e:
                 QMessageBox.warning(
                     self, "error", ("Failed to load account info for [{}],"
                                     " error info: {}!").format(name, e),
                     QMessageBox.Yes)
예제 #4
0
 def load_from_keystore(filename, password):
     with open(filename, "r") as f:
         keytext = json.load(f)
         privkey = Account.decrypt(keytext, password)
         ac = Account.from_key(privkey)
         f.close()
         return ac
예제 #5
0
def get_owner_account(priv_key_path_env_var: str = "DEPLOYMENT_PRIV_KEY_PATH",
                      priv_key_pwd_env_var: str = "DEPLOYMENT_PRIV_KEY_PWD"):

    priv_key_path = os.environ.get(priv_key_path_env_var, None)

    if priv_key_path:
        _priv_key_path = os.path.abspath(
            os.path.expanduser(os.path.expandvars(priv_key_path)))
        # IF env var to key file is provided
        priv_key_pwd = os.environ.get(priv_key_pwd_env_var, None)
        if priv_key_pwd is None:
            print(
                f'The DEPLOYMENT_PRIV_KEY_PWD env var is not defined, trying to proceed with prompting '
                f'password from stdin.')
            priv_key_pwd = getpass.getpass("Password for private key: ")
        with open(_priv_key_path) as f:
            encr_pk_json = json.load(f)
        pk = Account.decrypt(encr_pk_json, priv_key_pwd)
        owner = accounts.add(pk)
    else:
        print(
            f'The DEPLOYMENT_PRIV_KEY_PATH env var is not defined, trying to proceed with web3 provider accounts.'
        )
        # If not use default accounts
        owner = accounts[0]

    print(f'owner: {owner}')
    return owner
예제 #6
0
    def register(self, username, password):
        ac = Account.create(password)
        kf = Account.encrypt(ac.privateKey, password)
        keyfile = "{}/{}.keystore".format(client_config.account_keyfile_path, username)
        
        # file is exist, account is registed
        if os.access(keyfile, os.F_OK):
            return -1
        try:
            with open(keyfile, "w") as dump_f:
                json.dump(kf, dump_f)
                dump_f.close()

            with open(keyfile, "r") as dump_f:
                keytext = json.load(dump_f)
                privkey = Account.decrypt(keytext, password)
                client_account = Account.from_key(privkey)
                ps = PermissionService("./pythonsdk/contracts/precompile")
                ps.grant("t_rep1", client_account.address)
                ps.grant("t_company", client_account.address)
                del ps
        # write file failed
        except Exception as e:
            return -2
        return 0
예제 #7
0
 def load_default_account(self):
     if (client_config.account_keyfile != None):
         keystorefile = client_config.account_keyfile_path + "/" + client_config.account_keyfile
         with open(keystorefile, "r") as dump_f:
             keytext = json.load(dump_f)
             privkey = Account.decrypt(keytext,
                                       client_config.account_password)
             self.client_account = Account.from_key(privkey)
예제 #8
0
 def load_default_account(self):
     try:
         with open(self.keystore_file, "r") as dump_f:
             keytext = json.load(dump_f)
             privkey = Account.decrypt(keytext, client_config.account_password)
             self.client_account = Account.from_key(privkey)
     except Exception as e:
         raise BcosException("load account from {} failed, reason: {}"
                             .format(self.keystore_file, e))
예제 #9
0
    def load_default_account(self):
        if client_config.crypto_type == CRYPTO_TYPE_GM:
            # 加载国密账号
            if self.gm_account is not None:
                return  # 不需要重复加载
            try:
                self.gm_account = GM_Account()
                self.gm_account_file = "{}/{}".format(
                    client_config.account_keyfile_path,
                    client_config.gm_account_keyfile)
                if os.path.exists(self.gm_account_file) is False:
                    raise BcosException(
                        ("gm account keyfile file {} doesn't exist, "
                         "please check client_config.py again "
                         "and make sure this account exist").format(
                             self.gm_account_file))
                self.gm_account.load_from_file(
                    self.gm_account_file, client_config.gm_account_password)
                self.keypair = self.gm_account.keypair
                return
            except Exception as e:
                raise BcosException(
                    "load gm account from {} failed, reason: {}".format(
                        self.gm_account_file, e))

        # 默认的 ecdsa 账号
        try:
            if self.ecdsa_account is not None:
                return  # 不需要重复加载
            # check account keyfile
            self.keystore_file = "{}/{}".format(
                client_config.account_keyfile_path,
                client_config.account_keyfile)
            if os.path.exists(self.keystore_file) is False:
                raise BcosException(
                    ("keystore file {} doesn't exist, "
                     "please check client_config.py again "
                     "and make sure this account exist").format(
                         self.keystore_file))
            with open(self.keystore_file, "r") as dump_f:
                keytext = json.load(dump_f)
                privkey = Account.decrypt(keytext,
                                          client_config.account_password)
                self.ecdsa_account = Account.from_key(privkey)
                keypair = BcosKeyPair()
                keypair.private_key = self.ecdsa_account.privateKey
                keypair.public_key = self.ecdsa_account.publickey
                keypair.address = self.ecdsa_account.address
                self.keypair = keypair
        except Exception as e:
            raise BcosException(
                "load account from {} failed, reason: {}".format(
                    self.keystore_file, e))
예제 #10
0
 def login(self, username, password):
     keystore_file = "{}/{}".format(client_config.account_keyfile_path,
                                         username + ".keystore")
     if os.path.exists(keystore_file) is False:
         return -1
     try:
         with open(keystore_file, "r") as dump_f:
             keytext = json.load(dump_f)
             privkey = Account.decrypt(keytext, password)
             self.client.client_account = Account.from_key(privkey)
     except Exception as e:
         return -1
     return 0
예제 #11
0
 def sign(self, username, password, info):
     keystore_file = "{}/{}".format(client_config.account_keyfile_path,
                                         username + ".keystore")
     if os.path.exists(keystore_file) is False:
         return -1
     try:
         with open(keystore_file, "r") as dump_f:
             keytext = json.load(dump_f)
             privkey = Account.decrypt(keytext, password)
             msg = encode_defunct(text=info)
             signed_msg = Account.sign_message(msg, privkey)
             v = signed_msg['v']
             r = signed_msg['r']
             s = signed_msg['s']
             return v, r, s
     except Exception as e:
         print(e)
         return -1
예제 #12
0
        def create_ecdsa_account(name, password, forcewrite):
            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()
예제 #13
0
    def press_register(self):
        name, password, balance = self.line_name.text(), self.line_pwd.text(
        ), self.line_balance.text()
        # balabce代表启动资金
        balance = int(balance)
        if len(name) > 256:
            QMessageBox.warning(self, 'Error', '名称过长。')
            sys.exit(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)

        kf = Account.encrypt(ac.privateKey, password)
        keyfile = "{}/{}.keystore".format(client_config.account_keyfile_path,
                                          name)
        print("save to file : [{}]".format(keyfile))
        with open(keyfile, "w") as dump_f:
            json.dump(kf, dump_f)
            dump_f.close()
        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)
            privkey = Account.decrypt(keytext, password)
            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))
            dump_f.close()

        global client, contract_abi, to_address
        args = [name, ac.address, 'Company', balance]
        # 调用智能合约中的register函数
        receipt = client.sendRawTransactionGetReceipt(to_address, contract_abi,
                                                      "register", args)
        print("receipt:", receipt['output'])

        QMessageBox.information(self, 'Prompt', '注册成功。', QMessageBox.Ok)
예제 #14
0
def test_keystore():
    ac1 = Account.create('123456')
    print(ac1.address)
    print(encode_hex(ac1.key))
    print(ac1.publickey)
    print()

    kf = Account.encrypt(ac1.privateKey, "123456")
    print(kf)
    keyfile = "d:/blockchain/accounts/pyaccount.keystore"
    with open(keyfile, "w") as dump_f:
        json.dump(kf, dump_f)

    with open(keyfile, "r") as dump_f:
        keytext = json.load(dump_f)
        privkey = Account.decrypt(keytext, "123456")
        ac2 = Account.from_key(privkey)
        print("read from file:", ac2.address)
        print(encode_hex(ac2.key))
        print(ac2.publickey)
예제 #15
0
 def unlock_account(self,
                    account: str,
                    password: str,
                    duration: int = None) -> bool:
     """
     Decrypt the signing material from the key metadata file and cache it on
     the keystore instance is decryption is successful.
     """
     if not self.__signers.get(account):
         try:
             key_metadata = self.__keys[account]
         except ValueError:
             return False  # Decryption Failed
         except KeyError:
             raise self.UnknownAccount(account=account)
         else:
             # TODO: It is possible that password is None here passed form the above leayer,
             #       causing Account.decrypt to crash, expecting a value for password.
             signing_key = Account.from_key(
                 Account.decrypt(key_metadata, password))
             self.__signers[account] = signing_key
     return True
예제 #16
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)
예제 #17
0
    #--------------------------------------------------------------------------------------------
    validcmds.append("showaccount")
    usagemsg.append('''showaccount [name] [password]
    指定帐户名字(不带后缀)和密码,打开配置文件里默认账户文件路径下的[name].keystore文件,打印公私钥和地址
    ''')
    if cmd == 'showaccount':
        name = inputparams[0]
        password = inputparams[1]
        keyfile = "{}/{}.keystore".format(client_config.account_keyfile_path,
                                          name)
        print("show account : {}, keyfile:{} ,password {}  ".format(
            name, keyfile, password))
        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 !!! *****")

    validcmds.append("newaccount")
    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]
'''
  @author: kentzhang
  @date: 2019-06
'''
from eth_account.account import (Account)
from eth_utils.hexadecimal import encode_hex

ac1 = Account.create('123456')
print(ac1.address)
print(encode_hex(ac1.key))
print(ac1.publickey)
print()

kf = Account.encrypt(ac1.privateKey, "123456")
print(kf)
import json
keyfile = "d:/blockchain/accounts/pyaccount.keystore"
with open(keyfile, "w") as dump_f:
    json.dump(kf, dump_f)

with open(keyfile, "r") as dump_f:
    keytext = json.load(dump_f)
    privkey = Account.decrypt(keytext, "123456")
    ac2 = Account.from_key(privkey)
    print("read from file:", ac2.address)
    print(encode_hex(ac2.key))
    print(ac2.publickey)