Esempio n. 1
0
    def _set_samples(self, domain: str) -> (list, list, list, list):
        buf_blocks = list()
        buf_transactions_on_blocks = list(
        )  # block's transaction list which means confirmed transaction list
        buf_transactions = list()  # return value of 'get_transaction'
        buf_transaction_results = list(
        )  # return value of 'get_transaction_result'

        icon_service = IconService(HTTPProvider(domain, VERSION_FOR_TEST))
        target_block_heights = self._set_target_heights()
        for height in target_block_heights:
            block = icon_service.get_block(height, full_response=True)
            block = block['result']
            buf_blocks.append(block)
            for transaction in block[
                    'confirmed_transaction_list' if block['version'] ==
                    BLOCK_0_1A_VERSION else 'transactions']:
                buf_transactions_on_blocks.append(transaction)

                if ('tx_hash' or 'txHash') in transaction:
                    tx_hash = transaction['tx_hash' if 'tx_hash' in
                                          transaction else 'txHash']
                    tx_hash = add_0x_prefix(tx_hash)
                    tx = icon_service.get_transaction(tx_hash,
                                                      full_response=True)
                    tx = tx['result']
                    buf_transactions.append(tx)
                    tx_result = icon_service.get_transaction_result(
                        tx_hash, full_response=True)
                    tx_result = tx_result['result']
                    buf_transaction_results.append(tx_result)

        return buf_blocks, buf_transactions_on_blocks, buf_transactions, buf_transaction_results
Esempio n. 2
0
    def get_txresults(self, network: IconService, tx_hashes: list) -> list:
        tx_results: list = []

        for h in tx_hashes:
            tx_result = network.get_transaction_result(h)
            tx_results.append(tx_result)
        return tx_results
Esempio n. 3
0
    def test_integrate_converter(self):
        """
        Test integrating for the converter which checks that all of the data
        about the block, transaction, and transaction result have the right format.

        [Purpose]
        Check all of the data about the block, transaction, and transaction result.

        [Scenario]
        1. Get the last block data and validate the block data.
        2. Get all of the transaction data on that block and validate the transaction data.
        3. Get all of the transaction result data on that transaction and validate the transaction result data.
        4. Repeatedly, get the other blocks from the last to the first and validate all of three kinds of the data.
        """
        logger = getLogger("TEST CONVERTER")

        # No need to use logging, remove the line.
        set_logger(logger, 'DEBUG')

        logger.debug("TEST CONVERTER START")

        icon_service = IconService(HTTPProvider(TEST_HTTP_ENDPOINT_URI_V3))

        # Scenario 1: Get the last block data and validate the block data.
        last_block_height = icon_service.get_block("latest")["height"]

        for height in range(
                0, last_block_height if last_block_height < 30 else 30):
            # Scenario 2: Get all of the transaction data on that block and validate the transaction data.
            block = icon_service.get_block(height)
            # pprint.pprint(block)
            self.assertTrue(validate_block(block))

            # Except for the genesis block
            if height > 0:
                for transaction_in_block in block[
                        "confirmed_transaction_list"]:
                    # Scenario 3: Get all of the transaction result data on that transaction
                    # and validate the transaction result data.
                    transaction_result = icon_service.get_transaction_result(
                        transaction_in_block["txHash"])
                    # logger.debug(transaction_result)
                    # pprint.pprint(transaction_result)
                    self.assertTrue(
                        validate_transaction_result(transaction_result))
                    # Scenario 4: Repeatedly, get the other blocks from the last to the first
                    # and validate all of three kinds of the data.
                    transaction = icon_service.get_transaction(
                        transaction_in_block["txHash"])
                    # logger.debug(transaction)
                    # pprint.pprint(transaction)
                    self.assertTrue(validate_transaction(transaction))
Esempio n. 4
0
    def process_transaction(self, request: SignedTransaction,
                            network: IconService = None,
                            block_confirm_interval: int = tbears_server_config[TbConf.BLOCK_CONFIRM_INTERVAL]) -> dict:
        try:
            if network is not None:
                # Send the transaction to network
                tx_hash = network.send_transaction(request)
                sleep(block_confirm_interval)
                # Get transaction result
                tx_result = network.get_transaction_result(tx_hash)
            else:
                # process the transaction in local
                tx_result = self._process_transaction_in_local(request.signed_transaction_dict)
        except IconServiceBaseException as e:
            tx_result = e.message

        return tx_result
    def txresult(self, conf):
        """Query transaction result using given transaction hash.

        :param conf: txresult command configuration.
        :return: result of query.
        """
        uri, version = uri_parser(conf['uri'])
        icon_service = IconService(HTTPProvider(uri, version))

        response = icon_service.get_transaction_result(conf['hash'], True)

        if "error" in response:
            print('Got an error response')
            print(f"Can not get transaction \n{json.dumps(response, indent=4)}")
        else:
            print(f"Transaction : {json.dumps(response, indent=4)}")

        return response
Esempio n. 6
0
    def process_message_tx(self,
                           network: IconService = None,
                           msg: str = "dummy",
                           block_confirm_interval: int = -1) -> dict:
        if self._network_only and network is None:
            raise URLException("Set network URL")

        if block_confirm_interval == -1:
            block_confirm_interval = self._block_confirm_interval

        msg_byte = msg.encode('utf-8')

        # build message tx
        transaction = MessageTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._test1.get_address()) \
            .step_limit(10000000000) \
            .nid(3) \
            .nonce(100) \
            .data(f"0x{msg_byte.hex()}") \
            .build()

        # signing message tx
        request = SignedTransaction(transaction, self._test1)

        try:
            if network is not None:
                # Send the transaction to network
                tx_hash = network.send_transaction(request)
                sleep(block_confirm_interval)
                # Get transaction result
                tx_result = network.get_transaction_result(tx_hash)
            else:
                # process the transaction in local
                tx_results = self._process_transaction_in_local(
                    request.signed_transaction_dict)
        except IconServiceBaseException as e:
            tx_result = e.message

        return tx_result
    def test_integrate_converter(self):
        """
        Test integrating for the converter which checks that all of the data
        about the block, transaction, and transaction result have the right format.

        [Purpose]
        Check all of the data about the block, transaction, and transaction result.

        [Scenario]
        1. Get the last block data and validate the block data.
        2. Get all of the transaction data on that block and validate the transaction data.
        3. Get all of the transaction result data on that transaction and validate the transaction result data.
        4. Repeatedly, get the other blocks from the last to the first and validate all of three kinds of the data.
        """
        icon_service = IconService(HTTPProvider(BASE_DOMAIN_URL_V3_FOR_TEST, VERSION_FOR_TEST))

        # Scenario 1: Get the last block data and validate the block data.
        last_block_height = icon_service.get_block("latest")["height"]

        for height in range(0, last_block_height if last_block_height < 30 else 30):
            # Scenario 2: Get all of the transaction data on that block and validate the transaction data.
            block = icon_service.get_block(height)
            # pprint.pprint(block)
            self.assertTrue(validate_block(block))

            # Except for the genesis block
            if height > 0:
                for transaction_in_block in block["confirmed_transaction_list"]:
                    # Scenario 3: Get all of the transaction result data on that transaction
                    # and validate the transaction result data.
                    transaction_result = icon_service.get_transaction_result(transaction_in_block["txHash"])
                    # logger.debug(transaction_result)
                    # pprint.pprint(transaction_result)
                    self.assertTrue(validate_transaction_result(transaction_result))
                    # Scenario 4: Repeatedly, get the other blocks from the last to the first
                    # and validate all of three kinds of the data.
                    transaction = icon_service.get_transaction(transaction_in_block["txHash"])
                    # logger.debug(transaction)
                    # pprint.pprint(transaction)
                    self.assertTrue(validate_transaction(transaction))
