예제 #1
0
    def deploy(self, conf: dict) -> dict:
        """Deploy SCORE on the server.

        :param conf: deploy command configuration
        """
        # check keystore, and get password from user's terminal input
        password = conf.get('password', None)
        password = self._check_deploy(conf, password)

        if conf['mode'] == 'install':
            score_address = f'cx{"0"*40}'
        else:
            score_address = conf['to']

        content_type = "application/zip"
        # make zip and convert to hexadecimal string data (start with 0x) and return
        content = IconJsonrpc.gen_deploy_data_content(conf['project'])

        # make IconJsonrpc instance which is used for making request (with signature)
        if conf['keyStore']:
            deploy = IconJsonrpc.from_key_store(keystore=conf['keyStore'],
                                                password=password)
        else:
            deploy = IconJsonrpc.from_string(from_=conf['from'])

        uri = conf['uri']
        step_limit = conf.get('stepLimit', None)

        # make JSON-RPC 2.0 request standard format
        request = deploy.sendTransaction(to=score_address,
                                         nid=conf['nid'],
                                         step_limit=step_limit,
                                         data_type="deploy",
                                         data=IconJsonrpc.gen_deploy_data(
                                             params=conf.get(
                                                 'scoreParams', {}),
                                             content_type=content_type,
                                             content=content))

        if step_limit is None:
            step_limit = get_enough_step(request, uri)
            request['params']['stepLimit'] = hex(step_limit)
            deploy.put_signature(request['params'])

        # send request to the rpc server
        icon_client = IconClient(uri)
        response = icon_client.send(request)

        if 'error' in response:
            print('Got an error response')
            print(json.dumps(response, indent=4))
        else:
            print('Send deploy request successfully.')
            tx_hash = response['result']
            print(
                f'If you want to check SCORE deployed successfully, execute txresult command'
            )
            print(f"transaction hash: {tx_hash}")

        return response
예제 #2
0
    def sendtx(self, conf: dict):
        """Send transaction.

        :param conf: sendtx command configuration.
        :return: response of transfer.
        """
        with open(conf['json_file'], 'r') as jf:
            payload = json.load(jf)

        password = conf.get('password', None)
        password = self._check_sendtx(conf, password)

        if password:
            sendtx = IconJsonrpc.from_key_store(conf['keyStore'], password)
            params = payload['params']
            jsonrpc_params_to_pep_style(params)
            payload = sendtx.sendTransaction(**params)

        icon_client = IconClient(conf['uri'])
        response = icon_client.send(request=payload)

        if 'result' in response:
            print('Send transaction request successfully.')
            tx_hash = response['result']
            print(f"transaction hash: {tx_hash}")
        else:
            print('Got an error response')
            print(json.dumps(response, indent=4))

        return response
예제 #3
0
    def transfer(self, conf: dict):
        """Transfer ICX Coin.

        :param conf: transfer command configuration.
        :return: response of transfer.
        """
        # check value type(must be int), address and keystore file
        # if valid, return user input password
        password = conf.get('password', None)
        password = self._check_transfer(conf, password)

        if password:
            transfer = IconJsonrpc.from_key_store(conf['keyStore'], password)
        else:
            transfer = IconJsonrpc.from_string(conf['from'])

        # make JSON-RPC 2.0 request standard format(dict type)
        request = transfer.sendTransaction(to=conf['to'],
                                           value=hex(int(conf['value'])),
                                           nid=conf['nid'])

        # request to rpcserver
        icon_client = IconClient(conf['uri'])
        response = icon_client.send(request=request)

        if 'result' in response:
            print('Send transfer request successfully.')
            tx_hash = response['result']
            print(f"transaction hash: {tx_hash}")
        else:
            print('Got an error response')
            print(json.dumps(response, indent=4))

        return response
예제 #4
0
    def balance(self, conf: dict):
        """Query icx balance of given address

        :param conf: balance command configuration.
        """
        icon_client = IconClient(conf['uri'])

        response = icon_client.send(IconJsonrpc.getBalance(conf['address']))

        if "error" in response:
            print('Got an error response')
            print(json.dumps(response, indent=4))
        else:
            print(f"balance in hex: {response['result']}")
            print(f"balance in decimal: {int(response['result'], 16)}")
        return response
예제 #5
0
    def lastblock(self, conf):
        """Query last block

        :param conf: lastblock command configuration
        :return: result of query
        """
        icon_client = IconClient(conf['uri'])

        response = icon_client.send(IconJsonrpc.getLastBlock())

        if "error" in response:
            print(json.dumps(response, indent=4))
        else:
            print(f'block info : {json.dumps(response, indent=4)}')

        return response
