示例#1
0
    def Blockchain_GetBlock(self, engine: ExecutionEngine):
        data = engine.CurrentContext.EvaluationStack.Pop()

        if data:
            data = data.GetByteArray()
        else:
            return False

        block = None

        if len(data) <= 5:
            height = BigInteger.FromBytes(data)

            if Blockchain.Default() is not None:

                block = Blockchain.Default().GetBlockByHeight(height)

            elif height == 0:

                block = Blockchain.GenesisBlock()

        elif len(data) == 32:

            hash = UInt256(data=data).ToBytes()

            if Blockchain.Default() is not None:

                block = Blockchain.Default().GetBlockByHash(hash=hash)

            elif hash == Blockchain.GenesisBlock().Hash:

                block = Blockchain.GenesisBlock().Header

        engine.CurrentContext.EvaluationStack.PushT(
            StackItem.FromInterface(block))
        return True
示例#2
0
    def AsParameterType(type: ContractParameterType, item: StackItem):
        """
        Convert a StackItem to a ContractParameter object of a specified ContractParameterType
        Args:
            type (neo.SmartContract.ContractParameterType): The ContractParameterType to convert to
            item (neo.VM.InteropService.StackItem): The item to convert to a ContractParameter object

        Returns:

        """
        if type == ContractParameterType.Integer:
            return ContractParameter(type, value=item.GetBigInteger())
        elif type == ContractParameterType.Boolean:
            return ContractParameter(type, value=item.GetBoolean())
        elif type == ContractParameterType.Array:
            return ContractParameter(type, value=item.GetArray())
        elif type == ContractParameterType.String:
            return ContractParameter(type, value=item.GetString())
        elif type == ContractParameterType.InteropInterface:
            return ContractParameter(type, value=item.GetInterface())
        # all other types return a byte array
        else:
            return ContractParameter(type, value=item.GetByteArray())
示例#3
0
    def Contract_Create(self, engine):

        script = engine.EvaluationStack.Pop().GetByteArray()

        if len(script) > 1024 * 1024:
            return False

        param_list = engine.EvaluationStack.Pop().GetByteArray()
        if len(param_list) > 252:
            return False

        return_type = int(engine.EvaluationStack.Pop().GetBigInteger())

        contract_properties = int(engine.EvaluationStack.Pop().GetBigInteger())

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False

        name = engine.EvaluationStack.Pop().GetByteArray()

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        code_version = engine.EvaluationStack.Pop().GetByteArray()

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        author = engine.EvaluationStack.Pop().GetByteArray()

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        email = engine.EvaluationStack.Pop().GetByteArray()

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 65536:
            return False

        description = engine.EvaluationStack.Pop().GetByteArray()

        hash = Crypto.ToScriptHash(script, unhex=False)

        contract = self._contracts.TryGet(hash.ToBytes())

        if contract is None:
            code = FunctionCode(script=script,
                                param_list=param_list,
                                return_type=return_type,
                                contract_properties=contract_properties)

            contract = ContractState(code, contract_properties, name,
                                     code_version, author, email, description)

            self._contracts.GetAndChange(code.ScriptHash().ToBytes(), contract)

            self._contracts_created[hash.ToBytes()] = UInt160(
                data=engine.CurrentContext.ScriptHash())

        engine.EvaluationStack.PushT(StackItem.FromInterface(contract))

        self.events_to_dispatch.append(
            SmartContractEvent(SmartContractEvent.CONTRACT_CREATED, [contract],
                               hash,
                               Blockchain.Default().Height + 1,
                               engine.ScriptContainer.Hash
                               if engine.ScriptContainer else None,
                               test_mode=engine.testMode))
        return True
