コード例 #1
0
 def test_block_time_period(self, period, duration):
     '''
     用例id 1,2,3,4,5
     测试period的不同值,观察查看时间
     根据5种场景,分别出块时间约为1,3,5,10,1s
     '''
     log.info("更新cbft.json")
     self.get_cbft_json_data(period, duration)
     auto = AutoDeployPlaton(cbft=self.cbft_path)
     auto.start_all_node(self.node_yml)
     time.sleep(duration + 5)
     log.info("跟所有节点建立连接")
     w3_list = [connect_web3(url) for url in self.url_list]
     w3 = w3_list[0]
     block_number = w3.eth.blockNumber
     assert block_number > 1, "没有正常出块"
     log.info(block_number)
     start_time = w3.eth.getBlock(1).get("timestamp")
     end_time = w3.eth.getBlock(block_number).get("timestamp")
     use_time = end_time - start_time
     average_time = int(use_time / (block_number - 1))
     log.info("平均出块时间{}".format(average_time))
     if period == 0:
         period = 1
     deviation = int(period * 1000 * 0.5)
     assert period * 1000 - deviation < average_time < period * \
         1000 + deviation, "出块间隔过大或过小"
コード例 #2
0
ファイル: run.py プロジェクト: qiusese/PlatON-Tests
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)
コード例 #3
0
 def test_block_out_of_each_node_window(self):
     """
     用例id:73
     测试 N 个节点每个窗口期都在出块
     """
     log.info("更新cbft文件")
     self.get_cbft_json_data(period=1, duration=10)
     auto = AutoDeployPlaton(cbft=self.cbft_path)
     auto.start_all_node(self.node_yml)
     log.info("跟所有节点建立连接")
     w3_list = [connect_web3(url) for url in self.url_list]
     w3 = w3_list[0]
     start_block = w3.eth.blockNumber
     time.sleep(self.n * 10 + 5)
     block_number = w3.eth.blockNumber
     if block_number > 0:
         log.info("正在出块,块高:{}".format(block_number))
     node_id_dict = {}
     log.info("获取1至{}块的nodeID".format(block_number))
     for block in range(start_block, block_number + 1):
         node_id = get_pub_key(self.url_list[0], block)
         if node_id not in node_id_dict.keys():
             node_id_dict[node_id] = 1
         else:
             node_id_dict[node_id] += 1
     log.info("nodeID对应的出块数{}".format(node_id_dict))
     assert self.n == len(node_id_dict), "出块节点数少于共识节点数"
     for k, v in node_id_dict.items():
         assert 0 <= v <= 20, "节点{}出块周期约为10个块,实际为{}".format(k, v)
コード例 #4
0
 def test_testnet(self):
     """
     测试testnet连接
     :return:
     """
     if conf.IS_TEST_NET:
         auto = AutoDeployPlaton(net_type="testnet")
         auto.start_all_node(conf.TEST_NET_NODE,
                             is_need_init=False,
                             clean=True)
         collusion, nocollusion = get_node_list(conf.TEST_NET_NODE)
         time.sleep(10)
         block_list = []
         net_list = []
         for nodedict in collusion:
             url = nodedict["url"]
             w3 = connect_web3(url)
             block_list.append(w3.eth.blockNumber)
             net_list.append(w3.net.peerCount)
         log.info(block_list, net_list)
         assert min(block_list) > 0, "区块没有增长"
         for net in net_list:
             assert net >= len(collusion) - \
                 1, "共识节点连接节点数少于{}个".format(len(collusion) - 1)
         nocollusion_block_list = []
         nocollusion_net_list = []
         if max(block_list) < 250:
             time.sleep(250 - max(block_list) + 10)
         for nodedict in nocollusion:
             url = nodedict["url"]
             w3 = connect_web3(url)
             nocollusion_block_list.append(w3.eth.blockNumber)
             nocollusion_net_list.append(w3.net.peerCount)
         log.info(nocollusion_block_list, nocollusion_net_list)
         assert min(nocollusion_block_list) > 0, "区块没有增长"
         for net in nocollusion_net_list:
             assert net >= 1, "非共识节点没有连上测试网"
     else:
         pass