Esempio n. 8
0
    def process_transaction(self,
                            request: SignedTransaction,
                            network: IconService = None,
                            block_confirm_interval: int = -1) -> dict:
        if self._network_only and network is None:
            raise URLException("Set network URL")

        if block_confirm_interval == -1:
            block_confirm_interval = self._block_confirm_interval

        if network is not None:
            # Send the transaction to network
            tx_hash: str = network.send_transaction(request)
            sleep(block_confirm_interval + 0.1)
            # Get transaction result
            tx_result: dict = network.get_transaction_result(tx_hash)
        else:
            # process the transaction in local
            tx_hash: str = self._process_transaction_in_local(
                request.signed_transaction_dict)
            tx_result: dict = self._get_tx_result(tx_hash)
        return tx_result
Esempio n. 9
0
    def process_transaction_bulk(self,
                                 requests: list,
                                 network: IconService = None,
                                 block_confirm_interval: int = -1) -> list:
        if self._network_only and network is None:
            raise URLException("Set network URL")

        if block_confirm_interval == -1:
            block_confirm_interval = self._block_confirm_interval

        tx_results: list = []

        try:
            if network is not None:
                tx_hashes: list = []
                for req in requests:
                    # Send the transaction to network
                    tx_hash = network.send_transaction(req)
                    tx_hashes.append(tx_hash)

                sleep(block_confirm_interval)

                # Get transaction result
                for h in tx_hashes:
                    tx_result = network.get_transaction_result(h)
                    tx_results.append(tx_result)
            else:
                for req in requests:
                    # process the transaction in local
                    tx_result = self._process_transaction_in_local(
                        req.signed_transaction_dict)
                    tx_results.append(tx_result)
        except IconServiceBaseException as e:
            tx_result = e.message
            tx_results.append(tx_result)

        return tx_results
Esempio n. 10
0
class TestGetterMethods(unittest.TestCase):

    def setUp(self):
        self.wallet = KeyWallet.load(keystore_path, keystore_pw)
        self.tester_addr = self.wallet.get_address()
        self.icon_service = IconService(HTTPProvider(node_uri))
 
    def tearDown(self):
        pass 


    def test_name(self):
        call = CallBuilder().from_(self.tester_addr)\
                    .to(hello_world_address)\
                    .method("name")\
                    .build()
        result = self.icon_service.call(call)
        self.assertEqual(result, 'HelloWorld')


    def test_hello(self):
        call = CallBuilder().from_(self.tester_addr)\
                    .to(hello_world_address)\
                    .method("hello")\
                    .build()
        result = self.icon_service.call(call)
        self.assertEqual(result, 'Hello')


    def test_send_token_to_ca(self):
        call = CallBuilder().from_(self.tester_addr)\
                    .to(token_address)\
                    .method("balanceOf")\
                    .params({"_owner": hello_world_address})\
                    .build()
        balance_before = self.icon_service.call(call)
        token_value = "0x1"
        
        transaction = CallTransactionBuilder()\
            .from_(self.tester_addr)\
            .to(token_address)\
            .step_limit(2000000)\
            .nid(network_id)\
            .method("transfer")\
            .params({"_to":hello_world_address, "_value":token_value})\
            .build()

        signed_transaction = SignedTransaction(transaction, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)

        result = self.icon_service.get_transaction_result(tx_hash)
        self.assertEqual(result['status'], 1)
        self.assertFalse(result['eventLogs'] is None)

        balance_after = self.icon_service.call(call)
        self.assertEqual(int(balance_before,0)+int(token_value,0), int(balance_after,0))


    def test_send_icx_to_ca(self):
        balance_before = self.icon_service.get_balance(hello_world_address)
        icx_value = 1

        transaction = TransactionBuilder()\
            .from_(self.tester_addr)\
            .to(hello_world_address)\
            .value(icx_value)\
            .step_limit(2000000)\
            .nid(network_id)\
            .build()

        signed_transaction = SignedTransaction(transaction, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)

        result = self.icon_service.get_transaction_result(tx_hash)
        self.assertEqual(result['status'], 1)
        self.assertFalse(result['eventLogs'] is None)

        balance_after = self.icon_service.get_balance(hello_world_address)
        self.assertEqual(balance_before+icx_value, balance_after)
Esempio n. 11
0
class TestGetterMethods(unittest.TestCase):

    def setUp(self):
        self.wallet = KeyWallet.load(keystore_path, keystore_pw)
        self.tester_addr = self.wallet.get_address()
        self.icon_service = IconService(HTTPProvider(node_uri))
 
    def tearDown(self):
        pass 


    def test_name(self):
        call = CallBuilder().from_(self.tester_addr)\
                    .to(hello_world_address)\
                    .method("name")\
                    .build()
        result = self.icon_service.call(call)
        self.assertEqual(result, 'HelloWorld')


    def test_hello(self):
        call = CallBuilder().from_(self.tester_addr)\
                    .to(hello_world_address)\
                    .method("hello")\
                    .build()
        result = self.icon_service.call(call)
        self.assertEqual(result, 'Hello')


    def test_send_token_to_ca(self):
        call = CallBuilder().from_(self.tester_addr)\
                    .to(token_address)\
                    .method("balanceOf")\
                    .params({"_owner": hello_world_address})\
                    .build()
        balance_before = self.icon_service.call(call)
        token_value = "0x1"
        
        transaction = CallTransactionBuilder()\
            .from_(self.tester_addr)\
            .to(token_address)\
            .step_limit(2000000)\
            .nid(network_id)\
            .method("transfer")\
            .params({"_to":hello_world_address, "_value":token_value})\
            .build()

        signed_transaction = SignedTransaction(transaction, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)

        result = self.icon_service.get_transaction_result(tx_hash)
        self.assertEqual(result['status'], 1)
        self.assertFalse(result['eventLogs'] is None)

        balance_after = self.icon_service.call(call)
        self.assertEqual(int(balance_before,0)+int(token_value,0), int(balance_after,0))


    def test_send_icx_to_ca(self):
        balance_before = self.icon_service.get_balance(hello_world_address)
        icx_value = 1

        transaction = TransactionBuilder()\
            .from_(self.tester_addr)\
            .to(hello_world_address)\
            .value(icx_value)\
            .step_limit(2000000)\
            .nid(network_id)\
            .build()

        signed_transaction = SignedTransaction(transaction, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)

        result = self.icon_service.get_transaction_result(tx_hash)
        self.assertEqual(result['status'], 1)
        self.assertFalse(result['eventLogs'] is None)

        balance_after = self.icon_service.get_balance(hello_world_address)
        self.assertEqual(balance_before+icx_value, balance_after)
