Exemplo n.º 1
0
 def get(self, request, format=None):
     safe_funder_public_key = Account.from_key(settings.SAFE_FUNDER_PRIVATE_KEY).address \
         if settings.SAFE_FUNDER_PRIVATE_KEY else None
     safe_sender_public_key = Account.from_key(settings.SAFE_TX_SENDER_PRIVATE_KEY).address \
         if settings.SAFE_TX_SENDER_PRIVATE_KEY else None
     content = {
         'name': 'Safe Relay Service',
         'version': __version__,
         'api_version': self.request.version,
         'https_detected': self.request.is_secure(),
         'settings': {
             'ETHEREUM_NODE_URL':
             settings.ETHEREUM_NODE_URL,
             'ETH_HASH_PREFIX ':
             settings.ETH_HASH_PREFIX,
             'FIXED_GAS_PRICE':
             settings.FIXED_GAS_PRICE,
             'GAS_STATION_NUMBER_BLOCKS':
             settings.GAS_STATION_NUMBER_BLOCKS,
             'NOTIFICATION_SERVICE_PASS':
             bool(settings.NOTIFICATION_SERVICE_PASS),
             'NOTIFICATION_SERVICE_URI':
             settings.NOTIFICATION_SERVICE_URI,
             'SAFE_ACCOUNTS_BALANCE_WARNING':
             settings.SAFE_ACCOUNTS_BALANCE_WARNING,
             'SAFE_CHECK_DEPLOYER_FUNDED_DELAY':
             settings.SAFE_CHECK_DEPLOYER_FUNDED_DELAY,
             'SAFE_CHECK_DEPLOYER_FUNDED_RETRIES':
             settings.SAFE_CHECK_DEPLOYER_FUNDED_RETRIES,
             'SAFE_CONTRACT_ADDRESS':
             settings.SAFE_CONTRACT_ADDRESS,
             'SAFE_DEFAULT_CALLBACK_HANDLER':
             settings.SAFE_DEFAULT_CALLBACK_HANDLER,
             'SAFE_FIXED_CREATION_COST':
             settings.SAFE_FIXED_CREATION_COST,
             'SAFE_FUNDER_MAX_ETH':
             settings.SAFE_FUNDER_MAX_ETH,
             'SAFE_FUNDER_PUBLIC_KEY':
             safe_funder_public_key,
             'SAFE_FUNDING_CONFIRMATIONS':
             settings.SAFE_FUNDING_CONFIRMATIONS,
             'SAFE_PROXY_FACTORY_ADDRESS':
             settings.SAFE_PROXY_FACTORY_ADDRESS,
             'SAFE_PROXY_FACTORY_V1_0_0_ADDRESS':
             settings.SAFE_PROXY_FACTORY_V1_0_0_ADDRESS,
             'SAFE_TX_NOT_MINED_ALERT_MINUTES':
             settings.SAFE_TX_NOT_MINED_ALERT_MINUTES,
             'SAFE_TX_SENDER_PUBLIC_KEY':
             safe_sender_public_key,
             'SAFE_V0_0_1_CONTRACT_ADDRESS':
             settings.SAFE_V0_0_1_CONTRACT_ADDRESS,
             'SAFE_V1_0_0_CONTRACT_ADDRESS':
             settings.SAFE_V1_0_0_CONTRACT_ADDRESS,
             'SAFE_VALID_CONTRACT_ADDRESSES':
             settings.SAFE_VALID_CONTRACT_ADDRESSES,
         }
     }
     return Response(content)
Exemplo n.º 2
0
 def set_account_by_privkey(self, privkey):
     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
Exemplo n.º 3
0
def test_sign():
    print("sign test")
    # ac = Account.create("123456")
    # print("account priv key: ", ac.privateKey)
    privkey = "52413c714e418cc6fb06afb1bc3f6c54449c89a82a17c9a117a5aa0bad56a9cd"
    binprivkey = codecs.decode(privkey, "hex")
    pubkey = private_key_to_public_key(binprivkey)

    print("binary priv key: ", decode_hex(privkey))
    print("binary pub key: ", pubkey)
    acforverify = Account.from_key(binprivkey)
    msg = b"this is a test"
    msghash = keccak(msg)
    sig = acforverify._key_obj.sign_msg_hash(msghash)
    print("pulic key :", acforverify.publickey)
    vresult = sig.verify_msg_hash(msghash, acforverify.publickey)
    print("verify result ", vresult)
    (v, r, s) = ecdsa_raw_sign(msghash, decode_hex(privkey))

    vres = ecdsa_raw_verify(msghash, (r, s), pubkey)
    print("ecdsa raw verify: ", vres)

    recoverres = ecdsa_raw_recover(msghash, (v, r, s))
    print("raw recover result", recoverres)
    print("hex recover result", encode_hex(recoverres))
