Beispiel #1
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()
Beispiel #2
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)
Beispiel #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))
Beispiel #4
0
 def show_ecdsa_account(self, name, password):
     keyfile = "{}/{}".format(client_config.account_keyfile_path, name)
     if os.path.exists(keyfile) is False:
         keyfile = "{}/{}.keystore".format(
             client_config.account_keyfile_path, name)
         if os.path.exists(keyfile) is True and password is None:
             raise BcosException(
                 "When loading an account file in keystore format, a password must be provided"
             )
     # the keystore doesn't exists,try pem
     if os.path.exists(keyfile) is False:
         keyfile = "{}/{}.pem".format(client_config.account_keyfile_path,
                                      name)
     print("keyfile", keyfile)
     if os.path.exists(keyfile) is False:
         raise BcosException("account {} doesn't exists in path:{}".format(
             name, client_config.account_keyfile_path))
     # go to load from file
     print("show account : {}, keyname:{} ,password {}  ".format(
         name, keyfile, password))
     try:
         stat = StatTool.begin()
         ac = Signer_ECDSA.load_from_keyfile(keyfile, password)
         stat.done()
         print("decrypt use time : %.3f s" % (stat.time_used))
         print("address:\t", ac.address)
         print("privkey:\t", encode_hex(ac.key))
         print("pubkey :\t", ac.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))
        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))
Beispiel #6
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)
Beispiel #7
0
 def get_private_key_from_mnemonic(
         mnemonic: str,
         passphrase: str = "",
         hdpath: str = hdaccount.ETHEREUM_DEFAULT_PATH) -> bytes:
     seed = account.seed_from_mnemonic(mnemonic, passphrase)
     key = account.key_from_seed(seed, hdpath)
     hex_key = encode_hex(key)
     return hex_key[2:]
Beispiel #8
0
def encode_nodes(accounts):
    encoded_accounts = []
    for index in range(0, len(accounts)):
        data = accounts[index]
        encoded = encode_hex(
            encode_abi(["uint256", "address", "uint256"],
                       (index, data["account"], data["score"])))
        encoded_accounts.append(encoded)
    return encoded_accounts
Beispiel #9
0
    def sendRawTransaction(self,
                           to_address,
                           contract_abi,
                           fn_name,
                           args=None,
                           bin_data=None,
                           gasPrice=30000000,
                           packet_type=ChannelPack.TYPE_RPC):
        cmd = "sendRawTransaction"
        if to_address != "":
            common.check_and_format_address(to_address)
        # 第三个参数是方法的abi,可以传入None,encode_transaction_data做了修改,支持通过方法+参数在整个abi里找到对应的方法abi来编码

        if bin_data is None:
            functiondata = encode_transaction_data(fn_name, contract_abi, None,
                                                   args)
        # the args is None
        elif args is None:
            functiondata = bin_data
        # deploy with params
        else:
            fn_data = get_aligned_function_data(contract_abi, None, args)
            functiondata = bin_data + fn_data[2:]

        if to_address is not None and len(to_address) > 0:
            from eth_utils import to_checksum_address
            to_address = to_checksum_address(to_address)

        # load default account if not set .notice: account only use for
        # sign transaction for sendRawTransa# if self.client_account is None:
        self.load_default_account()
        # 填写一个bcos transaction 的 mapping
        import random
        txmap = dict()
        txmap["randomid"] = random.randint(0, 1000000000)  # 测试用 todo:改为随机数
        txmap["gasPrice"] = gasPrice
        txmap["gasLimit"] = gasPrice
        txmap["blockLimit"] = self.getBlockLimit()  # 501  # 测试用,todo:从链上查一下

        txmap["to"] = to_address
        txmap["value"] = 0
        txmap["data"] = functiondata
        txmap["fiscoChainId"] = self.fiscoChainId
        txmap["groupId"] = self.groupid
        txmap["extraData"] = ""
        #print("\n>>>>functiondata ",functiondata)
        sign = SignTx()
        sign.crypto_type = client_config.crypto_type
        # 关键流程:对交易签名,重构后全部统一到 SignTx 类(client/signtransaction.py)完成
        sign.gm_account = self.gm_account
        sign.ecdsa_account = self.ecdsa_account
        signed_result = sign.sign_transaction(txmap)
        #print("@@@@@rawTransaction : ",encode_hex(signedTxResult.rawTransaction))
        # signedTxResult.rawTransaction是二进制的,要放到rpc接口里要encode下
        params = [self.groupid, encode_hex(signed_result.rawTransaction)]
        result = self.common_request(cmd, params, packet_type)
        return result
        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()