示例#4
0
    def Storage_GetContext(self, engine):

        hash = UInt160(data=engine.CurrentContext.ScriptHash())
        context = StorageContext(script_hash=hash)
        engine.EvaluationStack.PushT(StackItem.FromInterface(context))
        return True
    def test_serialize_map(self):
        map2 = Map({
            StackItem.New(b'a'): StackItem.New(1),
            StackItem.New(b'b'): StackItem.New(2),
            StackItem.New(b'c'): StackItem.New(3),
        })

        self.engine.EvaluationStack.PushT(map2)

        self.state_reader.Runtime_Serialize(self.engine)
        self.state_reader.Runtime_Deserialize(self.engine)

        deserialized = self.engine.EvaluationStack.Pop()
        self.assertEqual(deserialized, map2)

        map3 = Map({
            StackItem.New(b'j'): StackItem.New(8),
            StackItem.New(b'k'): StackItem.New(2222),
        })

        map2.SetItem(StackItem.New(b'mymap'), map3)

        self.engine.EvaluationStack.PushT(map2)

        self.state_reader.Runtime_Serialize(self.engine)
        self.state_reader.Runtime_Deserialize(self.engine)

        deserialized = self.engine.EvaluationStack.Pop()
        self.assertEqual(deserialized, map2)
示例#6
0
    def test_iter_map(self):
        my_map = Map({
            StackItem.New('a'): StackItem.New(1),
            StackItem.New('b'): StackItem.New(3),
            StackItem.New('d'): StackItem.New(432)
        })

        self.econtext.EvaluationStack.PushT(my_map)
        self.engine.InvocationStack.PushT(self.econtext)

        self.service.Iterator_Create(self.engine)

        iterable = self.econtext.EvaluationStack.Peek(0).GetInterface()

        self.assertIsInstance(iterable, MapWrapper)

        keys = []
        values = []
        while iterable.Next():
            keys.append(iterable.Key())
            values.append(iterable.Value())

        self.assertEqual(
            keys, [StackItem.New('a'),
                   StackItem.New('b'),
                   StackItem.New('d')])
        self.assertEqual(keys, my_map.Keys)

        self.assertEqual(
            values, [StackItem.New(1),
                     StackItem.New(3),
                     StackItem.New(432)])
        self.assertEqual(values, my_map.Values)
 def test_cant_deserialize_item(self):
     self.econtext.EvaluationStack.PushT(StackItem.New(b'abc'))
     self.engine.InvocationStack.PushT(self.econtext)
     success = self.state_reader.Runtime_Deserialize(self.engine)
     self.assertFalse(success)
示例#8
0
    def Asset_Create(self, engine):

        tx = engine.ScriptContainer

        asset_type = int(engine.EvaluationStack.Pop().GetBigInteger())

        if asset_type not in AssetType.AllTypes() or \
                asset_type == AssetType.CreditFlag or \
                asset_type == AssetType.DutyFlag or \
                asset_type == AssetType.GoverningToken or \
                asset_type == AssetType.UtilityToken:

            return False

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 1024:
            return False

        name = engine.EvaluationStack.Pop().GetByteArray().decode('utf-8')

        amount = Fixed8(engine.EvaluationStack.Pop().GetBigInteger())

        if amount == Fixed8.Zero() or amount < Fixed8.NegativeSatoshi():
            return False

        if asset_type == AssetType.Invoice and amount != Fixed8.NegativeSatoshi(
        ):
            return False

        precision = int(engine.EvaluationStack.Pop().GetBigInteger())

        if precision > 8:
            return False

        if asset_type == AssetType.Share and precision != 0:
            return False

        if amount != Fixed8.NegativeSatoshi() and amount.value % pow(
                10, 8 - precision) != 0:
            return False

        ownerData = engine.EvaluationStack.Pop().GetByteArray()

        owner = ECDSA.decode_secp256r1(ownerData, unhex=False).G

        if owner.IsInfinity:
            return False

        if not self.CheckWitnessPubkey(engine, owner):
            logger.error("check witness false...")
            return False

        admin = UInt160(data=engine.EvaluationStack.Pop().GetByteArray())

        issuer = UInt160(data=engine.EvaluationStack.Pop().GetByteArray())

        new_asset = AssetState(asset_id=tx.Hash,
                               asset_type=asset_type,
                               name=name,
                               amount=amount,
                               available=Fixed8.Zero(),
                               precision=precision,
                               fee_mode=0,
                               fee=Fixed8.Zero(),
                               fee_addr=UInt160(),
                               owner=owner,
                               admin=admin,
                               issuer=issuer,
                               expiration=Blockchain.Default().Height + 1 +
                               2000000,
                               is_frozen=False)

        asset = self._assets.GetOrAdd(tx.Hash.ToBytes(), new_asset)

        # print("*****************************************************")
        # print("CREATED ASSET %s " % tx.Hash.ToBytes())
        # print("*****************************************************")
        engine.EvaluationStack.PushT(StackItem.FromInterface(asset))

        return True