Exemplo n.º 4
0
def test_p12():

    p12filename = "bin/0xea5d262806c5771ae57e8fe4051c91d62b1d67bf.p12"
    with open(p12filename, "rb") as f:

        p12buff = f.read()
        pwd = b"123456"
        (key, cert,
         additional_certificates) = pkcs12.load_key_and_certificates(
             bytes(p12buff), password=pwd, backend=default_backend())
        print("p12 privkey :", key)
        print("p12 privkey size:", key.key_size)
        print("p12 public  bytes:", key.public_key)

        # 用crypto加载p12文件,会有warning "PKCS#12 support in pyOpenSSL is deprecated.
        # You should use the APIs in cryptography."
        crypto_p12 = crypto.load_pkcs12(p12buff, pwd)
        print("crypto_p12: ", crypto_p12)
        print("crypto_p12 privatekey  : ", crypto_p12.get_privatekey())

        # 用cryto可以导出私钥到pem,但目前不能导出到p12
        privatekey = crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                            crypto_p12.get_privatekey())
        print("private pem :", privatekey)
        key = SigningKey.from_pem(privatekey)
        print("privkey : ", encode_hex(key.to_string()))
        ac2 = Account.from_key(encode_hex(key.to_string()))
        print("pubkey: ", ac2.publickey)
        print("address: ", ac2.address)
        f.close()
Exemplo n.º 5
0
def get_signature(message: str, key: str) -> dict:
    """ 
    Returns the signature of the given
    message when signed using the reveived
    key as the private key.

    :param message: string
    :param key: string
    :return: dict

        The key param will be interpreted as
        a hex string if possible. In that way,
        if an existing private key is received
        in hex form, the returned signature would
        be the same as if signed from the original
        wallet possesing that key.
        Otherwise a 32 bytes private key will be
        formed by adding leading null-bytes to
        the bytes of the received string.

    """
    try:
        key = bytes.fromhex(key)
    except ValueError:
        key = bytes(key, 'utf-8')
    key = (b'\00' * 32 + key)[-32:]
    acc = Account.from_key(key)

    # the received message is encoded as in EIP-191 "version ``E``"
    encoded = encode_defunct(text=message)

    signed = acc.sign_message(encoded)['signature'].hex()
    return {"address": acc.address, "signature": signed, "message": message}
Exemplo n.º 6
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))
Exemplo n.º 7
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)
Exemplo n.º 8
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
Exemplo n.º 9
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
Exemplo n.º 10
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
Exemplo n.º 11
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)
Exemplo n.º 12
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))
Exemplo n.º 13
0
 def load_from_pem(filename):
     with open(filename) as f:
         p = f.read()
         # print("pem file:", p)
         key = SigningKey.from_pem(p)
         # print("privkey : ", encode_hex(key.to_string()))
         ac = Account.from_key(encode_hex(key.to_string()))
         f.close()
         return ac