Beispiel #11
0
    def sendRawTransaction(self, to_address, contract_abi, fn_name, args=None,
                           bin_data=None, gasPrice=30000000,
                           packet_type=ChannelPack.TYPE_RPC):
        cmd = "sendRawTransaction"
        if to_address != "":
            common.check_and_format_address(to_address)
        # 第三个参数是方法的abi,可以传入None,encode_transaction_data做了修改,支持通过方法+参数在整个abi里找到对应的方法abi来编码

        if bin_data is None:
            functiondata = encode_transaction_data(fn_name, contract_abi, None, args)
        # the args is None
        elif args is None:
            functiondata = bin_data
        # deploy with params
        else:
            fn_data = get_aligned_function_data(contract_abi, None, args)
            functiondata = bin_data + fn_data[2:]

        if to_address is not None and len(to_address) > 0:
            from eth_utils import to_checksum_address
            to_address = to_checksum_address(to_address)

        # load default account if not set .notice: account only use for
        # sign transaction for sendRawTransaction
        if self.client_account is None:
            self.load_default_account()
        # 填写一个bcos transaction 的 mapping
        import random
        txmap = dict()
        txmap["randomid"] = random.randint(0, 1000000000)  # 测试用 todo:改为随机数
        txmap["gasPrice"] = gasPrice
        txmap["gasLimit"] = gasPrice
        txmap["blockLimit"] = self.getBlockLimit()  # 501  # 测试用,todo:从链上查一下

        txmap["to"] = to_address
        txmap["value"] = 0
        txmap["data"] = functiondata
        txmap["fiscoChainId"] = self.fiscoChainId
        txmap["groupId"] = self.groupid
        txmap["extraData"] = ""
        '''
        from datatypes.bcostransactions import (
            serializable_unsigned_transaction_from_dict,
        )
        # 将mapping构建一个transaction对象,非必要,用来对照的
        transaction = serializable_unsigned_transaction_from_dict(txmap)
        # 感受下transaction encode的原始数据
        print(encode_hex(rlp.encode(transaction)))
        '''

        # 实际上只需要用sign_transaction就可以获得rawTransaction的编码数据了,input :txmap,私钥
        signedTxResult = Account.sign_transaction(txmap, self.client_account.privateKey)
        # signedTxResult.rawTransaction是二进制的,要放到rpc接口里要encode下
        params = [self.groupid, encode_hex(signedTxResult.rawTransaction)]
        result = self.common_request(cmd, params, packet_type)
        return result
Beispiel #12
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)
Beispiel #13
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)
Beispiel #14
0
def sig_to_vrs(sig):
    """ Split a signature into r, s, v components """
    r = sig[:32]
    s = sig[32:64]
    v = int(encode_hex(sig[64:66]), 16)

    # Ethereum magic number
    if v in (0, 1):
        v += 27

    return [r, s, v]
Beispiel #15
0
    def to_node_entry(self, user, userData, cycle, index):
        """
        Use abi.encode() to encode data into the hex format used as raw node information in the tree
        This is the value that will be hashed to form the rest of the tree  
        """
        nodeEntry = {
            "user": user,
            "tokens": [],
            "cumulativeAmounts": [],
            "cycle": cycle,
            "index": index,
        }
        intAmounts = []
        for tokenAddress, cumulativeAmount in userData.items():
            nodeEntry["tokens"].append(tokenAddress)
            nodeEntry["cumulativeAmounts"].append(str(cumulativeAmount))
            intAmounts.append(int(cumulativeAmount))

        # print(
        #     int(nodeEntry["index"]),
        #     nodeEntry["user"],
        #     int(nodeEntry["cycle"]),
        #     nodeEntry["tokens"],
        #     intAmounts,
        # )

        encoded = encode_hex(
            encode_abi(
                ["uint", "address", "uint", "address[]", "uint[]"],
                (
                    int(nodeEntry["index"]),
                    nodeEntry["user"],
                    int(nodeEntry["cycle"]),
                    nodeEntry["tokens"],
                    intAmounts,
                ),
            ))

        # encoder = ClaimEncoder.at(web3.toChecksumAddress("0xf3ff1a5856b1726a8fef921ea57eab2c51466a93"))
        # claim = encoder.encodeClaim(
        #     nodeEntry["tokens"],
        #     nodeEntry["cumulativeAmounts"],
        #     nodeEntry["user"],
        #     nodeEntry["index"],
        #     nodeEntry["cycle"],
        # )[0]

        # console.log("nodeEntry", nodeEntry)
        # print("encoded", encoded)
        # print("claim", claim)

        return (nodeEntry, encoded)