Esempio n. 12
0
class TestGetterMethods(unittest.TestCase):

    def setUp(self):
        self.wallet = KeyWallet.load(keystore_path, keystore_pw)
        self.tester_addr = self.wallet.get_address()
        self.icon_service = IconService(HTTPProvider(node_uri))

    def test_vote_list(self):
        call = CallBuilder().from_(self.tester_addr)\
                    .to(vote_dao_address)\
                    .method("vote_list")\
                    .build()
        self.icon_service.call(call)

    def test_add_user(self):
        send = CallTransactionBuilder().from_(self.tester_addr) \
            .version(3) \
            .step_limit(3000000000000000000000) \
            .timestamp(0x573117f1d6568) \
            .nid(0x3) \
            .to(vote_dao_address) \
            .method("add_user") \
            .params({"contents": "hx8d29ac2645805452a6e921c888b23c58be862cf0"}) \
            .build()
        signed_transaction = SignedTransaction(send, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)
        result = self.icon_service.get_transaction_result(tx_hash)
        assert result['status'] == 0 or 1

    def test_remove_user(self):
        send = CallTransactionBuilder().from_(self.tester_addr) \
            .version(3) \
            .step_limit(3000000000000000000000) \
            .timestamp(0x573117f1d6568) \
            .nid(0x3) \
            .to(vote_dao_address) \
            .method("remove_user") \
            .params({"contents": "hx8d29ac2645805452a6e921c888b23c58be862cf0"}) \
            .build()
        signed_transaction = SignedTransaction(send, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)
        result = self.icon_service.get_transaction_result(tx_hash)
        assert result['status'] == 0 or 1

    def test_ox(self):
        send = CallTransactionBuilder().from_(self.tester_addr) \
            .version(3) \
            .step_limit(3000000000000000000000) \
            .timestamp(0x573117f1d6568) \
            .nid(0x3) \
            .to(vote_dao_address) \
            .method("ox") \
            .params({"contents": "tests"}) \
            .build()
        signed_transaction = SignedTransaction(send, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)
        result = self.icon_service.get_transaction_result(tx_hash)
        assert result['status'] == 0 or 1

    def vote(self):
        send = CallTransactionBuilder().from_(self.tester_addr) \
            .version(3) \
            .step_limit(3000000000000000000000) \
            .timestamp(0x573117f1d6568) \
            .nid(0x3) \
            .to(vote_dao_address) \
            .method("vote") \
            .params({"code": "O0","vote_res": "2"}) \
            .build()
        signed_transaction = SignedTransaction(send, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)
        result = self.icon_service.get_transaction_result(tx_hash)
        assert result['status'] == 0 or 1

    def delete(self):
        send = CallTransactionBuilder().from_(self.tester_addr) \
            .version(3) \
            .step_limit(3000000000000000000000) \
            .timestamp(0x573117f1d6568) \
            .nid(0x3) \
            .to(vote_dao_address) \
            .method("delete") \
            .params({"code": "O0"}) \
            .build()
        signed_transaction = SignedTransaction(send, self.wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)

        sleep(10)
        result = self.icon_service.get_transaction_result(tx_hash)
        assert result['status'] == 0 or 1
Esempio n. 13
0
class ServiceManager:
    def __init__(self, node_conf_path: str, wallet_path: str, passwd: str):

        # Node configuration to be connected
        with open(node_conf_path, "r") as f:
            node_conf = json.load(f)

        self._my_chain_name = node_conf["chain_name"]
        self._nid = int(node_conf["nid"], 16)

        self.web_protocol = node_conf["web_protocol"]

        if self.web_protocol == "ssl":
            self._icon_service = IconService(
                HTTPProvider("https://" + node_conf["address"], 3))
            self._ws_block = f"wss://{node_conf['address']}/api/ws/{node_conf['channel']}"
        elif self.web_protocol == "http":
            self._icon_service = IconService(
                HTTPProvider("http://" + node_conf["address"], 3))
            self._ws_block = f"ws://{node_conf['address']}/api/node/{node_conf['channel']}"
        else:
            print("[error] Not supported web_protocol")
            sys.exit()

        # Set wallet of actor
        self._wallet = KeyWallet.load(wallet_path, passwd)

        self._score_info = node_conf["scores"]

    # TODO 실제로는 없어도 되는 method
    def get_block(self, value=None) -> dict:
        block = self._icon_service.get_block(value)
        return block

    def get_rep_list(self):
        resp = self.query("cx0000000000000000000000000000000000000000",
                          "getPRepTerm", {})
        preps_info = resp["preps"]
        preps_list = []
        for item in preps_info:
            preps_list.append(item["address"])

        return preps_list

    def get_rep_list_local(self):
        node_info = f"http://localhost:9100/api/node"

        headers = {"content-type": "application/json"}
        body = {"jsonrpc": "2.0", "method": "node_getChannelInfos", "id": 1234}
        resp = requests.post(node_info, data=json.dumps(body),
                             headers=headers).json()

        assert resp["jsonrpc"]
        assert resp["id"]

        preps_list = []
        for item in resp["result"]["channel_infos"]["icon_dex"]["peers"]:
            preps_list.append(item["id"])

        return preps_list

    def get_tx_result_by_hash(self, tx_hash: str) -> dict:
        tx_result = self._icon_service.get_transaction_result(tx_hash)
        for key, value in tx_result.items():
            if isinstance(value, int):
                tx_result[key] = hex(value)

        try:
            tx_result["logsBloom"] = "0x" + tx_result["logsBloom"].hex()
        except KeyError:
            pass
        return tx_result

    def call_tx(self, score_addr: str, method: str, params: dict) -> dict:
        transaction = CallTransactionBuilder() \
            .from_(self._wallet.get_address()) \
            .to(score_addr) \
            .step_limit(STEP_LIMIT) \
            .nid(self._nid) \
            .nonce(NONCE) \
            .method(method) \
            .params(params) \
            .build()
        return self._send_transaction(transaction)

    def query(self, score_addr: str, method: str, params: dict):
        query = CallBuilder() \
            .from_(self._wallet.get_address()) \
            .to(score_addr) \
            .method(method) \
            .params(params) \
            .build()
        return self._icon_service.call(query)

    def dummy_tx_send(self, loop: int):
        for i in range(loop):
            transaction = CallTransactionBuilder().\
                from_(self._wallet.get_address()).\
                to(self._wallet.get_address()).\
                step_limit(STEP_LIMIT).\
                value(1).\
                nid(self.nid).\
                nonce(NONCE).\
                method("transfer").build()

            signed_tx = SignedTransaction(transaction, self._wallet)
            tx_hash = self.icon_service.send_transaction(signed_tx)
            print(f"[dc_log] dummy tx hash: {tx_hash}")

    def _send_transaction(self, transaction) -> dict:
        signed_tx = SignedTransaction(transaction, self._wallet)
        tx_hash = self._icon_service.send_transaction(signed_tx)

        sleep(SLEEP_TIMER)
        return self.get_tx_result_by_hash(tx_hash)

    @staticmethod
    def print_result(data: dict):

        print(
            "----------------------------------------------------------------------------------"
        )
        print("<Tx_result>")
        print(f" -    txHash: {data['txHash']}")
        print(f" -    height: {data['blockHeight']}")
        print(f" - blockHash: {data['blockHash']}")
        try:
            print(f" - scoreAddr: {data['scoreAddress']}")
        except KeyError:
            pass
        print(f" -  stepUsed: {data['stepUsed']}")
        print(f" -    status: {data['status']}")
        print(
            "----------------------------------------------------------------------------------\n\n"
        )

    @property
    def ws_addr(self):
        return self._ws_block

    @property
    def chain_name(self):
        return self._my_chain_name

    @property
    def nid(self):
        return self._nid

    @property
    def from_account(self):
        return self._wallet.get_address()

    @property
    def icon_service(self):
        return self._icon_service