示例#9
0
    def PushT(self, item):
        if not type(item) is StackItem and not issubclass(
                type(item), StackItem):
            item = StackItem.New(item)

        self._list.append(item)
    def test_wallet_token_sendfrom(self):
        with self.OpenWallet1():
            # test with no parameters
            with patch('sys.stdout', new=StringIO()) as mock_print:
                args = ['token', 'sendfrom']
                res = CommandWallet().execute(args)
                self.assertFalse(res)
                self.assertIn("specify the required parameter",
                              mock_print.getvalue())

            # test with insufficient parameters
            with patch('sys.stdout', new=StringIO()) as mock_print:
                args = ['token', 'sendfrom', 'arg1']
                res = CommandWallet().execute(args)
                self.assertFalse(res)
                self.assertIn("specify the required parameter",
                              mock_print.getvalue())

            # test with invalid token argument
            with patch('sys.stdout', new=StringIO()) as mock_print:
                args = [
                    'token', 'sendfrom', 'invalid_token_name', 'arg2', 'arg3',
                    '10'
                ]
                res = CommandWallet().execute(args)
                self.assertFalse(res)
                self.assertIn("does not represent a known NEP5 token",
                              mock_print.getvalue())

            # test with valid token arg, but invalid from_addr
            with patch('sys.stdout', new=StringIO()) as mock_print:
                args = [
                    'token', 'sendfrom', 'NXT4', 'invalid_from_addr', 'arg3',
                    '10'
                ]
                res = CommandWallet().execute(args)
                self.assertFalse(res)
                self.assertIn("not a valid address", mock_print.getvalue())

            # test with valid token and from_addr, but invalid to_addr
            with patch('sys.stdout', new=StringIO()) as mock_print:
                args = [
                    'token', 'sendfrom', 'NXT4',
                    'AZfFBeBqtJvaTK9JqG8uk6N7FppQY6byEg', 'invalid_to_addr',
                    '10'
                ]
                res = CommandWallet().execute(args)
                self.assertFalse(res)
                self.assertIn("not a valid address", mock_print.getvalue())

            # test with invalid amount
            with patch('sys.stdout', new=StringIO()) as mock_print:
                args = [
                    'token', 'sendfrom', 'NXT4',
                    'AZfFBeBqtJvaTK9JqG8uk6N7FppQY6byEg',
                    'AZfFBeBqtJvaTK9JqG8uk6N7FppQY6byEg', 'invalid_amount'
                ]
                res = CommandWallet().execute(args)
                self.assertFalse(res)
                self.assertIn("not a valid amount", mock_print.getvalue())

            # setup some variables that are re-used in the tests below
            token = list(PromptData.Wallet.GetTokens().values())[0]
            addr_from = PromptData.Wallet.GetDefaultContract().Address
            addr_to = self.watch_addr_str

            # test sending with invalid password
            with patch('sys.stdout', new=StringIO()) as mock_print:
                with patch('neo.Prompt.Commands.Tokens.token_get_allowance',
                           return_value=12300000000):
                    with patch('neo.Wallets.NEP5Token.NEP5Token.TransferFrom',
                               return_value=(self.Approve_Allowance(
                                   PromptData.Wallet, token))):
                        with patch('neo.Prompt.Commands.Tokens.prompt',
                                   side_effect=['blah']):
                            args = [
                                'token', 'sendfrom', 'NXT4', addr_from,
                                addr_to, '123'
                            ]
                            res = CommandWallet().execute(args)
                            self.assertFalse(res)
                            self.assertIn("incorrect password",
                                          mock_print.getvalue())

            # test sending something where the test run fails
            with patch('sys.stdout', new=StringIO()) as mock_print:
                exception_msg = "totally not expected error"
                with patch('neo.Prompt.Commands.Tokens.test_token_send_from',
                           side_effect=[Exception(exception_msg)]):
                    error_level = 30
                    with self.assertLogHandler('generic', error_level) as logs:
                        # the args don't really matter, except for the first 2
                        args = [
                            'token', 'sendfrom', 'NXT4', addr_from, addr_to,
                            '123'
                        ]
                        res = CommandWallet().execute(args)
                        self.assertFalse(res)
                        self.assertIn("Something really unexpected happened",
                                      mock_print.getvalue())
                        self.assertIn(exception_msg, logs.output[0])

            # test having the VM fail by returning None
            with patch('sys.stdout', new=StringIO()) as mock_print:
                with patch('neo.Prompt.Commands.Tokens.test_token_send_from',
                           side_effect=[(None, None, None, None)]):
                    # the args don't really matter, except for the first 2
                    args = [
                        'token', 'sendfrom', 'NXT4', addr_from, addr_to, '123'
                    ]
                    res = CommandWallet().execute(args)
                    self.assertFalse(res)
                    self.assertIn("no Transaction object or VM output",
                                  mock_print.getvalue())

            # test having the VM fail by returning a result that it not 1
            with patch('sys.stdout', new=StringIO()) as mock_print:
                bad_vm_result = [StackItem.New(0)]
                fake_tx = object()
                fake_fee = 111
                with patch('neo.Prompt.Commands.Tokens.test_token_send_from',
                           side_effect=[(None, fake_tx, fake_fee,
                                         bad_vm_result)]):
                    # the args don't really matter, except for the first 2
                    args = [
                        'token', 'sendfrom', 'NXT4', addr_from, addr_to, '123'
                    ]
                    res = CommandWallet().execute(args)
                    self.assertFalse(res)
                    self.assertIn("Virtual machine returned: 0",
                                  mock_print.getvalue())

            # test sending with insufficient allowance
            with patch('sys.stdout', new=StringIO()) as mock_print:
                res = CommandWallet().execute([
                    'token', 'sendfrom', token.symbol, addr_from, addr_to,
                    10000000
                ])
                self.assertFalse(res)
                self.assertIn("Insufficient allowance", mock_print.getvalue())

            with patch('neo.Prompt.Commands.Tokens.token_get_allowance',
                       return_value=12300000000):
                with patch('neo.Wallets.NEP5Token.NEP5Token.TransferFrom',
                           return_value=self.Approve_Allowance(
                               PromptData.Wallet, token)):
                    with patch('neo.Prompt.Commands.Tokens.prompt',
                               side_effect=[self.wallet_1_pass()]):
                        args = [
                            'token', 'sendfrom', 'NXT4', addr_from, addr_to,
                            '123'
                        ]
                        res = CommandWallet().execute(args)
                        self.assertTrue(res)
    def test_op_map13(self):
        self.econtext.EvaluationStack.PushT(Map(dict={StackItem.New('a'): StackItem.New(4), StackItem.New('b'): StackItem.New(5)}))
        self.econtext.EvaluationStack.PushT(StackItem.New('c'))
        self.engine.ExecuteOp(OpCode.HASKEY, self.econtext)

        self.assertEqual(self.econtext.EvaluationStack.Items[0].GetBoolean(), False)
