def test_install_result(self): IconScoreContext.engine.deploy.invoke = Mock() from_ = Address(AddressPrefix.EOA, os.urandom(20)) to_ = Address(AddressPrefix.EOA, os.urandom(20)) self._mock_context.tx = Transaction(os.urandom(32), 0, from_, to_, 0) self._mock_context.msg = Message(from_) tx_result = self._icon_service_engine._handle_icx_send_transaction( self._mock_context, { 'version': 3, 'from': from_, 'to': ZERO_SCORE_ADDRESS, 'dataType': 'deploy', 'timestamp': 0, 'data': { 'contentType': 'application/tbears', 'content': '/home/haha' } }) self._icon_service_engine._charge_transaction_fee.assert_called() self.assertEqual(1, tx_result.status) self.assertEqual(0, tx_result.tx_index) self.assertEqual(ZERO_SCORE_ADDRESS, tx_result.to) self.assertIsNotNone(tx_result.score_address) camel_dict = tx_result.to_dict(to_camel_case) self.assertNotIn('failure', camel_dict)
def test_tx_success(self): from_ = Address.from_data(AddressPrefix.EOA, os.urandom(20)) to_ = Address.from_data(AddressPrefix.EOA, os.urandom(20)) tx_index = randrange(0, 100) self._mock_context.tx = Transaction(os.urandom(32), tx_index, from_, to_, 0) self._mock_context.msg = Message(from_) params = { 'version': 3, 'from': from_, 'to': to_, 'value': 0, 'timestamp': 1234567890, 'nonce': 1 } self._icon_service_engine._process_transaction = Mock( return_value=None) tx_result = self._icon_service_engine._handle_icx_send_transaction( self._mock_context, params) self._icon_service_engine._charge_transaction_fee.assert_called() self.assertEqual(1, tx_result.status) self.assertEqual(tx_index, tx_result.tx_index) self.assertEqual(to_, tx_result.to) self.assertIsNone(tx_result.score_address) camel_dict = tx_result.to_dict(to_camel_case) self.assertNotIn('failure', camel_dict) self.assertNotIn('scoreAddress', camel_dict)
def test_tx_failure(self, score_invoke): score_invoke.side_effect = Mock( side_effect=InvalidParamsException("error")) from_ = Address.from_data(AddressPrefix.EOA, os.urandom(20)) to_ = Address.from_data(AddressPrefix.CONTRACT, os.urandom(20)) tx_index = randrange(0, 100) self._mock_context.tx = Transaction(os.urandom(32), tx_index, from_, to_, 0) self._mock_context.msg = Message(from_) self._mock_context.tx_batch = TransactionBatch() raise_exception_start_tag("test_tx_failure") tx_result = self._icon_service_engine._handle_icx_send_transaction( self._mock_context, { 'from': from_, 'to': to_ }) raise_exception_end_tag("test_tx_failure") self._icon_service_engine._charge_transaction_fee.assert_called() self.assertEqual(0, tx_result.status) self.assertEqual(tx_index, tx_result.tx_index) self.assertIsNone(tx_result.score_address) camel_dict = tx_result.to_dict(to_camel_case) self.assertNotIn('scoreAddress', camel_dict)
def test_sample_result(self): from_ = Address.from_data(AddressPrefix.EOA, b'from') to_ = Address.from_data(AddressPrefix.CONTRACT, b'to') self._mock_context.tx = Transaction(os.urandom(32), 1234, from_, to_, 0) self._mock_context.msg = Message(from_) IconScoreContext.engine.deploy.invoke = Mock() self._icon_service_engine._process_transaction = Mock(return_value=to_) tx_result = self._icon_service_engine._handle_icx_send_transaction( self._mock_context, { 'from': from_, 'to': to_ }) tx_result.score_address = to_ tx_result.event_logs = [ EventLog( Address.from_data(AddressPrefix.CONTRACT, b'addr_to'), [b'indexed', Address.from_data(AddressPrefix.EOA, b'index')], [True, 1234, 'str', None, b'test']) ] tx_result.logs_bloom = BloomFilter() tx_result.logs_bloom.add(b'1') tx_result.logs_bloom.add(b'2') tx_result.logs_bloom.add(b'3') tx_result.block = Block(123, hashlib.sha3_256(b'block').digest(), 1, None, 0) camel_dict = tx_result.to_dict(to_camel_case) self.assertIn('txHash', camel_dict) self.assertIn('blockHeight', camel_dict) self.assertIn('txIndex', camel_dict) self.assertIn('to', camel_dict) self.assertIn('scoreAddress', camel_dict) self.assertIn('stepUsed', camel_dict) self.assertIn('stepPrice', camel_dict) self.assertIn('eventLogs', camel_dict) self.assertIn('logsBloom', camel_dict) self.assertIn('status', camel_dict) self.assertEqual(1, len(camel_dict['eventLogs'])) self.assertIn('scoreAddress', camel_dict['eventLogs'][0]) self.assertIn('indexed', camel_dict['eventLogs'][0]) self.assertIn('data', camel_dict['eventLogs'][0]) self.assertEqual(256, len(camel_dict['logsBloom'])) converted_result = TypeConverter.convert_type_reverse(camel_dict) self.assertFalse(converted_result['txHash'].startswith('0x')) self.assertTrue(converted_result['blockHeight'].startswith('0x')) self.assertTrue(converted_result['txIndex'].startswith('0x')) self.assertTrue(converted_result['to'].startswith('cx')) self.assertTrue(converted_result['scoreAddress'].startswith('cx')) self.assertTrue(converted_result['stepUsed'].startswith('0x')) self.assertTrue(converted_result['logsBloom'].startswith('0x')) self.assertTrue(converted_result['status'].startswith('0x'))
def test_revert(self, mocker): mocker.patch.object(IconServiceEngine, "_charge_transaction_fee") mocker.patch.object(IconScoreEngine, "invoke") context = ContextContainer._get_context() icon_service_engine = IconServiceEngine() icon_service_engine._icx_engine = Mock(spec=IcxEngine) icon_service_engine._icon_score_deploy_engine = \ Mock(spec=DeployEngine) icon_service_engine._icon_pre_validator = Mock(spec=IconPreValidator) context.tx_batch = TransactionBatch() context.clear_batch = Mock() context.update_batch = Mock() from_ = Address.from_data(AddressPrefix.EOA, os.urandom(20)) to_ = Address.from_data(AddressPrefix.CONTRACT, os.urandom(20)) tx_index = randrange(0, 100) context.tx = Transaction(os.urandom(32), tx_index, from_, 0) context.msg = Message(from_) def intercept_charge_transaction_fee(*args, **kwargs): return {}, Mock(spec=int) IconServiceEngine._charge_transaction_fee.side_effect = \ intercept_charge_transaction_fee icon_service_engine._icon_score_deploy_engine.attach_mock( Mock(return_value=False), 'is_data_type_supported') reason = Mock(spec=str) code = ExceptionCode.SCORE_ERROR mock_revert = Mock(side_effect=IconScoreException(reason)) IconScoreEngine.invoke.side_effect = mock_revert raise_exception_start_tag("test_revert") tx_result = icon_service_engine._handle_icx_send_transaction( context, { 'version': 3, 'from': from_, 'to': to_ }) raise_exception_end_tag("test_revert") assert tx_result.status == 0 IconServiceEngine._charge_transaction_fee.assert_called() context.traces.append.assert_called() trace = context.traces.append.call_args[0][0] assert trace.trace == TraceType.REVERT assert trace.data[0] == code assert trace.data[1] == reason
def get_default_context(): context = IconScoreContext() block = Block() context.block = block context.icon_score_mapper = score_mapper context.traces = [] context.validate_score_blacklist = Mock(return_value=True) context.tx = Transaction() context.msg = Message() context.get_icon_score = get_icon_score context.block_batch = None context.tx_batch = None return context
def make_context(self): self._tx_index += 1 self._context = self._factory.create(IconScoreContextType.DIRECT) self._context.msg = Message(self.from_address, 0) tx_hash = create_tx_hash() self._context.new_icon_score_mapper = IconScoreMapper() self._context.tx = Transaction(tx_hash, origin=self.from_address) self._context.block = Block(1, create_block_hash(), 0, None) self._context.icon_score_mapper = self._icon_score_mapper self._context.icx = IcxEngine() self._context.icx.open(self._icx_storage) ContextContainer._push_context(self._context) self._context.validate_deployer = Mock() self._context.validate_score_blacklist = Mock()
def make_context(self): self._tx_index += 1 self._context = self._factory.create(IconScoreContextType.DIRECT) self._context.msg = Message(self._addr1, 0) self._context.tx = Transaction(create_tx_hash(), origin=self._addr1) self._context.block = Block(1, create_block_hash(), 0, None) self._context.icon_score_mapper = self._icon_score_mapper self._context.icx = IcxEngine() self.__step_counter_factory = IconScoreStepCounterFactory() self._step_counter: IconScoreStepCounter = \ self.__step_counter_factory.create(100) self._context.step_counter = self._step_counter self._context.icx.open(self._icx_storage) self._context.event_logs = Mock(spec=list) self._context.traces = Mock(spec=list)
def test_throw(self, score_invoke, IconServiceEngine_charge_transaction_fee): context = ContextContainer._get_context() self._icon_service_engine = IconServiceEngine() self._icon_service_engine._icx_engine = Mock(spec=IcxEngine) self._icon_service_engine._icon_score_deploy_engine = \ Mock(spec=DeployEngine) self._icon_service_engine._icon_pre_validator = Mock( spec=IconPreValidator) context.tx_batch = TransactionBatch() context.clear_batch = Mock() context.update_batch = Mock() from_ = Address.from_data(AddressPrefix.EOA, os.urandom(20)) to_ = Address.from_data(AddressPrefix.CONTRACT, os.urandom(20)) tx_index = randrange(0, 100) context.tx = Transaction(os.urandom(32), tx_index, from_, 0) context.msg = Message(from_) def intercept_charge_transaction_fee(*args, **kwargs): return {}, Mock(spec=int) IconServiceEngine_charge_transaction_fee.side_effect = \ intercept_charge_transaction_fee self._icon_service_engine._icon_score_deploy_engine.attach_mock( Mock(return_value=False), 'is_data_type_supported') error = Mock(spec=str) code = ExceptionCode.INVALID_PARAMETER mock_exception = Mock(side_effect=InvalidParamsException(error)) score_invoke.side_effect = mock_exception raise_exception_start_tag("test_throw") tx_result = self._icon_service_engine._handle_icx_send_transaction( context, {'version': 3, 'from': from_, 'to': to_}) raise_exception_end_tag("test_throw") self.assertEqual(0, tx_result.status) IconServiceEngine_charge_transaction_fee.assert_called() context.traces.append.assert_called() trace = context.traces.append.call_args[0][0] self.assertEqual(TraceType.THROW, trace.trace) self.assertEqual(code, trace.data[0]) self.assertEqual(error, trace.data[1])
def context(): ctx = IconScoreContext(IconScoreContextType.DIRECT) ctx.tx = Transaction(tx_hash=create_tx_hash(), origin=EOA1) ctx.block = Block(block_height=0, block_hash=create_block_hash(), timestamp=0, prev_hash=None) ctx.msg = Message(sender=EOA1, value=0) ctx.icon_score_mapper = IconScoreMapper() ctx.new_icon_score_mapper = {} ctx.step_counter = IconScoreStepCounter(1, {}, 1000, False) ctx.event_logs = [] ctx.traces = [] ctx.current_address = EOA1 IconScoreContext.storage = ContextStorage(deploy=Mock(spec=Storage), fee=None, icx=None, iiss=None, prep=None, issue=None, meta=None, rc=None, inv=None) ContextContainer._push_context(ctx) yield ctx ContextContainer._pop_context()
def test_score_invoke_failure(self): tx_hash = create_tx_hash() method = 'icx_sendTransaction' params = { 'from': self.from_, 'to': self._icon_score_address, 'value': 0, 'fee': 10**16, 'timestamp': 1234567890, 'txHash': tx_hash, 'dataType': 'call', 'data': { 'method': 'transfer', 'params': { 'to': self._to, 'value': 777 } } } context = _create_context(IconScoreContextType.INVOKE) context.tx = Transaction(tx_hash=params['txHash'], origin=params['from'], index=0, timestamp=params['timestamp'], nonce=params.get('nonce', None)) context.block = Mock(spec=Block) context.msg = Message(sender=params['from'], value=params['value']) context.cumulative_step_used = Mock(spec=int) context.cumulative_step_used.attach_mock(Mock(), '__add__') context.step_counter = Mock(spec=IconScoreStepCounter) context.event_logs = Mock(spec=list) context.logs_bloom = Mock(spec=BloomFilter) context.traces = Mock(spec=list) raise_exception_start_tag("test_score_invoke_failure") tx_result = self._engine._call(context, method, params) raise_exception_end_tag("test_score_invoke_failure") self.assertTrue(isinstance(tx_result, TransactionResult)) self.assertEqual(TransactionResult.FAILURE, tx_result.status) self.assertEqual(self._icon_score_address, tx_result.to) self.assertEqual(tx_hash, tx_result.tx_hash) self.assertIsNone(tx_result.score_address) context.traces.append.assert_called() context_factory.destroy(context)
def setUp(self): rmtree(self._ROOT_SCORE_PATH) rmtree(self._TEST_DB_PATH) archive_path = 'tests/sample/valid.zip' archive_path = os.path.join(TEST_ROOT_PATH, archive_path) zip_bytes = self.read_zipfile_as_byte(archive_path) install_path = os.path.join(TEST_ROOT_PATH, self._ROOT_SCORE_PATH) self.__unpack_zip_file(install_path, zip_bytes) db_path = os.path.join(TEST_ROOT_PATH, self._TEST_DB_PATH) ContextDatabaseFactory.open( db_path, ContextDatabaseFactory.Mode.SINGLE_DB) self.__ensure_dir(db_path) icx_db = ContextDatabaseFactory.create_by_name('icx_db') self.icx_storage = IcxStorage(icx_db) deploy_storage = IconScoreDeployStorage(self.icx_storage.db) deploy_engine = IconScoreDeployEngine() deploy_engine.open(self._ROOT_SCORE_PATH, 0, deploy_storage) IconScoreContext.icon_score_manager = IconScoreManager(deploy_engine) self.icon_score_loader = IconScoreLoader(self._ROOT_SCORE_PATH, 0) IconScoreMapper.icon_score_loader = self.icon_score_loader IconScoreMapper.deploy_storage = deploy_storage self.icon_score_mapper = IconScoreMapper() self.engine = IconScoreEngine() self.engine.open( self.icx_storage, self.icon_score_mapper) self._from = create_address(AddressPrefix.EOA) self._icon_score_address = create_address(AddressPrefix.CONTRACT) self.factory = IconScoreContextFactory(max_size=1) IconScoreContext.icon_score_mapper = self.icon_score_mapper self._context = self.factory.create(IconScoreContextType.DIRECT) self._context.msg = Message(self._from, 0) tx_hash = create_tx_hash() self._context.tx = Transaction( tx_hash, origin=create_address(AddressPrefix.EOA)) block_hash = create_block_hash() self._context.block = Block(1, block_hash, 0, None)
def make_context(self): self._tx_index += 1 self._context = IconScoreContext(IconScoreContextType.DIRECT) self._context.msg = Message(self.from_address, 0) tx_hash = create_tx_hash() self._context.new_icon_score_mapper = IconScoreMapper() self._context.tx = Transaction(tx_hash, origin=self.from_address, timestamp=randrange(1, 1000), nonce=randrange(1, 1000)) self._context.block = Block(1, create_block_hash(), 0, None, 0) self._context.icon_score_mapper = self._icon_score_mapper self._context.icx = IcxEngine() self._context.icx.open(self._icx_storage) ContextContainer._push_context(self._context) self._context.validate_score_blacklist = Mock() self._context.is_service_flag_on = Mock(return_value=False)
def test_call_on_invoke(self, get_service_flag): context = _create_context(IconScoreContextType.INVOKE) from_ = self._genesis_address to = self._to value = 1 * 10 ** 18 # 1 coin fee = 10 ** 16 # 0.01 coin method = 'icx_sendTransaction' params = { 'from': from_, 'to': to, 'value': value, 'fee': fee, 'timestamp': 1234567890, 'txHash': create_tx_hash() } step_limit: int = params.get('stepLimit', 0) if params.get('version', 2) < 3: step_limit = self._engine._step_counter_factory.get_max_step_limit( context.type) context.tx = Transaction(tx_hash=params['txHash'], index=0, origin=from_, timestamp=params['timestamp'], nonce=params.get('nonce', None)) context.msg = Message(from_) context.block = Mock(spec=Block) context.event_logs = [] context.step_counter: IconScoreStepCounter = \ self._engine._step_counter_factory.create(context.type) context.step_counter.reset(step_limit) get_service_flag.return_value = 0 self._engine._call(context, method, params) # from(genesis), to # no transfer to fee_treasury because fee charging is disabled tx_batch = context.tx_batch self.assertEqual(2, len(tx_batch))
def setUp(self): self._icon_service_engine = generate_service_engine() self._icon_service_engine._charge_transaction_fee = \ Mock(return_value=({}, 0)) IconScoreContext.engine.iiss.open = Mock() self._icon_service_engine._icon_pre_validator = \ Mock(spec=IconPreValidator) self._mock_context = IconScoreContext(IconScoreContextType.INVOKE) self._mock_context.tx = Transaction() self._mock_context.msg = Message() self._mock_context.block = Mock(spec=Block) self._mock_context.event_logs = [] self._mock_context.traces = [] self._mock_context._inv_container = IconScoreContext.engine.inv.inv_container.copy() self._mock_context.set_step_counter() self._mock_context.current_address = Mock(spec=Address)
def setUp(self): rmtree(self._SCORE_ROOT_PATH) rmtree(self._TEST_DB_PATH) archive_path = 'tests/sample/normal_score.zip' archive_path = os.path.join(TEST_ROOT_PATH, archive_path) zip_bytes = self.read_zipfile_as_byte(archive_path) install_path = os.path.join(TEST_ROOT_PATH, self._SCORE_ROOT_PATH) self.__unpack_zip_file(install_path, zip_bytes) db_path = os.path.join(TEST_ROOT_PATH, self._TEST_DB_PATH) ContextDatabaseFactory.open(db_path, ContextDatabaseFactory.Mode.SINGLE_DB) self.__ensure_dir(db_path) icx_db = ContextDatabaseFactory.create_by_name('icx_db') self.icx_storage = IcxStorage(icx_db) deploy_storage = IconScoreDeployStorage(self.icx_storage.db) deploy_engine = IconScoreDeployEngine() deploy_engine.open(deploy_storage) IconScoreClassLoader.init(self._SCORE_ROOT_PATH) IconScoreMapper.deploy_storage = deploy_storage self.icon_score_mapper = IconScoreMapper() self.engine = IconScoreEngine() # Use mock to prevent an exception from IconScoreEngine._validate_score_blacklist(). IconScoreEngine._validate_score_blacklist = mock.Mock() self._from = create_address(AddressPrefix.EOA) self._icon_score_address = create_address(AddressPrefix.CONTRACT) IconScoreContext.icon_score_deploy_engine = deploy_engine self._context = IconScoreContext(IconScoreContextType.DIRECT) self._context.msg = Message(self._from, 0) tx_hash = create_tx_hash() self._context.tx = Transaction(tx_hash, origin=create_address( AddressPrefix.EOA)) block_hash = create_block_hash() self._context.block = Block(1, block_hash, 0, None)
def test_call_on_invoke(self): context = _create_context(IconScoreContextType.INVOKE) from_ = self._genesis_address to = self._to value = 1 * 10**18 # 1 coin fee = 10**16 # 0.01 coin method = 'icx_sendTransaction' params = { 'from': from_, 'to': to, 'value': value, 'fee': fee, 'timestamp': 1234567890, 'txHash': create_tx_hash() } step_limit: int = params.get('stepLimit', 0) if params.get('version', 2) < 3: step_limit = self._engine._step_counter_factory.get_max_step_limit( context.type) context.tx = Transaction(tx_hash=params['txHash'], index=0, origin=from_, timestamp=params['timestamp'], nonce=params.get('nonce', None)) context.block = Mock(spec=Block) context.cumulative_step_used = Mock(spec=int) context.cumulative_step_used.attach_mock(Mock(), '__add__') context.step_counter: IconScoreStepCounter = self._engine. \ _step_counter_factory.create(step_limit) self._engine._call(context, method, params) # from(genesis), to # no transfer to fee_treasury because fee charging is disabled tx_batch = context.tx_batch self.assertEqual(2, len(tx_batch)) context_factory.destroy(context)
def get_default_context(): mock_context = Mock(spec=IconScoreContext) mock_context.configure_mock(msg=Message()) mock_context.configure_mock(tx=Transaction()) mock_context.configure_mock(block=Block()) mock_context.configure_mock(step_counter=None) mock_context.configure_mock(type=IconScoreContextType.QUERY) mock_context.configure_mock(func_type=IconScoreFuncType.WRITABLE) mock_context.configure_mock(current_address=None) mock_context.configure_mock(block_batch=None) mock_context.configure_mock(tx_batch=None) mock_context.configure_mock(event_logs=None) mock_context.configure_mock(event_log_stack=[]) mock_context.configure_mock(traces=[]) mock_context.configure_mock(icon_score_mapper=score_mapper) mock_context.configure_mock(revision=MAIN_NET_REVISION) mock_context.icon_score_mapper = score_mapper mock_context.validate_score_blacklist = Mock(return_value=True) mock_context.get_icon_score = get_icon_score return mock_context
def setUp(self): block_hash = create_block_hash() tx_hash = create_tx_hash() tx_index = 0 to = create_address(AddressPrefix.EOA) tx = Transaction(tx_hash, tx_index) block = Block(block_height=0, block_hash=block_hash, timestamp=0x1234567890, prev_hash=None) tx_result = TransactionResult(tx=tx, block=block, to=to) tx_result.event_logs = [] tx_result.failure = TransactionResult.Failure( code=ExceptionCode.SERVER_ERROR, message=str('Server error')) self.tx_result = tx_result
def setUp(self): self._icon_service_engine = generate_service_engine() self._icon_service_engine._charge_transaction_fee = \ Mock(return_value=({}, 0)) IconScoreContext.engine.iiss.open = Mock() step_counter_factory = IconScoreStepCounterFactory() step_counter_factory.get_step_cost = Mock(return_value=6000) self._icon_service_engine._step_counter_factory = step_counter_factory self._icon_service_engine._icon_pre_validator = \ Mock(spec=IconPreValidator) self._mock_context = IconScoreContext(IconScoreContextType.INVOKE) self._mock_context.tx = Transaction() self._mock_context.msg = Message() self._mock_context.block = Mock(spec=Block) self._mock_context.event_logs = [] self._mock_context.traces = [] self._mock_context.step_counter = step_counter_factory.create( IconScoreContextType.INVOKE) self._mock_context.current_address = Mock(spec=Address) self._mock_context.revision = 0