Exemple #1
0
def mock_duplicate_sign(dtype,
                        sk,
                        blskey,
                        block_number,
                        epoch=0,
                        view_number=0,
                        block_index=0,
                        index=0):
    """
    forged double sign
    :param dtype:
    :param sk:
    :param blskey:
    :param block_number:
    :param epoch:
    :param view_number:
    :param block_index:
    :param index:
    :return:
    """
    if sys.platform in "linux,linux2":
        tool_file = abspath("tool/linux/duplicateSign")
        run("chmod +x {}".format(tool_file))
    else:
        tool_file = abspath("tool/win/duplicateSign.exe")

    output = run(
        "{} -dtype={} -sk={} -blskey={} -blockNumber={} -epoch={} -viewNumber={} -blockIndex={} -vindex={}"
        .format(tool_file, dtype, sk, blskey, block_number, epoch, view_number,
                block_index, index))
    if not output:
        raise Exception("unable to use double sign tool")
    return output.strip("\n")
Exemple #2
0
def generate_blskey():
    """
    generate bls public and private keys
    :return:
        bls_private_key
        bls_public_key
    """
    if sys.platform in "linux,linux2":
        tool_file = abspath("tool/linux/keytool")
        run("chmod +x {}".format(tool_file))
    else:
        tool_file = abspath("tool/win/keytool.exe")
    keypair = run("{} genblskeypair".format(tool_file))
    if not keypair:
        raise Exception("unable to use generate blskey tool")
    lines = keypair.split("\n")
    bls_private_key = ""
    bls_public_key = ""
    for l in lines:
        kv = l.split(":")
        if kv[0] == "PrivateKey":
            bls_private_key = kv[1].strip()
        elif kv[0] == "PublicKey ":
            bls_public_key = kv[1].strip()
    if not bls_private_key or not bls_public_key:
        raise Exception("Blskey cannot be generated")
    return bls_private_key, bls_public_key
    def test_consensus_and_deconsensus_signed_contract_set_and_get_function(self, pt1):
        '''
        非共识节点&共识节点 wasm签名合约输入、输出结果校验
        '''
        pt = PlatonContractTransaction(pt1)
        wasm_path = abspath('./data/contract/inputtest.wasm')
        abi_path = abspath(
            './data/contract/inputtest.cpp.abi.json')
        address = pt.eth.coinbase
        contract_address = self._singed_contract_deploy(
            pt, wasm_path, abi_path)
        set_value = -100

        # 合约set方法存入int型数值
        data_list = [encoder.encode_type(2), encoder.encode_string('set'),
                     encoder.encode_int('int64', set_value)]
        trans_hex = pt.signed_contract_transaction(
            address, contract_address, data_list, self.private_key)
        result = ''
        for i in range(3):
            try:
                result = pt.eth.waitForTransactionReceipt(trans_hex)
            except:
                pt.reconnect()
        assert result != '', "等待超时,交易哈希:{}".format(trans_hex)

        # 合约get方法获取存入的数值校验是否一致
        data_list_for_call = [encoder.encode_type(
            2), encoder.encode_string('get')]
        receive = pt.contract_call(
            address, contract_address, data_list_for_call)
        get_value = contract_call_result_decode(receive)
        assert get_value == set_value, 'get结果异常,预期值:{},实际结果:{}'.format(
            set_value, get_value)
        time.sleep(1)
    def test_consensus_and_deconsensus_contract_transaction(self, pt1):
        '''
        非共识节点&共识节点 wasm合约交易、event事件、call方法测试
        '''
        pt = PlatonContractTransaction(pt1)
        wasm_path = abspath('./data/contract/sum.wasm')
        abi_path = abspath('./data/contract/sum.cpp.abi.json')
        address = pt.eth.coinbase
        contract_address = contract_deploy(pt, wasm_path, abi_path)

        # 发送合约交易
        data_list = [encoder.encode_type(
            2), encoder.encode_string('set')]
        trans_hex = pt.contract_transaction(
            address, contract_address, data_list)
        try:
            result = pt.eth.waitForTransactionReceipt(trans_hex)
        except:
            assert False, "等待超时,交易哈希:{}".format(trans_hex)
        # 解析event事件
        topics = result['logs'][0]['topics']
        data = result['logs'][0]['data']
        event = Event(json.load(open(abi_path)))
        event_data = event.event_data(topics, data)
        assert 'set success' in event_data['create'][0], '合约交易失败,event事件无"set success"'
        # call方法查询交易结果
        data_list_for_call = [encoder.encode_type(
            2), encoder.encode_string('get')]
        receive = pt.contract_call(
            address, contract_address, data_list_for_call)
        decoded_sum_result = int.from_bytes(receive, 'big')
        assert decoded_sum_result == 1, '自增失败,预期自增后结果为1,实际值为{}'.format(
            decoded_sum_result)