Exemplo n.º 14
0
 def get(self, request, format=None):
     safe_funder_public_key = (
         Account.from_key(settings.SAFE_FUNDER_PRIVATE_KEY).address
         if settings.SAFE_FUNDER_PRIVATE_KEY
         else None
     )
     safe_sender_public_key = (
         Account.from_key(settings.SAFE_TX_SENDER_PRIVATE_KEY).address
         if settings.SAFE_TX_SENDER_PRIVATE_KEY
         else None
     )
     content = {
         "name": "Safe Relay Service",
         "version": __version__,
         "api_version": self.request.version,
         "https_detected": self.request.is_secure(),
         "settings": {
             "ETHEREUM_NODE_URL": settings.ETHEREUM_NODE_URL,
             "ETH_HASH_PREFIX ": settings.ETH_HASH_PREFIX,
             "FIXED_GAS_PRICE": settings.FIXED_GAS_PRICE,
             "GAS_STATION_NUMBER_BLOCKS": settings.GAS_STATION_NUMBER_BLOCKS,
             "NOTIFICATION_SERVICE_PASS": bool(settings.NOTIFICATION_SERVICE_PASS),
             "NOTIFICATION_SERVICE_URI": settings.NOTIFICATION_SERVICE_URI,
             "SAFE_ACCOUNTS_BALANCE_WARNING": settings.SAFE_ACCOUNTS_BALANCE_WARNING,
             "SAFE_CHECK_DEPLOYER_FUNDED_DELAY": settings.SAFE_CHECK_DEPLOYER_FUNDED_DELAY,
             "SAFE_CHECK_DEPLOYER_FUNDED_RETRIES": settings.SAFE_CHECK_DEPLOYER_FUNDED_RETRIES,
             "SAFE_DEFAULT_CALLBACK_HANDLER": settings.SAFE_DEFAULT_CALLBACK_HANDLER,
             "SAFE_FIXED_CREATION_COST": settings.SAFE_FIXED_CREATION_COST,
             "SAFE_FUNDER_MAX_ETH": settings.SAFE_FUNDER_MAX_ETH,
             "SAFE_FUNDER_PUBLIC_KEY": safe_funder_public_key,
             "SAFE_FUNDING_CONFIRMATIONS": settings.SAFE_FUNDING_CONFIRMATIONS,
             "SAFE_PROXY_FACTORY_ADDRESS": settings.SAFE_PROXY_FACTORY_ADDRESS,
             "SAFE_PROXY_FACTORY_V1_0_0_ADDRESS": settings.SAFE_PROXY_FACTORY_V1_0_0_ADDRESS,
             "SAFE_TX_NOT_MINED_ALERT_MINUTES": settings.SAFE_TX_NOT_MINED_ALERT_MINUTES,
             "SAFE_TX_SENDER_PUBLIC_KEY": safe_sender_public_key,
             "SAFE_V0_0_1_CONTRACT_ADDRESS": settings.SAFE_V0_0_1_CONTRACT_ADDRESS,
             "SAFE_V1_0_0_CONTRACT_ADDRESS": settings.SAFE_V1_0_0_CONTRACT_ADDRESS,
             "SAFE_V1_1_1_CONTRACT_ADDRESS": settings.SAFE_V1_1_1_CONTRACT_ADDRESS,
             "SAFE_CONTRACT_ADDRESS": settings.SAFE_CONTRACT_ADDRESS,
             "SAFE_VALID_CONTRACT_ADDRESSES": settings.SAFE_VALID_CONTRACT_ADDRESSES,
         },
     }
     return Response(content)
Exemplo n.º 15
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))
Exemplo n.º 16
0
def test_pem():
    privkeyfile = "bin/0x2de5c210370daef452eb610af76c3a293ae1661f.pem.save"
    with open(privkeyfile) as f:
        p = f.read()
        print("pem file:", p)
        key = SigningKey.from_pem(p)
        print("privkey : ", encode_hex(key.to_string()))

        ac2 = Account.from_key(encode_hex(key.to_string()))
        print("pubkey: ", ac2.publickey)
        print("address: ", ac2.address)
        toPem = SigningKey.to_pem(key)
        print("pem from key", toPem)
Exemplo n.º 17
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
Exemplo n.º 18
0
    def load_default_account(self):
        try:

            self.client_account = Account.from_key(
                0xfb06406e4bd0f81ade6bd7da2015f634d52651e0e2dac8caeca1a8044b17ec48
            )
            # 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))
Exemplo n.º 19
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()
Exemplo n.º 20
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)
Exemplo n.º 21
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)
def run_test(test):
    global g_counter
    global g_failed_gas_check
    g_counter += 1
    trx = test['transaction']
    transaction_index = 0
    for data in trx['data']:
        for gas_limit in trx['gasLimit']:
            for value in trx['value']:
                prepare_env(test['pre'])

                value = hex2int(value)
                gas_price = hex2int(trx['gasPrice'])
                nonce = hex2int(trx['nonce'])
                to = trx['to']
                secret_key = trx['secretKey']
                a = Account.from_key('0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8')
                _from = a.address[2:]

                transaction = dict(nonce=nonce,
                                    gasPrice=gas_price,
                                    gas=gas_limit,
#                                    to=to,
                                    value=value,
                                    data=data)
                logger.info((_from, nonce))
                transaction = evm.pack_transaction(transaction)
                args = {'trx': transaction, 'sender': _from}
                ret = eosapi.push_action('helloworld11', 'raw2', args, {'helloworld11':'active'})
                output = ret['processed']['action_traces'][0]['console']
                logger.info(("++++logs:", output))
                output = bytes.fromhex(output)
                output = rlp.decode(output)
                logs = output[2]
                # logger.info(logs)
                logs = rlp.encode(logs)
                h = keccak(logs)

                assert h.hex() == test['post']['Istanbul'][transaction_index]['logs'][2:]

                transaction_index += 1
