def create_dummy_block(block_height: int = -1) -> 'Block': block_height: int = block_height if block_height >= 0 else random.randint(100, 10000) block_hash: bytes = os.urandom(32) timestamp_us: int = get_timestamp_us() prev_hash: bytes = os.urandom(32) return Block(block_height, block_hash, timestamp_us, prev_hash)
def context(): ctx = IconScoreContext(IconScoreContextType.DIRECT) block = Block(0, None, 0, None, 0) ctx.block = block ContextContainer._push_context(ctx) yield ctx ContextContainer._pop_context()
def test_commit_change_block_hash(self): block_height = 1 self._to = create_address(AddressPrefix.CONTRACT) instant_block_hash = create_block_hash() block_timestamp = 0 tx_hash = create_tx_hash() dummy_tx = { 'method': 'icx_sendTransaction', 'params': { 'nid': 3, 'version': 3, 'from': self._admin.address, 'to': self._to, 'value': 1 * 10**18, 'stepLimit': 1000000, 'timestamp': 1234567890, 'txHash': tx_hash } } block = Block(block_height, instant_block_hash, block_timestamp, self.genesis_block.hash, 0) self.icon_service_engine.invoke(block, [dummy_tx]) instant_block_hash = block.hash block_hash = create_block_hash() self.icon_service_engine.commit(block.height, instant_block_hash, block_hash) self.assertEqual(self.icon_service_engine._get_last_block().hash, block_hash) self.assertEqual(IconScoreContext.storage.icx.last_block.hash, block_hash)
def _create_iconservice_block(loopchain_block: "LoopchainBlock") -> "Block": return Block( block_height=loopchain_block.height, block_hash=loopchain_block.block_hash, timestamp=loopchain_block.timestamp, prev_hash=loopchain_block.prev_block_hash, )
def setUp(self) -> None: block_height: int = random.randint(1000, 10000) block_hash: bytes = os.urandom(32) prev_block_hash: bytes = os.urandom(32) timestamp_us: int = int(time.time() * 1000_000) cumulative_fee = random.randint(0, 10000) last_block = Block(block_height=block_height, block_hash=block_hash, timestamp=timestamp_us, prev_hash=prev_block_hash, cumulative_fee=cumulative_fee) block_height = last_block.height - 10 block_hash: bytes = os.urandom(32) term_start_block_height = block_height = block_height - 20 last_block: 'Block' = last_block metadata = Metadata(block_height, block_hash, term_start_block_height, last_block) assert metadata.block_height == block_height assert metadata.block_hash == block_hash assert metadata.term_start_block_height == term_start_block_height assert metadata.last_block == last_block self.metadata = metadata self.block_height = block_height self.block_hash = block_hash self.term_start_block_height = term_start_block_height self.last_block = last_block
def make_and_req_block_for_2_depth_invocation( self, tx_list: list, prev_block: 'Block', prev_block_generator: Optional['Address'] = None, prev_block_validators: Optional[List['Address']] = None, prev_block_votes: Optional[List[Tuple['Address', int]]] = None, ) -> Tuple['Block', List[bytes]]: block_height: int = prev_block.height + 1 block_hash = create_block_hash() timestamp_us = create_timestamp() block = Block(block_height, block_hash, timestamp_us, prev_block.hash, 0) context = IconScoreContext(IconScoreContextType.DIRECT) is_block_editable = False if context.is_decentralized(): is_block_editable = True tx_results, state_root_hash, added_transactions, next_preps = \ self.icon_service_engine.invoke(block=block, tx_requests=tx_list, prev_block_generator=prev_block_generator, prev_block_validators=prev_block_validators, prev_block_votes=prev_block_votes, is_block_editable=is_block_editable) self.add_tx_result(tx_results) return block, self.get_hash_list_from_tx_list(tx_list)
def make_and_req_block(self, tx_list: list, block_height: int = None, prev_block_generator: Optional['Address'] = None, prev_block_validators: Optional[List['Address']] = None, prev_block_votes: Optional[List[Tuple['Address', int]]] = None, block_hash: bytes = None) \ -> Tuple['Block', List[bytes]]: if block_height is None: block_height: int = self._block_height + 1 if block_hash is None: block_hash = create_block_hash() timestamp_us = create_timestamp() block = Block(block_height, block_hash, timestamp_us, self._prev_block_hash, 0) context = IconScoreContext(IconScoreContextType.DIRECT) is_block_editable = False self.icon_service_engine._set_revision_to_context(context) if context.is_decentralized(): is_block_editable = True tx_results, state_root_hash, added_transactions, main_prep_as_dict = \ self.icon_service_engine.invoke(block=block, tx_requests=tx_list, prev_block_generator=prev_block_generator, prev_block_validators=prev_block_validators, prev_block_votes=prev_block_votes, is_block_editable=is_block_editable) self.add_tx_result(tx_results) return block, self.get_hash_list_from_tx_list(tx_list)
def _create_invalid_block(self, block_height: int = None) -> 'Block': if block_height is None: block_height: int = self._block_height block_hash = create_block_hash() timestamp_us = create_timestamp() return Block(block_height, block_hash, timestamp_us, self._prev_block_hash, 0)
def _genesis_invoke(self) -> dict: tx_hash = create_tx_hash() timestamp_us = create_timestamp() request_params = { 'txHash': tx_hash, 'version': self._version, 'timestamp': timestamp_us } tx = { 'method': 'icx_sendTransaction', 'params': request_params, 'genesisData': { "accounts": [{ "name": "genesis", "address": self._genesis, "balance": 100 * self._icx_factor }, { "name": "fee_treasury", "address": self._fee_treasury, "balance": 0 }] }, } block_hash = create_block_hash() block = Block(self._block_height, block_hash, timestamp_us, None) invoke_response: dict = self.icon_service_engine.invoke(block, [tx]) self.icon_service_engine.commit(block) self._block_height += 1 self._prev_block_hash = block_hash return invoke_response
def test_invoke_v3_without_fee(self): block_height = 1 block_hash = create_block_hash() block_timestamp = 0 tx_hash = create_tx_hash() value = 1 * 10**18 tx_v3 = { 'method': 'icx_sendTransaction', 'params': { 'version': 3, 'from': self._genesis_address, 'to': self._to, 'value': value, 'stepLimit': 20000, 'timestamp': 1234567890, 'txHash': tx_hash } } block = Block(block_height, block_hash, block_timestamp, self.genesis_block.hash) tx_results, state_root_hash = self._engine.invoke(block, [tx_v3]) self.assertIsInstance(state_root_hash, bytes) self.assertEqual(len(state_root_hash), 32) self.assertEqual(len(tx_results), 1) tx_result: 'TransactionResult' = tx_results[0] self.assertIsNone(tx_result.failure) self.assertIsNone(tx_result.score_address) self.assertEqual(tx_result.status, 1) self.assertEqual(tx_result.block_height, block_height) self.assertEqual(tx_result.block_hash, block_hash) self.assertEqual(tx_result.tx_index, 0) self.assertEqual(tx_result.tx_hash, tx_hash) # step_used MUST BE 10**6 on protocol v2 step_unit = self._engine._step_counter_factory.get_step_cost( StepType.DEFAULT) self.assertEqual(tx_result.step_used, step_unit) step_price = self._engine._get_step_price() if self._engine._is_flag_on(IconServiceFlag.fee): # step_used MUST BE 10**10 on protocol v2 self.assertEqual(step_price, 10**10) else: self.assertEqual(step_price, 0) self.assertEqual(tx_result.step_price, step_price) self._engine.commit(block) # Check whether fee charging works well from_balance: int = \ self._engine._icx_engine.get_balance(None, self.from_) fee = tx_result.step_price * tx_result.step_used self.assertEqual(fee, 0) self.assertEqual(from_balance, self._total_supply - value - fee)
def create_iconservice_block(bin_block: BinBlock) -> Block: return Block( block_height=bin_block.height, block_hash=bin_block.block_hash, timestamp=bin_block.timestamp, prev_hash=bin_block.prev_block_hash, )
def _make_and_req_block_for_issue_test(self, tx_list: list, block_height: int = None, prev_block_generator: Optional['Address'] = None, prev_block_validators: Optional[List['Address']] = None, prev_block_votes: Optional[List[Tuple['Address', int]]] = None, is_block_editable=False, cumulative_fee: int = 0) -> Tuple['Block', List[bytes]]: if block_height is None: block_height: int = self._block_height + 1 block_hash = create_block_hash() timestamp_us = create_timestamp() block = Block(block_height, block_hash, timestamp_us, self._prev_block_hash, cumulative_fee) tx_results, _, added_transactions, main_prep_as_dict = \ self.icon_service_engine.invoke(block=block, tx_requests=tx_list, prev_block_generator=prev_block_generator, prev_block_validators=prev_block_validators, prev_block_votes=prev_block_votes, is_block_editable=is_block_editable) self.add_tx_result(tx_results) return block, self.get_hash_list_from_tx_list(tx_list)
def test_with_genesis_block(self, manager: 'PrecommitDataManager', create_dummy_precommit_data): block_hash = bytes(32) block = Block( block_height=0, timestamp=1234, block_hash=block_hash, prev_hash=None, ) precommit_data = create_dummy_precommit_data(block) # TEST: push # null_block -> genesis_block manager.push(precommit_data) assert manager.last_block == NULL_BLOCK assert len(manager) == 2 # TEST: get # null_block -> genesis_block assert manager.get(block_hash) == precommit_data assert len(manager) == 2 # TEST: commit # genesis_block only manager.commit(block) assert manager.last_block == block assert len(manager) == 1 # TEST clear manager.clear() assert manager.last_block == block assert len(manager) == 1
def test_invoke_v2_without_fee(self): block_height = 1 block_hash = create_block_hash() block_timestamp = 0 tx_hash = create_tx_hash() value = 1 * 10 ** 18 tx_v2 = { 'method': 'icx_sendTransaction', 'params': { 'from': self.from_, 'to': self._to, 'value': value, 'fee': 10 ** 16, 'timestamp': 1234567890, 'txHash': tx_hash } } block = Block(block_height, block_hash, block_timestamp, self.genesis_block.hash, 0) tx_results, state_root_hash, _, _ = self._engine.invoke(block, [tx_v2]) self.assertIsInstance(state_root_hash, bytes) self.assertEqual(len(state_root_hash), 32) self.assertEqual(len(tx_results), 1) tx_result: 'TransactionResult' = tx_results[0] self.assertIsNone(tx_result.failure) self.assertIsNone(tx_result.score_address) self.assertEqual(tx_result.status, 1) self.assertEqual(tx_result.block_height, block_height) self.assertEqual(tx_result.block_hash, block_hash) self.assertEqual(tx_result.tx_index, 0) self.assertEqual(tx_result.tx_hash, tx_hash) # step_used MUST BE 10 ** 6 on protocol v2 self.assertEqual(tx_result.step_used, 10**6) step_price = self._engine._step_counter_factory.get_step_price() # if self._engine._is_flag_on(IconServiceFlag.fee): # # step_used MUST BE 10**10 on protocol v2 # self.assertEqual(step_price, 10 ** 10) # else: # self.assertEqual(step_price, 0) self.assertEqual(tx_result.step_price, step_price) # Write updated states to levelDB self._engine.commit(block.height, block.hash, None) # Check whether fee charging works well context = _create_context(IconScoreContextType.DIRECT) from_balance: int = IconScoreContext.engine.icx.get_balance( context, self.from_) fee = tx_result.step_price * tx_result.step_used self.assertEqual(fee, 0) self.assertEqual(from_balance, self._total_supply - value - fee)
def debug_make_and_req_block(self, tx_list: list, prev_block_generator: Optional['Address'] = None, prev_block_validators: Optional[List['Address']] = None, prev_block_votes: Optional[List[Tuple['Address', int]]] = None, block: 'Block' = None) -> tuple: # Prevent a base transaction from being added to the original tx_list tx_list = copy.copy(tx_list) if block is None: block_height: int = self._block_height + 1 block_hash = create_block_hash() timestamp_us = create_timestamp() block = Block(block_height, block_hash, timestamp_us, self._prev_block_hash, 0) context = IconScoreContext(IconScoreContextType.DIRECT) is_block_editable = False self.icon_service_engine._set_revision_to_context(context) if context.is_decentralized(): is_block_editable = True tx_results, state_root_hash, added_transactions, main_prep_as_dict = \ self.icon_service_engine.invoke(block=block, tx_requests=tx_list, prev_block_generator=prev_block_generator, prev_block_validators=prev_block_validators, prev_block_votes=prev_block_votes, is_block_editable=is_block_editable) return block, tx_results, state_root_hash, added_transactions, main_prep_as_dict
def context(settable_inv_container: INVContainer): prep_engine = PRepEngine() prep_engine.prep_address_converter = mock.Mock() inv_engine = INVEngine() settable_inv_container.set_inv(StepPrice(10**10)) settable_inv_container.set_inv(StepCosts(STEP_COSTS)) settable_inv_container.set_inv( MaxStepLimits({IconScoreContextType.INVOKE: 2_500_000_000})) settable_inv_container.set_inv(RevisionCode(Revision.THREE.value)) inv_engine._inv_container = settable_inv_container IconScoreContext.engine = ContextEngine(prep=prep_engine, inv=inv_engine) context_factory = IconScoreContextFactory() block = Block(block_height=1, block_hash=b"1" * 40, prev_hash=b"0" * 40, timestamp=0) context = context_factory.create(IconScoreContextType.INVOKE, block) step_limit = 1_000_000_000 context.set_step_counter(step_limit) ContextContainer._push_context(context) yield context ContextContainer._pop_context()
def _make_and_req_block(self, tx_list: list, block_height: int = None) -> tuple: if block_height is None: block_height: int = self._block_height block_hash = create_block_hash() timestamp_us = create_timestamp() block = Block(block_height + 1, block_hash, timestamp_us, self._prev_block_hash) tx_results, state_root_hash, added_transactions, main_preps = self.icon_service_engine.invoke( block, tx_list) convert_tx_results = [ tx_result.to_dict(to_camel_case) for tx_result in tx_results ] results = { 'txResults': convert_tx_results, 'stateRootHash': bytes.hex(state_root_hash), 'addedTransactions': added_transactions } if main_preps: results['prep'] = main_preps response = MakeResponse.make_response(results) return block, response
def test_score_invoke_failure_by_readonly_external_call(self): block_height = 1 block_hash = create_block_hash() block_timestamp = 0 tx_hash = create_tx_hash() value = 0 to = self._governance_address step_limit = 200000000 tx_v3 = { 'method': 'icx_sendTransaction', 'params': { 'txHash': tx_hash, 'nid': 3, 'version': 3, 'from': self._admin.address, 'to': to, 'value': value, 'stepLimit': step_limit, 'timestamp': 1234567890, 'dataType': 'call', 'data': { 'method': 'getScoreStatus', 'params': { 'txHash': tx_hash } }, 'signature': 'VAia7YZ2Ji6igKWzjR2YsGa2m53nKPrfK7uXYW78QLE+ATehAVZPC40szvAiA6NEU5gCYB4c4qaQzqDh2ugcHgA=' } } block = Block(block_height, block_hash, block_timestamp, self.genesis_block.hash, 0) tx_results, state_root_hash, _, _, is_shutdown = self.icon_service_engine.invoke( block, [tx_v3]) self.assertIsInstance(state_root_hash, bytes) self.assertEqual(len(state_root_hash), 32) self.assertFalse(is_shutdown) self.assertEqual(len(tx_results), 1) tx_result: 'TransactionResult' = tx_results[0] self.assertIsNotNone(tx_result.failure) self.assertIsNone(tx_result.score_address) self.assertEqual(tx_result.status, 0) self.assertEqual(tx_result.block_height, block_height) self.assertEqual(tx_result.block_hash, block_hash) self.assertEqual(tx_result.tx_index, 0) self.assertEqual(tx_result.tx_hash, tx_hash)
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_block_to_str(self): block = Block(1, create_block_hash(), 100, create_block_hash()) self.assertEqual( f'height({block.height}) hash(0x{bytes.hex(block.hash)}) ' f'timestamp({block.timestamp}) prev_hash(0x{bytes.hex(block.prev_hash)})', str(block))
def setUp(self): self._state_db_root_path = '.db' self._score_root_path = '.score' rmtree(self._score_root_path) rmtree(self._state_db_root_path) engine = IconServiceEngine() conf = IconConfig("", default_icon_config) conf.load() conf.update_conf({ ConfigKey.BUILTIN_SCORE_OWNER: str(create_address(AddressPrefix.EOA)), ConfigKey.SCORE_ROOT_PATH: self._score_root_path, ConfigKey.STATE_DB_ROOT_PATH: self._state_db_root_path }) # engine._load_builtin_scores = Mock() # engine._init_global_value_by_governance_score = Mock() engine.open(conf) self._engine = engine self._genesis_address = create_address(AddressPrefix.EOA) self._treasury_address = create_address(AddressPrefix.EOA) self._governance_score_address =\ Address.from_string('cx0000000000000000000000000000000000000001') self.from_ = self._genesis_address self._to = create_address(AddressPrefix.EOA) self._icon_score_address = create_address(AddressPrefix.CONTRACT) self._total_supply = 100 * 10**18 accounts = [{ 'name': 'god', 'address': self._genesis_address, 'balance': self._total_supply }, { 'name': 'treasury', 'address': self._treasury_address, 'balance': 0 }] block = Block(0, create_block_hash(), 0, None) tx = { 'method': '', 'params': { 'txHash': create_tx_hash() }, 'genesisData': { 'accounts': accounts } } tx_lists = [tx] self._engine.invoke(block, tx_lists) self._engine.commit(block) self.genesis_block = block
def test_invoke_v2_with_zero_fee_and_malformed_to_address(self): block_height = 1 block_hash = create_block_hash() block_timestamp = 0 tx_hash = create_tx_hash() value = 1 * 10 ** 18 to = MalformedAddress.from_string('') fixed_fee: int = 10 ** 16 tx_v2 = { 'method': 'icx_sendTransaction', 'params': { 'from': self.from_, 'to': to, 'value': value, 'fee': fixed_fee, 'timestamp': 1234567890, 'txHash': tx_hash } } block = Block(block_height, block_hash, block_timestamp, self.genesis_block.hash) tx_results, state_root_hash = self._engine.invoke(block, [tx_v2]) self.assertIsInstance(state_root_hash, bytes) self.assertEqual(len(state_root_hash), 32) self.assertEqual(len(tx_results), 1) tx_result: 'TransactionResult' = tx_results[0] self.assertIsNone(tx_result.failure) self.assertIsNone(tx_result.score_address) self.assertEqual(tx_result.status, 1) self.assertEqual(tx_result.block_height, block_height) self.assertEqual(tx_result.block_hash, block_hash) self.assertEqual(tx_result.tx_index, 0) self.assertEqual(tx_result.tx_hash, tx_hash) # step_used MUST BE 10**6 on protocol v2 self.assertEqual(tx_result.step_used, 10**6) step_price = self._engine._step_counter_factory.get_step_price() self.assertEqual(tx_result.step_price, step_price) # Write updated states to levelDB self._engine.commit(block) # Check whether fee charging works well from_balance: int = self._engine._icx_engine.get_balance( None, self.from_) to_balance: int = self._engine._icx_engine.get_balance(None, to) fee = tx_result.step_price * tx_result.step_used self.assertEqual(0, fee) self.assertEqual(value, to_balance) self.assertEqual(from_balance, self._total_supply - value - fee)
def _create_context() -> 'IconScoreContext': context_factory = IconScoreContextFactory() block = Block(block_height=100, block_hash=os.urandom(32), timestamp=0, prev_hash=os.urandom(32), cumulative_fee=0) return context_factory.create(IconScoreContextType.INVOKE, block)
def test_instant_block_hash_compatibility(self): # success case: when icon service version is under 1.3.0 (these versions only get instant block hash) # define mocked commit method def prev_commit(obj, block: 'Block'): assert isinstance(obj, IconServiceEngine) assert isinstance(block, Block) IconServiceEngine.commit = prev_commit icon_integrate_test_base = IconIntegrateTestBase() icon_integrate_test_base.setUpClass() icon_integrate_test_base.setUp() instant_block = Block(block_height=1, block_hash=create_block_hash(), timestamp=create_timestamp(), prev_hash=create_block_hash(), cumulative_fee=0) icon_integrate_test_base._write_precommit_state(instant_block) icon_integrate_test_base.tearDown() # success case: when icon service version is 1.3.0 and more # (these versions get instant block hash and new block hash) # define mocked commit method def new_commit(obj, block_height: int, instant_block_hash: bytes, block_hash: Optional[bytes]): assert isinstance(obj, IconServiceEngine) assert isinstance(block_height, int) assert isinstance(instant_block_hash, bytes) assert isinstance(block_hash, bytes) IconServiceEngine.commit = new_commit icon_integrate_test_base = IconIntegrateTestBase() icon_integrate_test_base.setUpClass() icon_integrate_test_base.setUp() instant_block = Block(block_height=1, block_hash=create_block_hash(), timestamp=create_timestamp(), prev_hash=create_block_hash(), cumulative_fee=0) icon_integrate_test_base._write_precommit_state(instant_block) icon_integrate_test_base.tearDown()
def _genesis_invoke(self) -> list: tx_hash = create_tx_hash() timestamp_us = create_timestamp() request_params = { 'txHash': tx_hash, 'version': self._version, 'timestamp': timestamp_us } tx = { 'method': 'icx_sendTransaction', 'params': request_params, 'genesisData': { "accounts": [ { "name": "genesis", "address": self.genesis, "balance": 100 * self._icx_factor }, { "name": "fee_treasury", "address": self._fee_treasury, "balance": 0 }, { "name": "owner1", "address": self.owner1, "balance": 100 * self._icx_factor }, { "name": "owner2", "address": self.owner2, "balance": 100 * self._icx_factor }, { "name": "owner3", "address": self.owner3, "balance": 100 * self._icx_factor }, ] }, } block_hash = create_block_hash() block = Block(self._block_height, block_hash, timestamp_us, None) invoke_response, state_root_hash, added_transactions, next_preps = \ self.icon_service_engine.invoke(block=block, tx_requests=[tx]) self.icon_service_engine.commit(block.height, block.hash, None) self._block_height += 1 self._prev_block_hash = block_hash return invoke_response
def test_commit(self): block = Block(block_height=1, block_hash=create_block_hash(), timestamp=0, prev_hash=create_block_hash()) with self.assertRaises(ServerErrorException) as cm: self._engine.commit(block) e = cm.exception self.assertEqual(ExceptionCode.SERVER_ERROR, e.code) self.assertTrue(e.message.startswith('No precommit data'))
def setUp(self): self.block_hash: bytes = create_hash_256() self.prev_block_hash: bytes = create_hash_256() block = Block( block_height=10, block_hash=self.block_hash, timestamp=0, prev_hash=self.prev_block_hash) self.block_batch = BlockBatch(block)
def _create_base_transaction(self): context = IconScoreContext(IconScoreContextType.DIRECT) context._preps = context.engine.prep.preps.copy(mutable=True) context._term = context.engine.prep.term.copy() block_height: int = self._block_height block_hash = create_block_hash() timestamp_us = create_timestamp() block = Block(block_height, block_hash, timestamp_us, self._prev_block_hash, 0) context.block = block transaction = BaseTransactionCreator.create_base_transaction(context) return transaction
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.index = 1234 self._mock_context.tx.hash = hashlib.sha256(b'hash').digest() self._icon_service_engine._icon_score_deploy_engine.attach_mock( Mock(return_value=False), 'is_data_type_supported') tx_result = self._icon_service_engine._handle_icx_send_transaction( self._mock_context, {'from': from_, 'to': to_}) tx_result.score_address = \ Address.from_data(AddressPrefix.CONTRACT, b'score_address') 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.sha256(b'block').digest(), 1, None) 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_rollback(self): block = Block(block_height=1, block_hash=create_block_hash(), timestamp=0, prev_hash=self.genesis_block.hash) block_result, state_root_hash = self._engine.invoke(block, []) self.assertIsInstance(block_result, list) self.assertEqual(state_root_hash, hashlib.sha3_256(b'').digest()) self._engine.rollback(block) self.assertIsNone(self._engine._precommit_data_manager.get(block))