Exemple #5
0
    def __init__(self,
                 conf_tmp: ConfTmpDir,
                 install_supervisor=True,
                 install_dependency=True,
                 init_chain=True,
                 is_need_static=True,
                 can_deploy=True):
        self.can_deploy = can_deploy
        # local must file
        self.platon_bin_file = conf.PLATON_BIN_FILE
        self.genesis_file = conf.GENESIS_FILE
        self.supervisor_file = conf.SUPERVISOR_FILE
        self.node_file = conf.NODE_FILE
        self.address_file = conf.ADDRESS_FILE
        self.account_file = conf.ACCOUNT_FILE
        self.config_json_file = conf.CONFIG_JSON_FILE
        # local cache directory
        self.root_tmp = conf_tmp.tmp_root_path
        self.node_tmp = conf_tmp.LOCAL_TMP_FILE_FOR_NODE
        self.server_tmp = conf_tmp.LOCAL_TMP_FILE_FOR_SERVER
        self.env_tmp = conf_tmp.LOCAL_TMP_FILE_FOR_ENV
        self.genesis_tmp = conf_tmp.GENESIS_FILE
        self.static_node_tmp = conf_tmp.STATIC_NODE_FILE
        self.config_json_tmp = conf_tmp.CONFIG_JSON_FILE

        # server dependent installation
        self.install_supervisor = install_supervisor
        self.install_dependency = install_dependency

        # chain deployment customization
        self.init_chain = init_chain
        self.is_need_static = is_need_static
        self.log_level = 5
        self.syncmode = "full"
        self.append_cmd = ""

        # maximum number of threads
        self.max_worker = 30

        # environment id
        self.env_id = None

        # server remote directory
        self.deploy_path = conf.DEPLOY_PATH
        self.remote_supervisor_tmp = "{}/tmp/supervisor_{}/".format(
            self.deploy_path, conf_tmp.dir)
        self.remote_compression_tmp_path = "{}/tmp/env_{}/".format(
            self.deploy_path, conf_tmp.dir)

        # log related
        self.bug_log = abspath("./bug_log")
        self.tmp_log = abspath("./tmp_log")
    def test_consensus_and_deconsensus_contract_deploy(self, pt1):
        '''
        非共识节点&共识节点 部署wasm合约测试
        '''
        pt = PlatonContractTransaction(pt1)
        wasm_path = abspath('./data/contract/sum.wasm')
        abi_path = abspath('./data/contract/sum.cpp.abi.json')

        # 部署合约
        contract_address = contract_deploy(pt, wasm_path, abi_path)
        assert contract_address is not None, '合约部署失败,合约地址为空'
        contract_code = pt.eth.getCode(contract_address)
        assert len(contract_code) > 3, '合约部署异常,getCode(contract_address)结果异常'
Exemple #7
0
 def deploy_contract(self):
     consensus_list, _ = get_node_list(self.node_yml)
     url = consensus_list[0]['url']
     wt = PlatonContractTransaction(url)
     addrress = wt.w3.toChecksumAddress(conf.ADDRESS)
     wt.w3.personal.unlockAccount(addrress, conf.PASSWORD, 99999999)
     log.info("部署合约")
     resp = wt.contract_deploy(
         get_byte_code(abspath('./data/contract/sum.wasm')),
         get_abi_bytes(abspath('./data/contract/sum.cpp.abi.json')),
         addrress)
     log.info("获取合约交易信息")
     result = wt.eth.waitForTransactionReceipt(resp)
     contract_address = result['contractAddress']
     contract_number = result['blockNumber']
     return contract_address, resp, contract_number
def setup_module():
    pt_multi = PlatonContractTransaction(node_url)
    for k, w in config_data.wasm.items():
        contract_address = contract_deploy(pt_multi, abspath(w),
                                           abspath(config_data.abi[k]))
        config_data.contract_address[k] = contract_address
    handle(config_data.contract_address)
    send_data = {
        "to": send_address,
        "from": address,
        "gas": '9000',
        "gasPrice": '1000000000',
        "value": Web3.toWei(200, 'ether'),
    }
    tx_hash = pt_multi.eth.sendTransaction(send_data)
    pt_multi.eth.waitForTransactionReceipt(tx_hash)