Esempio n. 14
0
class TestUcBase(unittest.TestCase):
    _scoreAddrOfContractRegistry = ''
    _scoreAddrOfStoreAgentProxy = ''
    _scoreAddrOfOrderAgentProxy = ''
    _scoreAddrOfStoreAgent = ''
    _scoreAddrOfOrderAgent = ''

    @classmethod
    def setUpClass(self):
        self._currentDirPath = path.abspath(path.dirname(__file__))
        self._walletOfTest1 = KeyWallet.load(
            f'{self._currentDirPath}/.keystore/{TEST_KEYSTORE_TEST1}',
            'test1_Account')
        self._walletOfUc = KeyWallet.load(
            f'{self._currentDirPath}/.keystore/{TEST_KEYSTORE_UC}',
            TEST_KEYSTORE_PW)
        self._walletOfProvider = KeyWallet.load(
            f'{self._currentDirPath}/.keystore/{TEST_KEYSTORE_PROVIDER}',
            TEST_KEYSTORE_PW)
        self._walletOfCustomer = KeyWallet.load(
            f'{self._currentDirPath}/.keystore/{TEST_KEYSTORE_CUSTOMER}',
            TEST_KEYSTORE_PW)
        self._iconService = IconService(
            HTTPProvider(TEST_HTTP_ENDPOINT_URI_V3))

    def setUp(self):
        self._scoreAddrOfContractRegistry = self.__class__._scoreAddrOfContractRegistry
        self._scoreAddrOfOrderAgentProxy = self.__class__._scoreAddrOfOrderAgentProxy
        self._scoreAddrOfStoreAgentProxy = self.__class__._scoreAddrOfStoreAgentProxy
        self._scoreAddrOfOrderAgent = self.__class__._scoreAddrOfOrderAgent
        self._scoreAddrOfStoreAgent = self.__class__._scoreAddrOfStoreAgent

    def _deploy(self, _installContentBytes: bytes, _params: object) -> str:
        transaction = DeployTransactionBuilder()\
            .from_(self._walletOfUc.get_address())\
            .to('cx0000000000000000000000000000000000000000')\
            .step_limit(1000000000)\
            .nid(3)\
            .nonce(100)\
            .content_type('application/zip')\
            .content(_installContentBytes)\
            .params(_params)\
            .build()

        signedTransaction = SignedTransaction(transaction, self._walletOfUc)
        txHash = self._iconService.send_transaction(signedTransaction)

        scoreAddr = ''
        for i in range(1, 11):
            sleep(1)
            try:
                txResult = self._iconService.get_transaction_result(txHash)
            except:
                continue
            else:
                break

        self.assertNotEqual(txResult, None)
        scoreAddr = txResult['scoreAddress']
        self.assertNotEqual(scoreAddr, '')
        return scoreAddr

    def _sendTransaction(self, _transaction: object,
                         _wallet: object) -> object:
        signedTransaction = SignedTransaction(_transaction, _wallet)
        txHash = self._iconService.send_transaction(signedTransaction)

        txResult = None
        for i in range(1, 11):
            sleep(1)
            try:
                txResult = self._iconService.get_transaction_result(txHash)
            except:
                continue
            else:
                break

        self.assertNotEqual(txResult, None)
        self.assertEqual(txResult['status'], 0x1)
        return txResult

    def _sendCall(self, _call: object) -> object:
        return self._iconService.call(_call)

    def _getBalance(self, _owner: str) -> int:
        return self._iconService.get_balance(_owner)
class Deployer:
    def __init__(self, node_conf_path: str, wallet_path: str, passwd: str):

        # Node configuration to be connected
        with open(node_conf_path, "r") as f:
            node_conf = json.load(f)

        self._my_chain_name = node_conf["chain_name"]
        self._nid = int(node_conf["nid"], 16)

        if node_conf["web_protocol"] == "ssl":
            self._icon_service = IconService(
                HTTPProvider("https://" + node_conf["address"], 3))
        else:
            self._icon_service = IconService(
                HTTPProvider("http://" + node_conf["address"], 3))
        print(
            f"--------------------------------<Connecting node>--------------------------------"
        )
        print(f" - address    : {node_conf['address']}")
        print(f" - chain_name : {self._my_chain_name}")
        print(f" - nid        : {self._nid}")
        print(
            f"---------------------------------------------------------------------------------"
        )

        # Set wallet of deployer
        self._wallet = KeyWallet.load(wallet_path, passwd)
        # print(f"pk: {self._wallet.get_private_key()}")

        # Set deployed score address
        self._score_addr = ""  # It will be set after deployment
        self._score_path = ""
        self._score_params = {}
        self._score_info = ""

    def deploy_score(self) -> dict:
        tx_result = self._deploy_score(self._score_path, self._score_params)
        try:
            self._score_addr = tx_result["scoreAddress"]
        except KeyError:
            sys.exit()

        return {
            "deploy_txHash": tx_result["txHash"],
            "score_addr": self._score_addr,
            "info": self._score_info
        }

    def _deploy_score(self, score_path: str, params: dict) -> dict:

        # Make zipfile of a score
        # score_content = gen_deploy_data_content(score_path)

        shutil.make_archive("./tmp", "zip", score_path)
        with open("./tmp.zip", "rb") as z:
            score_content = z.read()
        os.remove("./tmp.zip")

        transaction = DeployTransactionBuilder() \
            .from_(self._wallet.get_address()) \
            .to("cx0000000000000000000000000000000000000000") \
            .step_limit(STEP_LIMIT) \
            .nid(self._nid) \
            .nonce(NONCE) \
            .content_type("application/zip") \
            .content(score_content) \
            .params(params) \
            .build()

        return self._send_transaction(transaction)

    def _call_tx(self, score_addr: str, method: str, params: dict) -> dict:

        transaction = CallTransactionBuilder() \
            .from_(self._wallet.get_address()) \
            .to(score_addr) \
            .step_limit(STEP_LIMIT) \
            .nid(self._nid) \
            .nonce(NONCE) \
            .method(method) \
            .params(params) \
            .build()
        return self._send_transaction(transaction)

    def _send_transaction(self, transaction):
        signed_tx = SignedTransaction(transaction, self._wallet)
        tx_hash = self._icon_service.send_transaction(signed_tx)

        sleep(SLEEP_TIMER)
        tx_result = self._icon_service.get_transaction_result(tx_hash)

        self.print_result(tx_result)
        return tx_result

    @property
    def score_addr(self):
        return self._score_addr

    @score_addr.setter
    def score_addr(self, my_addr):
        self._score_addr = my_addr

    @staticmethod
    def print_result(data: dict):
        print(
            "-----------------------------------<Tx_result>-----------------------------------"
        )
        print(f" -    txHash: {data['txHash']}")
        print(f" -    height: {data['blockHeight']}")
        try:
            print(
                f" -   failure: {data['failure']['code']}.{data['failure']['message']}"
            )
            print(f" - scoreAddr: {data['scoreAddress']}")
        except KeyError:
            pass

        print(f" -  stepUsed: {data['stepUsed']}")
        print(f" -    status: {data['status']}")
        print(
            "---------------------------------------------------------------------------------\n\n"
        )