예제 #6
0
    def blockbyhash(self, conf):
        """Query block with given hash

        :param conf: blockbyhash command configuration
        :return: result of query
        """
        icon_client = IconClient(conf['uri'])

        response = icon_client.send(IconJsonrpc.getBlockByHash(conf['hash']))

        if "error" in response:
            print('Got an error response')
            print(json.dumps(response, indent=4))
        else:
            print(f"block info : {json.dumps(response, indent=4)}")

        return response
예제 #7
0
    def sendtx(self, conf: dict):
        """Send transaction.

        :param conf: sendtx command configuration.
        :return: response of transfer.
        """
        with open(conf['json_file'], 'r') as jf:
            payload = json.load(jf)

        password = conf.get('password', None)
        password = self._check_sendtx(conf, password)

        if password:
            sendtx = IconJsonrpc.from_key_store(conf['keyStore'], password)
        else:
            sendtx = IconJsonrpc.from_string(payload['params']['from'])

        params = payload['params']
        params['from'] = None
        jsonrpc_params_to_pep_style(params)
        payload = sendtx.sendTransaction(**params)

        uri = conf['uri']
        step_limit = payload['params']['stepLimit']
        if step_limit is None:
            step_limit = conf.get('stepLimit', None)
            if step_limit is None:
                step_limit = get_enough_step(payload, uri)
            else:
                step_limit = int(step_limit, 16)
            payload['params']['stepLimit'] = hex(step_limit)
            sendtx.put_signature(payload['params'])

        # send request to the rpc server
        icon_client = IconClient(uri)
        response = icon_client.send(request=payload)

        if 'result' in response:
            print('Send transaction request successfully.')
            tx_hash = response['result']
            print(f"transaction hash: {tx_hash}")
        else:
            print('Got an error response')
            print(json.dumps(response, indent=4))

        return response
예제 #8
0
    def call(conf):
        """Request icx_call

        :param conf: call command configuration.
        :return: response of icx_call
        """
        icon_client = IconClient(conf['uri'])
        with open(conf['json_file'], 'r') as jf:
            payload = json.load(jf)

        response = icon_client.send(request=payload)

        if 'error' in response:
            print(json.dumps(response, indent=4))
        else:
            print(f'response : {json.dumps(response, indent=4)}')

        return response
예제 #9
0
    def scoreapi(self, conf):
        """Query score API of given score address.

        :param conf: scoreapi command configuration.
        :return: result of query.
        """
        icon_client = IconClient(conf['uri'])
        response = icon_client.send(IconJsonrpc.getScoreApi(conf['address']))

        if "error" in response:
            print('Got an error response')
            print(
                f"Can not get {conf['address']}'s API\n{json.dumps(response, indent=4)}"
            )
        else:
            print(f"SCORE API: {json.dumps(response['result'], indent=4)}")

        return response
예제 #10
0
    def totalsupply(conf: dict):
        """Query total supply of ICX

        :param conf: totalsupply command configuration
        """
        icon_client = IconClient(conf['uri'])

        response = icon_client.send(IconJsonrpc.getTotalSupply())

        if "error" in response:
            print('Got an error response')
            print(json.dumps(response, indent=4))
        else:
            print(f'Total supply of ICX in hex: {response["result"]}')
            print(
                f'Total supply of ICX in decimal: {int(response["result"], 16)}'
            )

        return response
예제 #11
0
    def txbyhash(self, conf):
        """Query transaction using given transaction hash.

        :param conf: txbyhash command configuration.
        :return: result of query.
        """
        icon_client = IconClient(conf['uri'])

        response = icon_client.send(
            IconJsonrpc.getTransactionByHash(conf['hash']))

        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
예제 #12
0
    def test_duplicated_tx(self):
        # test start, deploy, stop, clean command
        conf = self.cmd.cmdUtil.get_init_args(project=self.project_name,
                                              score_class=self.project_class)

        # init
        self.cmd.cmdUtil.init(conf)

        # start
        tbears_config_path = os.path.join(TEST_UTIL_DIRECTORY,
                                          f'test_tbears_server_config.json')
        start_conf = IconConfig(tbears_config_path, tbears_server_config)
        start_conf.load()
        start_conf['config'] = tbears_config_path
        self.start_conf = start_conf
        self.cmd.cmdServer.start(start_conf)
        self.assertTrue(self.cmd.cmdServer.is_service_running())

        # prepare to send
        genesis_info = start_conf['genesis']['accounts'][0]
        from_addr = genesis_info['address']
        icon_jsonrpc = IconJsonrpc.from_string(from_addr)
        icon_client = IconClient(
            f'http://127.0.0.1:{start_conf["port"]}/api/v3')

        to_addr = f'hx{"d"*40}'
        timestamp = hex(int(time.time() * 10**6))

        # send transaction
        request = icon_jsonrpc.sendTransaction(to=to_addr,
                                               timestamp=timestamp,
                                               step_limit='0x100000')
        response = icon_client.send(request)
        self.assertTrue('result' in response)

        # send again
        response = icon_client.send(request)
        self.assertTrue('error' in response)
        self.assertEqual(
            responseCodeMap[Response.fail_tx_invalid_duplicated_hash][1],
            response['error']['message'])