def ex_event(result, casedata):
    topics = result['logs'][0]['topics']
    d = result['logs'][0]['data']
    event = Event(
        json.load(open(abspath(config_data.abi[casedata["contract_name"]]))))
    event_data = event.event_data(topics, d)
    return event_data
Exemple #10
0
def setup(node_yml=None, collusion_number=0):
    if node_yml:
        conf.NODE_YML = abspath(node_yml)
    auto = AutoDeployPlaton()
    auto.check_node_yml(conf.NODE_YML)
    conf.NODE_NUMBER = collusion_number
    auto.start_all_node(conf.NODE_YML)
def setup(node_yml=None):
    if node_yml:
        conf.NODE_YML = abspath(node_yml)
    auto = AutoDeployPlaton(is_metrics=True)
    # auto.check_node_yml(conf.NODE_YML)
    # auto.booms(conf.NODE_YML)
    # auto.deploy_default_yml(conf.NODE_YML)
    auto.kill_of_yaml(conf.NODE_YML)
Exemple #12
0
def get_pub_key(url, block):
    """
    obtain signature nodes based on block information
    :param url: node url
    :param block: block height
    :return:
    """
    if sys.platform in "linux,linux2":
        tool_file = abspath("tool/linux/get_pubkey_for_blocknum")
        run("chmod +x {}".format(tool_file))
    else:
        tool_file = abspath("tool/win/get_pubkey_for_blocknum.exe")
    output = run("{} -url={} -blockNumber={}".format(tool_file, url, block))
    if not output:
        raise Exception("unable to use get node id tool")
    if "1111" in output or "2222" in output:
        raise Exception("get node id exception:{}".format(output))
    return output.strip("\n")
 def setup_class(self):
     self.auto.start_all_node(self.node_yml,
                              genesis_file=conf.GENESIS_TMP,
                              static_node_file=conf.STATIC_NODE_FILE)
     # 等一下,同步块高
     collusion, _ = get_node_list(conf.NODE_YML)
     collusion_w3 = connect_web3(collusion[0]["url"])
     collusion_block = collusion_w3.eth.blockNumber
     _, nocollusion = get_node_list(self.node_yml)
     self.url = nocollusion[0]['url']
     self.ip = nocollusion[0]["host"]
     self.wt = PlatonContractTransaction(self.url)
     self.password = conf.PASSWORD
     nocollusion_block = self.wt.eth.blockNumber
     if collusion_block - nocollusion_block >= 100:
         time.sleep(20)
     elif 100 > collusion_block - nocollusion_block >= 50:
         time.sleep(10)
     else:
         time.sleep(5)
     addrress = self.wt.w3.toChecksumAddress(conf.ADDRESS)
     self.wt.w3.personal.unlockAccount(addrress, self.password, 999999)
     """部署合约"""
     resp = self.wt.contract_deploy(
         get_byte_code(abspath('./data/contract/vccMain.wasm')),
         get_abi_bytes(abspath(r'./data/contract/vccMain.cpp.abi.json')),
         addrress)
     result = self.wt.eth.waitForTransactionReceipt(resp)
     self.contract_address = result['contractAddress']
     log.info(self.contract_address)
     if len(self.wt.eth.getCode(self.contract_address)) < 10:
         raise Exception("合约部署失败")
     node = nocollusion[0]
     ssh, sftp, t = connect_linux(node['host'],
                                  username=node['username'],
                                  password=node['password'])
     pwd_list = run_ssh(ssh, "pwd")
     pwd = pwd_list[0].strip("\r\n")
     account = 'UTC--2018-10-04T09-02-39.439063439Z--493301712671ada506ba6ca7891f436d29185821'
     self.wallet_path = '{}/{}/data16789/keystore/{}'.format(
         pwd, conf.DEPLOY_PATH, account)
     cmd = '''nohup java -jar ./vc_tool/vctool-1.0.jar  > ./vc_tool/nohup.out 2>&1 &'''
     run_ssh(ssh, cmd)
     self.get_url = 'http://{}:8112/test/getResult'.format(self.ip)