Esempio n. 16
0
    def test_integrate_converter(self):
        """
        Test integrating for the converter which checks that all of the data
        about the block, transaction, and transaction result have the right format.

        [Purpose]
        Check all of the data about the block, transaction, and transaction result.

        [Scenario]
        1. Get the last block data and validate the block data.
        2. Get all of the transaction data on that block and validate the transaction data.
        3. Get all of the transaction result data on that transaction and validate the transaction result data.
        4. Repeatedly, get the other blocks from the last to the first and validate all of three kinds of the data.
        """
        test_domains = self.domains + [BASE_DOMAIN_URL_V3_FOR_TEST]
        max_block_height = 100
        for domain in test_domains:
            icon_service = IconService(HTTPProvider(domain, VERSION_FOR_TEST))
            last_block_height = icon_service.get_block("latest")["height"]
            block_versions = [BLOCK_0_1A_VERSION, BLOCK_0_3_VERSION]
            for block_version in block_versions:
                if block_version == BLOCK_0_1A_VERSION:
                    block_template = BLOCK_0_1a
                    key_name_of_transactions = 'confirmed_transaction_list'
                else:
                    # After Mainnet apply for block 0.3, remove this remark right away.
                    continue

                    block_template = BLOCK_0_3
                    key_name_of_transactions = 'transactions'

                for height in range(last_block_height if last_block_height <
                                    max_block_height else max_block_height):
                    # Check block
                    block = icon_service.get_block(height,
                                                   full_response=True,
                                                   block_version=block_version)
                    block = block['result']
                    converted_block = icon_service.get_block(
                        height, block_version=block_version)
                    block_template = get_block_template_to_convert_transactions_for_genesis(
                        block, block_template)
                    self.assertTrue(
                        validate_block(block_template, block, converted_block))

                    if block["height"] == 0:
                        continue

                    for transaction_in_block in converted_block[
                            key_name_of_transactions]:
                        # Check transaction result
                        tx_result = icon_service.get_transaction_result(
                            transaction_in_block["txHash"], True)
                        tx_result = tx_result['result']
                        converted_transaction_result = icon_service.get_transaction_result(
                            transaction_in_block["txHash"])
                        self.assertTrue(
                            validate_transaction_result(
                                TRANSACTION_RESULT, tx_result,
                                converted_transaction_result))

                        # Check transaction
                        transaction = icon_service.get_transaction(
                            transaction_in_block["txHash"], True)
                        transaction = transaction['result']
                        converted_transaction = icon_service.get_transaction(
                            transaction_in_block["txHash"])
                        self.assertTrue(
                            validate_transaction(TRANSACTION, transaction,
                                                 converted_transaction))