コード例 #5
0
class TestLockeDpositionConfig:
    address = conf.ADDRESS
    pwd = conf.PASSWORD
    abi = conf.DPOS_CONTRACT_ABI
    cbft_json_path = conf.CBFT2
    node_yml_path = conf.PPOS_NODE_TEST_YML
    file = conf.CASE_DICT
    privatekey = conf.PRIVATE_KEY
    base_gas_price = 60000000000000
    base_gas = 21000
    staking_gas = base_gas + 32000 + 6000 + 100000
    transfer_gasPrice = Web3.toWei (1, 'ether')
    transfer_gas = 210000000
    value = 1000
    chainid = 120
    ConsensusSize = 150
    time_interval = 10
    initial_amount = {'FOUNDATION': 905000000000000000000000000,
                      'FOUNDATIONLOCKUP': 20000000000000000000000000,
                      'STAKING': 25000000000000000000000000,
                      'INCENTIVEPOOL': 45000000000000000000000000,
                      'DEVELOPERS': 5000000000000000000000000
                      }
    def start_init(self):
        #修改config参数
        CommonMethod.update_config(self,'EconomicModel','Common','ExpectedMinutes',3)
        CommonMethod.update_config(self,'EconomicModel','Common','PerRoundBlocks',10)
        CommonMethod.update_config(self,'EconomicModel','Common','ValidatorCount',5)
        CommonMethod.update_config(self,'EconomicModel','Staking','ElectionDistance',20)
        CommonMethod.update_config(self,'EconomicModel','Staking','StakeThreshold',1000)
        #启动节点
        self.auto = AutoDeployPlaton ()
        self.auto.start_all_node (self.node_yml_path)


    def test_unlock_Normal(self):
        '''
        只有一个锁仓期,到达解锁期返回解锁金额
        :param amount:
        :return:
        '''
        url = CommonMethod.link_list (self)
        platon_ppos = Ppos (url, self.address, self.chainid)
        address1, private_key1 = CommonMethod.read_private_key_list ()
        address2, private_key2 = CommonMethod.read_private_key_list ()

        # 签名转账
        result = platon_ppos.send_raw_transaction ('', Web3.toChecksumAddress (self.address),
                                                   Web3.toChecksumAddress (address1),
                                                   self.base_gas_price, self.base_gas, self.value, self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt (result)
        assert return_info is not None,"转账:{}失败".format(self.value)
        # 创建锁仓计划
        loukupbalace = Web3.toWei (50, 'ether')
        plan = [{'Epoch': 1, 'Amount': loukupbalace}]
        result = platon_ppos.CreateRestrictingPlan (address2, plan, privatekey=private_key1,
                                                    from_address=address1, gasPrice=self.base_gas_price,
                                                    gas=self.staking_gas)
        assert result['Status'] == True, "创建锁仓计划返回状态为:{} 有误".format (result['Status'])
        print(address2)
        balance = platon_ppos.eth.getBalance(address2)
        log.info ("锁仓之后账户余额:{}".format (balance))
        log.info("当前块高:{}".format(platon_ppos.eth.blockNumber))
        RestrictingInfo = platon_ppos.GetRestrictingInfo(address2)
        assert RestrictingInfo['Status'] == True, "获取锁仓计划返回状态为:{} 有误".format (result['Status'])
        dict_Info = json.loads(RestrictingInfo['Data'])
        assert dict_Info['balance'] == loukupbalace,"锁仓金额:{}有误".format(dict_Info['balance'])

        #验证到达锁仓解锁期之后账户金额
        CommonMethod.get_next_settlement_interval(self)
        balance2 = platon_ppos.eth.getBalance(address2)
        log.info ("解锁之后账户余额:{}".format (balance2))
        RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        assert RestrictingInfo['Status'] == True, "获取锁仓计划返回状态为:{} 有误".format (result['Status'])
        dict_Info = json.loads (RestrictingInfo['Data'])
        balance = platon_ppos.eth.getBalance(address2)
        assert dict_Info['balance'] == 0, "锁仓金额:{}有误".format (dict_Info['balance'])
        assert balance2 == loukupbalace,"返回的释放锁仓金额:{} 有误".format(balance)

    def test_multiple_unlock_Normal(self):
        '''
        多个锁仓期,到达部分解锁期返回解锁金额
        :return:
        '''
        url = CommonMethod.link_list (self)
        platon_ppos = Ppos (url, self.address, self.chainid)
        address1, private_key1 = CommonMethod.read_private_key_list ()
        address2, private_key2 = CommonMethod.read_private_key_list ()

        # 签名转账
        result = platon_ppos.send_raw_transaction ('', Web3.toChecksumAddress (self.address),
                                                   Web3.toChecksumAddress (address1),
                                                   self.base_gas_price, self.base_gas, self.value, self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt (result)
        assert return_info is not None,"转账:{}失败".format(self.value)
        loukupbalace = Web3.toWei (50, 'ether')
        plan = [{'Epoch': 1, 'Amount': loukupbalace},{'Epoch': 2, 'Amount': loukupbalace}]
        result = platon_ppos.CreateRestrictingPlan (address2, plan, privatekey=private_key1,
                                                    from_address=address1, gasPrice=self.base_gas_price,
                                                    gas=self.staking_gas)
        assert result['Status'] == True, "创建锁仓计划返回状态为:{} 有误".format (result['Status'])
        balance = platon_ppos.eth.getBalance (address2)
        log.info ("锁仓之后账户余额:{}".format (balance))
        log.info ("当前块高:{}".format (platon_ppos.eth.blockNumber))
        RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        assert RestrictingInfo['Status'] == True, "获取锁仓计划返回状态为:{} 有误".format (result['Status'])
        dict_Info = json.loads (RestrictingInfo['Data'])
        assert dict_Info['balance'] == loukupbalace*2, "锁仓金额:{}有误".format (dict_Info['balance'])

        # 验证到达锁仓第一个解锁期之后账户金额
        CommonMethod.get_next_settlement_interval (self)
        balance2 = platon_ppos.eth.getBalance (address2)
        log.info ("到达第一个解锁期后账户余额:{}".format (balance2))
        RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        assert RestrictingInfo['Status'] == True, "获取锁仓计划返回状态为:{} 有误".format (result['Status'])
        dict_Info = json.loads (RestrictingInfo['Data'])
        balance = platon_ppos.eth.getBalance (address2)
        assert dict_Info['balance'] == loukupbalace, "锁仓金额:{}有误".format (dict_Info['balance'])
        assert dict_Info['Entry'][0]['amount'] == loukupbalace,"第二个解锁期待释放金额:{}".format(dict_Info['Entry'][0]['amount'])
        assert balance2 == loukupbalace, "返回的释放锁仓金额:{} 有误".format (balance)

        #验证到达锁仓第二个解锁期之后账户金额
        CommonMethod.get_next_settlement_interval (self)
        balance3 = platon_ppos.eth.getBalance (address2)
        log.info ("到达第二个解锁期后账户余额:{}".format (balance2))
        RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        assert RestrictingInfo['Status'] == True, "获取锁仓计划返回状态为:{} 有误".format (result['Status'])
        dict_Info = json.loads (RestrictingInfo['Data'])
        balance = platon_ppos.eth.getBalance (address2)
        assert dict_Info['balance'] == 0, "锁仓金额:{}有误".format (dict_Info['balance'])
        assert balance3 == loukupbalace*2, "返回的释放锁仓金额:{} 有误".format (balance)

    def test_unlock_point_pledge_amount(self):
        '''
        到达解锁时间点,锁仓金额质押后在解锁期之后再申请退回质押金
        :return:
        '''
        nodeId = CommonMethod.get_no_candidate_list (self)
        url = CommonMethod.link_list (self)
        platon_ppos = Ppos (url, self.address, self.chainid)
        address1, private_key1 = CommonMethod.read_private_key_list ()
        address2, private_key2 = CommonMethod.read_private_key_list ()

        # 签名转账
        result = platon_ppos.send_raw_transaction ('', Web3.toChecksumAddress (self.address),
                                                   Web3.toChecksumAddress (address1),
                                                   self.base_gas_price, self.base_gas, self.value, self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt (result)
        assert return_info is not None,"转账:{}失败".format(self.value)

        # 给锁仓账号转手续费
        result = platon_ppos.send_raw_transaction ('', Web3.toChecksumAddress (self.address),
                                                   Web3.toChecksumAddress (address2),
                                                   self.base_gas_price, self.base_gas, self.value,
                                                   self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt (result)
        assert return_info is not None, "转账:{}失败".format (self.value)
        Balance = platon_ppos.eth.getBalance(address1)
        log.info("{}发起锁仓账户余额:{}".format(address1,Balance))
        Balance1 = platon_ppos.eth.getBalance (address1)
        log.info ("{}发起质押账号余额:{}".format (address2, Balance1))

        # 创建锁仓计划
        lockupamoutn = 900
        loukupbalace = Web3.toWei (lockupamoutn, 'ether')
        plan = [{'Epoch': 1, 'Amount': loukupbalace}]
        result = platon_ppos.CreateRestrictingPlan (address2, plan, privatekey=private_key1,
                                                    from_address=address1, gasPrice=self.base_gas_price,
                                                    gas=self.staking_gas)
        assert result['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format (result['Status'])
        RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        assert RestrictingInfo['Status'] == True, "查询锁仓计划返回的状态:{},用例失败".format (result['Status'])
        info = json.loads(RestrictingInfo['Data'])
        assert info['balance'] == loukupbalace,"锁仓计划可用余额:{},有误".format(info['balance'])
        balance2 = platon_ppos.eth.getBalance (address1)
        log.info ("{}创建锁仓后余额:{}".format (address1,balance2))

        # 申请质押节点
        version = get_version (platon_ppos)
        amount = 800
        result = platon_ppos.createStaking (1, address2, nodeId, 'externalId', 'nodeName', 'website', 'details',
                                            amount, version, privatekey=private_key2, from_address=address2,
                                            gasPrice=self.base_gas_price, gas=self.staking_gas)
        assert result['Status'] == True, "申请质押返回的状态:{},{},用例失败".format (result['Status'], result['ErrMsg'])
        balance3 = platon_ppos.eth.getBalance (address2)
        log.info ("{}质押完账户余额:{}".format (address2,balance3))
        RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        assert RestrictingInfo['Status'] == True, "获取锁仓计划返回状态为:{} 有误".format (result['Status'])
        dict_Info = json.loads (RestrictingInfo['Data'])
        assert dict_Info['balance'] == Web3.toWei(lockupamoutn - amount,'ether'), "锁仓金额:{}有误".format (dict_Info['balance'])

        # 到达解锁期之后锁仓账号余额
        CommonMethod.get_next_settlement_interval (self)
        balance4 = platon_ppos.eth.getBalance (address2)
        log.info("到达解锁期后预期账户余额:{}".format(balance3 + Web3.toWei(lockupamoutn - amount,'ether')))
        log.info("到达解锁期后实际账户余额:{}".format (balance4))
        assert balance4 == balance3 + Web3.toWei(lockupamoutn - amount,'ether'),"锁仓账户金额:{} 有误".format(balance4)
        RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        assert RestrictingInfo['Status'] == True, "获取锁仓计划返回状态为:{} 有误".format (result['Status'])
        dict_Info = json.loads (RestrictingInfo['Data'])
        assert dict_Info['balance'] == 0, "锁仓金额:{}有误".format (dict_Info['balance'])
        assert dict_Info['symbol'] == True,"锁仓的状态:{} 有误".format(dict_Info['symbol'])
        assert dict_Info['debt'] == Web3.toWei(amount,'ether'),"欠释放锁仓金额:{} 有误".format(dict_Info['debt'])

        # 申请退回质押金
        result = platon_ppos.unStaking (nodeId, privatekey=private_key2, from_address=address2,
                                        gasPrice=self.base_gas_price, gas=self.staking_gas)
        assert result['Status'] == True, "申请质押退回质押金返回的状态:{},用例失败".format (result['Status'])
        balance5 = platon_ppos.eth.getBalance (address2)
        log.info ("到达解锁期申请退回质押金后账户余额:{}".format (balance5))

        # 等待两个结算周期后查询锁仓账号情况
        CommonMethod.get_next_settlement_interval (self,3)
        RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        balance6 = platon_ppos.eth.getBalance (address2)
        log.info ("到达解锁期退回质押金后预期账户金额:{}".format (balance5 + loukupbalace))
        log.info ("到达解锁期退回质押金后实际账户余额:{}".format (balance6))
        assert balance6 == balance5 + loukupbalace, "锁仓账户金额:{} 有误".format (balance6)
        assert RestrictingInfo['Status'] == True, "获取锁仓计划返回状态为:{} 有误".format (result['Status'])
        dict_Info = json.loads (RestrictingInfo['Data'])
        assert dict_Info['balance'] == 0, "锁仓金额:{}有误".format (dict_Info['balance'])
        assert dict_Info['symbol'] == False, "锁仓的状态:{} 有误".format (dict_Info['symbol'])
        assert dict_Info['debt'] == 0, "欠释放锁仓金额:{} 有误".format (dict_Info['debt'])



    def test_unlock_point_delegtion_notbalance(self):
        '''
        1、到达解锁时间点用锁仓金额去委托节点,到达解锁期账户锁仓不足
        2、到达解锁期账户申请部分赎回委托
        3、全部赎回委托
        :return:
        '''
        nodeId = CommonMethod.get_no_candidate_list (self)
        url = CommonMethod.link_list (self)
        platon_ppos = Ppos (url, self.address, self.chainid)
        address1, private_key1 = CommonMethod.read_private_key_list ()
        address2, private_key2 = CommonMethod.read_private_key_list ()

        # 签名转账
        result = platon_ppos.send_raw_transaction ('', Web3.toChecksumAddress (self.address),
                                                   Web3.toChecksumAddress (address1),
                                                   self.base_gas_price, self.base_gas, self.value, self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt (result)
        assert return_info is not None, "转账质押账号手续费:{}失败".format (self.value)

        # 给锁仓账号转手续费
        result = platon_ppos.send_raw_transaction ('', Web3.toChecksumAddress (self.address),
                                                   Web3.toChecksumAddress (address2),
                                                   self.base_gas_price, self.base_gas, self.value,
                                                   conf.PRIVATE_KEY)
        return_info = platon_ppos.eth.waitForTransactionReceipt (result)
        assert return_info is not None, "转账锁仓账号手续费:{}失败".format (self.value)
        Balance = platon_ppos.eth.getBalance (address1)
        log.info ("{}发起锁仓账户余额:{}".format (address1, Balance))
        Balance1 = platon_ppos.eth.getBalance (address1)
        log.info ("{}发起质押账号余额:{}".format (address2, Balance1))

        # 申请质押节点
        version = get_version (platon_ppos)
        amount = 100
        result = platon_ppos.createStaking (0, address1, nodeId, 'externalId', 'nodeName', 'website', 'details',
                                            amount, version, privatekey=private_key1, from_address=address1,
                                            gasPrice=self.base_gas_price, gas=self.staking_gas)
        assert result['Status'] == True, "申请质押返回的状态:{},{},用例失败".format (result['Status'], result['ErrMsg'])
        Balance2 = platon_ppos.eth.getBalance (address1)
        log.info ("{}申请质押节点后账户余额:{}".format (address1, Balance2))

        # 创建锁仓计划
        lockupamoutn = 100
        loukupbalace = Web3.toWei (lockupamoutn, 'ether')
        plan = [{'Epoch': 1, 'Amount': loukupbalace}]
        result = platon_ppos.CreateRestrictingPlan (address2, plan, privatekey=private_key1,
                                                    from_address=address1, gasPrice=self.base_gas_price,
                                                    gas=self.staking_gas)
        assert result['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format (result['Status'])
        RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        assert RestrictingInfo['Status'] == True, "查询锁仓计划返回的状态:{},用例失败".format (result['Status'])
        dict_Info = json.loads (RestrictingInfo['Data'])
        assert dict_Info['balance'] == loukupbalace, "锁仓计划金额:{}有误".format (dict_Info['balance'])
        assert dict_Info['symbol'] == False, "锁仓的状态:{} 有误".format (dict_Info['symbol'])
        assert dict_Info['debt'] == 0, "欠释放锁仓金额:{} 有误".format (dict_Info['debt'])
        Balance3 = platon_ppos.eth.getBalance (address1)
        log.info ("{}创建锁仓计划后账户余额:{}".format (address1, Balance3))

        # 申请委托验证人节点
        amount = 100
        result = platon_ppos.delegate (1, nodeId, amount, privatekey=private_key2, from_address=address2,
                                              gasPrice=self.base_gas_price, gas=self.staking_gas)
        log.info ("申请委托地址:{}".format (address2))
        assert result['Status'] == True, "申请委托返回的状态:{},用例失败".format (result['Status'])
        balance4 = platon_ppos.eth.getBalance (address2)
        log.info ("{}申请委托验证人节点后账户余额:{}".format (address2,balance4))

        # 到达解锁期之后锁仓账号余额
        CommonMethod.get_next_settlement_interval (self)
        balance5 = platon_ppos.eth.getBalance (address2)
        log.info ("{}到达解锁期后实际账户余额:{}".format (address2,balance5))
        assert balance5 == balance4, "锁仓账户金额:{} 有误".format (balance5)
        RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        assert RestrictingInfo['Status'] == True, "获取锁仓计划返回状态为:{} 有误".format (result['Status'])
        dict_Info = json.loads (RestrictingInfo['Data'])
        assert dict_Info['balance'] == 0, "锁仓金额:{}有误".format (dict_Info['balance'])
        assert dict_Info['symbol'] == True, "锁仓的状态:{} 有误".format (dict_Info['symbol'])
        assert dict_Info['debt'] == loukupbalace, "欠释放锁仓金额:{} 有误".format (dict_Info['debt'])

        #申请赎回部分委托金
        partamount = 50
        msg = platon_ppos.getCandidateInfo (nodeId)
        stakingBlockNum = msg["Data"]["StakingBlockNum"]
        delegate_info = platon_ppos.unDelegate (stakingBlockNum, nodeId, partamount, privatekey=private_key2,
                                                from_address=address2, gasPrice=self.base_gas_price,
                                                gas=self.staking_gas)
        assert delegate_info['Status'] == True, "申请赎回委托返回的状态:{},用例失败".format (result['Status'])
        balance6 = platon_ppos.eth.getBalance (address2)
        log.info ("{}到达解锁期发起赎回部分委托后账户余额:{}".format (address2,balance6))

        #到达下个解锁期释放部分委托金
        CommonMethod.get_next_settlement_interval (self)
        balance7 = platon_ppos.eth.getBalance (address2)
        log.info ("赎回部分委托金后锁仓账户余额:{}".format (balance7))
        assert balance7 == balance6 + Web3.toWei (partamount, 'ether'),"到达解锁期赎回部分委托后账户余额:{}".format (balance7)
        RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        assert RestrictingInfo['Status'] == True, "获取锁仓计划返回状态为:{} 有误".format (result['Status'])
        dict_Info = json.loads (RestrictingInfo['Data'])
        assert dict_Info['balance'] == 0, "锁仓金额:{}有误".format (dict_Info['balance'])
        assert dict_Info['symbol'] == True, "锁仓的状态:{} 有误".format (dict_Info['symbol'])
        assert dict_Info['debt'] == loukupbalace - Web3.toWei (partamount, 'ether'), "欠释放锁仓金额:{} 有误".format (dict_Info[                                                                                         'debt'])
        #申请赎回全部委托金
        delegate_info = platon_ppos.unDelegate (stakingBlockNum, nodeId, lockupamoutn - partamount, privatekey=private_key2,
                                                from_address=address2, gasPrice=self.base_gas_price,
                                                gas=self.staking_gas)
        assert delegate_info['Status'] == True, "申请赎回委托返回的状态:{},用例失败".format (result['Status'])
        balance8 = platon_ppos.eth.getBalance (address2)
        log.info ("{}赎回全部委托金后锁仓账户余额:{}".format (address2,balance8))

        #到达下个解锁期释放全部委托金
        CommonMethod.get_next_settlement_interval (self)
        balance9 = platon_ppos.eth.getBalance (address2)
        log.info ("{}赎回全部委托金后实际账户余额:{}".format (address2,balance9))
        log.info ("{}赎回全部委托金后预期账户余额:{}".format (address2,balance8 + Web3.toWei (lockupamoutn - partamount, 'ether')))
        assert balance9 == balance8 + loukupbalace - Web3.toWei (partamount, 'ether'), "到达解锁期赎回委托后账户余额:{}".format                                                                                             (balance9)
        RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        assert RestrictingInfo['Status'] == True, "获取锁仓计划返回状态为:{} 有误".format (result['Status'])
        dict_Info = json.loads (RestrictingInfo['Data'])
        assert dict_Info['balance'] == 0, "锁仓金额:{}有误".format (dict_Info['balance'])
        assert dict_Info['symbol'] == False, "锁仓的状态:{} 有误".format (dict_Info['symbol'])
        assert dict_Info['debt'] == 0, "欠释放锁仓金额:{} 有误".format (dict_Info['debt'])

    def test_unlock_point_pledge_punish_amount(self):
        '''
        到达解锁期后处罚节点后锁仓账户的余额情况
        :return:
        '''
        nodeId = CommonMethod.get_no_candidate_list (self)
        log.info("质押节点ID:{}".format(nodeId))
        url = CommonMethod.link_list (self)
        platon_ppos = Ppos (url, self.address, self.chainid)
        address1, private_key1 = CommonMethod.read_private_key_list ()
        address2, private_key2 = CommonMethod.read_private_key_list ()

        # 给发起锁仓账户转手续费
        result = platon_ppos.send_raw_transaction ('', Web3.toChecksumAddress (self.address),
                                                   Web3.toChecksumAddress (address1),
                                                   self.base_gas_price, self.base_gas, self.value, self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt (result)
        assert return_info is not None, "转账:{}失败".format (self.value)

        # 给发起质押账号转手续费
        result = platon_ppos.send_raw_transaction ('', Web3.toChecksumAddress (self.address),
                                                   Web3.toChecksumAddress (address2),
                                                   self.base_gas_price, self.base_gas, self.value,
                                                   self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt (result)
        assert return_info is not None, "转账:{}失败".format (self.value)

        Balance = platon_ppos.eth.getBalance (address1)
        log.info ("{}账户余额:{}".format (address1, Balance))
        Balance1 = platon_ppos.eth.getBalance (address1)
        log.info ("{}账号余额:{}".format (address2, Balance1))

        # 创建锁仓计划
        lockupamoutn = 900
        loukupbalace = Web3.toWei (lockupamoutn, 'ether')
        plan = [{'Epoch': 3, 'Amount': loukupbalace}]
        result = platon_ppos.CreateRestrictingPlan (address2, plan, privatekey=private_key1,
                                                    from_address=address1, gasPrice=self.base_gas_price,
                                                    gas=self.staking_gas)
        assert result['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format (result['Status'])
        RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        assert RestrictingInfo['Status'] == True, "查询锁仓计划返回的状态:{},用例失败".format (result['Status'])
        Balance2 = platon_ppos.eth.getBalance (address1)
        log.info ("{}发起锁仓后账户余额:{}".format (address1, Balance2))

        # 申请质押节点
        version = get_version (platon_ppos)
        amount = 900
        result = platon_ppos.createStaking (1, address2, nodeId, 'externalId', 'nodeName', 'website', 'details',
                                            amount, version, privatekey=private_key2, from_address=address2,
                                            gasPrice=self.base_gas_price, gas=self.staking_gas)
        assert result['Status'] == True, "申请质押返回的状态:{},{},用例失败".format (result['Status'], result['ErrMsg'])
        platon_ppos.GetRestrictingInfo(address2)
        result = platon_ppos.getCandidateInfo(nodeId)
        assert result['Status'] == True, "获取质押节点返回状态为:{} 有误".format (result['Status'])
        RestrictingPlan = result['Data']['RestrictingPlanHes']
        assert RestrictingPlan == Web3.toWei (amount, 'ether'),'质押金额:{} 有误'.format(RestrictingPlan)
        Balance3 = platon_ppos.eth.getBalance (address2)
        log.info ("{}质押完锁仓账户余额:{}".format (address2,Balance3))

        #等待验证人加入共识出块节点
        CommonMethod.get_next_settlement_interval (self,1)
        Balance4 = platon_ppos.eth.getBalance (address2)
        log.info ("{}加入共识验证人后账户余额:{}".format (address2, Balance4))

        # 获取节点内置质押节点信息
        con_node, no_node = get_node_list (self.node_yml_path)
        nodes = con_node + no_node
        for node in nodes:
            if nodeId in node.values ():
                node_data = node
        log.info("{}质押节点信息:{}".format(address2,node_data))

        #停止质押节点
        self.auto = AutoDeployPlaton ()
        self.auto.kill (node_data)
        platon_ppos1 = connect_web3 (node_data['url'])
        assert not platon_ppos1.isConnected(),"节点:{} 连接异常".format(node_data['host'])

        # 到达解锁期后处罚节点后锁仓账户
        CommonMethod.get_next_settlement_interval (self,1)
        Balance5 = platon_ppos.eth.getBalance (address2)
        log.info ("{}到达解锁期后处罚节点后预期账户余额:{}".format (address2,Balance4 + Web3.toWei (amount-(amount * 0.2), 'ether')))
        log.info ("{}到达解锁期后处罚节点后实际账户余额:{}".format (address2,Balance5))
        result = platon_ppos.getCandidateInfo(nodeId)
        assert Balance5 == Balance4 + Web3.toWei (amount-(amount * 0.2), 'ether'), "锁仓账户金额:{} 有误".format (Balance4)
        RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        assert RestrictingInfo['Status'] == True, "获取锁仓计划返回状态为:{} 有误".format (result['Status'])
        dict_Info = json.loads (RestrictingInfo['Data'])
        assert dict_Info['balance'] == 0, "锁仓计划可用金额:{}有误".format (dict_Info['balance'])
        assert dict_Info['symbol'] == True, "欠释放状态:{} 有误".format (dict_Info['symbol'])
        assert dict_Info['debt'] == Web3.toWei (amount-(amount * 0.2), 'ether'), "欠释放锁仓金额:{} 有误".format (dict_Info['debt'])


    def test_eliminated_verifier_create_lockup(self):
        '''
        验证人违规被剔除验证人列表,申请质押节点
        :return:
        '''
        nodeId = CommonMethod.get_no_candidate_list (self)
        url = CommonMethod.link_list (self)
        platon_ppos = Ppos (url, self.address, self.chainid)
        address1, private_key1 = CommonMethod.read_private_key_list ()

        # 签名转账
        result = platon_ppos.send_raw_transaction ('', Web3.toChecksumAddress (self.address),
                                                   Web3.toChecksumAddress (address1),
                                                   self.base_gas_price, self.base_gas, self.value, self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt (result)
        assert return_info is not None, "转账:{}失败".format (self.value)

        balance = platon_ppos.eth.getBalance (address1)
        log.info ("{}发起锁仓账户余额:{}".format (address1,balance))

        # 创建锁仓计划
        lockupamoutn = 900
        loukupbalace = Web3.toWei (lockupamoutn, 'ether')
        plan = [{'Epoch': 5, 'Amount': loukupbalace}]
        result = platon_ppos.CreateRestrictingPlan (address1, plan, privatekey=private_key1,
                                                    from_address=address1, gasPrice=self.base_gas_price,
                                                    gas=self.staking_gas)
        assert result['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format (result['Status'])
        RestrictingInfo = platon_ppos.GetRestrictingInfo (address1)
        assert RestrictingInfo['Status'] == True, "查询锁仓计划返回的状态:{},用例失败".format (result['Status'])

        # 申请质押节点
        version = get_version (platon_ppos)
        amount = 200
        result = platon_ppos.createStaking (1, address1, nodeId, 'externalId', 'nodeName', 'website', 'details',
                                            amount, version, privatekey=private_key1, from_address=address1,
                                            gasPrice=self.base_gas_price, gas=self.staking_gas)
        assert result['Status'] == True, "申请质押返回的状态:{},{},用例失败".format (result['Status'], result['ErrMsg'])
        result = platon_ppos.getCandidateInfo(nodeId)
        log.info("质押节点信息:{}".format(result))

        # 等待成为共识验证人
        CommonMethod.get_next_settlement_interval (self)
        CandidateInfo = platon_ppos.getCandidateInfo(nodeId)
        log.info("验证人信息{}".format(CandidateInfo))
        VerifierList = platon_ppos.getVerifierList ()
        log.info ("当前验证人列表:{}".format (VerifierList))
        ValidatorList = platon_ppos.getValidatorList()
        log.info("当前共识验证人列表:{}".format(ValidatorList))



        # for dictinfo in CandidateInfo['Data']:
        #     if nodeId == dictinfo['NodeId']:
        #         log.info("节点id:{}已成为共识验证人".format(nodeId))
        #         break
        #     else:
        #         log.info("节点id:{}未成为共识验证人".format(nodeId))
        #         status=0
        #         assert status == 1

        # 获取节点内置质押节点信息
        con_node, no_node = get_node_list (self.node_yml_path)
        nodes = con_node + no_node
        for node in nodes:
            if nodeId in node.values ():
                node_data = node

        # 停止其中一个正在出块的节点信息
        self.auto = AutoDeployPlaton ()
        self.auto.kill (node_data)
        platon_ppos1 = connect_web3 (node_data['url'])
        assert not platon_ppos1.isConnected (), "节点:{} 连接异常".format (node_data['host'])

        # 等待节点被剔除验证人列表
        CommonMethod.get_next_consensus_wheel (self,2)

        # 申请质押节点
        version = get_version (platon_ppos)
        amount = 200
        result = platon_ppos.createStaking (1, address1, nodeId, 'externalId', 'nodeName', 'website', 'details',
                                            amount, version, privatekey=private_key1, from_address=address1,
                                            gasPrice=self.base_gas_price, gas=self.staking_gas)
        assert result['Status'] == False, "申请质押返回的状态:{},用例失败".format (result['Status'])

    def test_owe_amountstack_lock_plan(self):
        '''
        到达解锁时间点,如果账户锁仓不足再新增新的锁仓计划
        :return:
        '''
        nodeId = CommonMethod.get_no_candidate_list (self)
        url = CommonMethod.link_list (self)
        platon_ppos = Ppos (url, self.address, self.chainid)
        address1, private_key1 = CommonMethod.read_private_key_list ()
        address2, private_key2 = CommonMethod.read_private_key_list ()

        # 签名转账
        result = platon_ppos.send_raw_transaction ('', Web3.toChecksumAddress (self.address),
                                                   Web3.toChecksumAddress (address1),
                                                   self.base_gas_price, self.base_gas, self.value, self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt (result)
        assert return_info is not None, "转账:{}失败".format (self.value)

        # 创建锁仓计划
        lockupamoutn = 500
        loukupbalace = Web3.toWei (lockupamoutn, 'ether')
        plan = [{'Epoch': 1, 'Amount': loukupbalace}]
        result = platon_ppos.CreateRestrictingPlan (address2, plan, privatekey=private_key1,
                                                    from_address=address1, gasPrice=self.base_gas_price,
                                                    gas=self.staking_gas)
        assert result['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format (result['Status'])
        RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        assert RestrictingInfo['Status'] == True, "查询锁仓计划返回的状态:{},用例失败".format (result['Status'])

        # 给锁仓账号转手续费
        result = platon_ppos.send_raw_transaction ('', Web3.toChecksumAddress (self.address),
                                                   Web3.toChecksumAddress (address2),
                                                   self.base_gas_price, self.base_gas, self.value,
                                                   self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt (result)
        assert return_info is not None, "转账:{}失败".format (self.value)
        balance = platon_ppos.eth.getBalance(address2)
        log.info("锁仓账户余额:{}".format(balance))

        # 申请质押节点
        version = get_version (platon_ppos)
        amount = 500
        result = platon_ppos.createStaking (1, address2, nodeId, 'externalId', 'nodeName', 'website', 'details',
                                            amount, version, privatekey=private_key2, from_address=address2,
                                            gasPrice=self.base_gas_price, gas=self.staking_gas)
        assert result['Status'] == True, "申请质押返回的状态:{},{},用例失败".format (result['Status'], result['ErrMsg'])

        #到达解锁期释放锁仓金额
        CommonMethod.get_next_settlement_interval (self)
        platon_ppos.GetRestrictingInfo(address2)
        balance = platon_ppos.eth.getBalance(address2)
        log.info("到达解锁期释放锁仓余额:{}".format(balance))

        # 创建锁仓计划
        lockupamoutn = 100
        loukupbalace = Web3.toWei (lockupamoutn, 'ether')
        plan = [{'Epoch': 1, 'Amount': loukupbalace}]
        result = platon_ppos.CreateRestrictingPlan (address2, plan, privatekey=private_key1,
                                                    from_address=address1, gasPrice=self.base_gas_price,
                                                    gas=self.staking_gas)
        assert result['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format (result['Status'])
        RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        assert RestrictingInfo['Status'] == True, "查询锁仓计划返回的状态:{},用例失败".format (result['Status'])
        dict_Info = json.loads (RestrictingInfo['Data'])
        assert dict_Info['balance'] == Web3.toWei (100, 'ether'), "锁仓金额:{}有误".format (dict_Info['balance'])
        assert dict_Info['symbol'] == True, "锁仓的状态:{} 有误".format (dict_Info['symbol'])
        assert dict_Info['debt'] == Web3.toWei (500, 'ether'), "欠释放锁仓金额:{} 有误".format (dict_Info['debt'])



    def testss(self):
        url = CommonMethod.link_list (self)
        platon_ppos = Ppos (url, self.address, self.chainid)
        while 1:
            block = platon_ppos.eth.blockNumber
            print(block)
コード例 #6
0
class TestDposinit:
    address = conf.ADDRESS
    pwd = conf.PASSWORD
    abi = conf.DPOS_CONTRACT_ABI
    cbft_json_path = conf.CBFT2
    node_yml_path = conf.PPOS_NODE_TEST_YML
    file = conf.CASE_DICT
    privatekey = conf.PRIVATE_KEY
    base_gas_price = 60000000000000
    base_gas = 21000
    staking_gas = base_gas + 32000 + 6000 + 100000
    transfer_gasPrice = Web3.toWei(1, 'ether')
    transfer_gas = 210000000
    value = 1000
    chainid = 120
    ConsensusSize = 150
    time_interval = 10
    initial_amount = {
        'FOUNDATION': 905000000000000000000000000,
        'FOUNDATIONLOCKUP': 20000000000000000000000000,
        'STAKING': 25000000000000000000000000,
        'INCENTIVEPOOL': 45000000000000000000000000,
        'DEVELOPERS': 5000000000000000000000000
    }

    def start_init(self):
        # 修改config参数
        CommonMethod.update_config(self, 'EconomicModel', 'Common',
                                   'ExpectedMinutes', 3)
        CommonMethod.update_config(self, 'EconomicModel', 'Common',
                                   'PerRoundBlocks', 5)
        CommonMethod.update_config(self, 'EconomicModel', 'Common',
                                   'ValidatorCount', 10)
        CommonMethod.update_config(self, 'EconomicModel', 'Staking',
                                   'ElectionDistance', 10)
        CommonMethod.update_config(self, 'EconomicModel', 'Staking',
                                   'StakeThreshold', 1000)
        # 启动节点
        self.auto = AutoDeployPlaton()
        self.auto.start_all_node(self.node_yml_path)

    def test_init_token(self):
        '''
        验证链初始化后token各内置账户初始值
        :return:
        '''
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        FOUNDATION = platon_ppos.eth.getBalance(
            Web3.toChecksumAddress(conf.FOUNDATIONADDRESS))
        FOUNDATIONLOCKUP = platon_ppos.eth.getBalance(
            Web3.toChecksumAddress(conf.FOUNDATIONLOCKUPADDRESS))
        STAKING = platon_ppos.eth.getBalance(
            Web3.toChecksumAddress(conf.STAKINGADDRESS))
        INCENTIVEPOOL = platon_ppos.eth.getBalance(
            Web3.toChecksumAddress(conf.INCENTIVEPOOLADDRESS))
        DEVELOPERS = platon_ppos.eth.getBalance(
            Web3.toChecksumAddress(conf.DEVELOPERSADDRESS))
        token_init_total = conf.TOKENTOTAL
        if self.initial_amount['FOUNDATION'] != FOUNDATION:
            log.info("基金会初始金额:{}有误".format(FOUNDATION))
        elif self.initial_amount['FOUNDATIONLOCKUP'] != FOUNDATIONLOCKUP:
            log.info("基金会锁仓初始金额:{}有误".format(FOUNDATIONLOCKUP))
        elif self.initial_amount['STAKING'] != STAKING:
            log.info("质押账户初始金额:{}有误".format(STAKING))
        elif self.initial_amount['INCENTIVEPOOL'] != INCENTIVEPOOL:
            log.info("奖励池初始金额:{}有误".format(INCENTIVEPOOL))
        elif self.initial_amount['DEVELOPERS'] != DEVELOPERS:
            log.info("预留账户初始金额:{}有误".format(DEVELOPERS))
        reality_total = FOUNDATION + FOUNDATIONLOCKUP + STAKING + INCENTIVEPOOL + DEVELOPERS
        assert token_init_total == (
            reality_total), "初始化发行值{}有误".format(reality_total)

    def test_transfer_normal(self):
        '''
        验证初始化之后账户之间转账
        :return:
        '''
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        address1, private_key1 = CommonMethod.read_private_key_list()
        # 签名转账
        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address1), self.base_gas_price,
            self.base_gas, self.value, self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt(result)
        assert return_info is not None, "转账:{}失败".format(self.value)
        balance = platon_ppos.eth.getBalance(address1)
        log.info("转账金额{}".format(balance))
        assert Web3.toWei(self.value,
                          'ether') == balance, "转账金额:{}失败".format(balance)

    def test_fee_income(self):
        '''
        1、验证初始化之后普通账户转账内置账户
        2、验证初始内置账户没有基金会Staking奖励和出块奖励只有手续费收益
        :return:
        '''
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        incentive_pool_balance_befor = platon_ppos.eth.getBalance(
            conf.INCENTIVEPOOLADDRESS)
        log.info('交易前激励池查询余额:{}'.format(incentive_pool_balance_befor))
        address1, private_key1 = CommonMethod.read_private_key_list()
        # 签名转账
        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address1), self.base_gas_price,
            self.base_gas, self.value, self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt(result)
        assert return_info is not None, "转账:{}失败".format(self.value)
        incentive_pool_balance_after = platon_ppos.eth.getBalance(
            conf.INCENTIVEPOOLADDRESS)
        log.info('交易后激励池查询余额:{}'.format(incentive_pool_balance_after))
        difference = incentive_pool_balance_after - incentive_pool_balance_befor
        log.info('手续费的金额:{}'.format(difference))
        assert difference == 1260000000000000000, "手续费{}有误".format(difference)

    def test_punishment_income(self):
        '''
        验证低出块率验证节点的处罚金自动转账到激励池
        :return:
        '''
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        incentive_pool_balance_befor = platon_ppos.eth.getBalance(
            conf.INCENTIVEPOOLADDRESS)
        log.info('处罚之前激励池查询余额:{}'.format(incentive_pool_balance_befor))

        #获取节点内置质押节点信息
        nodeId = CommonMethod.read_out_nodeId(self, 'collusion')
        log.info("节点ID:{}".format(nodeId))
        con_node, no_node = get_node_list(self.node_yml_path)
        nodes = con_node + no_node
        for node in nodes:
            if nodeId in node.values():
                node_data = node

        #获取节点质押金额
        punishment_CandidateInfo = platon_ppos.getCandidateInfo(nodeId)
        assert punishment_CandidateInfo['Status'] == True, "查询锁仓信息失败"
        pledge_amount1 = punishment_CandidateInfo['Data']['Released']
        log.info("质押节点质押金:{}".format(pledge_amount1))

        # 停止其中一个正在出块的节点信息
        self.auto = AutoDeployPlaton()
        self.auto.kill(node_data)
        platon_ppos1 = connect_web3(node_data['url'])
        assert not platon_ppos1.isConnected(), "节点:{} 连接异常".format(
            node_data['host'])
        CommonMethod.get_next_settlement_interval(self)
        punishment_CandidateInfo = platon_ppos.getCandidateInfo(nodeId)
        pledge_amount3 = punishment_CandidateInfo['Data']['Released']
        log.info("节点低出块率后节点质押金:{}".format(pledge_amount3))
        incentive_pool_balance_after = platon_ppos.eth.getBalance(
            conf.INCENTIVEPOOLADDRESS)
        log.info('处罚之后激励池查询余额:{}'.format(incentive_pool_balance_after))
        assert incentive_pool_balance_after == incentive_pool_balance_befor + (
            pledge_amount1 - pledge_amount3)
コード例 #7
0
ファイル: test_dpos.py プロジェクト: wyq5610522/PlatON-Tests
class TestDpos:
    node_yml_path = conf.NODE_YML
    cbft_json_path = conf.CBFT2
    node_info = get_node_info(node_yml_path)
    rpc_list, enode_list, nodeid_list, ip_list, port_list = node_info.get(
        'collusion')
    rpc_list2, enode_list2, nodeid_list2, ip_list2, port_list2 = node_info.get(
        'nocollusion')
    cbft_dict = LoadFile(cbft_json_path).get_data()
    address = Web3.toChecksumAddress(conf.ADDRESS)
    pwd = conf.PASSWORD
    ticket_price = Web3.fromWei(
        int(cbft_dict['ppos']['ticket']['ticketPrice']), 'ether')
    allowed = int(cbft_dict['ppos']['candidate']['allowed'])
    total_ticket = int(cbft_dict['ppos']['ticket']['maxCount'])
    rpc_list += rpc_list2
    enode_list += enode_list2
    nodeid_list += nodeid_list2
    ip_list += ip_list2
    port_list += port_list2
    key_list = ["node" + str(i) for i in range(1, 1 + len(rpc_list))]
    rpc_dict = dict(zip(key_list, rpc_list))
    enode_dict = dict(zip(key_list, enode_list))
    nodeid_dict = dict(zip(key_list, nodeid_list))
    ip_dict = dict(zip(key_list, ip_list))
    port_dict = dict(zip(key_list, port_list))
    abi = conf.DPOS_CONTRACT_ABI

    def setup_class(self):
        self.auto = AutoDeployPlaton(cbft=self.cbft_json_path)
        self.auto.start_all_node(self.node_yml_path)
        self.platon_dpos1 = PlatonDpos(
            self.rpc_list[0], self.address, self.pwd, abi=self.abi)
        self.w3_list = [connect_web3(url) for url in self.rpc_list]
        self.new_address = Web3.toChecksumAddress(
            self.platon_dpos1.web3.personal.newAccount(self.pwd))
        self.send_data = {
            "to": self.new_address,
            "from": self.address,
            "gas": '9000',
            "gasPrice": '1000000000',
            "value": self.w3_list[0].toWei(100000, 'ether'),
        }
        tx_hash = self.platon_dpos1.eth.sendTransaction(self.send_data)
        self.platon_dpos1.eth.waitForTransactionReceipt(tx_hash)
        self.platon_dpos2 = PlatonDpos(
            self.rpc_list[0], self.new_address, self.pwd, abi=self.abi)
        self.fee = int(1000).to_bytes(4, 'big')
        self.extra = "Test"

    # def teardown_class(self):
    #     self.auto.start_all_node(self.node_yml_path)

    def check_event(self, msg):
        event_data, func_name = msg
        func_name += "Event"
        assert func_name in event_data, "{}中不包含{}键".format(
            event_data, func_name)
        event = event_data[func_name][0]
        event = json.loads(event)
        assert event["Ret"], "质押结果状态错误"
        assert event["ErrMsg"] == "success", "质押结果msg错误"

    def test_candidate_deposit(self):
        '''
        @Description: 质押节点,使其成为候选人
        @param {type} @@@@
        @return: @@@@
        '''
        result = self.platon_dpos1.CandidateDeposit(self.nodeid_dict['node5'], self.new_address, self.fee,
                                                    self.ip_dict['node5'],
                                                    self.port_dict['node5'], self.extra, value=100)
        self.check_event(result)
        candidate_info = self.platon_dpos1.GetCandidateDetails(
            self.nodeid_dict['node5'])
        assert isinstance(candidate_info, dict), "返回结果错误{}".format(
            candidate_info)
        assert candidate_info["Deposit"] == self.platon_dpos1.web3.toWei(
            100, 'ether')
        assert candidate_info["Host"] == self.ip_dict["node5"], "质押ip与传输的ip不一致"
        assert candidate_info["CandidateId"] == self.nodeid_dict["node5"], "质押nodeid与传输的不一致"
        assert candidate_info["Port"] == self.port_dict['node5'], "质押端口与传输的不一致,获取port:{},实际质押port:{}".format(
            candidate_info["Port"], self.port_dict['node5'])
        assert self.platon_dpos1.web3.toChecksumAddress(
            candidate_info["Owner"]) == self.new_address, "质押地址不正确"
        candidate_list = self.platon_dpos2.GetCandidateList()
        # 校验candidate_list包含节点179
        assert candidate_info in candidate_list, "候选人列表不包含节点{}".format(
            self.ip_dict['node5'])

    # @pytest.mark.skip
    # def add_pledge(self):
    #     '''
    #     已不支持增加质押,用例暂不执行
    #     增加质押
    #     :return:
    #     '''
    #     result = self.platon_dpos1.CandidateDeposit(self.nodeid_dict['node5'], self.new_address, self.fee,
    #                                                 self.ip_dict['node5'],
    #                                                 self.port_dict['node5'], self.extra, value=10)
    #     self.check_event(result)
    #     candidate_info = self.platon_dpos1.GetCandidateDetails(
    #         self.nodeid_dict['node5'])
    #     # candidate_info为节点179的质押信息
    #     assert isinstance(candidate_info, dict), "返回结果错误{}".format(
    #         candidate_info)
    #     assert candidate_info["Deposit"] == self.platon_dpos1.web3.toWei(
    #         60, 'ether')

    # @pytest.mark.skip
    # def test_refund_10(self):
    #     '''
    #     已不支持部分退款,用例暂不执行
    #     @Description: 查询退款金额低于10%
    #     @param {type} @@@@
    #     @return: @@@@
    #     '''
    #     i = 500000000000000000
    #     status = 0
    #     try:
    #         self.platon_dpos2.CandidateApplyWithdraw(
    #             self.nodeid_dict['node5'], i)
    #     except:
    #         status = 1
    #     assert status == 1, "低于10%应不允许提取"

    def test_refund(self):
        '''
        @Description: 查询退款是否正常,是否退出候选人列表
        @param {type} @@@@
        @return: @@@@
        '''
        i = 50000000000000000000
        start_balance = self.platon_dpos2.eth.getBalance(self.new_address)
        result = self.platon_dpos2.CandidateDeposit(self.nodeid_dict['node6'], self.new_address, self.fee,
                                                    self.ip_dict['node6'],
                                                    self.port_dict['node6'], self.extra, value=50)
        candidate_info = self.platon_dpos1.GetCandidateDetails(
            self.nodeid_dict['node6'])
        self.check_event(result)
        result = self.platon_dpos2.CandidateApplyWithdraw(
            self.nodeid_dict['node6'], i)
        self.check_event(result)
        time.sleep(3)
        withdraw_list = self.platon_dpos2.GetCandidateWithdrawInfos(
            self.nodeid_dict['node6'])
        assert withdraw_list["Balance"] == i, "申请退款的金额与查询结果不一致"
        result = self.platon_dpos1.CandidateWithdraw(self.nodeid_dict["node6"])
        self.check_event(result)
        end_balance = self.platon_dpos1.eth.getBalance(self.new_address)
        assert end_balance - start_balance < 100000000000000000, "退款金额错误,退款前:{}|退款后:{}".format(
            self.platon_dpos1.web3.fromWei(start_balance, 'ether'), self.platon_dpos1.web3.fromWei(end_balance, 'ether'))
        candidate_list = self.platon_dpos1.GetCandidateList()
        assert candidate_info not in candidate_list, "node6还在候选人列表中"

    def test_candidate_sort(self):
        '''
        @Description: 候选人排序
        @param {type} @@@@
        @return: @@@@
        '''
        # result_1 = self.platon_dpos1.CandidateDeposit(self.nodeid_dict['node5'], self.new_address, self.fee,
        #                                               self.ip_dict['node5'],
        #                                               self.port_dict['node5'], self.extra, value=45)
        # self.check_event(result_1)
        result_2 = self.platon_dpos1.CandidateDeposit(self.nodeid_dict['node6'], self.new_address, self.fee,
                                                      self.ip_dict['node6'],
                                                      self.port_dict['node6'], self.extra, value=160)
        self.check_event(result_2)
        candidate_list = self.platon_dpos1.GetCandidateList()
        candidate_info = self.platon_dpos1.GetCandidateDetails(
            self.nodeid_dict['node6'])
        assert candidate_list[0] == candidate_info, "候选人列表排序错误"

    def test_candidate_cap(self):
        '''
        @Description: 候选人列表容量
        @param {type} @@@@
        @return: @@@@
        '''
        status = 0
        candidate_info = self.platon_dpos1.GetCandidateDetails(
            self.nodeid_dict['node5'])
        result_1 = self.platon_dpos1.CandidateDeposit(self.nodeid_dict['node1'], self.new_address, self.fee,
                                                      self.ip_dict['node1'],
                                                      self.port_dict['node1'], self.extra, value=131)
        self.check_event(result_1)
        result_2 = self.platon_dpos1.CandidateDeposit(self.nodeid_dict['node2'], self.new_address, self.fee,
                                                      self.ip_dict['node2'],
                                                      self.port_dict['node2'], self.extra, value=135)
        self.check_event(result_2)
        result_3 = self.platon_dpos1.CandidateDeposit(self.nodeid_dict['node3'], self.new_address, self.fee,
                                                      self.ip_dict['node3'],
                                                      self.port_dict['node3'], self.extra, value=135)
        self.check_event(result_3)
        result_4 = self.platon_dpos1.CandidateDeposit(self.nodeid_dict['node4'], self.new_address, self.fee,
                                                      self.ip_dict['node4'],
                                                      self.port_dict['node4'], self.extra, value=140)
        self.check_event(result_4)
        candidate_list = self.platon_dpos1.GetCandidateList()
        log.info("入围节点列表:{}".format(candidate_list))
        assert candidate_info not in candidate_list, "node5还在候选人列表中"

    def test_ticket_price(self):
        '''校验票价是否与配置文件中一致'''
        price = self.platon_dpos1.GetTicketPrice()
        config_price = Web3.toWei(self.ticket_price, 'ether')
        assert config_price == price, '实际票价:{},与配置文件中:{},不一致'.format(
            config_price, price)

    def test_vote_ticket(self):
        '''投票'''
        value = self.allowed * self.ticket_price
        vote_info, _ = self.platon_dpos1.VoteTicket(self.allowed, self.ticket_price, self.nodeid_dict['node6'],
                                                    self.new_address, value)
        self.platon_dpos1.VoteTicket(self.allowed, self.ticket_price, self.nodeid_dict['node1'],
                                     self.new_address, value)
        self.platon_dpos1.VoteTicket(self.allowed, self.ticket_price, self.nodeid_dict['node2'],
                                     self.new_address, value)
        self.platon_dpos1.VoteTicket(self.allowed, self.ticket_price, self.nodeid_dict['node3'],
                                     self.new_address, value)
        vote_info, _ = self.platon_dpos1.VoteTicket(self.allowed - 1, self.ticket_price, self.nodeid_dict['node4'],
                                     self.new_address, value - 1)
        assert 'success' in vote_info['VoteTicketEvent'][0], '投票失败,结果:{}'.format(
            vote_info)

    # @pytest.skip
    # def test_ticket_detail(self):
    #     '''
    #     接口已经删除,用例屏蔽
    #     验证节点下选票数量、选票的详细信息
    #     '''
    #     ticket_ids = self.platon_dpos1.GetCandidateTicketIds(self.nodeid_dict['node1'])
    #     ticket_num = len(ticket_ids)
    #     assert ticket_num == self.allowed, '节点选票数:{}与已投票数:{}不一致'.format(ticket_num, self.allowed)
    #     ticket_detail = self.platon_dpos1.GetTicketDetail(ticket_ids[0])
    #     owner = Web3.toChecksumAddress(ticket_detail[0]['Owner'])
    #     assert owner == self.new_address, '投票人:{}与投票时用的钱包地址:{}不一致'.format(owner, self.new_address)
    #     dposite = ticket_detail[0]['Deposit']
    #     price = Web3.toWei(self.ticket_price, 'ether')
    #     assert dposite == price, '投票金额:{}与票价:{}不一致'.format(dposite, price)
    #     candidateid = ticket_detail[0]['CandidateId']
    #     assert candidateid == self.nodeid_dict['node1'], '票详情中节点id:{},与投票时节点id不一致:{}'.format(candidateid,
    #                                                                                          self.nodeid_dict['node1'])

    # @pytest.skip
    # def test_batch_ticket_detail(self):
    #     '''
    #     接口已删除,用例屏蔽
    #     验证批量获取节点下选票数量、选票的详细信息
    #     '''
    #     batch_ticket_ids = self.platon_dpos1.GetBatchCandidateTicketIds(
    #         [self.nodeid_dict['node1'], self.nodeid_dict['node2']])
    #     print('batch_ticket_ids = ', batch_ticket_ids)
    #     ticket_ids = batch_ticket_ids[0].get(self.nodeid_dict['node1'])
    #     ticket_ids_one = self.platon_dpos1.GetCandidateTicketIds(self.nodeid_dict['node1'])
    #     assert ticket_ids == ticket_ids_one, '批量获取详情{}\n单独获取详情{}不一致'.format(ticket_ids, ticket_ids_one)
    #     node1_tickets = batch_ticket_ids[0].get(self.nodeid_dict['node1'])
    #     node2_tickets = batch_ticket_ids[0].get(self.nodeid_dict['node2'])
    #     ticket_details = self.platon_dpos1.GetBatchTicketDetail([node1_tickets[0], node2_tickets[0]])
    #     ticket_detail = ticket_details[0]
    #     ticket_detail_one = self.platon_dpos1.GetTicketDetail(ticket_details[0]['TicketId'])[0]
    #     assert ticket_detail == ticket_detail_one, '批量获取的票详情{}与单独查询票详情不一致{}'.format(ticket_detail, ticket_detail_one)
    #     assert len(ticket_details) == 2, '批量获取票详情数{}不等于请求数2'.format(len(ticket_details))

    def test_vote_undpos_node(self):
        '''向非备选池节点投票'''
        value = self.allowed * self.ticket_price
        status = 0
        try:
            self.platon_dpos1.VoteTicket(self.allowed, self.ticket_price, self.nodeid_dict['node5'],
                                         self.new_address, value)
        except:
            status = 1
        assert status, '不在备选池的节点不能投票成功'

    def test_ticket_pool_remainder(self):
        '''验证票池剩余数量'''
        remaind = self.platon_dpos1.GetPoolRemainder()
        should_remaind = self.total_ticket - (self.allowed * 5 - 1)
        assert remaind == should_remaind, '票池剩余票:{}与已消费后应剩余数:{}不一致'.format(
            remaind, should_remaind)

    # @pytest.skip
    # def test_get_candidate_epoch(self):
    #     '''
    #     获取票龄详情接口已删除,无法获取选票产生区块,用例无法验证
    #     该接口以后会去掉,用例暂不运行
    #     验证候选人票龄
    #     '''
    #     ticket_ids = self.platon_dpos1.GetCandidateTicketIds(self.nodeid_dict['node1'])
    #     vote_block_number = self.platon_dpos1.GetTicketDetail(ticket_ids[0])[0]['BlockNumber']
    #     should_epoch = (self.platon_dpos1.eth.blockNumber - vote_block_number + 1) * len(ticket_ids)
    #     epoch = self.platon_dpos1.GetCandidateEpoch(self.nodeid_dict['node1'])
    #     assert epoch == should_epoch, '候选人票龄计算结果:{},与预期结果:{}不一致'.format(epoch, should_epoch)

    def test_get_candidate_ticket_count(self):
        '''批量查询候选节点的有效选票数量'''
        ctc_dict = self.platon_dpos1.GetCandidateTicketCount(
            '{}:{}:{}:{}'.format(self.nodeid_dict['node1'], self.nodeid_dict['node2'], self.nodeid_dict['node3'],
                                 self.nodeid_dict['node4']))
        count1 = int(ctc_dict.get(self.nodeid_dict['node1']))
        count2 = int(ctc_dict.get(self.nodeid_dict['node2']))
        count3 = int(ctc_dict.get(self.nodeid_dict['node3']))
        count4 = int(ctc_dict.get(self.nodeid_dict['node4']))
        assert count1 == self.allowed, '候选节点有效选票数量{},与预期结果{}不一致'.format(
            count1, self.allowed)
        assert count2 == self.allowed, '候选节点有效选票数量{},与预期结果{}不一致'.format(
            count2, self.allowed)
        assert count3 == self.allowed, '候选节点有效选票数量{},与预期结果{}不一致'.format(
            count3, self.allowed)
        assert count4 == self.allowed - \
            1, '候选节点有效选票数量{},与预期结果{}不一致'.format(count4, self.allowed)

    # def test_get_ticket_count_by_tx_hash(self):
    #     '''批量查询交易的有效选票数量'''
    #     _, tx_hash1 = self.platon_dpos1.VoteTicket(
    #         self.allowed, 1, self.nodeid_dict['node1'], self.address, 10)
    #     _, tx_hash2 = self.platon_dpos1.VoteTicket(
    #         self.allowed, 1, self.nodeid_dict['node2'], self.address, 10)
    #     _, tx_hash3 = self.platon_dpos1.VoteTicket(
    #         self.allowed, 1, self.nodeid_dict['node3'], self.address, 10)
    #     _, tx_hash4 = self.platon_dpos1.VoteTicket(
    #         self.allowed, 1, self.nodeid_dict['node4'], self.address, 10)
    #     tc_dict = self.platon_dpos1.GetTicketCountByTxHash(
    #         '{}:{}:{}:{}'.format(tx_hash1, tx_hash2, tx_hash3, tx_hash4))
    #     assert tc_dict.get(tx_hash1) == self.allowed, '交易的有效选票数量{},与预期结果{}不一致'.format(tc_dict.get(tx_hash1),
    #                                                                                   self.allowed)
    #     assert tc_dict.get(tx_hash2) == self.allowed, '交易的有效选票数量{},与预期结果{}不一致'.format(tc_dict.get(tx_hash2),
    #                                                                                   self.allowed)
    #     assert tc_dict.get(tx_hash3) == self.allowed, '交易的有效选票数量{},与预期结果{}不一致'.format(tc_dict.get(tx_hash3),
    #                                                                                   self.allowed)
    #     assert tc_dict.get(tx_hash4) == self.allowed, '交易的有效选票数量{},与预期结果{}不一致'.format(tc_dict.get(tx_hash4),
    #                                                                                   self.allowed)

    def test_verifiers(self):
        '''
        @Description: 验证人为候选人列表的前四,幸运票奖励发放
        @param {type} @@@@
        @return: @@@@
        '''
        before_reward = self.platon_dpos1.eth.getBalance(self.new_address)
        candidate_list = self.platon_dpos1.GetCandidateList()
        log.info("新的的入围节点列表:{}".format(candidate_list))
        candidate_id = [i['CandidateId'] for i in candidate_list]
        block_number = self.platon_dpos1.eth.blockNumber
        sleep_time = get_sleep_time(block_number)
        time.sleep(sleep_time)
        verfier_info_list = self.platon_dpos1.GetVerifiersList()
        log.info("验证人列表:{}".format(verfier_info_list))
        assert len(verfier_info_list) > 0,"查询结果异常,验证人列表为空。"
        verfier_list = [info['CandidateId'] for info in verfier_info_list]
        assert verfier_list == candidate_id[:4], "验证人没有取候选人的前四,验证人id:{}\n候选人id:{}".format(verfier_list,
                                                                                            candidate_list[:4])
        status = 1
        for verfier in verfier_list:
            if self.nodeid_dict['node4'] in verfier:
                status = 0
        assert status, '投票不达到门槛不能成为见证人'
        # 校验幸运选票是否发放奖励
        after_reward = self.platon_dpos1.eth.getBalance(self.new_address)
        assert after_reward > before_reward, '见证人奖励未发放,发放前余额:{},发放后余额:{}'.format(
            before_reward, after_reward)

    def test_verify_transaction(self):
        '''
        @Description: 切换验证人后,测试交易是否成功,所有节点块高是否一致
        @param {type} @@@@
        @return: @@@@
        '''
        tx_hash = self.platon_dpos1.eth.sendTransaction(self.send_data)
        self.platon_dpos1.eth.waitForTransactionReceipt(tx_hash)
        block_list = []
        for w in self.w3_list:
            block_list.append(w.eth.blockNumber)
        assert min(block_list) > 60, "区块没有正常增加"
        assert max(block_list) - min(block_list) < 5, "各节点区块高度差距过高"
        time.sleep(60)
        w3 = Web3(Web3.HTTPProvider(self.rpc_dict["node6"]))
        assert w3.net.peerCount >= 3, "节点node6连接的节点数少于3个"
コード例 #8
0
class CommonMethod():
    address = conf.ADDRESS
    pwd = conf.PASSWORD
    abi = conf.DPOS_CONTRACT_ABI
    cbft_json_path = conf.CBFT2
    node_yml_path = conf.PPOS_NODE_TEST_YML
    file = conf.CASE_DICT
    privatekey = conf.PRIVATE_KEY
    gasPrice = Web3.toWei(0.000000000000000001, 'ether')
    gas = 21000
    transfer_gasPrice = Web3.toWei(1, 'ether')
    transfer_gas = 210000000
    value = 1000
    time_interval = 10
    #ConsensusSize = 50
    ExpectedMinutes = 180
    chainid = 101

    def link_list(self):
        '''
        获取随机一个可以连接正常节点url
        :return:
        '''
        rpc_lastlist = []
        node_info = get_node_info(self.node_yml_path)
        self.rpc_list, enode_list, self.nodeid_list, ip_list, port_list = node_info.get(
            'collusion')
        for i in self.rpc_list:
            self.web3 = connect_web3(i)
            if self.web3.isConnected():
                rpc_lastlist.append(i)
        if rpc_lastlist:
            #log.info("目前可连接节点列表:{}".format(rpc_lastlist))
            index = random.randint(0, len(rpc_lastlist) - 1)
            url = rpc_lastlist[index]
            log.info("当前连接节点:{}".format(url))
            return url
        else:
            log.info("无可用节点")

    def get_next_settlement_interval(self,
                                     number=1,
                                     file=conf.PLATON_CONFIG_PATH):
        '''
        获取下个结算周期
        :param :
        :return:
        '''
        data = LoadFile(file).get_data()
        ExpectedMinutes = data['EconomicModel']['Common']['ExpectedMinutes']
        Interval = data['EconomicModel']['Common']['Interval']
        PerRoundBlocks = data['EconomicModel']['Common']['PerRoundBlocks']
        ValidatorCount = data['EconomicModel']['Common']['ValidatorCount']
        Consensuswheel = (ExpectedMinutes * 60) // (Interval * PerRoundBlocks *
                                                    ValidatorCount)
        ConsensusSize = Consensuswheel * (Interval * PerRoundBlocks *
                                          ValidatorCount)
        ConsensusSize = ConsensusSize * number
        log.info("结算周期块高:{}".format(ConsensusSize))
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        current_block = platon_ppos.eth.blockNumber
        differ_block = ConsensusSize - (current_block % ConsensusSize)
        current_end_block = current_block + differ_block
        log.info('当前块高:{} ,下个结算周期结束块高:{}'.format(current_block,
                                                 current_end_block))

        while 1:
            time.sleep(self.time_interval)
            current_block = platon_ppos.eth.blockNumber
            differ_block = ConsensusSize - (current_block % ConsensusSize)
            log.info('当前块高度:{},还差块高:{}'.format((current_block), differ_block))
            if current_block > current_end_block:
                break

    def get_next_consensus_wheel(self, number=1, file=conf.PLATON_CONFIG_PATH):
        '''
        获取下个共识轮
        :param :
        :return:
        '''
        data = LoadFile(file).get_data()
        Interval = data['EconomicModel']['Common']['Interval']
        PerRoundBlocks = data['EconomicModel']['Common']['PerRoundBlocks']
        ValidatorCount = data['EconomicModel']['Common']['ValidatorCount']
        ConsensusSize = Interval * PerRoundBlocks * ValidatorCount
        ConsensusSize = ConsensusSize * number
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        current_block = platon_ppos.eth.blockNumber
        differ_block = ConsensusSize - (current_block % ConsensusSize)
        current_end_block = current_block + differ_block
        log.info('当前块高:{} ,下个共识轮周期结束块高:{}'.format(current_block,
                                                  current_end_block))

        while 1:
            time.sleep(self.time_interval)
            current_block = platon_ppos.eth.blockNumber
            differ_block = ConsensusSize - (current_block % ConsensusSize)
            log.info('当前块高度:{},还差块高:{}'.format((current_block), differ_block))
            if current_block > current_end_block:
                break

    def read_out_nodeId(self, code):
        """
        读取节点id列表
        :param code: 共识节点或者非共识节点标识
        :return:
        """
        node_info = get_node_info(self.node_yml_path)
        self.rpc_list, enode_list, nodeid_list, ip_list, port_list = node_info.get(
            code)
        node_list_length = len(nodeid_list)
        index = random.randint(0, node_list_length - 1)
        nodeId = nodeid_list[index]
        return nodeId

    def test(self):
        self.auto = AutoDeployPlaton()
        self.auto.start_all_node(self.node_yml_path)
        # print(self.nodeid_list)

    def query_blockNumber(self):
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        while 1:
            current_block = platon_ppos.eth.blockNumber
            time.sleep(10)
            print(current_block)

    def update_config(self,
                      key1,
                      key2,
                      key3=None,
                      value=None,
                      file=conf.PLATON_CONFIG_PATH):
        '''
        修改config配置参数
        :param key1: 第一层级key
        :param key2: 第二层级key
        :param key3: 第三层级key
        :param value:
        :param file:
        :return:
        '''
        data = LoadFile(file).get_data()
        if key3 == None:
            data[key1][key2] = value
        else:
            data[key1][key2][key3] = value

        data = json.dumps(data)
        with open(conf.PLATON_CONFIG_PATH, "w") as f:
            f.write(data)
            f.close()

    def read_private_key_list(file=conf.PRIVATE_KEY_LIST):
        '''
        随机获取一组钱包地址和私钥
        :return:
        '''
        with open(file, 'r') as f:
            private_key_list = f.read().split("\n")
            index = random.randrange(1, len(private_key_list) - 1)  # 生成随机行数
            address, private_key = private_key_list[index].split(',')
        return address, private_key

    def get_no_candidate_list(self):
        '''
        获取未被质押的节点ID列表
        :return:
        '''
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        node_info = get_node_info(self.node_yml_path)
        self.rpc_list, enode_list, nodeid_list, ip_list, port_list = node_info.get(
            'nocollusion')
        no_candidate_list = []
        for index in range(len(nodeid_list)):
            nodeid = nodeid_list[index]
            result = platon_ppos.getCandidateInfo(nodeid)
            flag = result['Status']

            if not flag:
                no_candidate_list.append(nodeid)
        if no_candidate_list:
            node_list_length = len(no_candidate_list)
            index = random.randint(0, node_list_length - 1)
            nodeId = no_candidate_list[index]
            return nodeId
        else:
            CommonMethod.start_init(self)
            # self.rpc_list, enode_list, nodeid_list, ip_list, port_list = node_info.get ('nocollusion')
            return nodeid_list[0]

    def start_init(self):
        #修改config参数
        CommonMethod.update_config(self, 'EconomicModel', 'Common',
                                   'ExpectedMinutes', 3)
        CommonMethod.update_config(self, 'EconomicModel', 'Common',
                                   'PerRoundBlocks', 10)
        CommonMethod.update_config(self, 'EconomicModel', 'Common',
                                   'ValidatorCount', 5)
        CommonMethod.update_config(self, 'EconomicModel', 'Staking',
                                   'ElectionDistance', 20)
        CommonMethod.update_config(self, 'EconomicModel', 'Staking',
                                   'StakeThreshold', 1000)
        #启动节点
        self.auto = AutoDeployPlaton()
        self.auto.start_all_node(self.node_yml_path)

    def View_available_nodes(self):
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        node_info = get_node_info(self.node_yml_path)
        self.rpc_list, enode_list, nodeid_list, ip_list, port_list = node_info.get(
            'nocollusion')
        candidateinfo = platon_ppos.getCandidateList()
        candidateinfo = candidateinfo.get('Data')
        candidate_list = []
        for nodeid in candidateinfo:
            candidate_list.append(nodeid.get('NodeId'))

        if set(nodeid_list) <= set(candidate_list):
            CommonMethod.start_init(self)
コード例 #9
0
    def test_block_cycle_duration(self, period, duration, delay_time, number):
        '''
        用例id 6,7,8,9,10
        测试duration的不同值,观察出块周期
        根据5种场景,出块周期约为10,20,30,50,100
        '''
        self.get_cbft_json_data(period, duration)
        auto = AutoDeployPlaton(cbft=self.cbft_path)
        log.info("上传cbft文件成功")
        auto.start_all_node(self.node_yml)
        time.sleep(delay_time)
        log.info("跟所有节点建立连接")
        w3_list = [connect_web3(url) for url in self.url_list]
        w3 = w3_list[0]
        block_number = w3.eth.blockNumber
        if block_number > 0:
            log.info("正在出块,块高:{}".format(block_number))
        if block_number < number:
            raise Exception("出块很慢,没达到预期{}".format(number))
        node_id_dict = {}
        log.info("获取1至{}块的nodeID".format(number))
        for block in range(1, number):
            node_id = get_pub_key(self.url_list[0], block)
            if node_id not in node_id_dict.keys():
                node_id_dict[node_id] = [block]
            else:
                node_id_dict[node_id].append(block)
        log.info("获取到全部的nodeID对应的出块".format(node_id_dict))
        log.info("由于第一组nodeID收集数据不全,从第二组开始收集统计,删除第一组")
        node_id_list = []
        for node_id in node_id_dict.keys():
            node_id_list.append(node_id)
        node_id_dict.pop(node_id_list[0])
        log.info("统计出nodeID对应的出块ID{}".format(node_id_dict))
        print(node_id_dict)
        print(node_id_list)
        if duration == 10:
            block_cycle_a = node_id_dict.get(node_id_list[1])
            log.info("出块人A出块周期数:%s" % block_cycle_a)
            assert 7 <= len(block_cycle_a) <= 12, "出块周期预期在7到12,实际{}".format(
                len(block_cycle_a))
            block_cycle_b = node_id_dict.get(node_id_list[2])
            log.info("出块人B出块周期数:%s" % block_cycle_b)
            assert 7 <= len(block_cycle_b) <= 12, "出块周期预期在7到12,实际{}".format(
                len(block_cycle_b))
            times_tamp_a = w3.eth.getBlock(block_cycle_a[-1]).get("timestamp")
            times_tamp_b = w3.eth.getBlock(block_cycle_b[-1]).get("timestamp")
            log.info("获取出块人B的最后一个块的时间戳%s" % times_tamp_b)
            assert 8000 < times_tamp_b - \
                times_tamp_a < 12000, "预期出块周期为8到12s,实际为{}".format(
                    times_tamp_b - times_tamp_a)
            log.info(
                "出块人B最后一个块出块时间-出块人A最后一个块出块时间 = 出块周期时间{}".format(times_tamp_b -
                                                                times_tamp_a))

        if duration == 20:
            block_cycle_a = node_id_dict.get(node_id_list[1])
            log.info("出块人A出块周期数:%s" % block_cycle_a)
            assert 16 <= len(block_cycle_a) <= 23, "出块周期预期在16到23,实际{}".format(
                len(block_cycle_a))
            block_cycle_b = node_id_dict.get(node_id_list[2])
            log.info("出块人B出块周期数:%s" % block_cycle_b)
            assert 16 <= len(block_cycle_b) <= 23, "出块周期预期在16到23,实际{}".format(
                len(block_cycle_b))
            times_tamp_a = w3.eth.getBlock(block_cycle_a[-1]).get("timestamp")
            times_tamp_b = w3.eth.getBlock(block_cycle_b[-1]).get("timestamp")
            log.info("获取出块人B的最后一个块的时间戳%s" % times_tamp_b)
            assert 16000 < times_tamp_b - times_tamp_a < 23000, "预期出块周期为16到23s,实际为{}".format(
                times_tamp_b - times_tamp_a)
            log.info(
                "出块人B最后一个块出块时间-出块人A最后一个块出块时间 = 出块周期时间{}".format(times_tamp_b -
                                                                times_tamp_a))

        if duration == 30:
            block_cycle_a = node_id_dict.get(node_id_list[1])
            log.info("出块人A出块周期数:%s" % block_cycle_a)
            assert 26 <= len(block_cycle_a) <= 33, "出块周期预期在26到33,实际{}".format(
                len(block_cycle_a))
            block_cycle_b = node_id_dict.get(node_id_list[2])
            log.info("出块人B出块周期数:%s" % block_cycle_b)
            assert 26 <= len(block_cycle_b) <= 33, "出块周期预期在26到33,实际{}".format(
                len(block_cycle_b))
            times_tamp_a = w3.eth.getBlock(block_cycle_a[-1]).get("timestamp")
            times_tamp_b = w3.eth.getBlock(block_cycle_b[-1]).get("timestamp")
            log.info("获取出块人B的最后一个块的时间戳%s" % times_tamp_b)
            assert 26000 < times_tamp_b - times_tamp_a < 33000, "预期出块周期为26到30s,实际为{}".format(
                times_tamp_b - times_tamp_a)
            log.info(
                "出块人B最后一个块出块时间-出块人A最后一个块出块时间 = 出块周期时间{}".format(times_tamp_b -
                                                                times_tamp_a))

        if duration == 50:
            block_cycle_a = node_id_dict.get(node_id_list[1])
            log.info("出块人A出块周期数:%s" % block_cycle_a)
            assert 40 <= len(block_cycle_a) <= 60, "出块周期预期在40到60,实际{}".format(
                len(block_cycle_a))
            block_cycle_b = node_id_dict.get(node_id_list[2])
            log.info("出块人B出块周期数:%s" % block_cycle_b)
            assert 40 <= len(block_cycle_b) <= 60, "出块周期预期在40到60,实际{}".format(
                len(block_cycle_b))
            times_tamp_a = w3.eth.getBlock(block_cycle_a[-1]).get("timestamp")
            times_tamp_b = w3.eth.getBlock(block_cycle_b[-1]).get("timestamp")
            log.info("获取出块人B的最后一个块的时间戳%s" % times_tamp_b)
            assert 4000 < times_tamp_b - times_tamp_a < 60000, "预期出块周期为40到60s,实际为{}".format(
                times_tamp_b - times_tamp_a)
            log.info(
                "出块人B最后一个块出块时间-出块人A最后一个块出块时间 = 出块周期时间{}".format(times_tamp_b -
                                                                times_tamp_a))

        if duration == 100:
            block_cycle_a = node_id_dict.get(node_id_list[1])
            log.info("出块人A出块周期数:%s" % block_cycle_a)
            assert 90 <= len(
                block_cycle_a) <= 110, "出块周期预期在90到110,实际{}".format(
                    len(block_cycle_a))
            block_cycle_b = node_id_dict.get(node_id_list[2])
            log.info("出块人B出块周期数:%s" % block_cycle_b)
            assert 90 <= len(
                block_cycle_b) <= 110, "出块周期预期在90到110,实际{}".format(
                    len(block_cycle_b))
            times_tamp_a = w3.eth.getBlock(block_cycle_a[-1]).get("timestamp")
            times_tamp_b = w3.eth.getBlock(block_cycle_b[-1]).get("timestamp")
            log.info("获取出块人B的最后一个块的时间戳%s" % times_tamp_b)
            assert 90000 < times_tamp_b - times_tamp_a < 110000, "预期出块周期为99到110s,实际为{}".format(
                times_tamp_b - times_tamp_a)
            log.info(
                "出块人B最后一个块出块时间-出块人A最后一个块出块时间 = 出块周期时间{}".format(times_tamp_b -
                                                                times_tamp_a))
コード例 #10
0
class TestUndelegate():
    node_yml_path = conf.NODE_YML
    node_info = get_node_info(node_yml_path)
    rpc_list, enode_list, nodeid_list, ip_list, port_list = node_info.get(
        'collusion')
    rpc_list2, enode_list2, nodeid_list2, ip_list2, port_list2 = node_info.get(
        'nocollusion')

    address = Web3.toChecksumAddress(conf.ADDRESS)
    privatekey = conf.PRIVATE_KEY
    account_list = conf.account_list
    privatekey_list = conf.privatekey_list
    externalId = "1111111111"
    nodeName = "platon"
    website = "https://www.test.network"
    details = "supper node"
    programVersion = 1792
    illegal_nodeID = conf.illegal_nodeID

    genesis_path = conf.GENESIS_TMP
    """替换config.json"""
    get_config_data()
    config_json_path = conf.PLATON_CONFIG_PATH
    config_dict = LoadFile(config_json_path).get_data()
    amount_delegate = Web3.fromWei(
        int(config_dict['EconomicModel']['Staking']['MinimumThreshold']),
        'ether')
    amount = Web3.fromWei(
        int(config_dict['EconomicModel']['Staking']['StakeThreshold']),
        'ether')

    def setup_class(self):
        self.auto = AutoDeployPlaton()
        self.auto.start_all_node(self.node_yml_path)
        self.genesis_dict = LoadFile(self.genesis_path).get_data()
        self.chainid = int(self.genesis_dict["config"]["chainId"])
        self.ppos_link = Ppos(self.rpc_list[0], self.address, self.chainid)
        self.w3_list = [connect_web3(url) for url in self.rpc_list]
        """用新的钱包地址和未质押过的节点id封装对象"""
        self.ppos_noconsensus_1 = Ppos(self.rpc_list[0],
                                       self.account_list[0],
                                       self.chainid,
                                       privatekey=self.privatekey_list[0])
        self.ppos_noconsensus_2 = Ppos(self.rpc_list[0],
                                       self.account_list[1],
                                       self.chainid,
                                       privatekey=self.privatekey_list[1])
        self.ppos_noconsensus_3 = Ppos(self.rpc_list[0],
                                       self.account_list[2],
                                       self.chainid,
                                       privatekey=self.privatekey_list[2])
        self.ppos_noconsensus_4 = Ppos(self.rpc_list[0],
                                       self.account_list[3],
                                       self.chainid,
                                       privatekey=self.privatekey_list[3])
        self.ppos_noconsensus_5 = Ppos(self.rpc_list[0],
                                       self.account_list[4],
                                       self.chainid,
                                       privatekey=self.privatekey_list[4])
        self.ppos_noconsensus_6 = Ppos(self.rpc_list[0],
                                       self.account_list[5],
                                       self.chainid,
                                       privatekey=self.privatekey_list[5])
        self.eth = Eth(self.w3_list[0])

    def transaction(self,
                    w3,
                    from_address,
                    to_address=None,
                    value=1000000000000000000000000000000000,
                    gas=91000000,
                    gasPrice=9000000000,
                    pwd=conf.PASSWORD):
        """"
        转账公共方法
        """
        personal = Personal(w3)
        personal.unlockAccount(from_address, pwd, 666666)
        params = {
            'to': to_address,
            'from': from_address,
            'gas': gas,
            'gasPrice': gasPrice,
            'value': value
        }
        tx_hash = w3.eth.sendTransaction(params)
        result = w3.eth.waitForTransactionReceipt(HexBytes(tx_hash).hex())
        return result

    def getCandidateList(self):
        """
        获取实时验证人的nodeID list
        """
        msg = self.ppos_noconsensus_1.getCandidateList()
        recive_list = msg.get("Data")
        nodeid_list = []
        if recive_list is None:
            return recive_list
        else:
            for node_info in recive_list:
                nodeid_list.append(node_info.get("NodeId"))
        return nodeid_list

##############################赎回####################################################

    @allure.title("委托人未达到锁定期申请赎回")
    @pytest.mark.P0
    def test_unDelegate_part(self):
        """
         用例id 106 申请赎回委托
         用例id 111 委托人未达到锁定期申请赎回
         申请部分赎回
        """
        log.info("转账到钱包3")
        self.transaction(self.w3_list[0],
                         self.address,
                         to_address=self.account_list[2])
        log.info("转账到钱包4")
        self.transaction(self.w3_list[0],
                         self.address,
                         to_address=self.account_list[3])
        msg = self.ppos_noconsensus_1.getCandidateInfo(self.nodeid_list2[2])
        if msg['Data'] == "":
            log.info("质押节点3:{}成为验证节点".format(self.nodeid_list2[2]))
            self.ppos_noconsensus_3.createStaking(0, self.account_list[2],
                                                  self.nodeid_list2[2],
                                                  self.externalId,
                                                  self.nodeName, self.website,
                                                  self.details, self.amount,
                                                  self.programVersion)
        log.info("钱包4 {}委托到3 {}".format(self.account_list[3],
                                        self.account_list[2]))
        value = 100
        self.ppos_noconsensus_4.delegate(0, self.nodeid_list2[2], value)
        log.info("查询当前节点质押信息")
        msg = self.ppos_noconsensus_3.getCandidateInfo(self.nodeid_list2[2])
        stakingBlockNum = msg["Data"]["StakingBlockNum"]
        log.info("发起质押的区高{}".format(stakingBlockNum))
        delegate_value = 20
        self.ppos_noconsensus_4.unDelegate(stakingBlockNum,
                                           self.nodeid_list2[2],
                                           delegate_value)
        log.info("查询钱包{}的委托信息".format(self.account_list[3]))
        msg = self.ppos_noconsensus_4.getDelegateInfo(stakingBlockNum,
                                                      self.account_list[3],
                                                      self.nodeid_list2[2])
        print(msg)
        data = msg["Data"]
        """不清楚msg["Data"]对应value是str类型,需要再转字典"""
        data = json.loads(data)
        print(data)
        assert Web3.toChecksumAddress(data["Addr"]) == self.account_list[3]
        assert data["NodeId"] == self.nodeid_list2[2]
        print(data["ReleasedHes"])
        value = value - delegate_value
        result_value = Web3.toWei(value, "ether")
        assert data["ReleasedHes"] == result_value

    @allure.title("大于委托金额赎回")
    @pytest.mark.P0
    def test_unDelegate_iff(self):
        """
        验证 大于委托金额赎回
        """
        msg = self.ppos_noconsensus_1.getCandidateInfo(self.nodeid_list2[2])
        if msg['Data'] == "":
            log.info("质押节点3成为验证节点")
            self.ppos_noconsensus_3.createStaking(0, self.account_list[2],
                                                  self.nodeid_list2[2],
                                                  self.externalId,
                                                  self.nodeName, self.website,
                                                  self.details, self.amount,
                                                  self.programVersion)
        log.info("钱包4 委托到3 {}")
        value = 100
        self.ppos_noconsensus_4.delegate(0, self.nodeid_list2[2], value)
        msg = self.ppos_noconsensus_3.getCandidateInfo(self.nodeid_list2[2])
        stakingBlockNum = msg["Data"]["StakingBlockNum"]
        msg = self.ppos_noconsensus_4.getDelegateInfo(stakingBlockNum,
                                                      self.account_list[3],
                                                      self.nodeid_list2[2])
        data = msg["Data"]
        """不清楚msg["Data"]对应value是str类型,需要再转字典"""
        data = json.loads(data)
        releasedHes = data["ReleasedHes"]
        releasedHes = Web3.fromWei(releasedHes, 'ether')
        log.info("委托钱包可赎回的金额单位eth:{}".format(releasedHes))
        delegate_value = releasedHes + 20
        msg = self.ppos_noconsensus_4.unDelegate(stakingBlockNum,
                                                 self.nodeid_list2[2],
                                                 delegate_value)
        assert msg["Status"] == False
        err_msg = "withdrewDelegate err: The von of delegate is not enough"
        assert err_msg in msg["ErrMsg"]

    @allure.title("赎回全部委托的金额与赎回金额为0")
    @pytest.mark.P1
    def test_unDelegate_all(self):
        """
        验证 赎回全部委托的金额
        验证 赎回金额为0
        """
        log.info("转账到钱包1")
        self.transaction(self.w3_list[0],
                         self.address,
                         to_address=self.account_list[0])
        log.info("转账到钱包2")
        self.transaction(self.w3_list[0],
                         self.address,
                         to_address=self.account_list[1])

        log.info("节点1质押成为验证人")
        self.ppos_noconsensus_1.createStaking(0, self.account_list[0],
                                              self.nodeid_list2[0],
                                              self.externalId, self.nodeName,
                                              self.website, self.details,
                                              self.amount, self.programVersion)

        msg = self.ppos_noconsensus_1.getCandidateInfo(self.nodeid_list2[0])
        stakingBlockNum = msg["Data"]["StakingBlockNum"]
        log.info("查询节点质押信息,质押块高{}".format(stakingBlockNum))
        log.info("钱包2进行委托")
        value = 80
        self.ppos_noconsensus_2.delegate(0, self.nodeid_list2[0], value)
        msg = self.ppos_noconsensus_2.getDelegateInfo(stakingBlockNum,
                                                      self.account_list[1],
                                                      self.nodeid_list2[0])
        data = msg["Data"]
        """不清楚msg["Data"]对应value是str类型,需要再转字典"""
        data = json.loads(data)
        log.info(data)
        releasedHes = data["ReleasedHes"]
        releasedHes = Web3.fromWei(releasedHes, 'ether')
        log.info("委托钱包可赎回的金额单位eth:{}".format(releasedHes))
        account_before = self.eth.getBalance(self.account_list[1])
        msg = self.ppos_noconsensus_2.unDelegate(stakingBlockNum,
                                                 self.nodeid_list2[0],
                                                 releasedHes)
        assert msg["Status"] == True
        account_after = self.eth.getBalance(self.account_list[1])
        result_value = account_after - account_before
        ##为什么会赎回多那么多钱?1000000000000159999910972325109760
        assert account_before + data["ReleasedHes"] > account_after
        assert 70 < Web3.fromWei(result_value,
                                 "ether") < releasedHes, "赎回的金额减去gas应在这范围"
        log.info("全部委托金额赎回后,查询委托金额".format(account_after))
        msg = self.ppos_noconsensus_2.getDelegateInfo(stakingBlockNum,
                                                      self.account_list[1],
                                                      self.nodeid_list2[0])
        log.info(msg)
        """如果全部金额赎回,再查getDelegateInfo返回数据为空"""
        assert msg["Status"] == False
        assert msg["ErrMsg"] == "Delegate info is not found"

    @allure.title("多次委托,多次赎回")
    @pytest.mark.P1
    def test_multiple_delegate_undelegate(self):
        """
        验证多次委托,多次赎回
        """
        log.info("转账到钱包5")
        self.transaction(self.w3_list[0],
                         self.address,
                         to_address=self.account_list[4])
        log.info("转账到钱包6")
        self.transaction(self.w3_list[0],
                         self.address,
                         to_address=self.account_list[5])
        msg = self.ppos_noconsensus_5.getCandidateInfo(self.nodeid_list2[4])
        if msg['Data'] == "":
            log.info("质押节点5成为验证节点")
            self.ppos_noconsensus_5.createStaking(0, self.account_list[4],
                                                  self.nodeid_list2[4],
                                                  self.externalId,
                                                  self.nodeName, self.website,
                                                  self.details, self.amount,
                                                  self.programVersion)
        msg = self.ppos_noconsensus_5.getCandidateInfo(self.nodeid_list2[4])
        stakingBlockNum = msg["Data"]["StakingBlockNum"]
        log.info("查询节点质押信息回去质押块高{}".format(stakingBlockNum))
        value_list = [10, 11, 12, 13, 14, 15, 16, 17, 18]
        for value in value_list:
            log.info("钱包6 委托金额{}".format(value))
            self.ppos_noconsensus_6.delegate(0, self.nodeid_list2[4], value)
        msg = self.ppos_noconsensus_6.getDelegateInfo(stakingBlockNum,
                                                      self.account_list[5],
                                                      self.nodeid_list2[4])
        log.info(msg)
        data = json.loads(msg["Data"])
        releasedHes = Web3.fromWei(data["ReleasedHes"], 'ether')
        log.info("查询委托的金额{}eth".format(releasedHes))
        delegate_value = 0
        for i in value_list:
            delegate_value = i + delegate_value
        assert delegate_value == releasedHes, "委托的金额与查询到的金额不一致"
        for value in value_list:
            log.info("赎回的金额:{}eth".format(value))
            log.info("钱包6进行赎回")
            self.ppos_noconsensus_6.unDelegate(stakingBlockNum,
                                               self.nodeid_list2[4], value)
        log.info("赎回委托金额后查询委托信息")
        msg = self.ppos_noconsensus_6.getDelegateInfo(stakingBlockNum,
                                                      self.account_list[5],
                                                      self.nodeid_list2[4])
        """如果全部金额赎回,再查getDelegateInfo返回数据为空"""
        log.info(msg)
コード例 #11
0
class TestAddstaking():
    node_yml_path = conf.NODE_YML
    node_info = get_node_info(node_yml_path)
    rpc_list, enode_list, nodeid_list, ip_list, port_list = node_info.get(
        'collusion')
    rpc_list2, enode_list2, nodeid_list2, ip_list2, port_list2 = node_info.get(
        'nocollusion')

    address = Web3.toChecksumAddress(conf.ADDRESS)
    pwd = conf.PASSWORD
    privatekey = conf.PRIVATE_KEY
    account_list = conf.account_list
    privatekey_list = conf.privatekey_list
    externalId = "1111111111"
    nodeName = "platon"
    website = "https://www.test.network"
    details = "supper node"
    programVersion = 1792
    illegal_nodeID = conf.illegal_nodeID

    genesis_path = conf.GENESIS_TMP
    """替换config.json"""
    get_config_data()
    config_json_path = conf.PLATON_CONFIG_PATH
    config_dict = LoadFile(config_json_path).get_data()
    amount_delegate = Web3.fromWei(
        int(config_dict['EconomicModel']['Staking']['MinimumThreshold']),
        'ether')
    amount = Web3.fromWei(
        int(config_dict['EconomicModel']['Staking']['StakeThreshold']),
        'ether')

    def setup_class(self):
        self.auto = AutoDeployPlaton()
        self.auto.start_all_node(self.node_yml_path)
        self.genesis_dict = LoadFile(self.genesis_path).get_data()
        self.chainid = int(self.genesis_dict["config"]["chainId"])
        self.ppos_link = Ppos(self.rpc_list[0], self.address, self.chainid)
        self.ppos_link1 = Ppos(self.rpc_list[1], self.address, self.chainid)
        self.w3_list = [connect_web3(url) for url in self.rpc_list]
        """用新的钱包地址和未质押过的节点id封装对象"""
        self.ppos_noconsensus_1 = Ppos(self.rpc_list[0],
                                       self.account_list[0],
                                       self.chainid,
                                       privatekey=self.privatekey_list[0])
        self.ppos_noconsensus_2 = Ppos(self.rpc_list[0],
                                       self.account_list[1],
                                       self.chainid,
                                       privatekey=self.privatekey_list[1])
        self.ppos_noconsensus_3 = Ppos(self.rpc_list[0],
                                       self.account_list[2],
                                       self.chainid,
                                       privatekey=self.privatekey_list[2])
        self.ppos_noconsensus_4 = Ppos(self.rpc_list[0],
                                       self.account_list[3],
                                       self.chainid,
                                       privatekey=self.privatekey_list[3])
        self.ppos_noconsensus_5 = Ppos(self.rpc_list[0],
                                       self.account_list[4],
                                       self.chainid,
                                       privatekey=self.privatekey_list[4])
        self.ppos_noconsensus_6 = Ppos(self.rpc_list[0],
                                       self.account_list[5],
                                       self.chainid,
                                       privatekey=self.privatekey_list[5])
        self.eth = Eth(self.w3_list[0])

    def transaction(self,
                    w3,
                    from_address,
                    to_address=None,
                    value=1000000000000000000000000000000000,
                    gas=91000000,
                    gasPrice=9000000000,
                    pwd="88888888"):
        """"
        转账公共方法
        """
        personal = Personal(w3)
        personal.unlockAccount(from_address, pwd, 666666)
        params = {
            'to': to_address,
            'from': from_address,
            'gas': gas,
            'gasPrice': gasPrice,
            'value': value
        }
        tx_hash = w3.eth.sendTransaction(params)
        result = w3.eth.waitForTransactionReceipt(HexBytes(tx_hash).hex())
        return result

    def getCandidateList(self):
        """
        获取实时验证人的nodeID list
        """
        msg = self.ppos_noconsensus_1.getCandidateList()
        recive_list = msg.get("Data")
        nodeid_list = []
        if recive_list is None:
            return recive_list
        else:
            for node_info in recive_list:
                nodeid_list.append(node_info.get("NodeId"))
        return nodeid_list

    @allure.title("增加质押分别为{amount}")
    @pytest.mark.P1
    @pytest.mark.parametrize('amount', [100, 10000000, 1000000])
    def test_add_staking(self, amount):
        """
        用例id 72 账户余额足够,增加质押成功
        用例id 74 验证人在质押锁定期内增持的质押数量不限制
        """
        log.info("转账到钱包1")
        self.transaction(self.w3_list[0],
                         self.address,
                         to_address=self.account_list[0])
        nodeId = self.nodeid_list2[0]
        log.info("钱包1做一笔质押")
        self.ppos_noconsensus_1.createStaking(0, self.account_list[0], nodeId,
                                              self.externalId, self.nodeName,
                                              self.website, self.details,
                                              self.amount, self.programVersion)
        log.info("分别验证增持{}".format(amount))
        msg = self.ppos_noconsensus_1.addStaking(nodeId, typ=0, amount=amount)
        print(msg)
        assert msg.get("Status") == True, "返回状态错误"
        assert msg.get("ErrMsg") == 'ok', "返回消息错误"

        msg = self.ppos_noconsensus_1.getCandidateInfo(self.nodeid_list2[0])
        nodeid = msg["Data"]["NodeId"]
        assert nodeid == self.nodeid_list2[0]
        if amount == 100:
            assert Web3.fromWei(msg["Data"]["Shares"],
                                'ether') == self.amount + 100
        if amount == 10000000:
            assert Web3.fromWei(msg["Data"]["Shares"],
                                'ether') == self.amount + 100 + 10000000
        if amount == 1000000:
            assert Web3.fromWei(
                msg["Data"]["Shares"],
                'ether') == self.amount + 100 + 10000000 + 1000000

    @allure.title("非验证人增持质押")
    @pytest.mark.P2
    def test_not_illegal_addstaking(self):
        """
        用例id 78 非验证人增持质押
        """
        log.info("转账到钱包1")
        self.transaction(self.w3_list[0],
                         self.address,
                         to_address=self.account_list[0])
        nodeId = conf.illegal_nodeID
        msg = self.ppos_noconsensus_1.getCandidateInfo(self.nodeid_list2[0])
        if msg['Data'] == "":
            log.info("节点1成为验证人")
            self.ppos_noconsensus_1.createStaking(0, self.account_list[0],
                                                  self.nodeid_list2[0],
                                                  self.externalId,
                                                  self.nodeName, self.website,
                                                  self.details, self.amount,
                                                  self.programVersion)
        msg = self.ppos_noconsensus_1.addStaking(nodeId=nodeId,
                                                 typ=0,
                                                 amount=100)
        assert msg.get("Status") == False, "返回状态错误"
        assert msg.get("ErrMsg") == 'This candidate is not exist', "非验证人增持质押异常"

    @allure.title("编辑验证人信息-未成为验证人的nodeID")
    @pytest.mark.P1
    def test_editCandidate_nodeid(self):
        """
        验证修改未成为验证人的nodeID
        """
        externalId = "88888888"
        nodeName = "wuyiqin"
        website = "www://baidu.com"
        details = "node_1"
        account = self.account_list[0]
        nodeid = conf.illegal_nodeID

        self.transaction(self.w3_list[0],
                         self.address,
                         to_address=self.account_list[1])
        log.info("转账到钱包2")
        nodeId = self.nodeid_list2[1]
        msg = self.ppos_noconsensus_2.getCandidateInfo(nodeId)
        if msg['Data'] == "":
            log.info("节点2成为验证人")
            msg = self.ppos_noconsensus_2.createStaking(
                0, self.account_list[1], nodeId, self.externalId,
                self.nodeName, self.website, self.details, self.amount,
                self.programVersion)
            assert msg.get("Status") == True, "返回状态错误"
            assert msg.get("ErrMsg") == 'ok', "返回消息错误"
        log.info("节点2修改节点信息")
        msg = self.ppos_noconsensus_2.updateStakingInfo(
            account, nodeid, externalId, nodeName, website, details)
        log.info(msg)
        assert msg.get("Status") == False, "返回状态错误"

    @allure.title("编辑验证人信息-参数有效性验证")
    @pytest.mark.P0
    def test_editCandidate(self):
        """
        用例id 70 编辑验证人信息-参数有效性验证
        """
        externalId = "88888888"
        nodeName = "wuyiqin"
        website = "www://baidu.com"
        details = "node_1"
        account = self.account_list[0]

        self.transaction(self.w3_list[0],
                         self.address,
                         to_address=self.account_list[1])
        log.info("转账到钱包2")
        nodeId = self.nodeid_list2[1]
        msg = self.ppos_noconsensus_2.getCandidateInfo(nodeId)
        if msg['Data'] == "":
            log.info("节点2成为验证人")
            msg = self.ppos_noconsensus_2.createStaking(
                0, self.account_list[1], nodeId, self.externalId,
                self.nodeName, self.website, self.details, self.amount,
                self.programVersion)
            assert msg.get("Status") == True, "返回状态错误"
            assert msg.get("ErrMsg") == 'ok', "返回消息错误"
        log.info("节点2修改节点信息")
        msg = self.ppos_noconsensus_2.updateStakingInfo(
            account, self.nodeid_list2[1], externalId, nodeName, website,
            details)
        assert msg.get("Status") == True, "返回状态错误"
        assert msg.get("ErrMsg") == 'ok', "返回消息错误"
        log.info("查看节点2的信息")
        msg = self.ppos_noconsensus_2.getCandidateInfo(self.nodeid_list2[1])
        log.info(msg)
        assert msg["Data"]["ExternalId"] == externalId
        assert msg["Data"]["NodeName"] == nodeName
        assert msg["Data"]["Website"] == website
        assert msg["Data"]["Details"] == details
        log.info(self.account_list[0])
        BenefitAddress = Web3.toChecksumAddress(msg["Data"]["BenefitAddress"])
        log.info(BenefitAddress)
        assert BenefitAddress == account

    @allure.title("修改钱包地址,更改后的地址收益正常")
    @pytest.mark.P2
    def test_alter_address(self):
        """
        修改钱包地址,更改后的地址收益正常
        """
        log.info("转账到钱包2")
        self.transaction(self.w3_list[0],
                         self.address,
                         to_address=self.account_list[1])
        externalId = "88888888"
        nodeName = "helloword"
        website = "www://dddddd.com"
        details = "node_2"
        ####没钱的钱包#####
        account = conf.no_money[0]
        balance_before = self.eth.getBalance(account)
        assert balance_before == 0
        msg = self.ppos_noconsensus_1.getCandidateInfo(self.nodeid_list2[1])
        if msg['Data'] == "":
            log.info("质押节点2成为验证节点")
            msg = self.ppos_noconsensus_2.createStaking(
                0, self.account_list[0], self.nodeid_list2[1], self.externalId,
                self.nodeName, self.website, self.details, self.amount,
                self.programVersion)
            assert msg.get("Status") == True, "返回状态错误"
            assert msg.get("ErrMsg") == 'ok', "返回消息错误"
        log.info("修改节点2的信息")
        msg = self.ppos_noconsensus_2.updateStakingInfo(
            account, self.nodeid_list2[1], externalId, nodeName, website,
            details)
        assert msg.get("Status") == True, "返回状态错误"
        assert msg.get("ErrMsg") == 'ok', "返回消息错误"
        log.info("进入第2个结算周期")
        get_block_number(self.w3_list[0])
        log.info("进入第3个结算周期")
        get_block_number(self.w3_list[0])
        balance_after = self.eth.getBalance(account)
        log.info(balance_after)
        assert balance_after > 0, "修改后的钱包余额没增加"
        assert balance_after > balance_before, "地址更改后未发现余额增加"

    @allure.title("增加质押为{x}")
    @pytest.mark.P2
    @pytest.mark.parametrize('x', [0, (amount_delegate - 1)])
    def test_add_staking_zero(self, x):
        """测试增持金额为0,低于门槛"""

        log.info("转账到钱包3")
        self.transaction(self.w3_list[0],
                         self.address,
                         to_address=self.account_list[2])
        log.info("质押节点3,成为验证人")
        nodeId = self.nodeid_list2[2]
        self.ppos_noconsensus_3.createStaking(0, self.account_list[2], nodeId,
                                              self.externalId, self.nodeName,
                                              self.website, self.details,
                                              self.amount, self.programVersion)
        log.info("节点3增持质押".format(x))
        msg = self.ppos_noconsensus_3.addStaking(nodeId, typ=0, amount=x)
        log.info(msg)
        assert msg.get("Status") == False, "返回状态错误"

    @allure.title("账户余额不足增加质押")
    @pytest.mark.P2
    def test_Insufficient_addStaking(self):
        """
        用例id 73 账户余额不足,增加质押失败
        """
        log.info("转账到钱包5")
        self.transaction(self.w3_list[0],
                         self.address,
                         to_address=self.account_list[4])
        log.info("质押节点5成为验证人")
        nodeId = self.nodeid_list2[4]
        msg = self.ppos_noconsensus_5.createStaking(
            0, self.account_list[4], nodeId, self.externalId, self.nodeName,
            self.website, self.details, self.amount, self.programVersion)
        assert msg.get("Status") == True, "返回状态错误"
        amount = 100000000000000000000000000000000000
        msg = self.ppos_noconsensus_5.addStaking(nodeId=nodeId,
                                                 typ=0,
                                                 amount=amount)
        assert msg.get("Status") == False, "返回状态错误"
        msg_string = "The von of account is not enough"
        assert msg_string in msg.get("ErrMsg"), "余额不足发生质押异常"

    # @allure.title("验证人已申请退出中,申请增持质押")
    # def test_quit_and_addstaking(self):
    #     """
    #     用例id 77 验证人已申请退出中,申请增持质押
    #     """
    #     nodeId = self.nodeid_list2[0]
    #     msg = self.ppos_noconsensus_1.unStaking(nodeId)
    #     assert msg.get("Status") == True, "返回状态错误"
    #     assert msg.get("ErrMsg") == 'ok', "返回消错误"
    #     log.info("{}已经退出验证人.".format(nodeId))
    #     node_list = self.getCandidateList()
    #     log.info(self.nodeid_list2[0])
    #     log.info(node_list)
    #     assert self.nodeid_list2[0] not in node_list
    #     """验证人退出后,查询实时验证人列表返回的是空,可能是bug"""
    #     msg = self.ppos_noconsensus_1.addStaking(nodeId, typ=0, amount=100)
    #     assert msg.get("Status") == True, "返回状态错误"
    #     assert msg.get("ErrMsg") == 'This candidate is not exist'

    @allure.title("验证人已申请退出中,申请增持质押")
    @pytest.mark.P1
    def test_quit_and_addstaking(self):
        """
        用例id 77 验证人已申请退出中,申请增持质押
        """
        log.info("转账到钱包4")
        self.transaction(self.w3_list[0],
                         self.address,
                         to_address=self.account_list[3])

        nodeId = self.nodeid_list2[3]
        log.info("节点4发起质押")
        msg = self.ppos_noconsensus_4.createStaking(
            0, self.account_list[3], nodeId, self.externalId, self.nodeName,
            self.website, self.details, self.amount, self.programVersion)
        assert msg.get("Status") == True, "质押失败"
        log.info("节点4退出质押")
        msg = self.ppos_noconsensus_4.unStaking(nodeId)
        # print(msg)
        assert msg.get("Status") == True, "返回状态错误"
        assert msg.get("ErrMsg") == 'ok', "返回消息错误"
        log.info("{}已经退出验证人.".format(nodeId))
        node_list = self.getCandidateList()
        # print(nodeId)
        # print(node_list)
        assert nodeId not in node_list
        msg = self.ppos_noconsensus_1.getCandidateInfo(nodeId)
        assert msg['Data'] == ""
        msg = self.ppos_noconsensus_4.addStaking(nodeId, typ=0, amount=100)
        assert msg.get("Status") == False, "返回状态错误"
        assert msg.get("ErrMsg") == 'This candidate is not exist'
コード例 #12
0
class TestDposinit:
    address = Web3.toChecksumAddress(conf.ADDRESS)
    pwd = conf.PASSWORD
    abi = conf.DPOS_CONTRACT_ABI
    cbft_json_path = conf.CBFT2
    node_yml_path = conf.TWENTY_FIVENODE_YML
    file = conf.CASE_DICT

    def ppos_link(self, rpc_list):
        self.platon_dpos1 = PlatonDpos(rpc_list,
                                       self.address,
                                       self.pwd,
                                       abi=self.abi)
        return self.platon_dpos1

    def transfer_parameters(self, to_address, from_address):
        self.w3_list = [connect_web3(url) for url in self.rpc_list]
        self.send_data = {
            "to": to_address,
            "from": from_address,
            "gas": '9000',
            "gasPrice": '1000000000',
            "value": self.w3_list[0].toWei(100000, 'ether'),
        }
        return self.send_data

    def create_new_address(self):
        self.new_address = Web3.toChecksumAddress(
            self.ppos_link(self.rpc_list).web3.personal.newAccount(self.pwd))
        return self.new_address

    def update_config(self, file, key, data):
        with open(self.file, 'r', encoding='utf-8') as f:
            res = json.loads(f.read())

    def test_init_token(self):
        self.auto = AutoDeployPlaton(cbft=self.cbft_json_path)
        self.auto.start_all_node(self.node_yml_path)
        proportion = {
            'FOUNDATION': 0.001,
            'DEVELOPERS': 0.001,
            'INCENTIVEPOOL': 0.001,
            'RESERVED': 0.001
        }
        FOUNDATION = self.platon_ppos.eth.getBalance(conf.FOUNDATIONADDRESS)
        DEVELOPERS = self.platon_ppos.eth.getBalance(conf.DEVELOPERSADDRESS)
        INCENTIVEPOOL = self.platon_ppos.eth.getBalance(
            conf.INCENTIVEPOOLADDRESS)
        RESERVED = self.platon_ppos.eth.getBalance(conf.RESERVEDADDRESS)
        FOUNDATIONLOCKUP = self.platon_dpos1.eth.getBalance(
            conf.FOUNDATIONLOCKUPADDRESS)
        token_init_total = conf.TOKENTOTAL
        assert (token_init_total *
                proportion['FOUNDATION']) == (FOUNDATION + FOUNDATIONLOCKUP)
        assert (token_init_total * proportion['DEVELOPERS']) == DEVELOPERS
        assert (token_init_total *
                proportion['INCENTIVEPOOL']) == INCENTIVEPOOL
        assert (token_init_total * proportion['RESERVED']) == RESERVED
        assert token_init_total == (FOUNDATION + FOUNDATIONLOCKUP +
                                    DEVELOPERS + INCENTIVEPOOL + RESERVED)

    def test_token_transactions(self):
        node_info = get_node_info(conf.TWENTY_FIVENODE_YML)
        self.rpc_list, enode_list, nodeid_list, ip_list, port_list = node_info.get(
            'collusion')
        from_address = Web3.toChecksumAddress(conf.ADDRESS)
        to_address = Web3.toChecksumAddress(
            self.ppos_link(self.rpc_list).web3.personal.newAccount(self.pwd))
        send_data = self.transfer_parameters(to_address, from_address)
        self.platon_ppos.eth.sendTransaction(send_data)
        assert self.platon_dpos1.eth.getBalance(
            to_address) == self.w3_list[0].toWei(100000, 'ether')

    def test_token_loukup(self):
        #查看初始化时锁仓余额
        file = conf.GENESIS_TMP_OTHER
        genesis_dict = LoadFile(file).get_data()
        FOUNDATION = genesis_dict['alloc'][conf.FOUNDATIONADDRESS]
        FOUNDATIONLOCKUP = self.platon_dpos1.eth.getBalance(
            conf.FOUNDATIONLOCKUPADDRESS)
        node_info = get_node_info(conf.PPOS25NODE_YML)
        self.rpc_list, enode_list, nodeid_list, ip_list, port_list = node_info.get(
            'collusion')
        FOUNDATIONTOTAL = conf.TOKENTOTAL * 0.01
        assert FOUNDATIONTOTAL == (FOUNDATION + FOUNDATIONLOCKUP)

    def test_loukupplan(self):
        from_address = Web3.toChecksumAddress(conf.ADDRESS)
        to_address = Web3.toChecksumAddress(
            self.ppos_link(self.rpc_list).web3.personal.newAccount(self.pwd))
        send_data = self.transfer_parameters(to_address, from_address)
        self.platon_ppos.eth.sendTransaction(send_data)
        toaddressbalace = self.platon_dpos1.eth.getBalance(to_address)
        loukupbalace = toaddressbalace / 4
        plan = [{
            'Epoch': 3,
            'Amount': loukupbalace
        }, {
            'Epoch': 3,
            'Amount': loukupbalace
        }]
        Ppos.CreateRestrictingPlan(to_address, plan, to_address)
        result = Ppos.GetRestrictingInfo(to_address, to_address)

    def test_staking(self):
        pass
コード例 #13
0
class TestLockup():
    node_yml_path = conf.NODE_YML
    node_info = get_node_info(node_yml_path)
    rpc_list, enode_list, nodeid_list, ip_list, port_list = node_info.get(
        'collusion')
    rpc_list2, enode_list2, nodeid_list2, ip_list2, port_list2 = node_info.get(
        'nocollusion')

    address = Web3.toChecksumAddress(conf.ADDRESS)
    privatekey = conf.PRIVATE_KEY
    account_list = conf.account_list
    privatekey_list = conf.privatekey_list
    externalId = "1111111111"
    nodeName = "platon"
    website = "https://www.test.network"
    details = "supper node"
    programVersion = 1792
    illegal_nodeID = conf.illegal_nodeID

    genesis_path = conf.GENESIS_TMP

    get_config_data()
    config_json_path = conf.PLATON_CONFIG_PATH
    config_dict = LoadFile(config_json_path).get_data()
    amount_delegate = Web3.fromWei(
        int(config_dict['EconomicModel']['Staking']['MinimumThreshold']),
        'ether')
    amount = Web3.fromWei(
        int(config_dict['EconomicModel']['Staking']['StakeThreshold']),
        'ether')

    def setup_class(self):
        self.auto = AutoDeployPlaton()
        self.auto.start_all_node(self.node_yml_path)
        self.genesis_dict = LoadFile(self.genesis_path).get_data()
        self.chainid = int(self.genesis_dict["config"]["chainId"])
        self.ppos_link = Ppos(self.rpc_list[0], self.address, self.chainid)
        self.w3_list = [connect_web3(url) for url in self.rpc_list]
        """用新的钱包地址和未质押过的节点id封装对象"""
        self.ppos_noconsensus_1 = Ppos(self.rpc_list[0],
                                       self.account_list[0],
                                       self.chainid,
                                       privatekey=self.privatekey_list[0])
        self.ppos_noconsensus_2 = Ppos(self.rpc_list[0],
                                       self.account_list[1],
                                       self.chainid,
                                       privatekey=self.privatekey_list[1])
        self.ppos_noconsensus_3 = Ppos(self.rpc_list[0],
                                       self.account_list[2],
                                       self.chainid,
                                       privatekey=self.privatekey_list[2])
        self.ppos_noconsensus_4 = Ppos(self.rpc_list[0],
                                       self.account_list[3],
                                       self.chainid,
                                       privatekey=self.privatekey_list[3])
        self.ppos_noconsensus_5 = Ppos(self.rpc_list[0],
                                       self.account_list[4],
                                       self.chainid,
                                       privatekey=self.privatekey_list[4])
        self.ppos_noconsensus_6 = Ppos(self.rpc_list[0],
                                       self.account_list[5],
                                       self.chainid,
                                       privatekey=self.privatekey_list[5])
        self.eth = Eth(self.w3_list[0])

    def transaction(self,
                    w3,
                    from_address,
                    to_address=None,
                    value=100000000000000000000000000000000,
                    gas=91000000,
                    gasPrice=9000000000,
                    pwd=conf.PASSWORD):
        """"
        转账公共方法,转账1000w eth
        """
        personal = Personal(w3)
        personal.unlockAccount(from_address, pwd, 666666)
        params = {
            'to': to_address,
            'from': from_address,
            'gas': gas,
            'gasPrice': gasPrice,
            'value': value
        }
        tx_hash = w3.eth.sendTransaction(params)
        result = w3.eth.waitForTransactionReceipt(HexBytes(tx_hash).hex())
        return result

    def getCandidateList(self):
        """
        获取实时验证人的nodeID list
        """
        msg = self.ppos_noconsensus_1.getCandidateList()
        recive_list = msg.get("Data")
        nodeid_list = []
        if recive_list is None:
            return recive_list
        else:
            for node_info in recive_list:
                nodeid_list.append(node_info.get("NodeId"))
        return nodeid_list

    @allure.title("验证人退回质押金(未到达可解锁期)")
    @pytest.mark.P0
    def test_back_unstaking(self):
        """
        验证人退回质押金(未到达可解锁期)
        质押成为下个周期验证人,退出后,下一个结算周期退出
        """
        log.info("转账每个钱包")
        for to_account in self.account_list:
            self.transaction(self.w3_list[0],
                             self.address,
                             to_address=to_account)
        log.info("节点1质押金额{} eth".format(self.amount))
        self.ppos_noconsensus_1.createStaking(0, self.account_list[0],
                                              self.nodeid_list2[0],
                                              self.externalId, self.nodeName,
                                              self.website, self.details,
                                              self.amount, self.programVersion)
        account_1 = self.eth.getBalance(self.account_list[0])
        log.info(account_1)
        get_block_number(self.w3_list[0])
        log.info("查询第2个结算周期的验证人")
        node_list = getVerifierList()
        log.info(node_list)
        assert self.nodeid_list2[0] in node_list

        log.info("节点1在第2结算周期,锁定期申请退回")
        self.ppos_noconsensus_1.unStaking(nodeId=self.nodeid_list2[0])
        """发起退回消耗一定gas"""
        account_2 = self.eth.getBalance(self.account_list[0])
        log.info(account_2)
        assert account_1 > account_2, "发起退回的交易钱包异常"

        log.info("进入第3个结算周期")
        get_block_number(w3=self.w3_list[0])
        account_3 = self.eth.getBalance(self.account_list[0])
        log.info(account_3)
        assert account_3 > account_2
        assert account_3 - account_2 < Web3.toWei(self.amount, "ether")
        log.info(account_3 - account_2)

        node_list = getVerifierList()
        log.info(node_list)
        assert self.nodeid_list2[0] not in node_list

        log.info("进入第4个结算周期")
        get_block_number(w3=self.w3_list[0])
        account_4 = self.eth.getBalance(self.account_list[0])
        log.info(account_4)
        """ 第3个结算周期结束后质押金额已退 """
        log.info(account_4 - account_3)
        assert account_4 - account_3 > Web3.toWei(self.amount, "ether")
        assert account_4 - account_2 > Web3.toWei(self.amount, "ether")

    @allure.title("锁定期增加质押与委托")
    @pytest.mark.P0
    def test_lockup_addstaking(self):
        """
        用例id74 锁定期增加质押
        用例id 112 锁定期委托人进行委托
        """
        log.info("转账每个钱包")
        for to_account in self.account_list:
            self.transaction(self.w3_list[0],
                             self.address,
                             to_address=to_account)
        msg = self.ppos_noconsensus_1.getCandidateInfo(self.nodeid_list2[0])
        if msg["Data"] == "":
            log.info("节点1质押金额{} eth".format(self.amount))
            self.ppos_noconsensus_1.createStaking(0, self.account_list[0],
                                                  self.nodeid_list2[0],
                                                  self.externalId,
                                                  self.nodeName, self.website,
                                                  self.details, self.amount,
                                                  self.programVersion)
        log.info("进入锁定期")
        get_block_number(self.w3_list[0])
        value = 100
        msg = self.ppos_noconsensus_1.addStaking(self.nodeid_list2[0], 0,
                                                 value)
        assert msg.get("Status") == True
        msg = self.ppos_noconsensus_1.getCandidateInfo(self.nodeid_list2[0])
        log.info(msg)
        nodeid = msg["Data"]["NodeId"]
        log.info("增持后验证质押金额")
        assert msg["Data"]["Shares"] == 1000100000000000000000000
        assert msg["Data"]["Released"] == 1000000000000000000000000
        assert msg["Data"]["ReleasedHes"] == 100000000000000000000
        assert nodeid == self.nodeid_list2[0]
        self.ppos_noconsensus_2.delegate(0, self.nodeid_list2[0], 10)
        msg = self.ppos_noconsensus_2.getCandidateInfo(self.nodeid_list2[0])
        log.info(msg)
        assert msg["Data"]["Shares"] == 1000110000000000000000000
        stakingBlockNum = msg["Data"]["StakingBlockNum"]
        msg = self.ppos_noconsensus_2.getDelegateInfo(stakingBlockNum,
                                                      self.account_list[1],
                                                      self.nodeid_list2[0])
        data = msg["Data"]
        data = json.loads(data)
        assert Web3.toChecksumAddress(data["Addr"]) == self.account_list[1]
        assert data["NodeId"] == self.nodeid_list2[0]
        # assert Web3.fromWei(data["ReleasedHes"], 'ether') == 10

    @allure.title("验证根据质押+委托金额金额排名")
    @pytest.mark.P2
    def test_taking_cycle_ranking(self):
        """
        验证根据质押金额排名
        """
        log.info("转账每个钱包")
        for to_account in self.account_list:
            self.transaction(self.w3_list[0],
                             self.address,
                             to_address=to_account)

        log.info("质押节点2")
        self.ppos_noconsensus_2.createStaking(0, self.account_list[1],
                                              self.nodeid_list2[1],
                                              self.externalId, self.nodeName,
                                              self.website, self.details,
                                              self.amount, self.programVersion)
        log.info("质押节点3")
        self.ppos_noconsensus_3.createStaking(0, self.account_list[2],
                                              self.nodeid_list2[2],
                                              self.externalId, self.nodeName,
                                              self.website, self.details,
                                              self.amount + 130,
                                              self.programVersion)
        log.info("进入到下个结算周期")
        get_block_number(w3=self.w3_list[0])
        node_list = getVerifierList()
        log.info(node_list)

        msg = self.ppos_noconsensus_1.getCandidateInfo(self.nodeid_list2[1])
        log.info(msg)
        msg = self.ppos_noconsensus_1.getCandidateInfo(self.nodeid_list2[2])
        log.info(msg)

        assert self.nodeid_list2[2] in node_list
        assert self.nodeid_list2[1] in node_list
        assert self.nodeid_list2[2] == node_list[0]

        log.info("钱包4委托节点2 70eth")
        msg = self.ppos_noconsensus_4.delegate(0,
                                               nodeId=self.nodeid_list2[1],
                                               amount=70)
        print(msg)
        log.info("节点2增加质押61 eth")
        msg = self.ppos_noconsensus_2.addStaking(self.nodeid_list2[1],
                                                 0,
                                                 amount=61)
        print(msg)
        log.info("进入下一个结算周期")
        get_block_number(self.w3_list[0])

        node_list = getVerifierList()
        log.info(node_list)
        log.info(self.nodeid_list2[1])
        log.info(self.nodeid_list2[2])
        """预期节点2排在节点3之前"""
        msg = self.ppos_noconsensus_2.getCandidateInfo(self.nodeid_list2[1])
        log.info(msg)

        msg = self.ppos_noconsensus_3.getCandidateInfo(self.nodeid_list2[2])
        log.info(msg)

        assert node_list[0] == self.nodeid_list2[1]
        assert node_list[1] == self.nodeid_list2[2]

    @allure.title("质押相等的金额,按照时间先早排序")
    @pytest.mark.P1
    def test_same_amount_cycle(self):
        """
        质押相等的金额,按照时间先早排序
        """
        self.auto = AutoDeployPlaton()
        self.auto.start_all_node(self.node_yml_path)
        log.info("转账每个钱包")
        for to_account in self.account_list:
            self.transaction(self.w3_list[0],
                             self.address,
                             to_address=to_account)

        log.info("质押节点4金额200eth")
        self.ppos_noconsensus_4.createStaking(0, self.account_list[3],
                                              self.nodeid_list2[3],
                                              self.externalId, self.nodeName,
                                              self.website, self.details,
                                              self.amount + 200,
                                              self.programVersion)
        log.info("质押节点5金额200eth")
        self.ppos_noconsensus_5.createStaking(0, self.account_list[4],
                                              self.nodeid_list2[4],
                                              self.externalId, self.nodeName,
                                              self.website, self.details,
                                              self.amount + 200,
                                              self.programVersion)
        log.info("进入到下个结算周期")
        get_block_number(self.w3_list[0])

        node_list = getVerifierList()
        log.info(node_list)
        log.info(self.nodeid_list2[3])
        log.info(self.nodeid_list2[4])
        assert node_list[0] == self.nodeid_list2[3]
        assert node_list[1] == self.nodeid_list2[4]

    @allure.title("验证人申请退回所有质押金(包含初始质押金和当前结算期内质押金)")
    @pytest.mark.P2
    def test_unstaking_all(self):
        log.info("转账每个钱包")
        for to_account in self.account_list:
            self.transaction(self.w3_list[0],
                             self.address,
                             to_address=to_account)
        value_before = self.eth.getBalance(self.account_list[5])
        log.info(value_before)
        self.ppos_noconsensus_6.createStaking(0, self.account_list[5],
                                              self.nodeid_list2[5],
                                              self.externalId, self.nodeName,
                                              self.website, self.details,
                                              self.amount, self.programVersion)

        log.info("进入第2个结算周期")
        get_block_number(self.w3_list[0])
        log.info("节点6增持金额")
        self.ppos_noconsensus_6.addStaking(self.nodeid_list2[5], 0,
                                           self.amount + 1000)
        log.info("进入第3个结算周期")
        get_block_number(self.w3_list[0])
        log.info("节点6发起退回")
        self.ppos_noconsensus_6.unStaking(nodeId=self.nodeid_list2[5])
        log.info("进入第4个结算周期")
        get_block_number(self.w3_list[0])
        value = self.eth.getBalance(self.account_list[5])
        log.info(value)
        assert value < value_before, "钱还在锁定期,预期未退回,实际异常"
        log.info("进入第5个结算周期")
        get_block_number(self.w3_list[0])
        value_after = self.eth.getBalance(self.account_list[5])
        log.info(value_after)
        log.info(value_after - value_before)
        amount_sum = self.amount * 2 + 1000
        log.info(Web3.toWei(amount_sum, "ether"))
        assert value_after > value_before, "出块奖励异常"
        assert value_after > value + Web3.toWei(
            amount_sum, "ether"), "解锁期的余额大于锁定期的余额+质押+增持金额,但是发生异常"

    @allure.title("根据金额排名,从高到低排名")
    @pytest.mark.P0
    def test_ranking(self):
        """
        测试根据金额排名,从高到低排名
        """
        self.auto = AutoDeployPlaton()
        self.auto.start_all_node(self.node_yml_path)
        log.info("转账每个钱包")
        for to_account in self.account_list:
            self.transaction(self.w3_list[0],
                             self.address,
                             to_address=to_account)

        self.ppos_noconsensus_1.createStaking(0, self.account_list[0],
                                              self.nodeid_list2[0],
                                              self.externalId, self.nodeName,
                                              self.website, self.details,
                                              self.amount + 50,
                                              self.programVersion)
        self.ppos_noconsensus_2.createStaking(0, self.account_list[1],
                                              self.nodeid_list2[1],
                                              self.externalId, self.nodeName,
                                              self.website, self.details,
                                              self.amount + 40,
                                              self.programVersion)
        self.ppos_noconsensus_3.createStaking(0, self.account_list[2],
                                              self.nodeid_list2[2],
                                              self.externalId, self.nodeName,
                                              self.website, self.details,
                                              self.amount + 30,
                                              self.programVersion)
        self.ppos_noconsensus_4.createStaking(0, self.account_list[3],
                                              self.nodeid_list2[3],
                                              self.externalId, self.nodeName,
                                              self.website, self.details,
                                              self.amount + 20,
                                              self.programVersion)
        self.ppos_noconsensus_5.createStaking(0, self.account_list[4],
                                              self.nodeid_list2[4],
                                              self.externalId, self.nodeName,
                                              self.website, self.details,
                                              self.amount + 10,
                                              self.programVersion)
        self.ppos_noconsensus_6.createStaking(0, self.account_list[5],
                                              self.nodeid_list2[5],
                                              self.externalId, self.nodeName,
                                              self.website, self.details,
                                              self.amount, self.programVersion)
        log.info("进入下个周期")
        get_block_number(self.w3_list[0])
        node_list = getVerifierList()
        log.info(node_list)
        """根据config配置验证人数"""
        # assert self.nodeid_list2[5] not in node_list
        assert node_list[0] == self.nodeid_list2[0]
        assert node_list[1] == self.nodeid_list2[1]
        assert node_list[2] == self.nodeid_list2[2]
        assert node_list[3] == self.nodeid_list2[3]
        assert node_list[4] == self.nodeid_list2[4]
        assert node_list[5] == self.nodeid_list2[-1]
コード例 #14
0
class TestDelegate():
    node_yml_path = conf.NODE_YML
    node_info = get_node_info(node_yml_path)
    rpc_list, enode_list, nodeid_list, ip_list, port_list = node_info.get(
        'collusion')
    rpc_list2, enode_list2, nodeid_list2, ip_list2, port_list2 = node_info.get(
        'nocollusion')

    address = Web3.toChecksumAddress(conf.ADDRESS)
    privatekey = conf.PRIVATE_KEY
    account_list = conf.account_list
    privatekey_list = conf.privatekey_list
    externalId = "1111111111"
    nodeName = "platon"
    website = "https://www.test.network"
    details = "supper node"
    programVersion = 1792
    illegal_nodeID = conf.illegal_nodeID
    genesis_path = conf.GENESIS_TMP


    """替换config.json"""
    get_config_data()
    config_json_path = conf.PLATON_CONFIG_PATH
    config_dict = LoadFile(config_json_path).get_data()
    amount_delegate = Web3.fromWei(
        int(config_dict['EconomicModel']['Staking']['MinimumThreshold']), 'ether')
    amount = Web3.fromWei(
        int(config_dict['EconomicModel']['Staking']['StakeThreshold']), 'ether')


    def setup_class(self):
        self.auto = AutoDeployPlaton()
        self.auto.start_all_node(self.node_yml_path)
        self.genesis_dict = LoadFile(self.genesis_path).get_data()
        self.chainid = int(self.genesis_dict["config"]["chainId"])
        self.ppos_link = Ppos(
            self.rpc_list[0],self.address,self.chainid)
        self.w3_list = [connect_web3(url) for url in self.rpc_list]
        """用新的钱包地址和未质押过的节点id封装对象"""
        self.ppos_noconsensus_1 = Ppos(self.rpc_list[0], self.account_list[0],self.chainid,privatekey=self.privatekey_list[0])
        self.ppos_noconsensus_2 = Ppos(self.rpc_list[0], self.account_list[1],self.chainid,privatekey=self.privatekey_list[1])
        self.ppos_noconsensus_3 = Ppos(self.rpc_list[0], self.account_list[2],self.chainid,privatekey=self.privatekey_list[2])
        self.ppos_noconsensus_4 = Ppos(self.rpc_list[0], self.account_list[3],self.chainid,privatekey=self.privatekey_list[3])
        self.ppos_noconsensus_5 = Ppos(self.rpc_list[0], self.account_list[4],self.chainid,privatekey=self.privatekey_list[4])
        self.ppos_noconsensus_6 = Ppos(self.rpc_list[0], self.account_list[5],self.chainid,privatekey=self.privatekey_list[5])
        self.eth = Eth(self.w3_list[0])


    def transaction(self,w3, from_address, to_address=None,value=1000000000000000000000000000000000,
                    gas=91000000, gasPrice=9000000000,pwd=conf.PASSWORD):
        """"
        转账公共方法
        """
        personal = Personal(w3)
        personal.unlockAccount(from_address, pwd, 666666)
        params = {
            'to': to_address,
            'from': from_address,
            'gas': gas,
            'gasPrice': gasPrice,
            'value': value
        }
        tx_hash = w3.eth.sendTransaction(params)
        result = w3.eth.waitForTransactionReceipt(HexBytes(tx_hash).hex())
        return result


    def getCandidateList(self):
        """
        获取实时验证人的nodeID list
        """
        msg = self.ppos_noconsensus_1.getCandidateList()
        recive_list = msg.get("Data")
        nodeid_list = []
        if recive_list is None:
            return recive_list
        else:
            for node_info in recive_list:
                nodeid_list.append(node_info.get("NodeId"))
        return nodeid_list


    @allure.title("委托金额分别为{amount}")
    @pytest.mark.P1
    @pytest.mark.parametrize('amount', [amount_delegate-1, 0])
    def test_illege_delegate(self,amount):
        """
        用例id 委托金额小于门槛
        """
        log.info("转账每个钱包")
        for to_account in self.account_list:
            self.transaction(self.w3_list[0],self.address,to_address=to_account)
        log.info("质押节点1:{}成为验证人".format(self.nodeid_list2[0]))

        self.ppos_noconsensus_1.createStaking(0, self.account_list[0], self.nodeid_list2[0],
                                              self.externalId, self.nodeName, self.website, self.details,
                                              self.amount, self.programVersion)
        log.info("钱包2委托金额")
        msg = self.ppos_noconsensus_2.delegate(0, self.nodeid_list2[0], amount)
        log.info(msg)
        assert msg.get("Status") == False,"委托金额异常"


    @allure.title("质押过的钱包委托失败")
    @pytest.mark.P1
    def test_delegate_verifier(self):
        """
        测试质押过的钱包不能去委托
        """
        log.info("转账到钱包1")
        self.transaction(self.w3_list[0], self.address, to_address=self.account_list[0])
        log.info("转账到钱包2")
        self.transaction(self.w3_list[0], self.address, to_address=self.account_list[1])
        amount = self.amount_delegate
        msg = self.ppos_noconsensus_1.getCandidateInfo(self.nodeid_list2[0])
        if msg['Data']!= "":
            log.info("质押过的钱包1不能再去质押")
            msg = self.ppos_noconsensus_1.delegate(0, self.nodeid_list2[0], amount)
            # print(msg)
            assert msg.get("Status") == False
            msg_string = "is not allowed to be used for delegating"
            assert msg_string in msg["ErrMsg"], "质押过的钱包不能进行质押出现异常"
        else:
            log.info("质押节点1:{}成为验证人".format(self.nodeid_list2[0]))
            self.ppos_noconsensus_1.createStaking(0, self.account_list[0], self.nodeid_list2[0],
                                                  self.externalId, self.nodeName, self.website, self.details,
                                                  self.amount, self.programVersion)
            log.info("质押过的钱包1不能再去质押")
            msg = self.ppos_noconsensus_1.delegate(0, self.nodeid_list2[0], amount)
            assert msg.get("Status") == False
            log.info(msg)
            msg_string = "is not allowed to be used for delegating"
            assert msg_string in msg["ErrMsg"], "质押过的钱包不能进行质押出现异常"


    @allure.title("发起委托成功")
    @pytest.mark.P0
    def test_delegate(self):
        """
        用例id 95 委托成功,查询节点信息,金额
        用例id 98 委托人与验证人验证,验证人存在
        """
        log.info("转账到钱包1")
        self.transaction(self.w3_list[0], self.address, to_address=self.account_list[0])
        log.info("转账到钱包2")
        self.transaction(self.w3_list[0], self.address, to_address=self.account_list[1])
        amount = self.amount_delegate
        msg = self.ppos_noconsensus_1.getCandidateInfo(self.nodeid_list2[0])
        if msg['Data']!= "":
            log.info("钱包2委托节点1")
            msg = self.ppos_noconsensus_2.delegate(0,self.nodeid_list2[0],amount)
            assert msg.get("Status") == True
            assert msg.get("ErrMsg") == 'ok'
        else:
            log.info("质押节点1:{}成为验证人".format(self.nodeid_list2[0]))
            self.ppos_noconsensus_1.createStaking(0, self.account_list[0], self.nodeid_list2[0],
                                                  self.externalId, self.nodeName, self.website, self.details,
                                                  self.amount, self.programVersion)
            msg = self.ppos_noconsensus_2.delegate(0,self.nodeid_list2[0],amount)
            assert msg.get("Status") == True
            assert msg.get("ErrMsg") == 'ok'


    @allure.title("查询当前单个委托信息")
    @pytest.mark.P0
    def test_getDelegateInfo(self):
        """
        用例id 94 查询当前单个委托信息
        """

        log.info("转账到钱包5")
        self.transaction(self.w3_list[0], self.address, to_address=self.account_list[4])
        log.info("转账到钱包6")
        self.transaction(self.w3_list[0], self.address, to_address=self.account_list[5])

        log.info("质押节点5成为验证人")
        self.ppos_noconsensus_5.createStaking(0, self.account_list[4], self.nodeid_list2[4],
                                              self.externalId, self.nodeName, self.website, self.details,
                                              self.amount, self.programVersion)
        msg = self.ppos_noconsensus_6.delegate(0, self.nodeid_list2[4], self.amount_delegate)
        assert msg.get("Status") == True
        assert msg.get("ErrMsg") == 'ok'
        log.info("查询质押节点5信息")
        msg = self.ppos_noconsensus_5.getCandidateInfo(self.nodeid_list2[4])
        assert msg["Data"]["NodeId"] == self.nodeid_list2[4]
        log.info("查询质押+委托的金额正确")
        assert Web3.fromWei(msg["Data"]["Shares"], 'ether') == self.amount + self.amount_delegate
        assert Web3.fromWei(msg["Data"]["ReleasedHes"], 'ether') == self.amount
        stakingBlockNum = msg["Data"]["StakingBlockNum"]
        log.info("质押的块高{}".format(stakingBlockNum))
        msg = self.ppos_noconsensus_6.getDelegateInfo(stakingBlockNum, self.account_list[5], self.nodeid_list2[4])
        data = msg["Data"]
        data = json.loads(data)
        assert Web3.toChecksumAddress(data["Addr"]) == self.account_list[5]
        assert data["NodeId"] == self.nodeid_list2[4]
        assert Web3.fromWei(data["ReleasedHes"], 'ether') == self.amount_delegate


    @allure.title("余额不足委托失败")
    @pytest.mark.P2
    def test_insufficient_delegate(self):
        """
        用例96 余额不足委托失败
        """
        log.info("转账到钱包1")
        self.transaction(self.w3_list[0], self.address, to_address=self.account_list[0])
        log.info("转账到钱包2")
        self.transaction(self.w3_list[0], self.address, to_address=self.account_list[1])
        amount = 1000000000000000000000000000000
        msg = self.ppos_noconsensus_1.getCandidateInfo(self.nodeid_list2[0])
        if msg['Data']!= "":
            msg = self.ppos_noconsensus_2.delegate(0, self.nodeid_list2[0], amount)
            # print(msg)
            assert msg.get("Status") == False
            assert msg.get("ErrMsg") == 'Delegate failed: The von of account is not enough'
        else:
            log.info("质押节点1:{}成为验证人".format(self.nodeid_list2[0]))
            self.ppos_noconsensus_1.createStaking(0, self.account_list[0], self.nodeid_list2[0],
                                                  self.externalId, self.nodeName, self.website, self.details,
                                                  self.amount, self.programVersion)
            msg = self.ppos_noconsensus_2.delegate(0, self.nodeid_list2[0], amount)
            # print(msg)
            assert msg.get("Status") == False
            assert msg.get("ErrMsg") == 'Delegate failed: The von of account is not enough'


    @allure.title("验证人不存在进行委托")
    @pytest.mark.P2
    def test_not_nodeId_delegate(self):
        """
        用例72 验证人不存在进行委托
        """
        log.info("转账到钱包2")
        self.transaction(self.w3_list[0], self.address, to_address=self.account_list[1])
        value = self.amount_delegate
        nodeid = conf.illegal_nodeID
        msg = self.ppos_noconsensus_2.delegate(0, nodeid, value)
        print(msg)
        assert msg.get("Status") == False
        assert msg.get("ErrMsg") == 'This candidate is not exist'


    @allure.title("验证人退出后,委托人信息还存在")
    @pytest.mark.P1
    def test_back_unStaking_commissioned(self):
        """
        用例id 82 验证人申请退回质押金,委托金额还生效
        用例id 83 验证人退出后,委托人信息还存在
        """
        log.info("转账到钱包1")
        self.transaction(self.w3_list[0], self.address, to_address=self.account_list[0])
        log.info("转账到钱包2")
        self.transaction(self.w3_list[0], self.address, to_address=self.account_list[1])
        msg = self.ppos_noconsensus_1.getCandidateInfo(self.nodeid_list2[0])
        if msg['Data']== "":
            log.info("节点1再次成为验证人")
            self.ppos_noconsensus_1.createStaking(0, self.account_list[0], self.nodeid_list2[0],
                                                  self.externalId, self.nodeName, self.website, self.details,
                                                  self.amount, self.programVersion)
            log.info("钱包2进行委托100")
            self.ppos_noconsensus_2.delegate(0, self.nodeid_list2[0], 100)
            log.info("节点1退出验证人")
            self.ppos_noconsensus_1.unStaking(self.nodeid_list2[0])
            msg = self.ppos_noconsensus_2.getDelegateListByAddr(self.account_list[1])
            log.info(msg)
            StakingBlockNum = msg["Data"][0]["StakingBlockNum"]
            msg = self.ppos_noconsensus_2.getDelegateInfo(StakingBlockNum,self.account_list[1],self.nodeid_list2[0])
            log.info(msg)
            data = msg["Data"]
            data = json.loads(data)
            log.info(data)
            assert Web3.toChecksumAddress(data["Addr"]) == self.account_list[1]
            assert data["NodeId"] == self.nodeid_list2[0]
        else:
            log.info("钱包2进行委托100")
            self.ppos_noconsensus_2.delegate(0, self.nodeid_list2[0], 100)
            log.info("节点1退出验证人")
            self.ppos_noconsensus_1.unStaking(self.nodeid_list2[0])
            msg = self.ppos_noconsensus_2.getDelegateListByAddr(self.account_list[1])
            log.info(msg)
            StakingBlockNum = msg["Data"][0]["StakingBlockNum"]
            msg = self.ppos_noconsensus_2.getDelegateInfo(StakingBlockNum,self.account_list[1],self.nodeid_list2[0])
            log.info(msg)
            data = msg["Data"]
            data = json.loads(data)
            log.info(data)
            assert Web3.toChecksumAddress(data["Addr"]) == self.account_list[1]
            assert data["NodeId"] == self.nodeid_list2[0]



    @allure.title("验证节点退出后,再成为验证节点,钱包委托信息有2个")
    @pytest.mark.P2
    def test_identifier_quit_delegate(self):
        """
        委托验证节点,验证节点退出后,再成为验证节点,再去委托:预期有2个委托消息
        """
        log.info("转账到钱包3")
        self.transaction(self.w3_list[0], self.address, to_address=self.account_list[2])
        log.info("转账到钱包4")
        self.transaction(self.w3_list[0], self.address, to_address=self.account_list[3])

        log.info("质押节点3:{}成为验证节点".format(self.nodeid_list2[2]))
        self.ppos_noconsensus_3.createStaking(0, self.account_list[2], self.nodeid_list2[2],
                                              self.externalId, self.nodeName, self.website, self.details,
                                              self.amount, self.programVersion)
        log.info("钱包4:{}进行委托".format(self.account_list[3]))
        self.ppos_noconsensus_4.delegate(0,self.nodeid_list2[2],50)
        log.info("质押节点3退出验证人{}".format(self.nodeid_list2[2]))
        self.ppos_noconsensus_3.unStaking(self.nodeid_list2[2])
        log.info("{}再次成为验证人".format(self.nodeid_list2[2]))
        self.ppos_noconsensus_3.createStaking(0, self.account_list[2],self.nodeid_list2[2],self.externalId,
                                           self.nodeName, self.website, self.details,self.amount,self.programVersion)
        log.info("钱包4:{}再次进行委托".format(self.account_list[3]))
        msg = self.ppos_noconsensus_4.delegate(0,self.nodeid_list2[2],100)
        print(msg)
        log.info("查询钱包的委托情况")
        msg = self.ppos_noconsensus_4.getDelegateListByAddr(self.account_list[3])
        log.info(msg)
        log.info(msg["Data"])
        print(len(msg["Data"]))
        assert len(msg["Data"]) == 2
        for i in msg["Data"]:
            assert Web3.toChecksumAddress(i["Addr"]) == self.account_list[3]
            assert i["NodeId"] == self.nodeid_list2[2]
コード例 #15
0
class TestLockeDposition:
    address = conf.ADDRESS
    pwd = conf.PASSWORD
    abi = conf.DPOS_CONTRACT_ABI
    cbft_json_path = conf.CBFT2
    node_yml_path = conf.PPOS_NODE_TEST_YML
    file = conf.CASE_DICT
    privatekey = conf.PRIVATE_KEY
    base_gas_price = 60000000000000
    base_gas = 21000
    staking_gas = base_gas + 32000 + 6000 + 100000
    transfer_gasPrice = Web3.toWei(1, 'ether')
    transfer_gas = 210000000
    value = 1000
    chainid = 120
    ConsensusSize = 250
    time_interval = 10
    initial_amount = {
        'FOUNDATION': 905000000000000000000000000,
        'FOUNDATIONLOCKUP': 20000000000000000000000000,
        'STAKING': 25000000000000000000000000,
        'INCENTIVEPOOL': 45000000000000000000000000,
        'DEVELOPERS': 5000000000000000000000000
    }

    def start_init(self):
        #修改config参数
        CommonMethod.update_config(self, 'EconomicModel', 'Common',
                                   'ExpectedMinutes', 3)
        CommonMethod.update_config(self, 'EconomicModel', 'Common',
                                   'PerRoundBlocks', 10)
        CommonMethod.update_config(self, 'EconomicModel', 'Common',
                                   'ValidatorCount', 5)
        CommonMethod.update_config(self, 'EconomicModel', 'Staking',
                                   'ElectionDistance', 20)
        CommonMethod.update_config(self, 'EconomicModel', 'Staking',
                                   'StakeThreshold', 1000)
        #启动节点
        self.auto = AutoDeployPlaton()
        self.auto.start_all_node(self.node_yml_path)

    @allure.title("查看初始化时锁仓余额和锁仓信息")
    def test_init_loukup(self):
        '''
        查询初始化链后基金会锁仓金额
        以及查询初始锁仓计划信息的有效性
        :return:
        '''
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        lockupbalance = platon_ppos.eth.getBalance(
            conf.FOUNDATIONLOCKUPADDRESS)
        FOUNDATIONLOCKUP = self.initial_amount['FOUNDATIONLOCKUP']
        assert lockupbalance == FOUNDATIONLOCKUP
        result = platon_ppos.GetRestrictingInfo(conf.INCENTIVEPOOLADDRESS)
        assert result['Status'] == True, ",锁仓计划信息查询状态为{}".format(
            result['Status'])
        dict_info = json.loads(result['Data'])
        assert dict_info['balance'] == self.initial_amount[
            'FOUNDATIONLOCKUP'], '锁仓初始金额{}有误'.format(lockupbalance)

    def test_loukupplan(self):
        '''
        验证正常锁仓功能
        参数输入:
        Epoch:1
        Amount:50 ether
        :return:
        '''
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        address1, private_key1 = CommonMethod.read_private_key_list()
        # 签名转账
        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address1), self.base_gas_price,
            self.base_gas, self.value, self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt(result)
        assert return_info is not None, "转账:{}失败".format(self.value)
        #查询锁仓账户的余额
        lockup_before = platon_ppos.eth.getBalance(
            conf.FOUNDATIONLOCKUPADDRESS)
        log.info("发起锁仓账户的余额:{}".format(lockup_before))

        #创建锁仓计划
        loukupbalace = Web3.toWei(50, 'ether')
        plan = [{'Epoch': 1, 'Amount': loukupbalace}]
        result = platon_ppos.CreateRestrictingPlan(
            address1,
            plan,
            privatekey=private_key1,
            from_address=address1,
            gasPrice=self.base_gas_price,
            gas=self.staking_gas)
        assert result['Status'] == True, "创建锁仓计划返回状态为:{} 有误".format(
            result['Status'])
        lockup_after = platon_ppos.eth.getBalance(conf.FOUNDATIONLOCKUPADDRESS)
        assert lockup_after == lockup_before + loukupbalace, "锁仓账户金额:{}有误".format(
            lockup_after)

        #查看锁仓计划明细
        detail = platon_ppos.GetRestrictingInfo(address1)
        assert detail['Status'] == True, "查询锁仓计划信息返回状态为:{}".format(
            result['Status'])
        RestrictingInfo = json.loads(detail['Data'])
        assert RestrictingInfo[
            'balance'] == loukupbalace, "创建锁仓计划金额:{}有误".format(lockup_after)

    @allure.title("根据不同参数创建锁仓计划")
    @pytest.mark.parametrize('number,amount', [(1, 0.1), (0, 100), (36, 100),
                                               (37, 100), ('ss', 100)])
    def test_loukupplan_abnormal(self, number, amount):
        '''
        创建锁仓计划时,参数有效性验证
        number : 锁仓解锁期
        amount : 锁仓金额
        :param number:
        :param amount:
        :return:
        '''

        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        address1, private_key1 = CommonMethod.read_private_key_list()
        # 签名转账
        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address1), self.base_gas_price,
            self.base_gas, self.value, self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt(result)
        assert return_info is not None, "转账:{}失败".format(self.value)
        loukupbalace = Web3.toWei(amount, 'ether')
        #loukupbalace = amount
        plan = [{'Epoch': number, 'Amount': loukupbalace}]
        log.info("创建锁仓计划参数:{}".format(plan))

        if type(number) == int and type(amount) == int:
            if 0 < number <= 36 and 1 <= amount:

                result = platon_ppos.CreateRestrictingPlan(
                    address1,
                    plan,
                    privatekey=private_key1,
                    from_address=address1,
                    gasPrice=self.base_gas_price,
                    gas=self.staking_gas)
                assert result['Status'] == True, '创建锁仓状态为:{},用例失败'.format(
                    result['Status'])

            else:
                result = platon_ppos.CreateRestrictingPlan(
                    address1,
                    plan,
                    privatekey=private_key1,
                    from_address=address1,
                    gasPrice=self.base_gas_price,
                    gas=self.staking_gas)
                assert result['Status'] == False, '创建锁仓状态为:{},用例失败'.format(
                    result['Status'])
        else:
            result = platon_ppos.CreateRestrictingPlan(
                address1,
                plan,
                privatekey=private_key1,
                from_address=address1,
                gasPrice=self.base_gas_price,
                gas=self.staking_gas)
            assert result['Status'] == False, '创建锁仓状态为:{},用例失败'.format(
                result['Status'])

    @allure.title("锁仓金额大于账户余额")
    def test_loukupplan_amount(self):
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        address1, private_key1 = CommonMethod.read_private_key_list()
        # 签名转账
        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address1), self.base_gas_price,
            self.base_gas, self.value, self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt(result)
        assert return_info is not None, "转账:{}失败".format(self.value)
        loukupbalace = Web3.toWei(10000, 'ether')
        plan = [{'Epoch': 1, 'Amount': loukupbalace}]
        result = platon_ppos.CreateRestrictingPlan(
            address1,
            plan,
            privatekey=private_key1,
            from_address=address1,
            gasPrice=self.base_gas_price,
            gas=self.staking_gas)
        assert result['Status'] == False, '创建锁仓计划返回状态为{},用例失败'.format(
            result['Status'])

    @allure.title("多个锁仓期金额情况验证")
    @pytest.mark.parametrize('balace1,balace2', [(300, 300), (500, 600)])
    def test_loukupplan_Moredeadline(self, balace1, balace2):
        '''
        验证一个锁仓计划里有多个解锁期
        amount : 锁仓
        balace1 : 第一个锁仓期的锁仓金额
        balace2 : 第二个锁仓期的锁仓金额
        :return:
        '''
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        address1, private_key1 = CommonMethod.read_private_key_list()

        # 签名转账
        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address1), self.base_gas_price,
            self.base_gas, self.value, self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt(result)
        assert return_info is not None, "转账:{}失败".format(self.value)
        loukupbalace1 = Web3.toWei(balace1, 'ether')
        loukupbalace2 = Web3.toWei(balace2, 'ether')
        if (balace1 + balace2) < self.value:
            plan = [{
                'Epoch': 1,
                'Amount': loukupbalace1
            }, {
                'Epoch': 2,
                'Amount': loukupbalace2
            }]
            result = platon_ppos.CreateRestrictingPlan(
                address1,
                plan,
                privatekey=private_key1,
                from_address=address1,
                gasPrice=self.base_gas_price,
                gas=self.staking_gas)
            assert result['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format(
                result['Status'])
        elif (balace1 + balace2) >= self.value:
            plan = [{
                'Epoch': 1,
                'Amount': loukupbalace1
            }, {
                'Epoch': 2,
                'Amount': loukupbalace2
            }]
            result = platon_ppos.CreateRestrictingPlan(
                address1,
                plan,
                privatekey=private_key1,
                from_address=address1,
                gasPrice=self.base_gas_price,
                gas=self.staking_gas)
            assert result['Status'] == False, "创建锁仓计划返回的状态:{},用例失败".format(
                result['Status'])
        else:
            log.info('锁仓输入的金额:{}出现异常'.format((loukupbalace1 + loukupbalace2)))
            Status = 1
            assert Status == 0, 'error:创建锁仓失败'

    @allure.title("锁仓计划多个相同解锁期情况验证")
    @pytest.mark.parametrize('Status,', [(1), (2), (3), (4)])
    def test_loukupplan_sameperiod(self, Status):
        '''
        验证一个锁仓计划里有多个相同解锁期
        code =1 :同个account在一个锁仓计划里有相同解锁期
        code =2 :同个account在不同锁仓计划里有相同解锁期
        :return:
        '''
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)

        address1, private_key1 = CommonMethod.read_private_key_list()

        # 签名转账
        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address1), self.base_gas_price,
            self.base_gas, self.value, self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt(result)
        assert return_info is not None, "转账:{}失败".format(self.value)
        period1 = 1
        period2 = 2
        loukupbalace = Web3.toWei(100, 'ether')

        if Status == 1:
            plan = [{
                'Epoch': period1,
                'Amount': loukupbalace
            }, {
                'Epoch': period1,
                'Amount': loukupbalace
            }]
            log.info("锁仓参数:{}".format(plan))
            log.info("当前块高:{}".format(platon_ppos.eth.blockNumber))
            result = platon_ppos.CreateRestrictingPlan(
                address1,
                plan,
                privatekey=private_key1,
                from_address=address1,
                gasPrice=self.base_gas_price,
                gas=self.staking_gas)
            assert result['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format(
                result['Status'])
            RestrictingInfo = platon_ppos.GetRestrictingInfo(address1)
            json_data = json.loads(RestrictingInfo['Data'])
            assert json_data['Entry'][0]['amount'] == (
                loukupbalace + loukupbalace), '锁仓金额{}有误'.format(
                    json_data['Entry'][0]['amount'])

        elif Status == 2:
            plan = [{'Epoch': period1, 'Amount': loukupbalace}]
            log.info("锁仓参数:{}".format(plan))
            log.info("当前块高:{}".format(platon_ppos.eth.blockNumber))
            result = platon_ppos.CreateRestrictingPlan(
                address1,
                plan,
                privatekey=private_key1,
                from_address=address1,
                gasPrice=self.base_gas_price,
                gas=self.staking_gas)
            assert result['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format(
                result['Status'])
            log.info("锁仓参数:{}".format(plan))
            log.info("当前块高:{}".format(platon_ppos.eth.blockNumber))
            result1 = platon_ppos.CreateRestrictingPlan(
                address1,
                plan,
                privatekey=private_key1,
                from_address=address1,
                gasPrice=self.base_gas_price,
                gas=self.staking_gas)
            assert result1['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format(
                result['Status'])
            RestrictingInfo = platon_ppos.GetRestrictingInfo(address1)
            json_data = json.loads(RestrictingInfo['Data'])
            assert json_data['balance'] == (loukupbalace +
                                            loukupbalace), '锁仓金额{}有误'.format(
                                                json_data['balance'])
            assert json_data['Entry'][0]['amount'] == (
                loukupbalace + loukupbalace), '锁仓金额{}有误'.format(
                    json_data['Entry'][0]['amount'])
        elif Status == 3:
            plan = [{'Epoch': period1, 'Amount': loukupbalace}]
            log.info("锁仓参数:{}".format(plan))
            log.info("当前块高:{}".format(platon_ppos.eth.blockNumber))
            result1 = platon_ppos.CreateRestrictingPlan(
                address1,
                plan,
                privatekey=private_key1,
                from_address=address1,
                gasPrice=self.base_gas_price,
                gas=self.staking_gas)
            assert result1['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format(
                result['Status'])
            RestrictingInfo = platon_ppos.GetRestrictingInfo(address1)

            plan = [{'Epoch': period2, 'Amount': loukupbalace}]
            log.info("锁仓参数:{}".format(plan))
            log.info("当前块高:{}".format(platon_ppos.eth.blockNumber))
            result1 = platon_ppos.CreateRestrictingPlan(
                address1,
                plan,
                privatekey=private_key1,
                from_address=address1,
                gasPrice=self.base_gas_price,
                gas=self.staking_gas)
            assert result1['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format(
                result['Status'])
            RestrictingInfo = platon_ppos.GetRestrictingInfo(address1)
            json_data = json.loads(RestrictingInfo['Data'])
            assert json_data['balance'] == (loukupbalace *
                                            2), '锁仓金额{}有误'.format(
                                                json_data['balance'])
            assert json_data['Entry'][0]['amount'] + json_data['Entry'][1][
                'amount'] == json_data[
                    'balance'], '锁仓金额{}有误                           '.format(
                        json_data['Entry'][0]['amount'] +
                        json_data['Entry'][1]['amount'])

        elif Status == 4:
            plan = [{
                'Epoch': 2,
                'Amount': loukupbalace
            }, {
                'Epoch': 3,
                'Amount': loukupbalace
            }]
            log.info("锁仓参数:{}".format(plan))
            log.info("当前块高:{}".format(platon_ppos.eth.blockNumber))
            result1 = platon_ppos.CreateRestrictingPlan(
                address1,
                plan,
                privatekey=private_key1,
                from_address=address1,
                gasPrice=self.base_gas_price,
                gas=self.staking_gas)
            assert result1['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format(
                result['Status'])
            RestrictingInfo = platon_ppos.GetRestrictingInfo(address1)

            plan = [{
                'Epoch': 2,
                'Amount': loukupbalace
            }, {
                'Epoch': 3,
                'Amount': loukupbalace
            }]
            log.info("锁仓参数:{}".format(plan))
            log.info("当前块高:{}".format(platon_ppos.eth.blockNumber))
            result1 = platon_ppos.CreateRestrictingPlan(
                address1,
                plan,
                privatekey=private_key1,
                from_address=address1,
                gasPrice=self.base_gas_price,
                gas=self.staking_gas)
            assert result1['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format(
                result['Status'])
            RestrictingInfo = platon_ppos.GetRestrictingInfo(address1)
            json_data = json.loads(RestrictingInfo['Data'])
            assert json_data['balance'] == (loukupbalace *
                                            4), '锁仓金额{}有误'.format(
                                                json_data['balance'])
            assert json_data['Entry'][0]['amount'] + json_data['Entry'][1][
                'amount'] == json_data[
                    'balance'], '锁仓金额{}有误                           '.format(
                        json_data['Entry'][0]['amount'] +
                        json_data['Entry'][1]['amount'])

        else:
            Status = 1
            assert Status == 0, '输入的Status:{}有误'.format(Status)

    @allure.title("验证锁仓账户和释放到账账户为同一个时质押扣费验证")
    @pytest.mark.parametrize('amount,', [(0), (500), (900), (910)])
    def test_lockup_pledge(self, amount):
        '''
        验证锁仓账户和释放到账账户为同一个时锁仓质押扣费情况
        amount:质押金额
        :return:
        '''
        nodeId = CommonMethod.read_out_nodeId(self, 'nocollusion')
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)

        address1, private_key1 = CommonMethod.read_private_key_list()

        # 签名转账
        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address1), self.base_gas_price,
            self.base_gas, self.value, self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt(result)
        assert return_info is not None, "转账:{}失败".format(self.value)
        loukupbalace = Web3.toWei(900, 'ether')
        plan = [{'Epoch': 1, 'Amount': loukupbalace}]
        balance = platon_ppos.eth.getBalance(address1)
        log.info("锁仓账号余额:{}".format(balance))

        lockup_before = platon_ppos.eth.getBalance(
            conf.FOUNDATIONLOCKUPADDRESS)
        log.info("创建锁仓计划之前锁仓合约余额:{}".format(lockup_before))

        #创建锁仓计划
        result = platon_ppos.CreateRestrictingPlan(
            address1,
            plan,
            privatekey=private_key1,
            from_address=address1,
            gasPrice=self.base_gas_price,
            gas=self.staking_gas)
        assert result['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format(
            result['Status'])
        lockup_after = platon_ppos.eth.getBalance(conf.FOUNDATIONLOCKUPADDRESS)
        log.info("创建锁仓计划之后锁仓合约余额:{}".format(lockup_after))
        assert lockup_after == lockup_before + loukupbalace, "锁仓计划金额{}".format(
            lockup_after)
        staking_befor = platon_ppos.eth.getBalance(conf.STAKINGADDRESS)
        log.info("发起验证人质押之前质押合约余额:{}".format(staking_befor))

        if 0 < Web3.toWei(amount, 'ether') <= loukupbalace:
            # 发起质押
            version = get_version(platon_ppos)
            result = platon_ppos.createStaking(1,
                                               address1,
                                               nodeId,
                                               'externalId',
                                               'nodeName',
                                               'website',
                                               'details',
                                               amount,
                                               version,
                                               privatekey=private_key1,
                                               from_address=address1,
                                               gasPrice=self.base_gas_price,
                                               gas=self.staking_gas)
            assert result['Status'] == True, "申请质押返回的状态:{},用例失败".format(
                result['Status'])

            #质押账户余额增加
            staking_after = platon_ppos.eth.getBalance(conf.STAKINGADDRESS)
            log.info("发起验证人质押之后质押合约余额:{}".format(staking_after))
            assert staking_after == staking_befor + Web3.toWei(
                amount, 'ether'), "质押账户余额:{}有误".format(staking_after)

            #锁仓合约地址余额减少
            lock_balance = platon_ppos.eth.getBalance(
                conf.FOUNDATIONLOCKUPADDRESS)
            log.info("发起验证人质押之后锁仓合约余额:{}".format(lock_balance))
            assert lock_balance == lockup_after - Web3.toWei(
                amount, 'ether'), "锁仓合约余额:{}有误".format(lock_balance)

            #发起锁仓账户余额减少手续费
            pledge_balance_after = platon_ppos.eth.getBalance(address1)
            log.info("锁仓账号余额:{}".format(pledge_balance_after))
            assert balance > pledge_balance_after, "发起锁仓账户余额减少{}手续费有误".format(
                address1)
            RestrictingInfo = platon_ppos.GetRestrictingInfo(address1)
            assert result['Status'] == True, "查询锁仓信息返回的状态:{},用例失败".format(
                result['Status'])

            #验证锁仓计划里的锁仓可用余额减少
            Info = json.loads(RestrictingInfo['Data'])
            assert loukupbalace == Info['balance'] + Web3.toWei(
                amount,
                'ether'), "查询{}锁仓余额失败".format(Info['balance'] +
                                              Web3.toWei(amount, 'ether'))

        else:
            # 发起质押
            version = get_version(platon_ppos)
            nodeId = CommonMethod.get_no_candidate_list(self)
            result = platon_ppos.createStaking(1,
                                               address1,
                                               nodeId,
                                               'externalId',
                                               'nodeName',
                                               'website',
                                               'details',
                                               amount,
                                               version,
                                               privatekey=private_key1,
                                               from_address=address1,
                                               gasPrice=self.base_gas_price,
                                               gas=self.staking_gas)
            assert result['Status'] == False, "创建锁仓信息返回的状态:{},用例失败".format(
                result['Status'])

    @allure.title("验证锁仓账户和释放到账账户为不同时质押扣费验证")
    def test_morelockup_pledge(self):
        '''
        验证锁仓账户和释放到账账户为不同时锁仓质押扣费情况
        amount:质押金额
        :return:
        '''
        nodeId = CommonMethod.get_no_candidate_list(self)
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)

        address1, private_key1 = CommonMethod.read_private_key_list()
        address2, private_key2 = CommonMethod.read_private_key_list()

        # 签名转账
        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address1), self.base_gas_price,
            self.base_gas, self.value, self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt(result)
        assert return_info is not None, "转账:{}失败".format(self.value)

        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address2), self.base_gas_price,
            self.base_gas, self.value, self.privatekey)
        return_info = platon_ppos.eth.waitForTransactionReceipt(result)

        assert return_info is not None, "转账:{}失败".format(self.value)
        balance = platon_ppos.eth.getBalance(address1)
        log.info("发起锁仓账户余额:{}".format(balance))
        loukupbalace = Web3.toWei(900, 'ether')
        plan = [{'Epoch': 1, 'Amount': loukupbalace}]

        #创建锁仓计划
        result = platon_ppos.CreateRestrictingPlan(
            address2,
            plan,
            privatekey=private_key1,
            from_address=address1,
            gasPrice=self.base_gas_price,
            gas=self.staking_gas)
        assert result['Status'] == True, "创建锁仓信息返回的状态:{},用例失败".format(
            result['Status'])
        RestrictingInfo = platon_ppos.GetRestrictingInfo(address2)
        assert RestrictingInfo['Status'] == True, "创建锁仓信息返回的状态:{},用例失败".format(
            result['Status'])

        # 锁仓账号发起质押

        version = get_version(platon_ppos)
        result = platon_ppos.createStaking(1,
                                           address1,
                                           nodeId,
                                           'externalId',
                                           'nodeName',
                                           'website',
                                           'details',
                                           900,
                                           version,
                                           privatekey=private_key1,
                                           from_address=address1,
                                           gasPrice=self.base_gas_price,
                                           gas=self.staking_gas)
        assert result['Status'] == False, "创建锁仓信息返回的状态:{},用例失败".format(
            result['Status'])

    @allure.title("验证锁仓账户和释放到账账户为同一个时委托扣费")
    @pytest.mark.parametrize('amount,', [(0), (100), (300), (310)])
    def test_lockup_entrust(self, amount):
        '''
        锁仓账户和释放到账账户为同一个时委托扣费验证
        :param amount:
        :return:
        '''
        nodeId = CommonMethod.get_no_candidate_list(self)
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        address1, private_key1 = CommonMethod.read_private_key_list()
        address2, private_key2 = CommonMethod.read_private_key_list()
        # 签名转账
        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address2), self.base_gas_price,
            self.base_gas, self.value, self.privatekey)
        return_info1 = platon_ppos.eth.waitForTransactionReceipt(result)
        assert return_info1 is not None, "转账:{}失败".format(self.value)
        # 签名转账
        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address1), self.base_gas_price,
            self.base_gas, self.value, self.privatekey)
        return_info2 = platon_ppos.eth.waitForTransactionReceipt(result)
        assert return_info2 is not None, "转账:{}失败".format(self.value)
        balance1 = platon_ppos.eth.getBalance(address1)
        log.info("{}发起锁仓和质押的账户余额:{}".format(address1, balance1))
        balance = platon_ppos.eth.getBalance(address2)
        log.info("{}发起委托账户余额:{}".format(address2, balance))
        loukupbalace = Web3.toWei(300, 'ether')
        plan = [{'Epoch': 1, 'Amount': loukupbalace}]

        # 创建锁仓计划
        result = platon_ppos.CreateRestrictingPlan(
            address2,
            plan,
            privatekey=private_key1,
            from_address=address1,
            gasPrice=self.base_gas_price,
            gas=self.staking_gas)
        assert result['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format(
            result['Status'])
        lockup_after = platon_ppos.eth.getBalance(conf.FOUNDATIONLOCKUPADDRESS)
        RestrictingInfo = platon_ppos.GetRestrictingInfo(address2)
        info = json.loads(RestrictingInfo['Data'])
        log.info("锁仓计划可用余额:{}".format(info['balance']))
        balance2 = platon_ppos.eth.getBalance(address1)
        log.info("{}发起锁仓后账户余额:{}".format(address1, balance2))
        lock_balance1 = platon_ppos.eth.getBalance(
            conf.FOUNDATIONLOCKUPADDRESS)
        log.info("委托前锁仓合约地址余额:{}".format(lock_balance1))

        # 发起质押
        version = get_version(platon_ppos)
        result = platon_ppos.createStaking(0,
                                           address1,
                                           nodeId,
                                           'externalId',
                                           'nodeName',
                                           'website',
                                           'details',
                                           100,
                                           version,
                                           privatekey=private_key1,
                                           from_address=address1,
                                           gasPrice=self.base_gas_price,
                                           gas=self.staking_gas)
        assert result['Status'] == True, "创建锁仓信息返回的状态:{},用例失败".format(
            result['Status'])
        balance3 = platon_ppos.eth.getBalance(address1)
        log.info("{}发起质押后账户余额:{}".format(address1, balance3))
        staking_befor = platon_ppos.eth.getBalance(conf.STAKINGADDRESS)
        log.info("委托前质押合约地址余额:{}".format(staking_befor))

        #委托金额小于锁仓金额发起委托
        if 0 < Web3.toWei(amount, 'ether') <= loukupbalace:
            log.info("委托金额:{}".format(Web3.toWei(amount, 'ether')))
            delegate_info = platon_ppos.delegate(1,
                                                 nodeId,
                                                 amount,
                                                 privatekey=private_key2,
                                                 from_address=address2,
                                                 gasPrice=self.base_gas_price,
                                                 gas=self.staking_gas)
            assert delegate_info[
                'Status'] == True, "查询锁仓计划返回的状态:{},用例失败".format(
                    result['Status'])
            balance4 = platon_ppos.eth.getBalance(address2)
            log.info("{}发起委托后账户余额:{}".format(address2, balance4))
            #质押账户余额增加
            staking_after = platon_ppos.eth.getBalance(conf.STAKINGADDRESS)
            log.info("委托后质押合约地址余额:{}".format(staking_after))
            assert staking_after == staking_befor + Web3.toWei(
                amount, 'ether'), "质押账户余额:{}".format(staking_after)
            #锁仓合约地址余额减少
            lock_balance = platon_ppos.eth.getBalance(
                conf.FOUNDATIONLOCKUPADDRESS)
            log.info("委托后锁仓合约地址余额:{}".format(lock_balance))
            assert lock_balance == lockup_after - Web3.toWei(
                amount, 'ether'), "锁仓合约余额:{}".format(lock_balance)
        #委托金额大于锁仓金额发起委托
        else:
            delegate_info = platon_ppos.delegate(1,
                                                 nodeId,
                                                 amount,
                                                 privatekey=private_key2,
                                                 from_address=address2,
                                                 gasPrice=self.base_gas_price,
                                                 gas=self.staking_gas)
            assert delegate_info[
                'Status'] == False, "申请委托返回的状态:{},用例失败".format(
                    result['Status'])

    def test_morelockup_entrust(self):
        '''
        验证锁仓账户和释放到账账户为不同时锁仓委托扣费情况
        code:1、锁仓账户有余额支付委托手续费。
        :return:
        '''
        nodeId = CommonMethod.get_no_candidate_list(self)
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        address1, private_key1 = CommonMethod.read_private_key_list()
        address2, private_key2 = CommonMethod.read_private_key_list()
        # 为质押和锁仓账户转账手续费
        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address1), self.base_gas_price,
            self.base_gas, self.value, self.privatekey)
        return_info2 = platon_ppos.eth.waitForTransactionReceipt(result)
        assert return_info2 is not None, "转账:{}失败".format(self.value)
        #为委托账号转账手续费
        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address2), self.base_gas_price,
            self.base_gas, self.value, self.privatekey)
        return_info1 = platon_ppos.eth.waitForTransactionReceipt(result)
        assert return_info1 is not None, "转账:{}失败".format(self.value)
        Balance = platon_ppos.eth.getBalance(address1)
        log.info("{}质押和锁仓账户:{}".format(address1, Balance))
        Balance1 = platon_ppos.eth.getBalance(address2)
        log.info("{}委托账号:{}".format(address2, Balance1))

        # 发起质押
        version = get_version(platon_ppos)
        result = platon_ppos.createStaking(0,
                                           address1,
                                           nodeId,
                                           'externalId',
                                           'nodeName',
                                           'website',
                                           'details',
                                           100,
                                           version,
                                           privatekey=private_key1,
                                           from_address=address1,
                                           gasPrice=self.base_gas_price,
                                           gas=self.staking_gas)
        assert result['Status'] == True, "创建锁仓信息返回的状态:{},用例失败".format(
            result['Status'])
        Balance2 = platon_ppos.eth.getBalance(address1)
        log.info("{}质押后账户余额:{}".format(address1, Balance2))

        # 创建锁仓计划
        loukupbalace = Web3.toWei(500, 'ether')
        plan = [{'Epoch': 1, 'Amount': loukupbalace}]
        result = platon_ppos.CreateRestrictingPlan(
            address2,
            plan,
            privatekey=private_key1,
            from_address=address1,
            gasPrice=self.base_gas_price,
            gas=self.staking_gas)
        assert result['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format(
            result['Status'])
        # RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        # assert RestrictingInfo['Status'] == True, "查询锁仓计划返回的状态:{},用例失败".format (result['Status'])
        Balance3 = platon_ppos.eth.getBalance(address1)
        log.info("{}创建锁仓后账户余额:{}".format(address1, Balance3))

        # 锁仓账号发起委托
        delegate_info = platon_ppos.delegate(1,
                                             nodeId,
                                             500,
                                             privatekey=private_key2,
                                             from_address=address2,
                                             gasPrice=self.base_gas_price,
                                             gas=self.staking_gas)
        assert delegate_info['Status'] == True, "申请委托返回的状态:{},用例失败".format(
            result['Status'])
        Balance4 = platon_ppos.eth.getBalance(address2)
        log.info("{}委托后账户余额:{}".format(address2, Balance4))
        RestrictingInfo = platon_ppos.GetRestrictingInfo(address2)
        info = json.loads(RestrictingInfo['Data'])
        assert info['balance'] == 0, "锁仓可用余额:{},有误".format(info['balance'])

    def test_lockup_Withdrawal_of_pledge(self):
        '''
        锁仓账户申请完质押后又退回质押金
        :return:
        '''
        nodeId = CommonMethod.get_no_candidate_list(self)
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        address1, private_key1 = CommonMethod.read_private_key_list()
        address2, private_key2 = CommonMethod.read_private_key_list()

        # 签名转账
        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address1), self.base_gas_price,
            self.base_gas, self.value, self.privatekey)
        return_info2 = platon_ppos.eth.waitForTransactionReceipt(result)
        assert return_info2 is not None, "转账:{}失败".format(self.value)

        # 创建锁仓计划
        balance = platon_ppos.eth.getBalance(address1)
        log.info("发起锁仓账户余额:{}".format(balance))
        loukupbalace = Web3.toWei(800, 'ether')
        plan = [{'Epoch': 2, 'Amount': loukupbalace}]
        result = platon_ppos.CreateRestrictingPlan(
            address2,
            plan,
            privatekey=private_key1,
            from_address=address1,
            gasPrice=self.base_gas_price,
            gas=self.staking_gas)
        assert result['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format(
            result['Status'])
        # RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        # assert RestrictingInfo['Status'] == True, "查询锁仓计划返回的状态:{},用例失败".format (result['Status'])

        lockup_before = platon_ppos.eth.getBalance(
            conf.FOUNDATIONLOCKUPADDRESS)
        log.info("申请质押节点之前锁仓账户金额:{}".format(lockup_before))
        Staking_before = platon_ppos.eth.getBalance(conf.STAKINGADDRESS)
        log.info("申请质押节点之前Staking账户金额:{}".format(Staking_before))
        RestrictingInfo = platon_ppos.GetRestrictingInfo(address2)
        RestrictingInfo = json.loads(RestrictingInfo['Data'])
        log.info("锁仓计划可用余额:{}".format(RestrictingInfo['balance']))

        # 签名转账
        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address2), self.base_gas_price,
            self.base_gas, self.value, self.privatekey)
        return_info2 = platon_ppos.eth.waitForTransactionReceipt(result)
        assert return_info2 is not None, "转账:{}失败".format(self.value)

        # 发起质押
        version = get_version(platon_ppos)
        amount = 800
        result = platon_ppos.createStaking(1,
                                           address2,
                                           nodeId,
                                           'externalId',
                                           'nodeName',
                                           'website',
                                           'details',
                                           amount,
                                           version,
                                           privatekey=private_key2,
                                           from_address=address2,
                                           gasPrice=self.base_gas_price,
                                           gas=self.staking_gas)
        assert result['Status'] == True, "申请质押返回的状态:{},用例失败".format(
            result['Status'])

        #查询每个账户余额
        CandidateInfo = platon_ppos.getCandidateInfo(nodeId)
        log.info("质押节点信息:{}".format(CandidateInfo))
        lockup_Back_before = platon_ppos.eth.getBalance(
            conf.FOUNDATIONLOCKUPADDRESS)
        log.info("退回质押金之前锁仓账户金额:{}".format(lockup_Back_before))
        Staking_Back_before = platon_ppos.eth.getBalance(conf.STAKINGADDRESS)
        log.info("退回质押金之前Staking账户金额:{}".format(Staking_Back_before))
        RestrictingInfo = platon_ppos.GetRestrictingInfo(address2)
        RestrictingInfo = json.loads(RestrictingInfo['Data'])
        log.info("锁仓计划可用余额:{}".format(RestrictingInfo['balance']))

        #申请退回质押金
        result = platon_ppos.unStaking(nodeId,
                                       privatekey=private_key2,
                                       from_address=address2,
                                       gasPrice=self.base_gas_price,
                                       gas=self.staking_gas)
        assert result['Status'] == True, "申请质押退回质押金返回的状态:{},用例失败".format(
            result['Status'])
        lockup_end = platon_ppos.eth.getBalance(conf.FOUNDATIONLOCKUPADDRESS)
        log.info("退回质押金之后锁仓账户金额:{}".format(lockup_end))
        Staking_end = platon_ppos.eth.getBalance(conf.STAKINGADDRESS)
        log.info("退回质押金之后Staking账户金额:{}".format(Staking_end))
        RestrictingInfo = platon_ppos.GetRestrictingInfo(address2)
        RestrictingInfo = json.loads(RestrictingInfo['Data'])
        log.info("锁仓计划可用余额:{}".format(RestrictingInfo['balance']))
        assert lockup_end == lockup_before, "质押金退回后锁仓金额:{}有误".format(
            lockup_end)
        assert Staking_end == Staking_before, "质押金退回后Staking金额:{}有误".format(
            Staking_end)
        assert RestrictingInfo[
            'balance'] == loukupbalace, "锁仓计划金额:{}有误".format(
                RestrictingInfo['balance'])

    def test_lockup_redemption_of_entrust(self):
        '''
        锁仓账户发起委托之后赎回委托验证
        :return:
        '''
        nodeId = CommonMethod.get_no_candidate_list(self)
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        address1, private_key1 = CommonMethod.read_private_key_list()
        address2, private_key2 = CommonMethod.read_private_key_list()

        # 签名转账
        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address1), self.base_gas_price,
            self.base_gas, self.value, self.privatekey)
        return_info2 = platon_ppos.eth.waitForTransactionReceipt(result)
        assert return_info2 is not None, "转账:{}失败".format(self.value)

        # 给锁仓账号转手续费
        result = platon_ppos.send_raw_transaction(
            '', Web3.toChecksumAddress(self.address),
            Web3.toChecksumAddress(address2), self.base_gas_price,
            self.base_gas, self.value, conf.PRIVATE_KEY)
        return_info = platon_ppos.eth.waitForTransactionReceipt(result)

        assert return_info is not None, "转账锁仓账号手续费:{}失败".format(self.value)

        # 申请质押节点
        version = get_version(platon_ppos)
        amount = 100
        result = platon_ppos.createStaking(0,
                                           address1,
                                           nodeId,
                                           'externalId',
                                           'nodeName',
                                           'website',
                                           'details',
                                           amount,
                                           version,
                                           privatekey=private_key1,
                                           from_address=address1,
                                           gasPrice=self.base_gas_price,
                                           gas=self.staking_gas)
        assert result['Status'] == True, "申请质押返回的状态:{},{}用例失败".format(
            result['Status'], result['ErrMsg'])

        # 创建锁仓计划
        loukupbalace = Web3.toWei(500, 'ether')
        plan = [{'Epoch': 1, 'Amount': loukupbalace}]
        result = platon_ppos.CreateRestrictingPlan(
            address2,
            plan,
            privatekey=private_key1,
            from_address=address1,
            gasPrice=self.base_gas_price,
            gas=self.staking_gas)
        assert result['Status'] == True, "创建锁仓计划返回的状态:{},用例失败".format(
            result['Status'])
        # RestrictingInfo = platon_ppos.GetRestrictingInfo (address2)
        # assert RestrictingInfo['Status'] == True, "查询锁仓计划返回的状态:{},用例失败".format (result['Status'])

        balance = platon_ppos.eth.getBalance(address2)
        log.info("发起锁仓账户余额:{}".format(balance))
        lockup_before = platon_ppos.eth.getBalance(
            conf.FOUNDATIONLOCKUPADDRESS)
        log.info("申请委托之前锁仓账户金额:{}".format(lockup_before))
        Staking_before = platon_ppos.eth.getBalance(conf.STAKINGADDRESS)
        log.info("申请委托之前Staking账户金额:{}".format(Staking_before))
        RestrictingInfo = platon_ppos.GetRestrictingInfo(address2)
        RestrictingInfo = json.loads(RestrictingInfo['Data'])
        log.info("锁仓计划可用余额:{}".format(RestrictingInfo['balance']))

        #申请委托验证人节点
        amount = 500
        delegate_info = platon_ppos.delegate(1,
                                             nodeId,
                                             amount,
                                             privatekey=private_key2,
                                             from_address=address2,
                                             gasPrice=self.base_gas_price,
                                             gas=self.staking_gas)
        assert delegate_info['Status'] == True, "申请委托返回的状态:{},用例失败".format(
            result['Status'])

        lockup_back_before = platon_ppos.eth.getBalance(
            conf.FOUNDATIONLOCKUPADDRESS)
        log.info("申请委托之后锁仓账户金额:{}".format(lockup_back_before))
        Staking_back_before = platon_ppos.eth.getBalance(conf.STAKINGADDRESS)
        log.info("申请委托之后Staking账户金额:{}".format(Staking_back_before))
        RestrictingInfo = platon_ppos.GetRestrictingInfo(address2)
        RestrictingInfo = json.loads(RestrictingInfo['Data'])
        log.info("锁仓计划可用余额:{}".format(RestrictingInfo['balance']))

        #申请赎回委托
        msg = platon_ppos.getCandidateInfo(nodeId)
        stakingBlockNum = msg["Data"]["StakingBlockNum"]
        delegate_info = platon_ppos.unDelegate(stakingBlockNum,
                                               nodeId,
                                               amount,
                                               privatekey=private_key2,
                                               from_address=address2,
                                               gasPrice=self.base_gas_price,
                                               gas=self.staking_gas)
        assert delegate_info['Status'] == True, "申请赎回委托返回的状态:{},用例失败".format(
            result['Status'])

        lockup_end = platon_ppos.eth.getBalance(conf.FOUNDATIONLOCKUPADDRESS)
        log.info("赎回委托之后锁仓账户金额:{}".format(lockup_end))
        Staking_end = platon_ppos.eth.getBalance(conf.STAKINGADDRESS)
        log.info("赎回委托之后Staking账户金额:{}".format(Staking_end))
        RestrictingInfo = platon_ppos.GetRestrictingInfo(address2)
        Info = json.loads(RestrictingInfo['Data'])
        log.info("锁仓计划余额:{}".format(Info['balance']))

        assert lockup_end == lockup_before, "质押金退回后锁仓金额:{}有误".format(
            lockup_end)
        assert Staking_end == Staking_before, "质押金退回后Staking金额:{}有误".format(
            Staking_end)
        assert Info['balance'] == loukupbalace, "锁仓计划金额:{}有误".format(
            RestrictingInfo['balance'])

    # def test_loukupplan_amount(self):
    #     '''
    #     账户余额为0的时候调用锁仓接口
    #     :return:
    #     '''
    #     platon_ppos = Ppos ('http://10.10.8.157:6789', self.address, chainid=102,
    #                         privatekey=conf.PRIVATE_KEY)
    #     # platon_ppos = self.ppos_link ()
    #     address1 = '0x51a9A03153a5c3c203F6D16233e3B7244844A457'
    #     privatekey1 = '25f9fdf3249bb47f239df0c59d23781c271e8b7e9a94e9e694c15717c1941502'
    #     try:
    #         loukupbalace = Web3.toWei (100, 'ether')
    #         plan = [{'Epoch': 1, 'Amount': loukupbalace}]
    #         result = platon_ppos.CreateRestrictingPlan (address1, plan, privatekey1,
    #                                                     from_address=address1, gasPrice=self.gasPrice, gas=self.gas)
    #         assert result['Status'] == 'false'
    #     except:
    #         Status = 1
    #         assert Status == 0, '创建锁仓计划失败'

    def query_amount(self):
        url = CommonMethod.link_list(self)
        platon_ppos = Ppos(url, self.address, self.chainid)
        # lockup_after = platon_ppos.eth.getBalance (conf.FOUNDATIONLOCKUPADDRESS)
        # log.info ("退回质押金之后锁仓账户金额:{}".format (lockup_after))
        # Staking_after = platon_ppos.eth.getBalance (conf.STAKINGADDRESS)
        # log.info ("退回质押金之后Staking账户金额:{}".format (Staking_after))
        while 1:
            current_block = platon_ppos.eth.blockNumber
            log.info("当前块高:{}".format(current_block))
            time.sleep(10)