Exemple #14
0
def get_pub_key(url, block):
    """
    根据区块信息获取签名节点
    :param url: 节点url
    :param block: 块高
    :return:
    """
    if sys.platform == "linux":
        run("chmod +x ./utils/pubkey/pubkey")
        output = run("./utils/pubkey/pubkey -url={} -blockNumber={}".format(
            url, block))
    else:
        output = run("pubkey -url={} -blockNumber={}".format(url, block))
    if not output:
        raise Exception("无法使用获取节点id程序,windows请确保{}配置到环境变量中".format(
            abspath("./utils/pubkey")))
    if "1111" in output or "2222" in output:
        raise Exception("获取节点id异常:{}".format(output))
    return output.strip("\n")
Exemple #15
0
    cfg = TestConfig(conf_tmp=conf_tmp,
                     install_supervisor=install_supervisor,
                     install_dependency=install_dependency,
                     init_chain=init_chain,
                     can_deploy=can_deploy)
    if node_file:
        cfg.node_file = node_file
    if account_file:
        cfg.account_file = account_file
    return TestEnvironment(cfg)


if __name__ == "__main__":
    from tests.lib import get_no_pledge_node, get_no_pledge_node_list, get_pledge_list, check_node_in_list

    node_filename = abspath("deploy/node/debug_4_4.yml")
    env = create_env(node_file=node_filename)
    env.shutdown()
    exit(0)
    # print(os.path.getctime(env.cfg.platon_bin_file))
    # new_cfg = copy.copy(env.cfg)
    # new_cfg.syncmode = "fast"
    # print(env.cfg.syncmode)
    log.info("测试部署")
    env.cfg.syncmode = "fast"
    # env.deploy_all(abspath("deploy/tmp/genesis_0.8.0.json"))
    for node in env.get_all_nodes():
        node.admin.addPeer(
            "enode://d203e37d86f1757ee4bbeafd7a0b0b6f7d4f22afaad3c63337e92d9056251dcca95515cb23d5a040e3416e1ebbb303aa52ea535103b9b8c8c2adc98ea3b41c01@10.10.8.195:16789"
        )
        print(node.web3.net.peerCount)
Exemple #16
0
    def deploy_default_list(self, node_list):
        """
        根据节点列表,使用默认参数部署节点
        :param node_list: 节点列表
        :return:
        """
        self.kill_of_list(node_list)
        self.stop_of_list(node_list)
        self.deploy_all_supervisor(node_list)
        run_thread(node_list, self.deploy_default)
        self.check_deploy_status(node_list)

    def deploy_default_yml(self, node_yml):
        """
        根据节点配置文件,使用默认参数部署节点
        :param node_yml: 节点配置文件
        :return:
        """
        self.check_node_yml(node_yml)
        collusion_list, nocollusion_list = get_node_list(node_yml)
        node_list = collusion_list + nocollusion_list
        self.deploy_default_list(node_list)


if __name__ == "__main__":
    s = AutoDeployPlaton()
    # s.deploy_default_yml(abspath("./deploy/node/25_cbft.yml"))
    # s.kill_of_yaml(abspath("./deploy/node/cbft_4.yml"))
    s.start_all_node(abspath("./deploy/node/cbft_4.yml"))