示例#12
0
    def Contract_Migrate(self, engine: ExecutionEngine):

        script = engine.CurrentContext.EvaluationStack.Pop().GetByteArray()

        if len(script) > 1024 * 1024:
            return False

        param_list = engine.CurrentContext.EvaluationStack.Pop().GetByteArray()

        if len(param_list) > 252:
            return False

        return_type = int(
            engine.CurrentContext.EvaluationStack.Pop().GetBigInteger())

        contract_properties = engine.CurrentContext.EvaluationStack.Pop(
        ).GetBigInteger()

        if len(engine.CurrentContext.EvaluationStack.Peek().GetByteArray()
               ) > 252:
            return False

        name = engine.CurrentContext.EvaluationStack.Pop().GetByteArray(
        ).decode('utf-8')

        if len(engine.CurrentContext.EvaluationStack.Peek().GetByteArray()
               ) > 252:
            return False
        version = engine.CurrentContext.EvaluationStack.Pop().GetByteArray(
        ).decode('utf-8')

        if len(engine.CurrentContext.EvaluationStack.Peek().GetByteArray()
               ) > 252:
            return False
        author = engine.CurrentContext.EvaluationStack.Pop().GetByteArray(
        ).decode('utf-8')

        if len(engine.CurrentContext.EvaluationStack.Peek().GetByteArray()
               ) > 252:
            return False
        email = engine.CurrentContext.EvaluationStack.Pop().GetByteArray(
        ).decode('utf-8')

        if len(engine.CurrentContext.EvaluationStack.Peek().GetByteArray()
               ) > 65536:
            return False
        description = engine.CurrentContext.EvaluationStack.Pop().GetByteArray(
        ).decode('utf-8')

        hash = Crypto.ToScriptHash(script, unhex=False)

        contract = self.Snapshot.Contracts.TryGet(hash.ToBytes())

        if contract is None:

            code = FunctionCode(script=script,
                                param_list=param_list,
                                return_type=return_type)

            contract = ContractState(code=code,
                                     contract_properties=contract_properties,
                                     name=name,
                                     version=version,
                                     author=author,
                                     email=email,
                                     description=description)

            self.Snapshot.Contracts.Add(hash.ToBytes(), contract)

            cur_hash = UInt160(data=engine.CurrentContext.ScriptHash())
            self._contracts_created[hash.ToBytes()] = cur_hash

            if contract.HasStorage:
                to_add = []
                for key, item in self.Snapshot.Storages.Find(
                        cur_hash.ToArray()):
                    key = StorageKey(script_hash=hash, key=key[20:])
                    to_add.append((key.ToArray(), item))

                for k, v in to_add:
                    self.Snapshot.Storages.Add(k, v)

        engine.CurrentContext.EvaluationStack.PushT(
            StackItem.FromInterface(contract))

        self.events_to_dispatch.append(
            SmartContractEvent(SmartContractEvent.CONTRACT_MIGRATED,
                               ContractParameter(
                                   ContractParameterType.InteropInterface,
                                   contract),
                               hash,
                               GetBlockchain().Height + 1,
                               engine.ScriptContainer.Hash
                               if engine.ScriptContainer else None,
                               test_mode=engine.testMode))

        return self.Contract_Destroy(engine)