Beispiel #16
0
    def to_node_entry(self, user, userData, cycle, index):
        nodeEntry = {
            "user": user,
            "tokens": [],
            "cumulativeAmounts": [],
            "cycle": cycle,
            "index": index,
        }
        for tokenAddress, cumulativeAmount in userData.items():
            nodeEntry["tokens"].append(tokenAddress)
            nodeEntry["cumulativeAmounts"].append(str(cumulativeAmount))

        # encoded = encode_hex(
        #     encode_abi_packed(
        #         ["uint", "address", "uint", "address[]", "uint[]"],
        #         (
        #             nodeEntry["index"],
        #             nodeEntry["user"],
        #             nodeEntry["cycle"],
        #             nodeEntry["tokens"],
        #             nodeEntry["cumulativeAmounts"],
        #         ),
        #     )
        # )

        encoder = ClaimEncoder.at("0x19be80e976cb397ae584d350153914ced7c1b1d2")

        claim = encoder.encodeClaim(
            nodeEntry["tokens"],
            nodeEntry["cumulativeAmounts"],
            nodeEntry["index"],
            nodeEntry["cycle"],
            nodeEntry["user"],
        )[0]

        local = encoder.encodeClaim.encode_input(
            nodeEntry["tokens"],
            nodeEntry["cumulativeAmounts"],
            nodeEntry["index"],
            nodeEntry["cycle"],
            nodeEntry["user"],
        )

        console.log("claimcheck", claim, local)

        encoded = encode_hex(claim)

        # console.log("nodeEntry", nodeEntry)
        # console.log("encoded", encoded)
        return (nodeEntry, encoded)
Beispiel #17
0
def valid_metamask_message(address, message, signature):
    #address = attrs['address']
    #message = attrs['msg']
    #signature = attrs['signed_msg']

    r = int(signature[0:66], 16)
    s = int(add_0x_prefix(signature[66:130]), 16)
    v = int(add_0x_prefix(signature[130:132]), 16)
    if v not in (27, 28):
        v += 27

    message_hash = defunct_hash_message(text=message)
    pubkey = ecrecover_to_pub(decode_hex(message_hash.hex()), v, r, s)
    signer_address = encode_hex(sha3(pubkey)[-20:])

    if signer_address != address.lower():
        raise ValidationError({'result': 'Incorrect signature'}, code=400)

    return True
Beispiel #18
0
def main():
    with open("merkle/badger_scores.json") as f:
        accounts = json.load(f)

    accounts = parse_accounts(accounts)

    encoded_accounts = encode_nodes(accounts)
    tree = MerkleTree(encoded_accounts)

    output = {"root": encode_hex(tree.root), "claims": {}}

    for index in range(0, len(accounts)):
        data = accounts[index]
        node = encoded_accounts[index]

        output["claims"][data["account"]] = {
            "account": data["account"],
            "score": data["score"],
            "proof": tree.get_proof(index),
            "node": node,
        }

    with open("merkle/yearn_merklelist.json", "w") as f:
        json.dump(output, f, indent=4)
Beispiel #19
0
    def to_node_entry(self, user, userData, cycle, index):
        """
        Use abi.encode() to encode data into the hex format used as raw node information in the tree
        This is the value that will be hashed to form the rest of the tree  
        """
        nodeEntry = {
            "user": user,
            "tokens": [],
            "cumulativeAmounts": [],
            "cycle": cycle,
            "index": index,
        }
        intAmounts = []
        for tokenAddress, cumulativeAmount in userData.items():
            nodeEntry["tokens"].append(tokenAddress)
            nodeEntry["cumulativeAmounts"].append(str(int(cumulativeAmount)))
            intAmounts.append(int(cumulativeAmount))


        # console.print(
        #     "Encoding Node entry...",
        #     {
        #         "index": int(nodeEntry["index"]),
        #         "account": nodeEntry["user"],
        #         "cycle": int(nodeEntry["cycle"]),
        #         "tokens": nodeEntry["tokens"],
        #         "cumulativeAmounts": nodeEntry["cumulativeAmounts"],
        #         "(integer encoded)": intAmounts,
        #     }
        # )

        encoded_local = encode_hex(
            encode_abi(
                ["uint", "address", "uint", "address[]", "uint[]"],
                (
                    int(nodeEntry["index"]),
                    nodeEntry["user"],
                    int(nodeEntry["cycle"]),
                    nodeEntry["tokens"],
                    intAmounts,
                ),
            )
        )

        encoder = BadgerTree.at(web3.toChecksumAddress("0x660802Fc641b154aBA66a62137e71f331B6d787A"))

        # console.print("nodeEntry", nodeEntry)
        # console.print("encoded_local", encoded_local)

        # ===== Verify encoding on-chain =====
        # encoded_chain = encoder.encodeClaim(
        #     nodeEntry["tokens"],
        #     nodeEntry["cumulativeAmounts"],
        #     nodeEntry["user"],
        #     nodeEntry["index"],
        #     nodeEntry["cycle"],
        # )[0]

        # console.print("encoded_onchain", encoded_chain)
        # assert encoded_local == encoded_chain

        return (nodeEntry, encoded_local)