Exemple #17
0
    :param module: 测试的模块,只能是transaction,contract,ppos,blockchain,collusion,vc,如果有多个,用','分割
    :return:
    """
    case_dict = conf.CASE_DICT
    version_dict = conf.VERSION_DICT
    if version:
        case = version_dict[version]
    elif module:
        case = " ".join([case_dict[m] for m in module.split(",")])
    elif case:
        case = case
    else:
        raise Exception("请传入需要测试的用例、版本或模块")
    report = time.strftime("%Y-%m-%d_%H%M%S", time.localtime())
    excute_cases = r"-s -v --disable-warnings {} --alluredir={} --junitxml={}".format(
        case, abspath("./report/allure/{}".format(report)),
        abspath("./report/junitxml/{}.xml".format(report)))
    pytest.main(excute_cases)


def setup(node_yml=None, collusion_number=0):
    if node_yml:
        conf.NODE_YML = abspath(node_yml)
    auto = AutoDeployPlaton()
    auto.check_node_yml(conf.NODE_YML)
    conf.NODE_NUMBER = collusion_number
    auto.start_all_node(conf.NODE_YML)


def teardown():
    auto = AutoDeployPlaton()
class TestVC:
    node_yml = abspath("deploy/node/vc_node.yml")
    auto = AutoDeployPlaton()

    def setup_class(self):
        self.auto.start_all_node(self.node_yml,
                                 genesis_file=conf.GENESIS_TMP,
                                 static_node_file=conf.STATIC_NODE_FILE)
        # 等一下,同步块高
        collusion, _ = get_node_list(conf.NODE_YML)
        collusion_w3 = connect_web3(collusion[0]["url"])
        collusion_block = collusion_w3.eth.blockNumber
        _, nocollusion = get_node_list(self.node_yml)
        self.url = nocollusion[0]['url']
        self.ip = nocollusion[0]["host"]
        self.wt = PlatonContractTransaction(self.url)
        self.password = conf.PASSWORD
        nocollusion_block = self.wt.eth.blockNumber
        if collusion_block - nocollusion_block >= 100:
            time.sleep(20)
        elif 100 > collusion_block - nocollusion_block >= 50:
            time.sleep(10)
        else:
            time.sleep(5)
        addrress = self.wt.w3.toChecksumAddress(conf.ADDRESS)
        self.wt.w3.personal.unlockAccount(addrress, self.password, 999999)
        """部署合约"""
        resp = self.wt.contract_deploy(
            get_byte_code(abspath('./data/contract/vccMain.wasm')),
            get_abi_bytes(abspath(r'./data/contract/vccMain.cpp.abi.json')),
            addrress)
        result = self.wt.eth.waitForTransactionReceipt(resp)
        self.contract_address = result['contractAddress']
        log.info(self.contract_address)
        if len(self.wt.eth.getCode(self.contract_address)) < 10:
            raise Exception("合约部署失败")
        node = nocollusion[0]
        ssh, sftp, t = connect_linux(node['host'],
                                     username=node['username'],
                                     password=node['password'])
        pwd_list = run_ssh(ssh, "pwd")
        pwd = pwd_list[0].strip("\r\n")
        account = 'UTC--2018-10-04T09-02-39.439063439Z--493301712671ada506ba6ca7891f436d29185821'
        self.wallet_path = '{}/{}/data16789/keystore/{}'.format(
            pwd, conf.DEPLOY_PATH, account)
        cmd = '''nohup java -jar ./vc_tool/vctool-1.0.jar  > ./vc_tool/nohup.out 2>&1 &'''
        run_ssh(ssh, cmd)
        self.get_url = 'http://{}:8112/test/getResult'.format(self.ip)

    def tearDown(self):
        self.auto.kill_of_yaml(self.node_yml)

    def get_transaction_hash(self, value, gas, gasPrice):
        '''
        :return:交易hash
        '''
        url = 'http://{}:8112/test/startVC'.format(self.ip)
        data = {
            'walletPath': self.wallet_path,
            'walletPass': self.password,
            'contractAddress': self.contract_address,
            'input': '20#30',
            'value': value,
            'gas': gas,
            'gasPrice': gasPrice
        }

        ret = requests.post(url=url, data=data)
        hash = ret.text
        assert hash is not None, '哈希预期返回成功{},实际失败'.format(hash)
        return hash

    def get_vc_taskid(self, value=4300000, gas=4300000, gasPrice=22000000000):
        '''
        :return:taskid vc任务号
        '''
        hash = self.get_transaction_hash(value, gas, gasPrice)
        url = 'http://{}:8112/test/getTaskIdForHash'.format(self.ip)
        data = {
            'walletPath': self.wallet_path,
            'walletPass': self.password,
            'contractAddress': self.contract_address,
            'hash': hash
        }
        ret = requests.post(url=url, data=data)
        taskid = ret.text
        assert taskid is not None, 'taskid预期返回成功{},实际失败'.format(taskid)
        return taskid

    def test_vc_result_add(self):
        '''
        获取VC合约add的值
        :return:
        '''
        taskid = self.get_vc_taskid()
        time.sleep(30)
        data = {
            'walletPath': self.wallet_path,
            'walletPass': self.password,
            'contractAddress': self.contract_address,
            'taskId': taskid
        }
        ret = requests.post(url=self.get_url, data=data)
        result = int(ret.text)
        assert result == 50, '预期结果为50,实际结果为{}'.format(result)
        assert ret.status_code == 200, '预期返回响应码为200,实际为{}'.format(
            str(ret.status_code))

    def test_value_outsize(self):
        '''
        value过大
        :return:
        '''
        taskid = self.get_vc_taskid(value=100000000000000000000000000)
        time.sleep(30)
        data = {
            'walletPath': self.wallet_path,
            'walletPass': self.password,
            'contractAddress': self.contract_address,
            'taskId': taskid
        }
        ret = requests.post(url=self.get_url, data=data)
        result = int(ret.text)
        assert result == 0, '预期结果为0,实际结果为{}'.format(result)

    def test_value_insuff(self):
        '''
        value为0
        :return:
        '''
        taskid = self.get_vc_taskid(value=0)
        time.sleep(30)
        data = {
            'walletPath': self.wallet_path,
            'walletPass': self.password,
            'contractAddress': self.contract_address,
            'taskId': taskid
        }
        ret = requests.post(url=self.get_url, data=data)
        result = int(ret.text)
        assert result == 50, '预期结果为50,实际结果为{}'.format(result)

    def test_gas_outsize(self):
        '''
        gas值超过范围内
        :return:
        '''
        taskid = self.get_vc_taskid(gas=1000000000000000000)
        time.sleep(30)
        data = {
            'walletPath': self.wallet_path,
            'walletPass': self.password,
            'contractAddress': self.contract_address,
            'taskId': taskid
        }

        status = 0
        try:
            ret = requests.post(url=self.get_url, data=data)
            assert ret.status_code != 200, '预期返回响应失败,实际为{}'.format(
                str(ret.status_code))
        except:
            status = 1
        assert status == 1, '预期gas过大,返回异常,实际返回成功'

    def test_gas_insuff(self):
        '''
        gas值过小
        :return:
        '''
        taskid = self.get_vc_taskid(gas=10)
        time.sleep(30)
        data = {
            'walletPath': self.wallet_path,
            'walletPass': self.password,
            'contractAddress': self.contract_address,
            'taskId': taskid
        }

        status = 0
        try:
            ret = requests.post(url=self.get_url, data=data)
            assert ret.status_code != 200, '预期返回响应失败,实际为{}'.format(
                str(ret.status_code))
        except:
            status = 1
        assert status == 1, '预期gas过小,返回异常,实际返回成功'
class TestContract:
    node_yml = conf.NODE_YML
    collusion_list, nocollusion_list = get_node_list(node_yml)
    nocollusion_url = nocollusion_list[0]['url']
    collusion_url = collusion_list[0]['url']
    address = Web3.toChecksumAddress(conf.ADDRESS)
    private_key_hex = conf.PRIVATE_KEY
    private_key = HexBytes(private_key_hex)
    url_list = [nocollusion_url, collusion_url]
    param_list = [(abspath('./data/contract/Fibonacci.wasm'),
                   abspath('./data/contract/Fibonacci.cpp.abi.json'), 10, 143),
                  (abspath('./data/contract/matmul.wasm'),
                   abspath('./data/contract/matmul.cpp.abi.json'), 10, -183325)]

    @allure.title("非共识节点&共识节点 部署wasm合约测试")
    @pytest.mark.parametrize('pt1', url_list)
    def test_consensus_and_deconsensus_contract_deploy(self, pt1):
        '''
        非共识节点&共识节点 部署wasm合约测试
        '''
        pt = PlatonContractTransaction(pt1)
        wasm_path = abspath('./data/contract/sum.wasm')
        abi_path = abspath('./data/contract/sum.cpp.abi.json')

        # 部署合约
        contract_address = contract_deploy(pt, wasm_path, abi_path)
        assert contract_address is not None, '合约部署失败,合约地址为空'
        contract_code = pt.eth.getCode(contract_address)
        assert len(contract_code) > 3, '合约部署异常,getCode(contract_address)结果异常'

    @allure.title("非共识节点&共识节点 wasm合约交易、event事件、call方法测试")
    @pytest.mark.parametrize('pt1', url_list)
    def test_consensus_and_deconsensus_contract_transaction(self, pt1):
        '''
        非共识节点&共识节点 wasm合约交易、event事件、call方法测试
        '''
        pt = PlatonContractTransaction(pt1)
        wasm_path = abspath('./data/contract/sum.wasm')
        abi_path = abspath('./data/contract/sum.cpp.abi.json')
        address = pt.eth.coinbase
        contract_address = contract_deploy(pt, wasm_path, abi_path)

        # 发送合约交易
        data_list = [encoder.encode_type(
            2), encoder.encode_string('set')]
        trans_hex = pt.contract_transaction(
            address, contract_address, data_list)
        try:
            result = pt.eth.waitForTransactionReceipt(trans_hex)
        except:
            assert False, "等待超时,交易哈希:{}".format(trans_hex)
        # 解析event事件
        topics = result['logs'][0]['topics']
        data = result['logs'][0]['data']
        event = Event(json.load(open(abi_path)))
        event_data = event.event_data(topics, data)
        assert 'set success' in event_data['create'][0], '合约交易失败,event事件无"set success"'
        # call方法查询交易结果
        data_list_for_call = [encoder.encode_type(
            2), encoder.encode_string('get')]
        receive = pt.contract_call(
            address, contract_address, data_list_for_call)
        decoded_sum_result = int.from_bytes(receive, 'big')
        assert decoded_sum_result == 1, '自增失败,预期自增后结果为1,实际值为{}'.format(
            decoded_sum_result)

    @allure.title("非共识节点&共识节点 wasm合约输入、输出结果校验")
    @pytest.mark.parametrize('pt1', url_list)
    def test_consensus_and_deconsensus_contract_set_and_get_function(self, pt1):
        '''
        非共识节点&共识节点 wasm合约输入、输出结果校验
        '''
        pt = PlatonContractTransaction(pt1)
        wasm_path = abspath('./data/contract/inputtest.wasm')
        abi_path = abspath(
            './data/contract/inputtest.cpp.abi.json')
        address = pt.eth.coinbase
        contract_address = contract_deploy(pt, wasm_path, abi_path)
        set_value = -100

        # 合约set方法存入int型数值
        data_list = [encoder.encode_type(2), encoder.encode_string('set'),
                     encoder.encode_int('int64', set_value)]
        trans_hex = pt.contract_transaction(
            address, contract_address, data_list)
        try:
            result = pt.eth.waitForTransactionReceipt(trans_hex)
        except:
            assert False, "等待超时,交易哈希:{}".format(trans_hex)
        # 合约get方法获取存入的数值校验是否一致
        data_list_for_call = [encoder.encode_type(
            2), encoder.encode_string('get')]
        receive = pt.contract_call(
            address, contract_address, data_list_for_call)
        get_value = contract_call_result_decode(receive)
        assert get_value == set_value, 'get结果异常,预期值:{},实际结果:{}'.format(
            set_value, get_value)

    def _singed_contract_deploy(self, pt, wasm_path, abi_path):
        '''
        部署wasm签名合约方法
        '''
        deploy_trans_hash = pt.signed_contract_deploy(get_byte_code(wasm_path),
                                                      get_abi_bytes(
                                                          abi_path),
                                                      self.address, self.private_key)
        try:
            result = pt.eth.waitForTransactionReceipt(deploy_trans_hash)
        except:
            assert False, "等待超时,交易哈希:{}".format(deploy_trans_hash)
        contract_address = result['contractAddress']
        assert len(pt.eth.getCode(contract_address)
                   ) > 3, '合约部署异常,getCode(contract_address)结果异常'
        return contract_address

    @allure.title("非共识节点&共识节点 部署wasm签名合约测试")
    @pytest.mark.parametrize('pt1', url_list)
    def test_consensus_and_deconsensus_singed_contract_deploy(self, pt1):
        '''
        非共识节点&共识节点 部署wasm签名合约测试
        '''
        pt = PlatonContractTransaction(pt1)
        wasm_path = abspath('./data/contract/sum.wasm')
        abi_path = abspath('./data/contract/sum.cpp.abi.json')

        # 部署合约
        contract_address = self._singed_contract_deploy(
            pt, wasm_path, abi_path)
        assert contract_address is not None, '合约部署失败,合约地址为空'
        contract_code = pt.eth.getCode(contract_address)
        assert len(contract_code) > 3, '合约部署异常,getCode(contract_address)结果异常'

    @allure.title("非共识节点&共识节点 wasm合约签名交易、event事件、call方法测试")
    @pytest.mark.parametrize('pt1', url_list)
    def test_consensus_and_deconsensus_singed_contract_transaction(self, pt1):
        '''
        非共识节点&共识节点 wasm合约签名交易、event事件、call方法测试
        '''
        pt = PlatonContractTransaction(pt1)
        wasm_path = abspath('./data/contract/sum.wasm')
        abi_path = abspath('./data/contract/sum.cpp.abi.json')
        address = pt.eth.coinbase
        contract_address = self._singed_contract_deploy(
            pt, wasm_path, abi_path)

        # 发送合约交易
        data_list = [encoder.encode_type(
            2), encoder.encode_string('set')]
        trans_hex = pt.signed_contract_transaction(
            address, contract_address, data_list, self.private_key)
        try:
            result = pt.eth.waitForTransactionReceipt(trans_hex)
        except:
            assert False, "等待超时,交易哈希:{}".format(trans_hex)
        # 解析event事件
        topics = result['logs'][0]['topics']
        data = result['logs'][0]['data']
        event = Event(json.load(open(abi_path)))
        event_data = event.event_data(topics, data)
        assert 'set success' in event_data['create'][0], '合约交易失败,event事件无"set success"'
        # call方法查询交易结果
        data_list_for_call = [encoder.encode_type(
            2), encoder.encode_string('get')]
        receive = pt.contract_call(
            address, contract_address, data_list_for_call)
        decoded_sum_result = int.from_bytes(receive, 'big')
        assert decoded_sum_result == 1, '自增失败,预期自增后结果为1,实际值为{}'.format(
            decoded_sum_result)

    @allure.title("非共识节点&共识节点 wasm签名合约输入、输出结果校验")
    @pytest.mark.parametrize('pt1', url_list)
    def test_consensus_and_deconsensus_signed_contract_set_and_get_function(self, pt1):
        '''
        非共识节点&共识节点 wasm签名合约输入、输出结果校验
        '''
        pt = PlatonContractTransaction(pt1)
        wasm_path = abspath('./data/contract/inputtest.wasm')
        abi_path = abspath(
            './data/contract/inputtest.cpp.abi.json')
        address = pt.eth.coinbase
        contract_address = self._singed_contract_deploy(
            pt, wasm_path, abi_path)
        set_value = -100

        # 合约set方法存入int型数值
        data_list = [encoder.encode_type(2), encoder.encode_string('set'),
                     encoder.encode_int('int64', set_value)]
        trans_hex = pt.signed_contract_transaction(
            address, contract_address, data_list, self.private_key)
        result = ''
        for i in range(3):
            try:
                result = pt.eth.waitForTransactionReceipt(trans_hex)
            except:
                pt.reconnect()
        assert result != '', "等待超时,交易哈希:{}".format(trans_hex)

        # 合约get方法获取存入的数值校验是否一致
        data_list_for_call = [encoder.encode_type(
            2), encoder.encode_string('get')]
        receive = pt.contract_call(
            address, contract_address, data_list_for_call)
        get_value = contract_call_result_decode(receive)
        assert get_value == set_value, 'get结果异常,预期值:{},实际结果:{}'.format(
            set_value, get_value)
        time.sleep(1)

    @allure.title("各算法合约计算结果测试")
    @pytest.mark.parametrize('wasm_path,abi_path,set_value,expect_value', param_list)
    def test_calc_contracts(self, wasm_path, abi_path, set_value, expect_value):
        '''
        各算法合约计算结果测试
        '''
        pt_one = PlatonContractTransaction(self.nocollusion_url)
        address = pt_one.eth.coinbase
        contract_address = contract_deploy(
            pt_one, wasm_path, abi_path)

        # 合约set方法存入int型数值
        data_list = [encoder.encode_type(2), encoder.encode_string('set'),
                     encoder.encode_int('int64', set_value)]
        trans_hex = pt_one.contract_transaction(
            address, contract_address, data_list)
        try:
            result = pt_one.eth.waitForTransactionReceipt(trans_hex)
        except:
            assert False, "等待超时,交易哈希:{}".format(trans_hex)
        # 合约get方法获取存入的数值校验是否一致
        data_list_for_call = [encoder.encode_type(
            2), encoder.encode_string('get')]
        receive = pt_one.contract_call(
            address, contract_address, data_list_for_call)
        get_value = contract_call_result_decode(receive)
        assert get_value == expect_value, 'get结果异常,预期值:{},实际结果:{}'.format(
            expect_value, get_value)
Exemple #20
0
def send_to_gap(block_list, msg, node_yml):
    error = "出现问题原因:区块差距过大\n\n"
    error += "最高块高为:{},".format(max(block_list))
    error += "最低块高为:{}\n".format(min(block_list))
    msg = error + msg
    EmailInfo.header = "D网稳定性测试监控汇报-块高差距过大"
    send_email(EmailInfo, msg)
    stop(node_yml)


def send_to_block(msg, node_yml):
    error = "出现问题原因:已经120s各节点块高没有增长\n\n"
    msg = error + msg
    EmailInfo.header = "D网稳定性测试监控汇报-不出块"
    send_email(EmailInfo, msg)
    stop(node_yml)


def stop(node_yml):
    auto = AutoDeployPlaton()
    auto.stop_of_yml(node_yml)
    raise Exception("出现报错,监控停止")


if __name__ == "__main__":
    try:
        node_yml = sys.argv[1]
    except:
        node_yml = abspath("./deploy/node/cbft_25_node.yml")
    monitor(node_yml)