class TestTest(IconIntegrateTestBase):
    TEST_HTTP_ENDPOINT_URI_V3 = "https://zicon.net.solidwallet.io/api/v3"
    #Address of recently deployed contract


    def setUp(self):
        super().setUp()
        self.contracts = {}
        self.contracts['sicx1'] = "cx20fa65cffc720db31e78fba6db5d58f58babd933"
        self.contracts['staking1'] = "cx25c39ed0d27853e44af8ab2739d6af832f35d533"
        self.contracts['staking2'] = "cx8b250e76bc919f73068571c26cadecde69e63b46"
        self.contracts['staking3'] = "cx3502e9af253098d187578ca826fe71032f116e47"
        # WARNING: ICON service emulation is not working with IISS.
        # You can stake and delegate but can't get any I-Score for reward.
        # If you want to test IISS stuff correctly, set self.icon_service and send requests to the network
        self.icon_service = IconService(HTTPProvider(self.TEST_HTTP_ENDPOINT_URI_V3))
        private2="093f12dba9dc75da81ecafc88de73ef9b311b555939aeb5a875dc6ad8feef424"
        private3="167f6ec1694ab63243efdce98f6f6bfdcef0575cefbb86ffe3826f8373f12b85"
        self._test2 = KeyWallet.load(bytes.fromhex(private2))
        self._test3 = KeyWallet.load(bytes.fromhex(private3))

        #
        # If you want to send requests to the network, uncomment next line and set self.TEST_HTTP_ENDPOINT_URI_V3



    @retry(JSONRPCException, tries=10, delay=1, back_off=2)
    def _get_tx_result(self,_tx_hash):
        tx_result = self.icon_service.get_transaction_result(_tx_hash)
        return tx_result

    # Sends the call request
    @retry(JSONRPCException, tries=10, delay=1, back_off=2)
    def get_tx_result(self,_call):
        tx_result = self.icon_service.call(_call)
        return tx_result

    def test_add_collateral(self):
        print('======================================================================')
        print('Test Add Collateral')
        print('----------------------------------------------------------------------')
        settings = [
                    #{'name': 'Sending 30 ICX from test_account1', 'from' : self._test1.get_address(),'value':25 * 10 ** 18, 'params' : {'_to': self._test1.get_address()},'sign':self._test1},
                    #{'name': 'Sending 80 ICX from test_account1', 'from' : self._test1.get_address(),'value':40 * 10 ** 18, 'params' : {'_to': self._test1.get_address()},'sign': self._test1},
                    {'name': 'Sending 15 ICX from test_account2', 'from' : self._test2.get_address(),'value':15 * 10 ** 18, 'params' : {'_to': self._test2.get_address()},'sign': self._test2}
                    # {'name': 'Sending 15 ICX from test_account2', 'from' : self._test3.get_address(),'value':15 * 10 ** 18, 'params' : {'_to': self._test3.get_address()},'sign': self._test3}
                     ]

        for sett in settings:
            print('======================================================================')
            print(sett['name'])
            print('----------------------------------------------------------------------')

            transaction = CallTransactionBuilder() \
            .from_(sett['from']) \
            .to(self.contracts['staking1']) \
            .value (sett['value']) \
            .step_limit(10000000) \
            .nid(80) \
            .nonce(100) \
            .method('addCollateral') \
            .params(sett['params']) \
            .build()
            # Returns the signed transaction object having a signature
            signed_transaction = SignedTransaction(transaction, sett['sign'])

            # process the transaction in zicon
            tx_hash = self.icon_service.send_transaction(signed_transaction)
            _tx_result= self._get_tx_result(tx_hash)
             #check Transaction result
            print (_tx_result)
            self.assertTrue('status' in _tx_result)
            self.assertEqual(True, _tx_result['status'])
            # contract_delegation_call = CallBuilder().from_(sett['from']) \
            #     .to(self.contracts['staking1']) \
            #     .method("getDelegationFromNetwork") \
            #     .build()
            # response_delegation_contract = self.get_tx_result(contract_delegation_call)
            # print('----------------------------------------------------------------------')
            # print('Delegation List from Network')
            # print('----------------------------------------------------------------------')
            # delegation_from_contract = {}
            # #Iterating through contract delegations
            # for i in response_delegation_contract["delegations"]:
            #     delegation_from_contract[i['address']] = i['value']
            # print(delegation_from_contract)
            # check call result
            # if sett['name'] == 'Test Case 1.3':
            #     self.assertEqual(response_delegation,delegation_from_contract)

    # def test_update_delegation(self):
    #     print('======================================================================')
    #     print(' *******************Test Update Delegations***************************')
    #     print('----------------------------------------------------------------------')
    #     settings = [{'name': 'Test Case 1.1', 'wAddress':'staking3', 'params' : {'_user_delegations':[{'_address': 'hxc5772df538f620e1f61ef2cc3cddcea9d6ff5063',  '_votes_in_per' : "50"},
    #                                                               {'_address': 'hx7ce8e9c5e1ee02c6167b99b5bb4d00bdf63d0a30',  '_votes_in_per' : "50"}]}},
    #                 {'name': 'Test Case 2.1', 'wAddress':'staking1', "params" : {'_user_delegations':[{'_address': 'hxc5772df538f620e1f61ef2cc3cddcea9d6ff5063',  '_votes_in_per' : "5"},{'_address': 'hx7ce8e9c5e1ee02c6167b99b5bb4d00bdf63d0a30',  '_votes_in_per' : "10"},
    #                                                               {'_address': 'hxbdc3baae0632fad453d62130d3379900a323f5b4',  '_votes_in_per' : "15"}]}},
    #                 {'name': 'Test Case 2.2', 'wAddress':'staking1', 'params' : {'_user_delegations':[{'_address': 'hx95248f3757afcb50efa99f529183ba401a82273c',  '_votes_in_per' : "50"},{'_address': 'hx95248f3757afcb50efa99f529183ba401a82273c',  '_votes_in_per' : "50"},
    #                                                               {'_address': 'hxc89dfd4bf903b39ca98db905443ca9020f955e8c',  '_votes_in_per' : "50"}]}},
    #                 {'name': 'Test Case 2.3', 'wAddress':'staking1', 'params' : {}},
    #                 {'name': 'Test Case 2.4', 'wAddress':'staking1', 'params' : {'_user_delegations':[{'_address': 'hx4917005bf4b8188b9591da520fc1c6dab8fe717f',  '_votes_in_per' : "50"},
    #                                                               {'_address': 'hx9a24e7a53e031ab6aa7b831b1dbe4200bd3f9483',  '_votes_in_per' : "50"}]}},
    #                 {'name': 'Test Case 2.5', 'wAddress':'staking1', 'params' : {'_user_delegations':[{'_address': 'hx8573a132f3df5c34a292fc16cb33737ffe10b367',  '_votes_in_per' : "40"},{'_address': 'hx6bd3a3b1390e99194ced786725e0f0725fc1960b',  '_votes_in_per' : "15"},
    #                                                               {'_address': 'hx7cc2bb9d84ff3b5843f83d07818ebcff31be29e5',  '_votes_in_per' : "45"}]}},
    #                 {'name': 'Test Case 2.6', 'wAddress':'staking1', 'params' : {'_user_delegations':[{'_address': 'hx2d058aa34a76b2039e7cc59f18633aabd272d89f',  '_votes_in_per' : "100"}]}},
    #                 ]
    #     for sett in settings:
    #         print('======================================================================')
    #         print(sett['name'])
    #         print('----------------------------------------------------------------------')

    #         call_transaction = CallTransactionBuilder() \
    #             .from_(self._test1.get_address()) \
    #             .to(self.contracts[sett['wAddress']]) \
    #             .nid(80) \
    #             .step_limit(10000000) \
    #             .nonce(100) \
    #             .method('updateDelegations') \
    #             .params(sett['params']) \
    #             .build()
    #         # Returns the signed transaction object having a signature
    #         signed_transaction = SignedTransaction(call_transaction, self._test1)
    #         # process the transaction in zicon
    #         tx_hash = self.icon_service.send_transaction(signed_transaction)
    #         _tx_result= self._get_tx_result(tx_hash)
    #          #check Transaction result
    #         print (_tx_result)
    #         if sett['name'] == 'Test Case 1.1' or sett['name'] == 'Test Case 2.1' or sett['name'] == 'Test Case 2.2' or sett['name'] == 'Test Case 2.3':
    #             self.assertEqual(_tx_result,_tx_result)
    #         else:
    #             self.assertTrue('status' in _tx_result)
    #             self.assertEqual(True, _tx_result['status'])
    #             delegation_call = CallBuilder().from_(self._test1.get_address()) \
    #                 .to(self.contracts[sett['wAddress']]) \
    #                 .method("getPrepDelegations") \
    #                 .build()

    #             contract_delegation_call = CallBuilder().from_(self._test1.get_address()) \
    #                 .to(self.contracts[sett['wAddress']]) \
    #                 .method("getDelegationFromNetwork") \
    #                 .build()
    #             response_delegation = self.get_tx_result(delegation_call)
    #             response_delegation_contract = self.get_tx_result(contract_delegation_call)
    #             print('----------------------------------------------------------------------')
    #             print('Delegation List')
    #             print('----------------------------------------------------------------------')
    #             print (response_delegation)
    #             print('----------------------------------------------------------------------')
    #             print('Delegation List from Network')
    #             print('----------------------------------------------------------------------')
    #             delegation_from_contract = {}
    #             #Iterating through contract delegations
    #             for i in response_delegation_contract["delegations"]:
    #                 delegation_from_contract[i['address']] = i['value']
    #             print(delegation_from_contract)

    # def test_wclaim_iscore(self):
    #     print('======================================================================')
    #     print(' **********************Test Claim IScore*****************************')
    #     print('----------------------------------------------------------------------')

    #     transaction = CallTransactionBuilder() \
    #         .from_(self._test1.get_address()) \
    #         .to(self.contracts['staking1']) \
    #         .step_limit(10000000) \
    #         .nid(80) \
    #         .nonce(100) \
    #         .method('_claim_iscore') \
    #         .build()
    #     # # Returns the signed transaction object having a signature
    #     signed_transaction = SignedTransaction(transaction, self._test1)

    #     # # process the transaction in zicon
    #     tx_hash = self.icon_service.send_transaction(signed_transaction)
    #     _tx_result= self._get_tx_result(tx_hash)
    #     print (_tx_result)
    #     # #check Transaction result
    #     self.assertTrue('status' in _tx_result)
    #     self.assertEqual(True, _tx_result['status'])


    #     contract_delegation_call = CallBuilder().from_(self._test1.get_address()) \
    #         .to(self.contracts['staking1']) \
    #         .method("getLifetimeReward") \
    #         .build()
    #     response_delegation_contract = self.get_tx_result(contract_delegation_call)

    #     print('----------------------------------------------------------------------')
    #     print('Delegation List from Network')
    #     print('----------------------------------------------------------------------')
    #     delegation_from_contract = {}
    #     # #Iterating through contract delegations
    #     # for i in response_delegation_contract["delegations"]:
    #     #     delegation_from_contract[i['address']] = i['value']
    #     # print(delegation_from_contract)
    #     print(response_delegation_contract)


    # def test_tr(self):
    #     print('======================================================================')
    #     print(' *******************Test Update Delegations***************************')
    #     print('----------------------------------------------------------------------')
    #     settings = [{'name': 'Test Case 1.1', 'wAddress':'staking3', 'params' : {'_user_delegations':[{'_address': 'hxc5772df538f620e1f61ef2cc3cddcea9d6ff5063',  '_votes_in_per' : "50"},
    #                                                               {'_address': 'hx7ce8e9c5e1ee02c6167b99b5bb4d00bdf63d0a30',  '_votes_in_per' : "50"}]}},
    #                 {'name': 'Test Case 2.1', 'wAddress':'staking1', "params" : {'_user_delegations':[{'_address': 'hxc5772df538f620e1f61ef2cc3cddcea9d6ff5063',  '_votes_in_per' : "5"},{'_address': 'hx7ce8e9c5e1ee02c6167b99b5bb4d00bdf63d0a30',  '_votes_in_per' : "10"},
    #                                                               {'_address': 'hxbdc3baae0632fad453d62130d3379900a323f5b4',  '_votes_in_per' : "15"}]}},
    #                 {'name': 'Test Case 2.2', 'wAddress':'staking1', 'params' : {'_user_delegations':[{'_address': 'hx95248f3757afcb50efa99f529183ba401a82273c',  '_votes_in_per' : "50"},{'_address': 'hx95248f3757afcb50efa99f529183ba401a82273c',  '_votes_in_per' : "50"},
    #                                                               {'_address': 'hxc89dfd4bf903b39ca98db905443ca9020f955e8c',  '_votes_in_per' : "50"}]}},
    #                 {'name': 'Test Case 2.3', 'wAddress':'staking1', 'params' : {}},
    #                 {'name': 'Test Case 2.4', 'wAddress':'staking1', 'params' : {'_user_delegations':[{'_address': 'hx4917005bf4b8188b9591da520fc1c6dab8fe717f',  '_votes_in_per' : "50"},
    #                                                               {'_address': 'hx9a24e7a53e031ab6aa7b831b1dbe4200bd3f9483',  '_votes_in_per' : "50"}]}},
    #                 {'name': 'Test Case 2.5', 'wAddress':'staking1', 'params' : {'_user_delegations':[{'_address': 'hx8573a132f3df5c34a292fc16cb33737ffe10b367',  '_votes_in_per' : "40"},{'_address': 'hx6bd3a3b1390e99194ced786725e0f0725fc1960b',  '_votes_in_per' : "15"},
    #                                                               {'_address': 'hx7cc2bb9d84ff3b5843f83d07818ebcff31be29e5',  '_votes_in_per' : "45"}]}},
    #                 {'name': 'Test Case 2.6', 'wAddress':'staking1', 'params' : {'_user_delegations':[{'_address': 'hx23dfce82d36268f4cc3b943fa65d4c9632d23e76',  '_votes_in_per' : "100"}]}},
    #                 ]
    #     for sett in settings:
    #         print('======================================================================')
    #         print(sett['name'])
    #         print('----------------------------------------------------------------------')

    #         call_transaction = CallTransactionBuilder() \
    #             .from_(self._test1.get_address()) \
    #             .to(self.contracts[sett['wAddress']]) \
    #             .nid(80) \
    #             .step_limit(10000000) \
    #             .nonce(100) \
    #             .method('updateDelegations') \
    #             .params(sett['params']) \
    #             .build()
    #         # Returns the signed transaction object having a signature
    #         signed_transaction = SignedTransaction(call_transaction, self._test1)
    #         # process the transaction in zicon
    #         tx_hash = self.icon_service.send_transaction(signed_transaction)
    #         _tx_result= self._get_tx_result(tx_hash)
    #          #check Transaction result
    #         print (_tx_result)
    #         if sett['name'] == 'Test Case 1.1' or sett['name'] == 'Test Case 2.1' or sett['name'] == 'Test Case 2.2' or sett['name'] == 'Test Case 2.3':
    #             self.assertEqual(_tx_result,_tx_result)
    #         else:
    #             self.assertTrue('status' in _tx_result)
    #             self.assertEqual(True, _tx_result['status'])
    #             delegation_call = CallBuilder().from_(self._test1.get_address()) \
    #                 .to(self.contracts[sett['wAddress']]) \
    #                 .method("getPrepDelegations") \
    #                 .build()

    #             contract_delegation_call = CallBuilder().from_(self._test1.get_address()) \
    #                 .to(self.contracts[sett['wAddress']]) \
    #                 .method("getDelegationFromNetwork") \
    #                 .build()
    #             response_delegation = self.get_tx_result(delegation_call)
    #             response_delegation_contract = self.get_tx_result(contract_delegation_call)
    #             print('----------------------------------------------------------------------')
    #             print('Delegation List')
    #             print('----------------------------------------------------------------------')
    #             print (response_delegation)
    #             print('----------------------------------------------------------------------')
    #             print('Delegation List from Network')
    #             print('----------------------------------------------------------------------')
    #             delegation_from_contract = {}
    #             #Iterating through contract delegations
    #             for i in response_delegation_contract["delegations"]:
    #                 delegation_from_contract[i['address']] = i['value']
    #             print(delegation_from_contract)



    # def test_unstake(self):
    #     print('======================================================================')
    #     print('Test Unstake')
    #     print('----------------------------------------------------------------------')
    #     data = "{\"method\": \"unstake\"}".encode("utf-8")
    #     settings = [
    #                 # {'name': 'Test Case 1.1', 'from' : self._test1.get_address(), 'wAddress':'sicx1', 'params' : {'_to': self.contracts['staking1'],'_value': 20 * 10**18,'_data':data},'sign': self._test1,'delegation_address':'staking1'},
    #                 {'name': 'Test Case 1.2', 'from' : self._test2.get_address(), 'wAddress':'sicx1', 'params' : {'_to': self.contracts['staking1'], '_value': 20 * 10**18,'_data':data},'sign': self._test2,'delegation_address':'staking1'},
    #                 ]

    #     for sett in settings:
    #         print('======================================================================')
    #         print(sett['name'])
    #         print('----------------------------------------------------------------------')

    #         transaction = CallTransactionBuilder() \
    #         .from_(sett['from']) \
    #         .to(self.contracts[sett['wAddress']]) \
    #         .step_limit(10000000) \
    #         .nid(80) \
    #         .nonce(100) \
    #         .method('transfer') \
    #         .params(sett['params']) \
    #         .build()
    #         # Returns the signed transaction object having a signature
    #         signed_transaction = SignedTransaction(transaction, sett['sign'])

    #         # process the transaction in zicon
    #         tx_hash = self.icon_service.send_transaction(signed_transaction)
    #         _tx_result= self._get_tx_result(tx_hash)
    #          #check Transaction result
    #         print (_tx_result)
    #         self.assertTrue('status' in _tx_result)
    #         self.assertEqual(True, _tx_result['status'])
    #     # Address =[self._test1.get_address(),self._test2.get_address()]
    #     # for test in Address:
    #     #     contract_delegation_call = CallBuilder().from_(test) \
    #     #         .to(self.contracts[sett['delegation_address']]) \
    #     #         .method("getDelegationFromNetwork") \
    #     #         .build()
    #     #     response_delegation_contract = self.get_tx_result(contract_delegation_call)
    #     #     print('----------------------------------------------------------------------')
    #     #     print('Delegation List from Network')
    #     #     print('----------------------------------------------------------------------')
    #     #     delegation_from_contract = {}
    #     #     #Iterating through contract delegations
    #     #     for i in response_delegation_contract["delegations"]:
    #     #         delegation_from_contract[i['address']] = i['value']
    #     #     print(delegation_from_contract)
    #     # check call result
    #     # if sett['name'] == 'Test Case 1.3':
    #     #     self.assertEqual(response_delegation,delegation_from_contract)


    # def test_send_ICX(self):
    #     print('======================================================================')
    #     print('Test Send ICX')
    #     print('----------------------------------------------------------------------')
    #     settings = [
    #                 {'name': 'Test Case 1.1', 'from' : self._test1.get_address(), 'wAddress':'staking1', 'params' : {'_to': self._test2.get_address(),'_value': 800 }}
    #                 ]
    #     for sett in settings:
    #         print('======================================================================')
    #         print(sett['name'])
    #         print('----------------------------------------------------------------------')

    #         call_transaction = CallTransactionBuilder() \
    #             .from_(self._test1.get_address()) \
    #             .to(self.contracts[sett['wAddress']]) \
    #             .nid(80) \
    #             .step_limit(10000000) \
    #             .nonce(100) \
    #             .method('_send_ICX') \
    #             .params(sett['params']) \
    #             .build()
    #         # Returns the signed transaction object having a signature
    #         signed_transaction = SignedTransaction(call_transaction, self._test1)
    #         # process the transaction in zicon
    #         tx_hash = self.icon_service.send_transaction(signed_transaction)
    #         _tx_result= self._get_tx_result(tx_hash)
    #          #check Transaction result
    #         print (_tx_result)
    #         self.assertTrue('status' in _tx_result)
    #         self.assertEqual(True, _tx_result['status'])
    #         delegation_call = CallBuilder().from_(self._test1.get_address()) \
    #             .to(self.contracts[sett['wAddress']]) \
    #             .method("getPrepDelegations") \
    #             .build()

    #         contract_delegation_call = CallBuilder().from_(self._test1.get_address()) \
    #             .to(self.contracts[sett['wAddress']]) \
    #             .method("getDelegationFromNetwork") \
    #             .build()
    #         response_delegation = self.get_tx_result(delegation_call)
    #         response_delegation_contract = self.get_tx_result(contract_delegation_call)
    #         print('----------------------------------------------------------------------')
    #         print('Delegation List')
    #         print('----------------------------------------------------------------------')
    #         print (response_delegation)
    #         print('----------------------------------------------------------------------')
    #         print('Delegation List from Network')
    #         print('----------------------------------------------------------------------')
    #         delegation_from_contract = {}
    #         #Iterating through contract delegations
    #         for i in response_delegation_contract["delegations"]:
    #             delegation_from_contract[i['address']] = i['value']
    #         print(delegation_from_contract)
    



    def test_lifeTime(self):
        print('======================================================================')
        print('getLifetimeReward')
        print('----------------------------------------------------------------------')

        _call = CallBuilder().from_(self._test1.get_address()) \
            .to(self.contracts['staking1']) \
            .method("getLifetimeReward") \
            .build()

        response = self.get_tx_result(_call)
        # check call result
        print (response)
        

    def test_getRate(self):
        print('======================================================================')
        print('Test getRate ')
        print('----------------------------------------------------------------------')

        _call = CallBuilder().from_(self._test1.get_address()) \
            .to(self.contracts['staking1']) \
            .method("getRate") \
            .build()

        response = self.get_tx_result(_call)
        # check call result
        print (response)
        

    def test_getTodayRate(self):
        print('======================================================================')
        print('Test getTodayRate')
        print('----------------------------------------------------------------------')

        _call = CallBuilder().from_(self._test1.get_address()) \
            .to(self.contracts['staking1']) \
            .method("getTodayRate") \
            .build()

        response = self.get_tx_result(_call)
        # check call result
        print (response)