Beispiel #20
0
    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))
    if cmd == 'newaccount':
        name = inputparams[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)
def test_event_signature_to_log_topic(event_signature, expected):
    bytes_topic = event_signature_to_log_topic(event_signature)
    hex_topic = encode_hex(bytes_topic)
    assert hex_topic == expected
def test_event_abi_to_log_topic(event_abi, expected):
    bytes_topic = event_abi_to_log_topic(event_abi)
    hex_topic = encode_hex(bytes_topic)
    assert hex_topic == expected
def test_fn_signature_to_4byte_selector(signature, expected):
    bytes_selector = function_signature_to_4byte_selector(signature)
    hex_selector = encode_hex(bytes_selector)
    assert hex_selector == expected
def test_fn_abi_to_4byte_selector(fn_abi, expected):
    bytes_selector = function_abi_to_4byte_selector(fn_abi)
    hex_selector = encode_hex(bytes_selector)
    assert hex_selector == expected
'''
  @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)
    def to_node_entry(self, user, userData, cycle, index):
        nodeEntry = {
            "user": user,
            "tokens": [],
            "cumulativeAmounts": [],
            "cycle": cycle,
            "index": index,
        }
        intAmounts = []
        for tokenAddress, cumulativeAmount in userData.items():
            nodeEntry["tokens"].append(tokenAddress)
            nodeEntry["cumulativeAmounts"].append(str(cumulativeAmount))
            intAmounts.append(int(cumulativeAmount))

        # print(
        #     int(nodeEntry["index"]),
        #     nodeEntry["user"],
        #     int(nodeEntry["cycle"]),
        #     nodeEntry["tokens"],
        #     intAmounts,
        # )

        address = nodeEntry["tokens"][0]
        # print(address, address[2:])

        bytearray.fromhex(address[2:])

        encoded = encode_hex(
            encode_abi_packed(
                ["uint", "address", "uint", "address", "uint[]"],
                (
                    int(nodeEntry["index"]),
                    nodeEntry["user"],
                    int(nodeEntry["cycle"]),
                    address,
                    intAmounts,
                ),
            )
        )

        surgeryIndex = 64 + 40 + 64 + 2

        after = encoded[surgeryIndex:]
        before = encoded[0:surgeryIndex]
        before = before + "000000000000000000000000"

        postSurgery = before + after
        # print("post", postSurgery)

        # encoder = ClaimEncoder.at("0x19be80e976cb397ae584d350153914ced7c1b1d2")

        # claim = encoder.encodeClaim(
        #     nodeEntry["tokens"],
        #     nodeEntry["cumulativeAmounts"],
        #     nodeEntry["index"],
        #     nodeEntry["cycle"],
        #     nodeEntry["user"],
        # )[0]

        # local = encoder.encodeClaim.encode_input(
        #     nodeEntry["tokens"],
        #     nodeEntry["cumulativeAmounts"],
        #     nodeEntry["index"],
        #     nodeEntry["cycle"],
        #     nodeEntry["user"],
        # )

        # print("claim", claim)
        # print("encoded", encoded)

        # encoded = encode_hex(postSurgery)
        # print("encoded", encoded)

        # console.log("nodeEntry", nodeEntry)
        # console.log("encoded", encoded)
        return (nodeEntry, postSurgery)
Beispiel #28
0
import os
import time
from configobj import ConfigObj

from eth_utils.hexadecimal import encode_hex
import json
keyfile = "./bin/accounts/pyaccount.keystore"

# 从keystore打开一个公私钥对
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: address", ac2.address)
    print("pubkey: ", ac2.publickey)
    print("privkey: ", encode_hex(ac2.key))
    dump_f.close()

'''
    #也可以从私钥文本得到一个可用来签名的帐户对象
    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))
