Пример #1
0
    def _test_block_from_bytes_to_bytes_msg_pack(self, block_hash: bytes, prev_block_hash: Optional[bytes]):
        revision = Revision.IISS.value
        cumulative_fee = 10
        block1 = Block(1, block_hash, 100, prev_block_hash, cumulative_fee)
        data = Block.to_bytes(block1, revision)
        self.assertTrue(isinstance(data, bytes))

        block2 = Block.from_bytes(data)
        self.assertEqual(block2.height, 1)
        self.assertEqual(block2.hash, block_hash)
        self.assertEqual(block2.timestamp, 100)
        self.assertEqual(block2.prev_hash, prev_block_hash)
        self.assertEqual(block2.cumulative_fee, cumulative_fee)
Пример #2
0
def _test_block_from_bytes_to_bytes_msg_pack(block_hash: bytes,
                                             prev_block_hash: Optional[bytes]):
    revision = Revision.IISS.value
    cumulative_fee = 10
    block1 = Block(1, block_hash, 100, prev_block_hash, cumulative_fee)
    data = Block.to_bytes(block1, revision)
    assert isinstance(data, bytes)

    block2 = Block.from_bytes(data)
    assert block2.height == 1
    assert block2.hash == block_hash
    assert block2.timestamp == 100
    assert block2.prev_hash == prev_block_hash
    assert block2.cumulative_fee == cumulative_fee
Пример #3
0
    def _test_block_from_bytes_to_bytes_struct(self, block_hash: bytes, prev_block_hash: Optional[bytes]):
        revision = 0
        cumulative_fee = 10
        block1 = Block(1, block_hash, 100, prev_block_hash, cumulative_fee)
        data = Block.to_bytes(block1, revision)
        self.assertTrue(isinstance(data, bytes))
        self.assertEqual(1 + DEFAULT_BYTE_SIZE + DEFAULT_BYTE_SIZE + DEFAULT_BYTE_SIZE + DEFAULT_BYTE_SIZE, len(data))

        block2 = Block.from_bytes(data)
        self.assertEqual(block2.height, 1)
        self.assertEqual(block2.hash, block_hash)
        self.assertEqual(block2.timestamp, 100)
        self.assertEqual(block2.prev_hash, prev_block_hash)
        # as cumulative fee is not recorded, result should be zero (not 10)
        self.assertEqual(block2.cumulative_fee, 0)
Пример #4
0
    def _test_Block_from_bytes_to_bytes(self, block_hash: bytes,
                                        prev_block_hash: Optional[bytes]):
        block1 = Block(1, block_hash, 100, prev_block_hash)
        data = Block.to_bytes(block1)
        self.assertEqual(bytes(block1), data)
        self.assertTrue(isinstance(data, bytes))
        self.assertEqual(
            1 + DEFAULT_BYTE_SIZE + DEFAULT_BYTE_SIZE + DEFAULT_BYTE_SIZE +
            DEFAULT_BYTE_SIZE, len(data))

        block2 = Block.from_bytes(data)
        self.assertEqual(block2.height, 1)
        self.assertEqual(block2.hash, block_hash)
        self.assertEqual(block2.timestamp, 100)
        self.assertEqual(block2.prev_hash, prev_block_hash)
Пример #5
0
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()
Пример #6
0
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)
Пример #7
0
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_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)
Пример #9
0
    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)
Пример #10
0
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 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
Пример #12
0
    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)
Пример #13
0
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,
    )
Пример #14
0
    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)
Пример #15
0
    def _invoke(self, request: dict):
        """Process transactions in a block

        :param request:
        :return:
        """

        response = None
        try:
            params = TypeConverter.convert(request, ParamType.INVOKE)
            converted_block_params = params['block']
            block = Block.from_dict(converted_block_params)

            converted_tx_requests = params['transactions']
            tx_results, state_root_hash = self._icon_service_engine.invoke(
                block=block, tx_requests=converted_tx_requests)

            convert_tx_results = \
                {bytes.hex(tx_result.tx_hash): tx_result.to_dict(to_camel_case) for tx_result in tx_results}
            results = {
                'txResults': convert_tx_results,
                'stateRootHash': bytes.hex(state_root_hash)
            }
            response = MakeResponse.make_response(results)
        except IconServiceBaseException as icon_e:
            self._log_exception(icon_e, ICON_SERVICE_LOG_TAG)
            response = MakeResponse.make_error_response(
                icon_e.code, icon_e.message)
        except Exception as e:
            self._log_exception(e, ICON_SERVICE_LOG_TAG)
            response = MakeResponse.make_error_response(
                ExceptionCode.SERVER_ERROR, str(e))
        finally:
            Logger.info(f'invoke response with {response}', ICON_INNER_LOG_TAG)
            return response
Пример #16
0
    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
Пример #17
0
    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)
Пример #18
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
Пример #19
0
    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)
Пример #20
0
    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)
Пример #21
0
    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
Пример #22
0
    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
Пример #23
0
    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)
Пример #24
0
    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'))
Пример #25
0
def _test_block_from_bytes_to_bytes_struct(block_hash: bytes,
                                           prev_block_hash: Optional[bytes]):
    revision = 0
    cumulative_fee = 10
    block1 = Block(1, block_hash, 100, prev_block_hash, cumulative_fee)
    data = Block.to_bytes(block1, revision)
    assert isinstance(data, bytes)
    assert 1 + DEFAULT_BYTE_SIZE + DEFAULT_BYTE_SIZE + DEFAULT_BYTE_SIZE + DEFAULT_BYTE_SIZE == len(
        data)

    block2 = Block.from_bytes(data)
    assert block2.height == 1
    assert block2.hash == block_hash
    assert block2.timestamp == 100
    assert block2.prev_hash == prev_block_hash
    # as cumulative fee is not recorded, result should be zero (not 10)
    assert block2.cumulative_fee == 0
Пример #26
0
    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))
Пример #27
0
    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)
Пример #29
0
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)
Пример #30
0
    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()