示例#13
0
    def Contract_Create(self, engine: ExecutionEngine):

        script = engine.CurrentContext.EvaluationStack.Pop().GetByteArray()

        if len(script) > 1024 * 1024:
            return False

        param_list = engine.CurrentContext.EvaluationStack.Pop().GetByteArray()
        if len(param_list) > 252:
            return False
        return_type = int(
            engine.CurrentContext.EvaluationStack.Pop().GetBigInteger())
        if return_type < 0 or return_type > 0xff:
            raise ValueError("Invalid return type data popped from stack")

        contract_properties = int(
            engine.CurrentContext.EvaluationStack.Pop().GetBigInteger())

        if len(engine.CurrentContext.EvaluationStack.Peek().GetByteArray()
               ) > 252:
            return False
        name = engine.CurrentContext.EvaluationStack.Pop().GetByteArray()

        if len(engine.CurrentContext.EvaluationStack.Peek().GetByteArray()
               ) > 252:
            return False
        code_version = engine.CurrentContext.EvaluationStack.Pop(
        ).GetByteArray()

        if len(engine.CurrentContext.EvaluationStack.Peek().GetByteArray()
               ) > 252:
            return False
        author = engine.CurrentContext.EvaluationStack.Pop().GetByteArray()

        if len(engine.CurrentContext.EvaluationStack.Peek().GetByteArray()
               ) > 252:
            return False
        email = engine.CurrentContext.EvaluationStack.Pop().GetByteArray()

        if len(engine.CurrentContext.EvaluationStack.Peek().GetByteArray()
               ) > 65536:
            return False

        description = engine.CurrentContext.EvaluationStack.Pop().GetByteArray(
        )

        hash = Crypto.ToScriptHash(script, unhex=False)

        contract = self.Snapshot.Contracts.TryGet(hash.ToBytes())

        if contract is None:
            try:
                code = FunctionCode(script=script,
                                    param_list=param_list,
                                    return_type=return_type,
                                    contract_properties=contract_properties)
            except ValueError:
                # exception is caused by an invalid `return_type`. neo-cli accepts this , but we throw an exception
                # this is a dirty hack to work around the VM state difference that it causes until neo-cli hopefully fixes it
                # see https://github.com/neo-project/neo/issues/827
                code = FunctionCode(script=script,
                                    param_list=param_list,
                                    contract_properties=contract_properties)
                code.ReturnType = return_type

            contract = ContractState(code, contract_properties, name,
                                     code_version, author, email, description)

            self.Snapshot.Contracts.Add(code.ScriptHash().ToBytes(), contract)

            self._contracts_created[hash.ToBytes()] = UInt160(
                data=engine.CurrentContext.ScriptHash())

        engine.CurrentContext.EvaluationStack.PushT(
            StackItem.FromInterface(contract))

        self.events_to_dispatch.append(
            SmartContractEvent(SmartContractEvent.CONTRACT_CREATED,
                               ContractParameter(
                                   ContractParameterType.InteropInterface,
                                   contract),
                               hash,
                               GetBlockchain().Height + 1,
                               engine.ScriptContainer.Hash
                               if engine.ScriptContainer else None,
                               test_mode=engine.testMode))
        return True