'''
# 从abi文件获得abi的文本定义
contractFile = r"./contracts/SimpleInfo.abi"
with open(contractFile, 'r') as load_f:
    contract_abi = json.load(load_f)
    load_f.close()
Beispiel #29
0
txmap["randomid"] = random.randint(0, 1000000000)  # 测试用 todo:改为随机数
txmap["gasPrice"] = 30000000
txmap["gasLimit"] = 30000000
txmap["blockLimit"] = 300  # 测试用,todo:从链上查一下
txmap["to"] = contractAddress
txmap["value"] = 0
txmap["data"] = functiondata
txmap["fiscoChainId"] = 1
txmap["groupId"] = 1
txmap["extraData"] = ""
# txmap["chainId"]=None #chainId没用了,fiscoChainId有用
print(txmap)
# 将mapping构建一个transaction对象,非必要,用来对照的
transaction = serializable_unsigned_transaction_from_dict(txmap)
# 感受下transaction encode的原始数据
print("[rlpencode transaction]", encode_hex(rlp.encode(transaction)))

# 实际上只需要用sign_transaction就可以获得rawTransaction的编码数据了,input :txmap,私钥

signedTxResult = signer.sign_transaction(txmap)

#print("signedTxResult",signedTxResult )
# signedTxResult.rawTransaction是二进制的,要放到rpc接口里要encode下
print("rawTransaction encode:", encode_hex(signedTxResult.rawTransaction))


def encode_transaction(unsigned_transaction, vrs):
    (v, r, s) = vrs
    chain_naive_transaction = dissoc(unsigned_transaction.as_dict(), 'v', 'r',
                                     's')
    signed_transaction = BcosTransaction(v=v,
Beispiel #30
0
    def send_transaction_getReceipt(self,
                                    fn_name,
                                    fn_args,
                                    gasPrice=30000000,
                                    isdeploy=False,
                                    from_account_signer=None):
        """
        send transactions to CNS contract with the givn function name and args
        """
        try:
            contract_abi, args = self.format_abi_args(fn_name, fn_args,
                                                      isdeploy)
            contract_bin = None
            if isdeploy is True and os.path.exists(
                    self.contract_bin_path) is True:
                with open(self.contract_bin_path, "rb") as f:
                    contract_bin = f.read()
                    f.close()
                    # print(contract_bin)
                    if self.contract_bin_path.endswith("wasm"):
                        contract_bin = encode_hex(contract_bin)
                    else:
                        contract_bin = bytes.decode(contract_bin, "utf-8")

                if contract_bin is not None and len(contract_bin) > 0x40000:
                    raise BcosException(
                        ("contract bin size overflow,"
                         " limit: 0x40000(256K), size: {})").format(
                             len(contract_bin), 16))

            receipt = super().sendRawTransactionGetReceipt(
                self.contract_addr,
                contract_abi,
                fn_name,
                args,
                contract_bin,
                gasPrice,
                from_account_signer=from_account_signer)
            # check status
            if "status" not in receipt.keys() or \
                    "output" not in receipt.keys():
                raise BcosError(-1, None,
                                ("send transaction failed"
                                 "for empty status and output,"
                                 "transaction receipt:{}").format(receipt))
            status = receipt["status"]
            status_code = int(status, 16)
            error_message = transaction_status_code.TransactionStatusCode.get_error_message(
                status_code)
            if error_message is not None:
                raise BcosException(
                    "call error, error message: {}".format(error_message))

            if receipt["output"] is None:
                raise TransactionException(receipt,
                                           ("send transaction failed,"
                                            "status: {}, gasUsed: {}").format(
                                                status, receipt["gasUsed"]))
            if fn_name is not None and fn_args is not None and self.dataparser is not None:
                output = self.dataparser.parse_receipt_output(
                    fn_name, receipt["output"])
            else:
                output = None
            return (receipt, output)
        except BcosError as e:
            self.logger.error(
                "send transaction failed, fn_name: {}, fn_args:{}, error_info:{}"
                .format(fn_name, fn_args, e))
            raise e
        except CompileError as e:
            self.logger.error(
                ("send transaction failed for compile soldity failed,"
                 "contract_path {}, error_info:{}").format(self.sol_path, e))
            raise e