Esempio n. 18
0
class IconNetwork:
    def __init__(self, endpoint, network_id):
        self.endpoint = endpoint
        self.network_id = network_id
        self.icon_service = IconService(HTTPProvider(endpoint, network_id))

    def get_max_step_limit(self, wallet_address):
        params = {'contextType': 'invoke'}

        call_data = CallBuilder() \
          .from_(wallet_address) \
          .to(GOVERNANCE_ADDRESS) \
          .method('getMaxStepLimit') \
          .params(params) \
          .build()

        result = self.icon_service.call(call_data)
        return convert_hex_str_to_int(result)

    def deploy_contract(self, contract_info, account_info):
        wallet = KeyWallet.load(bytes.fromhex(account_info['wallet_key']))
        contract_content_bytes = gen_deploy_data_content(
            contract_info['contract_file'])

        deploy_transaction = DeployTransactionBuilder() \
          .from_(wallet.get_address()) \
          .to(SCORE_INSTALL_ADDRESS) \
          .step_limit(self.get_max_step_limit(wallet.get_address())) \
          .nid(self.network_id) \
          .nonce(self.network_id) \
          .content_type('application/zip') \
          .content(contract_content_bytes) \
          .params(contract_info['params']) \
          .version(self.network_id) \
          .build()

        signed_transaction = SignedTransaction(deploy_transaction, wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)
        # print('tx_hash:', tx_hash)

        tx_result = self.get_transaction_result(tx_hash)
        return tx_result

    def get_transaction_result(self, tx_hash):
        max_retries = 10
        retry_count = 0
        sleep_seconds = 5
        tx_result = None

        while retry_count < max_retries:
            tx_result = self.get_transaction_result_once(tx_hash)

            if None != tx_result:
                retry_count = max_retries
            else:
                retry_count += 1
                # print('Retrying {0} in {1} seconds'.format(retry_count, sleep_seconds))
                time.sleep(sleep_seconds)

        # tx_result might be still None if all retries failed.
        return tx_result

    def get_transaction_result_once(self, tx_hash):
        try:
            tx_result = self.icon_service.get_transaction_result(tx_hash)
            # print('tx_result:', tx_result)
            return tx_result
        except:
            error = sys.exc_info()
            # print('get_transaction_result error:', error[1])
            return None

    def read_data(self, contract_address, table_name, wallet_key, params):
        wallet = KeyWallet.load(bytes.fromhex(wallet_key))

        call_data = CallBuilder() \
          .from_(wallet.get_address()) \
          .to(contract_address) \
          .method('get' + table_name) \
          .params(params) \
          .build()

        result = self.icon_service.call(call_data)
        return result

    def write_data(self, contract_address, action_name, wallet_key, params):
        wallet = KeyWallet.load(bytes.fromhex(wallet_key))

        call_transaction = CallTransactionBuilder() \
          .from_(wallet.get_address()) \
          .to(contract_address) \
          .step_limit(self.get_max_step_limit(wallet.get_address())) \
          .nid(self.network_id) \
          .nonce(self.network_id) \
          .method(action_name) \
          .params(params) \
          .build()

        signed_transaction = SignedTransaction(call_transaction, wallet)
        tx_hash = self.icon_service.send_transaction(signed_transaction)
        # print('tx_hash:', tx_hash)

        tx_result = self.get_transaction_result(tx_hash)
        return tx_result

    def create_data(self, contract_address, table_name, wallet_key, data):
        return self.write_data(contract_address, 'cre' + table_name,
                               wallet_key, data)

    def update_data(self, contract_address, table_name, wallet_key, data):
        return self.write_data(contract_address, 'upd' + table_name,
                               wallet_key, data)

    def delete_data(self, contract_address, table_name, wallet_key, data):
        return self.write_data(contract_address, 'del' + table_name,
                               wallet_key, data)