示例#14
0
    def Contract_Migrate(self, engine):

        script = engine.EvaluationStack.Pop().GetByteArray()

        if len(script) > 1024 * 1024:
            return False

        param_list = engine.EvaluationStack.Pop().GetByteArray()

        if len(param_list) > 252:
            return False

        return_type = int(engine.EvaluationStack.Pop().GetBigInteger())

        contract_properties = engine.EvaluationStack.Pop().GetBigInteger()

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False

        name = engine.EvaluationStack.Pop().GetByteArray().decode('utf-8')

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        version = engine.EvaluationStack.Pop().GetByteArray().decode('utf-8')

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        author = engine.EvaluationStack.Pop().GetByteArray().decode('utf-8')

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        email = engine.EvaluationStack.Pop().GetByteArray().decode('utf-8')

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 65536:
            return False
        description = engine.EvaluationStack.Pop().GetByteArray().decode(
            'utf-8')

        hash = Crypto.ToScriptHash(script, unhex=False)

        contract = self._contracts.TryGet(hash.ToBytes())

        if contract is None:

            code = FunctionCode(script=script,
                                param_list=param_list,
                                return_type=return_type)

            contract = ContractState(code=code,
                                     contract_properties=contract_properties,
                                     name=name,
                                     version=version,
                                     author=author,
                                     email=email,
                                     description=description)

            self._contracts.Add(hash.ToBytes(), contract)

            self._contracts_created[hash.ToBytes()] = UInt160(
                data=engine.CurrentContext.ScriptHash())

            if contract.HasStorage:

                for pair in self._storages.Find(
                        engine.CurrentContext.ScriptHash()):
                    key = StorageKey(script_hash=hash, key=pair.Key.Key)
                    item = StorageItem(pair.Value.Value)
                    self._storages.Add(key, item)

        engine.EvaluationStack.PushT(StackItem.FromInterface(contract))

        self.events_to_dispatch.append(
            SmartContractEvent(SmartContractEvent.CONTRACT_MIGRATED,
                               [contract],
                               hash,
                               Blockchain.Default().Height + 1,
                               engine.ScriptContainer.Hash
                               if engine.ScriptContainer else None,
                               test_mode=engine.testMode))

        return self.Contract_Destroy(engine)
示例#15
0
 def Key(self):
     return StackItem.New(self.key)