コード例 #16
0
class TestDposinit:
    address = Web3.toChecksumAddress(conf.ADDRESS)
    pwd = conf.PASSWORD
    abi = conf.DPOS_CONTRACT_ABI
    cbft_json_path = conf.CBFT2
    node_yml_path = conf.TWENTY_FIVENODE_YML
    file = conf.CASE_DICT
    privatekey = conf.PRIVATE_KEY
    gasPrice = Web3.toWei(0.000000000000000001, 'ether')
    gas = 21000
    value = 1000
    initial_amount = {
        'FOUNDATION': 905000000000000000000000000,
        'FOUNDATIONLOCKUP': 20000000000000000000000000,
        'STAKING': 25000000000000000000000000,
        'INCENTIVEPOOL': 45000000000000000000000000,
        'DEVELOPERS': 5000000000000000000000000
    }

    def ppos_link(self,
                  url=None,
                  address=conf.ADDRESS,
                  privatekey=conf.PRIVATE_KEY):
        if url is None:
            node_info = get_node_info(conf.TWENTY_FIVENODE_YML)
            self.rpc_list, enode_list, nodeid_list, ip_list, port_list = node_info.get(
                'collusion')
            rpc_list_length = len(self.rpc_list) - 1
            index = random.randint(0, rpc_list_length)
            url = self.rpc_list[index]

        self.platon_ppos = Ppos(url,
                                address=address,
                                chainid=101,
                                privatekey=privatekey)
        return self.platon_ppos

    def create_new_address(self, platon_ppos):
        self.new_address = platon_ppos.Web3.toChecksumAddress(
            self.ppos_link().web3.personal.newAccount(self.pwd))
        return self.new_address

    # def update_config(self, file, key, data):
    #     with open(self.file, 'r', encoding='utf-8') as f:
    #         res = json.loads(f.read())

    def ppos_sendTransaction(self, to_address, from_address, gas, gasPrice,
                             value):
        platon_ppos = self.ppos_link()
        self.send_data = {
            "to": to_address,
            "from": from_address,
            "gas": gas,
            "gasPrice": gasPrice,
            "value": value,
        }
        a = platon_ppos.eth.estimateGas(self.send_data)
        tx_hash = platon_ppos.eth.sendTransaction(self.send_data)
        self.platon_ppos.eth.waitForTransactionReceipt(tx_hash)

    def setup_class(self):
        self.auto = AutoDeployPlaton(cbft=self.cbft_json_path)
        self.auto.start_all_node(self.node_yml_path)

    def test_init_token(self):
        '''
        验证链初始化后token各内置账户初始值
        :return:
        '''

        platon_ppos = self.ppos_link()
        FOUNDATION = platon_ppos.eth.getBalance(
            Web3.toChecksumAddress(conf.FOUNDATIONADDRESS))
        assert self.initial_amount['FOUNDATION'] == FOUNDATION
        FOUNDATIONLOCKUP = self.platon_ppos.eth.getBalance(
            Web3.toChecksumAddress(conf.FOUNDATIONLOCKUPADDRESS))
        assert self.initial_amount['FOUNDATIONLOCKUP'] == FOUNDATIONLOCKUP
        STAKING = self.platon_ppos.eth.getBalance(
            Web3.toChecksumAddress(conf.STAKINGADDRESS))
        assert self.initial_amount['STAKING'] == STAKING
        INCENTIVEPOOL = self.platon_ppos.eth.getBalance(
            Web3.toChecksumAddress(conf.INCENTIVEPOOLADDRESS))
        assert self.initial_amount['INCENTIVEPOOL'] == INCENTIVEPOOL
        DEVELOPERS = self.platon_ppos.eth.getBalance(
            Web3.toChecksumAddress(conf.DEVELOPERSADDRESS))
        assert self.initial_amount['DEVELOPERS'] == DEVELOPERS
        token_init_total = conf.TOKENTOTAL
        assert token_init_total == (FOUNDATION + FOUNDATIONLOCKUP + STAKING +
                                    INCENTIVEPOOL + DEVELOPERS)

    def test_transfer_normal(self):
        '''
        验证初始化之后账户之间转账
        :return:
        '''
        platon_ppos = self.ppos_link()
        address1 = '0x684b43Cf53C78aA567840174a55442d7a9282679'
        privatekey1 = 'a5ac52e828e2656309933339cf12d30755f918e368fffc7c265b55da718ff893'
        try:
            platon_ppos.send_raw_transaction(
                '', Web3.toChecksumAddress(conf.ADDRESS),
                Web3.toChecksumAddress(address1), self.gasPrice, self.gas,
                self.value, conf.PRIVATE_KEY)
            Balance1 = platon_ppos.eth.getBalance('address1')
            assert Web3.toWei(self.value, 'ether') == Balance1
        except:
            status = 1
            assert status == 0, '账号余额不足,无法发起转账'

    def test_transfer_notsufficientfunds(self):
        '''
        账户余额不足的情况下进行转账
        :return:
        '''
        platon_ppos = self.ppos_link()
        #账户1
        address1 = '0x684b43Cf53C78aA567840174a55442d7a9282679'
        privatekey1 = 'a5ac52e828e2656309933339cf12d30755f918e368fffc7c265b55da718ff893'
        #账户2
        address2 = '0xc128fDBb500096974Db713b563dBeF597461C5dD'
        privatekey2 = 'c03975513e3de5b1c63fb4b31470111119d5ef1e580d14ebd23aee48f580ac13'
        balance = platon_ppos.eth.getBalance(address1)
        if balance == 0:
            try:
                platon_ppos.send_raw_transaction(
                    '', Web3.toChecksumAddress(address1),
                    Web3.toChecksumAddress(address2), self.gasPrice, self.gas,
                    self.value, privatekey1)
            except:
                status = 1
                assert status == 0, '账号余额不足,无法发起转账'
        else:
            log.info('账号:{}已转账,请切换账号再试'.format(address1))

    def test_transfer_funds(self):
        '''
        验证初始化之后普通账户转账内置账户
        :return:
        '''
        platon_ppos = self.ppos_link()
        lockup_balancebe_before = platon_ppos.eth.getBalance(
            conf.INCENTIVEPOOLADDRESS)
        # 签名转账
        try:
            platon_ppos.send_raw_transaction(
                '', Web3.toChecksumAddress(conf.ADDRESS),
                Web3.toChecksumAddress(conf.INCENTIVEPOOLADDRESS),
                self.gasPrice, self.gas, self.value, conf.PRIVATE_KEY)
            lockup_balancebe_after = platon_ppos.eth.getBalance(
                conf.INCENTIVEPOOLADDRESS)
            assert lockup_balancebe_before + Web3.toWei(
                self.value, 'ether') == lockup_balancebe_after
        except:
            status = 1
            assert status == 0, '无法发起转账'

    @allure.title("查看初始化时锁仓余额和锁仓信息")
    def test_token_loukup(self):
        '''
        查询初始化链后基金会锁仓金额
        以及查询初始锁仓计划信息的有效性
        :return:
        '''
        #platon_ppos = self.ppos_link ()
        platon_ppos = Ppos('http://10.10.8.157:6789',
                           self.address,
                           chainid=102,
                           privatekey=conf.PRIVATE_KEY)
        lockupbalance = platon_ppos.eth.getBalance(
            conf.FOUNDATIONLOCKUPADDRESS)
        FOUNDATIONLOCKUP = self.initial_amount['FOUNDATIONLOCKUP']
        assert lockupbalance == FOUNDATIONLOCKUP
        result = platon_ppos.GetRestrictingInfo(conf.INCENTIVEPOOLADDRESS)
        print(result)
        if result['Status'] == 'True':
            assert result['Date']['balance'] == self.initial_amount[
                'FOUNDATIONLOCKUP']
        else:
            log.info("初始锁仓金额:{},锁仓计划信息查询结果有误".format(lockupbalance))

    def test_loukupplan(self):
        '''
        验证正常锁仓功能
        参数输入:
        Epoch:1
        Amount:50 ether
        :return:
        '''
        platon_ppos = Ppos('http://10.10.8.157:6789',
                           self.address,
                           chainid=102,
                           privatekey=conf.PRIVATE_KEY)
        #platon_ppos = self.ppos_link ()
        address1 = '0x472599739f398c24ad8Cdc03476b20D6469eAf46'
        privatekey1 = '61279a4b654aef7c3065c0cf550cdce460682875c218de893544a4799b57cc41'
        #非签名转账
        # platon_ppos.web3.personal.unlockAccount(conf.ADDRESS, conf.PASSWORD, 2222)
        # self.ppos_sendTransaction(address1,conf.ADDRESS,self.gas,self.gasPrice,Web3.toWei(10000,'ether'))
        #签名转账
        platon_ppos.send_raw_transaction('',
                                         Web3.toChecksumAddress(conf.ADDRESS),
                                         Web3.toChecksumAddress(address1),
                                         self.gasPrice, self.gas, self.value,
                                         conf.PRIVATE_KEY)
        balance = platon_ppos.eth.getBalance(address1)
        log.info("发起锁仓账户的余额:{}", balance)
        if balance > 0:
            try:
                loukupbalace = Web3.toWei(50, 'ether')
                plan = [{'Epoch': 1, 'Amount': loukupbalace}]
                lockup_before = platon_ppos.eth.getBalance(
                    conf.FOUNDATIONLOCKUPADDRESS)
                #创建锁仓计划
                result = platon_ppos.CreateRestrictingPlan(
                    address1,
                    plan,
                    privatekey1,
                    from_address=address1,
                    gasPrice=self.gasPrice)
                lockup_after = platon_ppos.eth.getBalance(
                    conf.FOUNDATIONLOCKUPADDRESS)
                #查看锁仓计划明细
                RestrictingInfo = platon_ppos.GetRestrictingInfo(address1)
                if result['status'] == 'True':
                    assert RestrictingInfo['balance'] == loukupbalace
                else:
                    log.info("查询锁仓计划信息返回状态为:{}".format(result['status']))

                assert lockup_after == lockup_before + loukupbalace
            except:
                status = 1
                assert status == 0, '创建锁仓计划失败'

    @allure.title("根据不同参数创建锁仓计划")
    @pytest.mark.parametrize('number,amount', [(1, 0.1), (-1, 3), (0.1, 3),
                                               (37, 3)])
    def test_loukupplan_abnormal(self, number, amount):
        '''
        创建锁仓计划时,参数有效性验证
        number : 锁仓解锁期
        amount : 锁仓金额
        :param number:
        :param amount:
        :return:
        '''
        address1 = '0x9148528b98a0065D185F01dbc59baB88CdbE7Ad2'
        private_key1 = '6ccbf153f7409af1e5df7a1ef77daaca4759f0a6b50ef73fe9ccd5738cc2fda1'
        platon_ppos = Ppos('http://10.10.8.157:6789',
                           self.address,
                           chainid=102,
                           privatekey=conf.PRIVATE_KEY)
        # platon_ppos = self.ppos_link ()
        try:
            loukupbalace = Web3.toWei(amount, 'ether')
            plan = [{'Epoch': number, 'Amount': loukupbalace}]
            #当锁仓金额输入小于 1ether
            if number >= 1 and amount < 1:
                result = platon_ppos.CreateRestrictingPlan(
                    address1,
                    plan,
                    conf.PRIVATE_KEY,
                    from_address=conf.ADDRESS,
                    gasPrice=self.gasPrice,
                    gas=self.gas)
                assert result['status'] == 'false'
            #当锁仓解锁期输入非正整数倍
            elif number < 0 or type(number) == float:
                result = platon_ppos.CreateRestrictingPlan(
                    address1,
                    plan,
                    conf.PRIVATE_KEY,
                    from_address=conf.ADDRESS,
                    gasPrice=self.gasPrice,
                    gas=self.gas)
                assert result['status'] == 'false'
            #当锁仓解锁期大于36个结算期
            elif number > 36:
                result = platon_ppos.CreateRestrictingPlan(
                    address1,
                    plan,
                    conf.PRIVATE_KEY,
                    from_address=conf.ADDRESS,
                    gasPrice=self.gasPrice,
                    gas=self.gas)
                assert result['status'] == 'false'

        except:
            status = 1
            assert status == 0, '创建锁仓计划失败'

    @allure.title("锁仓金额大于账户余额")
    def test_loukupplan_amount(self):
        platon_ppos = Ppos('http://10.10.8.157:6789',
                           self.address,
                           chainid=102,
                           privatekey=conf.PRIVATE_KEY)
        # platon_ppos = self.ppos_link ()
        address1 = '0x51a9A03153a5c3c203F6D16233e3B7244844A457'
        privatekey1 = '25f9fdf3249bb47f239df0c59d23781c271e8b7e9a94e9e694c15717c1941502'
        # 签名转账
        platon_ppos.send_raw_transaction('',
                                         Web3.toChecksumAddress(conf.ADDRESS),
                                         Web3.toChecksumAddress(address1),
                                         self.gasPrice, self.gas, self.value,
                                         conf.PRIVATE_KEY)
        balance = platon_ppos.eth.getBalance(address1)
        if balance > 0:
            try:
                loukupbalace = Web3.toWei(10000, 'ether')
                plan = [{'Epoch': 1, 'Amount': loukupbalace}]
                result = platon_ppos.CreateRestrictingPlan(
                    address1,
                    plan,
                    privatekey1,
                    from_address=address1,
                    gasPrice=self.gasPrice,
                    gas=self.gas)
                assert result['status'] == 'false'
            except:
                status = 1
                assert status == 0, '创建锁仓计划失败'
        else:
            log.info('error:转账失败')

    @allure.title("多个锁仓期金额情况验证")
    @pytest.mark.parametrize('balace1,balace2', [(300, 300), (500, 600)])
    def test_loukupplan_Moredeadline(self, balace1, balace2):
        '''
        验证一个锁仓计划里有多个解锁期
        amount : 锁仓
        balace1 : 第一个锁仓期的锁仓金额
        balace2 : 第二个锁仓期的锁仓金额
        :return:
        '''
        platon_ppos = Ppos('http://10.10.8.157:6789',
                           self.address,
                           chainid=102,
                           privatekey=conf.PRIVATE_KEY)
        # platon_ppos = self.ppos_link ()
        address1 = '0x51a9A03153a5c3c203F6D16233e3B7244844A457'
        privatekey1 = '25f9fdf3249bb47f239df0c59d23781c271e8b7e9a94e9e694c15717c1941502'
        # 签名转账
        platon_ppos.send_raw_transaction('',
                                         Web3.toChecksumAddress(conf.ADDRESS),
                                         Web3.toChecksumAddress(address1),
                                         self.gasPrice, self.gas, self.value,
                                         conf.PRIVATE_KEY)
        balance = platon_ppos.eth.getBalance(address1)
        if balance > 0:
            try:
                loukupbalace1 = Web3.toWei(balace1, 'ether')
                loukupbalace2 = Web3.toWei(balace2, 'ether')
                if (loukupbalace1 + loukupbalace2) < self.value:
                    plan = [{
                        'Epoch': 1,
                        'Amount': loukupbalace1
                    }, {
                        'Epoch': 2,
                        'Amount': loukupbalace2
                    }]
                    result = platon_ppos.CreateRestrictingPlan(
                        address1,
                        plan,
                        privatekey1,
                        from_address=address1,
                        gasPrice=self.gasPrice,
                        gas=self.gas)
                    assert result['status'] == 'True'
                elif self.value <= (loukupbalace1 + loukupbalace2):
                    plan = [{
                        'Epoch': 1,
                        'Amount': loukupbalace1
                    }, {
                        'Epoch': 2,
                        'Amount': loukupbalace2
                    }]
                    result = platon_ppos.CreateRestrictingPlan(
                        address1,
                        plan,
                        privatekey1,
                        from_address=address1,
                        gasPrice=self.gasPrice,
                        gas=self.gas)
                    assert result['status'] == 'false'
                else:
                    log.info('锁仓输入的金额:{}出现异常'.format(
                        (loukupbalace1 + loukupbalace2)))

            except:
                status = 1
                assert status == 0, '创建锁仓计划失败'
        else:
            log.info('error:转账失败')

    @allure.title("锁仓计划多个相同解锁期情况验证")
    @pytest.mark.parametrize('code,', [(1), (2)])
    def test_loukupplan_sameperiod(self, code):
        '''
        验证一个锁仓计划里有多个相同解锁期
        code =1 :同个account在一个锁仓计划里有相同解锁期
        code =2 :同个account在不同锁仓计划里有相同解锁期
        :return:
        '''
        platon_ppos = Ppos('http://10.10.8.157:6789',
                           self.address,
                           chainid=102,
                           privatekey=conf.PRIVATE_KEY)
        # platon_ppos = self.ppos_link ()
        address1 = '0x51a9A03153a5c3c203F6D16233e3B7244844A457'
        privatekey1 = '25f9fdf3249bb47f239df0c59d23781c271e8b7e9a94e9e694c15717c1941502'
        # 签名转账
        platon_ppos.send_raw_transaction('',
                                         Web3.toChecksumAddress(conf.ADDRESS),
                                         Web3.toChecksumAddress(address1),
                                         self.gasPrice, self.gas, 1000,
                                         conf.PRIVATE_KEY)
        balance = platon_ppos.eth.getBalance(address1)
        if balance > 0:
            try:
                period1 = 1
                period2 = 2
                loukupbalace = Web3.toWei(100, 'ether')
                if code == 1:
                    plan = [{
                        'Epoch': period1,
                        'Amount': loukupbalace
                    }, {
                        'Epoch': period1,
                        'Amount': loukupbalace
                    }]
                    result = platon_ppos.CreateRestrictingPlan(
                        address1,
                        plan,
                        privatekey1,
                        from_address=address1,
                        gasPrice=self.gasPrice,
                        gas=self.gas)
                    assert result['status'] == 'True'
                    RestrictingInfo = platon_ppos.GetRestrictingInfo(address1)
                    json_data = json.loads(RestrictingInfo['Data'])
                    assert json_data['Entry'][0]['amount'] == (loukupbalace +
                                                               loukupbalace)

                elif code == 2:
                    plan = [{
                        'Epoch': period1,
                        'Amount': loukupbalace
                    }, {
                        'Epoch': period2,
                        'Amount': loukupbalace
                    }]
                    result = platon_ppos.CreateRestrictingPlan(
                        address1,
                        plan,
                        privatekey1,
                        from_address=address1,
                        gasPrice=self.gasPrice,
                        gas=self.gas)
                    assert result['status'] == 'True'
                    loukupbalace2 = Web3.toWei(200, 'ether')
                    plan = [{
                        'Epoch': period1,
                        'Amount': loukupbalace2
                    }, {
                        'Epoch': period2,
                        'Amount': loukupbalace2
                    }]
                    result1 = platon_ppos.CreateRestrictingPlan(
                        address1,
                        plan,
                        privatekey1,
                        from_address=address1,
                        gasPrice=self.gasPrice,
                        gas=self.gas)
                    assert result1['status'] == 'True'
                    RestrictingInfo = platon_ppos.GetRestrictingInfo(address1)
                    json_data = json.loads(RestrictingInfo['Data'])
                    assert json_data['Entry'][0]['amount'] == (loukupbalace +
                                                               loukupbalace2)
                else:
                    log.info('输入的code:{}有误'.format(code))
            except:
                status = 1
                assert status == 0, '创建锁仓计划失败'
        else:
            log.info('error:转账失败')

    # def test_loukupplan_amount(self):
    #     '''
    #     账户余额为0的时候调用锁仓接口
    #     :return:
    #     '''
    #     platon_ppos = Ppos ('http://10.10.8.157:6789', self.address, chainid=102,
    #                         privatekey=conf.PRIVATE_KEY)
    #     # platon_ppos = self.ppos_link ()
    #     address1 = '0x51a9A03153a5c3c203F6D16233e3B7244844A457'
    #     privatekey1 = '25f9fdf3249bb47f239df0c59d23781c271e8b7e9a94e9e694c15717c1941502'
    #     try:
    #         loukupbalace = Web3.toWei (100, 'ether')
    #         plan = [{'Epoch': 1, 'Amount': loukupbalace}]
    #         result = platon_ppos.CreateRestrictingPlan (address1, plan, privatekey1,
    #                                                     from_address=address1, gasPrice=self.gasPrice, gas=self.gas)
    #         assert result['status'] == 'false'
    #     except:
    #         status = 1
    #         assert status == 0, '创建锁仓计划失败'

    def test_Incentive_pool(self):
        platon_ppos = Ppos('http://10.10.8.157:6789',
                           self.address,
                           chainid=102,
                           privatekey=conf.PRIVATE_KEY)
        #platon_ppos = self.ppos_link ()
        lockupbalance = platon_ppos.eth.getBalance(conf.INCENTIVEPOOLADDRESS)
        log.info('激励池查询余额:{}'.format(lockupbalance))
        INCENTIVEPOOL = self.initial_amount['INCENTIVEPOOL']
        assert lockupbalance == INCENTIVEPOOL

    def test_fee_income(self):
        platon_ppos = Ppos('http://10.10.8.157:6789',
                           self.address,
                           chainid=102,
                           privatekey=conf.PRIVATE_KEY)
        #platon_ppos = self.ppos_link ()
        incentive_pool_balance_befor = platon_ppos.eth.getBalance(
            conf.INCENTIVEPOOLADDRESS)
        log.info('交易前激励池查询余额:{}'.format(incentive_pool_balance_befor))
        # 签名转账
        address1 = '0x51a9A03153a5c3c203F6D16233e3B7244844A457'
        privatekey1 = '25f9fdf3249bb47f239df0c59d23781c271e8b7e9a94e9e694c15717c1941502'
        try:
            platon_ppos.send_raw_transaction(
                '', Web3.toChecksumAddress(conf.ADDRESS),
                Web3.toChecksumAddress(address1), self.gasPrice, self.gas,
                self.value, conf.PRIVATE_KEY)
            balance = platon_ppos.eth.getBalance(address1)
            if balance == Web3.toWei(self.value, 'ether'):
                incentive_pool_balance_after = platon_ppos.eth.getBalance(
                    conf.INCENTIVEPOOLADDRESS)
                log.info('交易前激励池查询余额:{}'.format(incentive_pool_balance_after))
                difference = incentive_pool_balance_after - incentive_pool_balance_befor
                log.info('手续费的金额:{}'.format(difference))
                assert difference == self.gas
            else:
                log.info("转账{}金额错误".format(Web3.toWei(self.value, 'ether')))
        except:
            status = 1
            assert status == 0, '转账失败'

    def test_punishment_income(self):
        '''
        验证低出块率验证节点的处罚金自动转账到激励池
        :return:
        '''
        #随机获取其中一个正在出块的节点信息
        node_info = get_node_list(conf.TWENTY_FIVENODE_YML)
        node_info_length = len(node_info) - 1
        index = random.randint(0, node_info_length)
        node_data = node_info[0][index]
        print(node_data)
        platon_ppos = Ppos('http://10.10.8.157:6789',
                           self.address,
                           chainid=102,
                           privatekey=conf.PRIVATE_KEY)
        # platon_ppos = self.ppos_link ()
        incentive_pool_balance_befor = platon_ppos.eth.getBalance(
            conf.INCENTIVEPOOLADDRESS)
        log.info('处罚之前激励池查询余额:{}'.format(incentive_pool_balance_befor))
        #停止其中一个正在出块的节点信息
        try:
            self.auto = AutoDeployPlaton(cbft=self.cbft_json_path)
            self.auto.kill(node_data)
            platon_ppos = self.ppos_link(node_data['url'])
            if not platon_ppos.web3.isConnected():
                platon_ppos = self.ppos_link()
                current_block = platon_ppos.eth.blockNumber()
                waiting_time = 250 - (current_block % 250)
                time.sleep(waiting_time + 1)
                incentive_pool_balance_after = platon_ppos.eth.getBalance(
                    conf.INCENTIVEPOOLADDRESS)
                log.info('处罚之后激励池查询余额:{}'.format(incentive_pool_balance_after))
                punishment_CandidateInfo = platon_ppos.getCandidateInfo(
                    node_data['id'])
                if punishment_CandidateInfo['Status'] == 'True':
                    punishment_amount = punishment_CandidateInfo['Data'][
                        'Shares'] * (20 / 100)
                    assert incentive_pool_balance_after == incentive_pool_balance_befor + punishment_amount
                else:
                    log.info("查询处罚节点:{}质押信息失败".format(node_data['host']))
            else:
                log.info("当前质押节点:{}链接正常".format(node_data['host']))
        except:
            status = 1
            assert status == 0, '停止节点:{}失败'.format(node_data['host'])