Esempio n. 19
0
class RPCmanager(object):
    def __init__(self, _conf_rpc: dict) -> None:
        # Key Wallet with Password
        self.key_wallet = KeyWallet.load(_conf_rpc["KeyWallet"]["File"],
                                         _conf_rpc["KeyWallet"]["Password"])
        # Service Endpoint (URL)
        self.service_endpoint = IconService(
            HTTPProvider(_conf_rpc["Service Endpoint"]))
        # Smart Contract Address
        self.id_contract_address = _conf_rpc["ID Contract Address"]
        self.ptm_contract_address = _conf_rpc["PTM Contract Address"]
        self.pgm_contract_address = _conf_rpc["PGM Contract Address"]
        # Network ID
        self.nid = int(_conf_rpc["Network ID"])

    def getMethod(self, _method: dict, type: str) -> str:
        if type == "DIR":
            contract_address = self.id_contract_address
        elif type == "PTM":
            contract_address = self.ptm_contract_address
        elif type == "PGM":
            contract_address = self.pgm_contract_address
        else:
            print("Not supported contract type")
            pass

        call = CallBuilder() \
            .from_(self.key_wallet.get_address()) \
            .to(contract_address) \
            .method(_method["name"]) \
            .params(_method["params"]) \
            .build()

        result = self.service_endpoint.call(call)
        print(result)

        return result

    def setMethod(self, _method: dict, type: str) -> dict:
        result = {}
        if type == "DIR":
            contract_address = self.id_contract_address
        elif type == "PTM":
            contract_address = self.ptm_contract_address
        elif type == "PGM":
            contract_address = self.pgm_contract_address
        else:
            print("Not supported contract type")
            result["status"] = "failure"
            result["message"] = ""
            return result

        if not _method.__contains__("params"):
            _method["params"] = ""

        transaction = CallTransactionBuilder() \
            .from_(self.key_wallet.get_address()) \
            .to(contract_address) \
            .step_limit(10000000) \
            .nid(self.nid) \
            .method(_method["name"]) \
            .params(_method["params"]) \
            .build()

        # sign the transaction with key wallet
        signed_tx = SignedTransaction(transaction, self.key_wallet)
        # commit(send) the signed transaction to the service endpoint
        tx_hash = self.service_endpoint.send_transaction(signed_tx)
        sleep(3)  # wait a second for the transaction to be finalized
        tx_result = self.service_endpoint.get_transaction_result(tx_hash)
        print(tx_result)

        if "failure" in tx_result:
            result["status"] = "failure"
            result["message"] = tx_result["failure"]
        else:
            result["status"] = "success"
            result["message"] = tx_result["eventLogs"][0]["data"]

        return result