예제 #13
0
    def test_send_request_to_server(self):
        # Correct request
        payload = {"jsonrpc": "2.0", "method": "icx_getTotalSupply", "id": 111}
        client = IconClient('http://127.0.0.1:9000/api/v3')
        response = client.send(payload)

        # the return type should 'dict'
        expected_type = type({})
        self.assertEqual(type(response), expected_type)

        self.assertIsNotNone(response['result'])

        # Incorrect request: input url which is omitted port number
        payload = {"jsonrpc": "2.0", "method": "icx_getTotalSupply", "id": 111}
        client = IconClient('http://127.0.0.1:/api/v3')
        # check get response correctly, don't check the response data
        self.assertRaises(Exception, client.send, payload)

        # Incorrect request: invalid url to working server
        payload = {"jsonrpc": "2.0", "method": "icx_getTotalSupply", "id": 111}
        client = IconClient('http://127.0.0.1:9000/api/invalidUrl')
        # check get response correctly, don't check the response data
        self.assertRaises(IconClientException, client.send, payload)

        # Incorrect request: invalid url to not working service
        payload = {"jsonrpc": "2.0", "method": "icx_getTotalSupply", "id": 111}
        client = IconClient('http://127.0.0.1:19001/api/invalidUrl')
        # check get response correctly, don't check the response data
        self.assertRaises(Exception, client.send, payload)

        # Bad request: invalid payload data (nonexistent method name)
        incorrect_payload = {
            "jsonrpc": "2.0",
            "method": "icx_invalid_requests",
            "id": 111
        }
        client = IconClient('http://127.0.0.1:9000/api/v3')
        response = client.send(incorrect_payload)
        self.assertIsNotNone(response['error'])

        # Bad request: insufficient payload data (method is not set)
        insufficient_payload = {"jsonrpc": "2.0", "id": 111}
        client = IconClient('http://127.0.0.1:9000/api/v3')
        response = client.send(insufficient_payload)
        self.assertIsNotNone(response['error'])

        # requests when server stopped
        self.cmd.cmdServer.stop(self.conf)
        payload = {"jsonrpc": "2.0", "method": "icx_getTotalSupply", "id": 111}
        client = IconClient('http://127.0.0.1:9000/api/v3')
        self.assertRaises(Exception, client.send, payload)

        self.cmd.cmdScore.clear(self.conf)
예제 #14
0
    def deploy(self, conf: dict) -> dict:
        """Deploy SCORE on the server.

        :param conf: deploy command configuration
        """
        if conf['contentType'] == 'tbears' and not CommandServer.is_service_running(
        ):
            raise TBearsCommandException(f'Start tbears service first')

        # check keystore, and get password from user's terminal input
        password = conf.get('password', None)
        password = self._check_deploy(conf, password)

        step_limit = conf.get('stepLimit', "0x1234000")

        if conf['mode'] == 'install':
            score_address = f'cx{"0"*40}'
        else:
            score_address = conf['to']

        if conf['contentType'] == 'zip':
            content_type = "application/zip"
            # make zip and convert to hexadecimal string data(start with 0x) and return
            content = IconJsonrpc.gen_deploy_data_content(conf['project'])
        else:
            content_type = "application/tbears"
            content = os.path.abspath(conf['project'])

        # make IconJsonrpc instance which is used for making request(with signature)
        if conf['keyStore']:
            deploy = IconJsonrpc.from_key_store(keystore=conf['keyStore'],
                                                password=password)
        else:
            deploy = IconJsonrpc.from_string(from_=conf['from'])

        # make JSON-RPC 2.0 request standard format
        request = deploy.sendTransaction(to=score_address,
                                         nid=conf['nid'],
                                         step_limit=step_limit,
                                         data_type="deploy",
                                         data=IconJsonrpc.gen_deploy_data(
                                             params=conf.get(
                                                 'scoreParams', {}),
                                             content_type=content_type,
                                             content=content))

        # send request to rpcserver
        icon_client = IconClient(conf['uri'])
        response = icon_client.send(request)

        if 'error' in response:
            print('Got an error response')
            print(json.dumps(response, indent=4))
        else:
            print('Send deploy request successfully.')
            tx_hash = response['result']
            print(
                f'If you want to check SCORE deployed successfully, execute txresult command'
            )
            print(f"transaction hash: {tx_hash}")

        return response