示例#16
0
    def Contract_Create(self, engine):

        script = engine.EvaluationStack.Pop().GetByteArray()

        if len(script) > 1024 * 1024:
            return False

        param_list = engine.EvaluationStack.Pop().GetByteArray()
        if len(param_list) > 252:
            return False

        return_type = int(engine.EvaluationStack.Pop().GetBigInteger())

        contract_properties = int(engine.EvaluationStack.Pop().GetBigInteger())

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        name = engine.EvaluationStack.Pop().GetByteArray()

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        code_version = engine.EvaluationStack.Pop().GetByteArray()

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        author = engine.EvaluationStack.Pop().GetByteArray()

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        email = engine.EvaluationStack.Pop().GetByteArray()

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 65536:
            return False

        description = engine.EvaluationStack.Pop().GetByteArray()

        hash = Crypto.ToScriptHash(script, unhex=False)

        contract = self._contracts.TryGet(hash.ToBytes())

        if contract is None:

            code = FunctionCode(script=script,
                                param_list=param_list,
                                return_type=return_type,
                                contract_properties=contract_properties)

            contract = ContractState(code, contract_properties, name,
                                     code_version, author, email, description)

            self._contracts.GetAndChange(code.ScriptHash().ToBytes(), contract)

            self._contracts_created[hash.ToBytes()] = UInt160(
                data=engine.CurrentContext.ScriptHash())

        engine.EvaluationStack.PushT(StackItem.FromInterface(contract))

        # logger.info("*****************************************************")
        # logger.info("CREATED CONTRACT %s " % hash.ToBytes())
        # logger.info("*****************************************************")
        return True
示例#17
0
 def Value(self):
     return StackItem.New(self.value)
示例#18
0
    def Contract_Migrate(self, engine):

        script = engine.EvaluationStack.Pop().GetByteArray()

        if len(script) > 1024 * 1024:
            return False

        param_list = engine.EvaluationStack.Pop().GetByteArray()

        if len(param_list) > 252:
            return False

        return_type = int(engine.EvaluationStack.Pop().GetBigInteger())

        needs_storage = engine.EvaluationStack.Pop().GetBoolean()

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        name = engine.EvaluationStack.Pop().GetByteArray().decode('utf-8')

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        version = engine.EvaluationStack.Pop().GetByteArray().decode('utf-8')

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        author = engine.EvaluationStack.Pop().GetByteArray().decode('utf-8')

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        email = engine.EvaluationStack.Pop().GetByteArray().decode('utf-8')

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 65536:
            return False
        description = engine.EvaluationStack.Pop().GetByteArray().decode(
            'utf-8')

        hash = Crypto.ToScriptHash(script, unhex=False)

        contract = self._contracts.TryGet(hash.ToBytes())

        if contract is None:

            code = FunctionCode(script=script,
                                param_list=param_list,
                                return_type=return_type)

            contract = ContractState(code=code,
                                     has_storage=needs_storage,
                                     name=name,
                                     version=version,
                                     author=author,
                                     email=email,
                                     description=description)

            self._contracts.Add(hash.ToBytes(), contract)

            self._contracts_created[hash.ToBytes()] = UInt160(
                data=engine.CurrentContext.ScriptHash)

            if needs_storage:

                for pair in self._storages.Find(
                        engine.CurrentContext.ScriptHash()):

                    key = StorageKey(script_hash=hash, key=pair.Key.Key)
                    item = StorageItem(pair.Value.Value)
                    self._storages.Add(key, item)

        engine.EvaluationStack.PushT(StackItem.FromInterface(contract))

        # print("*****************************************************")
        # print("MIGRATED CONTRACT %s " % hash.ToBytes())
        # print("*****************************************************")

        return True
 def test_cant_serialize_iop_item(self):
     genesis = Blockchain.GenesisBlock()
     self.econtext.EvaluationStack.PushT(StackItem.FromInterface(genesis))
     self.engine.InvocationStack.PushT(self.econtext)
     cant_do = self.state_reader.Runtime_Serialize(self.engine)
     self.assertEqual(cant_do, False)