Exemplo n.º 23
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
Exemplo n.º 24
0
 def set_account_by_keystorefile(self, account_keyfile):
     try:
         self.keystore_file = "{}/{}".format(
             client_config.account_keyfile_path, 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 = keytext["privateKey"]
             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))
Exemplo n.º 25
0
def private_key_to_account(val: _PrivateKey) -> Account:
    normalized_key = key_normalizer(val)
    return Account.from_key(normalized_key)
Exemplo n.º 26
0
    指定帐户名字(不带后缀)和密码,打开配置文件里默认账户文件路径下的[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]
    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'''.format(
        client_config.account_keyfile_path))
Exemplo n.º 27
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)
Exemplo n.º 28
0
def private_key_to_address(private_key: str) -> str:
    return Account.from_key(private_key).address
Exemplo n.º 29
0
 txmap = dict()
 txmap["randomid"] = 10003  # 测试用 todo:改为随机数
 txmap["gasPrice"] = 30000000
 txmap["gasLimit"] = 30000000
 txmap["blockLimit"] = 501  # 测试用,todo:从链上查一下
 txmap["to"] = contractAddress
 txmap["value"] = 0
 txmap["data"] = set_tx_data
 txmap["fiscoChainId"] = 1
 txmap["groupId"] = 1
 txmap["extraData"] = ""
 # 将mapping构建一个transaction对象,非必要,用来对照的
 transaction = serializable_unsigned_transaction_from_dict(txmap)
 # 感受下transaction encode的原始数据
 print(encode_hex(rlp.encode(transaction)))
 ac3 = Account.from_key(
     "255f01b066a90853a0aa18565653d7b944cd2048c03613a9ff31cb9df9e693e5")
 print("test from key")
 print("read from file: address", ac3.address)
 print("pubkey: ", ac3.publickey)
 print("privkey: ", encode_hex(ac3.key))
 # 实际上只需要用sign_transaction就可以获得rawTransaction的编码数据了,input :txmap,私钥
 signedTxResult = Account.sign_transaction(txmap, ac3.privateKey)
 print(signedTxResult)
 print(encode_hex(signedTxResult["rawTransaction"]))
 if False:
     #call encode
     fn_name = "get"
     contract_abi = parser.contract_abi
     args = []
     res = encode_transaction_data(fn_name, contract_abi, None, args)
     print("tx data:", res)
Exemplo n.º 30
0
    privkey = "52413c714e418cc6fb06afb1bc3f6c54449c89a82a17c9a117a5aa0bad56a9cd"
    binprivkey = codecs.decode(privkey, "hex")
    pubkey = private_key_to_public_key(binprivkey)

    print("binary priv key: ", decode_hex(privkey))
    print("binary pub key: ", pubkey)
    acforverify = Account.from_key(binprivkey)
    msg = b"this is a test"
    msghash = keccak(msg)
    sig = acforverify._key_obj.sign_msg_hash(msghash)
    print("pulic key :", acforverify.publickey)
    vresult = sig.verify_msg_hash(msghash, acforverify.publickey)
    print("verify result ", vresult)
    (v, r, s) = ecdsa_raw_sign(msghash, decode_hex(privkey))

    vres = ecdsa_raw_verify(msghash, (r, s), pubkey)
    print("ecdsa raw verify: ", vres)

    recoverres = ecdsa_raw_recover(msghash, (v, r, s))
    print("raw recover result", recoverres)
    print("hex recover result", encode_hex(recoverres))


#test_p12()
# test_pem()
#test_sign()
ac1 = Account.from_key(
    "6eb7d91a86ee378defd30ef8abb9b72499845c05846a2d408583f0e1a4903f5d")
print(ac1.address)
print(encode_hex(ac1.key))
print(ac1.publickey)