Exemple #1
0
        public override async Task <LaunchProgramResponse> LaunchProgram(LaunchProgramRequest request, ServerCallContext context)
        {
            if (request.Arguments == null)
            {
                var success = await InteropService.LaunchProgram(request.ProgramName);

                return(new LaunchProgramResponse()
                {
                    Success = success
                });
            }
            else
            {
                var success = await InteropService.LaunchProgram(request.ProgramName, request.Arguments);

                return(new LaunchProgramResponse()
                {
                    Success = success
                });
            }
        }
Exemple #2
0
        public void ApplicationEngineReusedStorage_PartialReuseTwice()
        {
            var key      = new byte[] { (byte)OpCode.PUSH1 };
            var oldValue = new byte[] { (byte)OpCode.PUSH1 };
            var value    = new byte[] { (byte)OpCode.PUSH1, (byte)OpCode.PUSH1 };

            byte[] script = CreateMultiplePutScript(key, value);

            ContractState contractState = TestUtils.GetContract(script);

            contractState.Manifest.Features = ContractFeatures.HasStorage;

            StorageKey  skey  = TestUtils.GetStorageKey(contractState.Id, key);
            StorageItem sItem = TestUtils.GetStorageItem(oldValue);

            var snapshot = Blockchain.Singleton.GetSnapshot();

            snapshot.Storages.Add(skey, sItem);
            snapshot.Contracts.Add(script.ToScriptHash(), contractState);

            using (ApplicationEngine ae = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, testMode: true))
            {
                Debugger debugger = new Debugger(ae);
                ae.LoadScript(script);
                debugger.StepInto(); //push key
                debugger.StepInto(); //push value
                debugger.StepInto(); //syscall Storage.GetContext
                var setupPrice         = ae.GasConsumed;
                var incrementDataPrice = InteropService.GetPrice(InteropService.Storage.Put, ae.CurrentContext.EvaluationStack, ae.Snapshot);
                incrementDataPrice.Should().Be(1 * InteropService.Storage.GasPerByte);
                debugger.StepInto(); // syscall Storage.Put

                debugger.StepInto(); //push key
                debugger.StepInto(); //push value
                debugger.StepInto();
                setupPrice = ae.GasConsumed;
                var reusedDataPrice = InteropService.GetPrice(InteropService.Storage.Put, ae.CurrentContext.EvaluationStack, ae.Snapshot);
                reusedDataPrice.Should().Be(1 * InteropService.Storage.GasPerByte); // = PUT basic fee
            }
        }
Exemple #3
0
        public void TestStorage_PutEx()
        {
            var engine = GetEngine(false, true);

            engine.CurrentContext.EvaluationStack.Push(1);
            InteropService.Invoke(engine, InteropService.System_Storage_PutEx).Should().BeFalse();

            var mockSnapshot = new Mock <Snapshot>();
            var state        = TestUtils.GetContract();

            state.Manifest.Features = ContractFeatures.HasStorage;
            var storageKey = new StorageKey
            {
                ScriptHash = new UInt160(TestUtils.GetByteArray(20, 0x42)),
                Key        = new byte[] { 0x01 }
            };
            var storageItem = new StorageItem
            {
                Value      = new byte[] { 0x01, 0x02, 0x03, 0x04 },
                IsConstant = false
            };

            mockSnapshot.SetupGet(p => p.Contracts).Returns(new TestDataCache <UInt160, ContractState>(state.ScriptHash, state));
            mockSnapshot.SetupGet(p => p.Storages).Returns(new TestDataCache <StorageKey, StorageItem>(storageKey, storageItem));
            engine = new ApplicationEngine(TriggerType.Application, null, mockSnapshot.Object, 0);
            engine.LoadScript(new byte[] { 0x01 });
            var key            = new byte[] { 0x01 };
            var value          = new byte[] { 0x02 };
            var storageContext = new StorageContext
            {
                ScriptHash = state.ScriptHash,
                IsReadOnly = false
            };

            engine.CurrentContext.EvaluationStack.Push((int)StorageFlags.None);
            engine.CurrentContext.EvaluationStack.Push(value);
            engine.CurrentContext.EvaluationStack.Push(key);
            engine.CurrentContext.EvaluationStack.Push(new InteropInterface <StorageContext>(storageContext));
            InteropService.Invoke(engine, InteropService.System_Storage_PutEx).Should().BeTrue();
        }
Exemple #4
0
        public void TestStorage_PutEx()
        {
            var engine = GetEngine(false, true);

            engine.CurrentContext.EvaluationStack.Push(1);
            InteropService.Invoke(engine, InteropService.Storage.PutEx).Should().BeFalse();

            var snapshot = Blockchain.Singleton.GetSnapshot();
            var state    = TestUtils.GetContract();

            state.Manifest.Features = ContractFeatures.HasStorage;
            var storageKey = new StorageKey
            {
                ScriptHash = new UInt160(TestUtils.GetByteArray(20, 0x42)),
                Key        = new byte[] { 0x01 }
            };
            var storageItem = new StorageItem
            {
                Value      = new byte[] { 0x01, 0x02, 0x03, 0x04 },
                IsConstant = false
            };

            snapshot.Contracts.Add(state.ScriptHash, state);
            snapshot.Storages.Add(storageKey, storageItem);
            engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0);
            engine.LoadScript(new byte[] { 0x01 });
            var key            = new byte[] { 0x01 };
            var value          = new byte[] { 0x02 };
            var storageContext = new StorageContext
            {
                ScriptHash = state.ScriptHash,
                IsReadOnly = false
            };

            engine.CurrentContext.EvaluationStack.Push((int)StorageFlags.None);
            engine.CurrentContext.EvaluationStack.Push(value);
            engine.CurrentContext.EvaluationStack.Push(key);
            engine.CurrentContext.EvaluationStack.Push(new InteropInterface(storageContext));
            InteropService.Invoke(engine, InteropService.Storage.PutEx).Should().BeTrue();
        }
Exemple #5
0
        protected override void ExecuteCmdlet()
        {
            WorkflowServicesManager workflowServicesManager = new WorkflowServicesManager(ClientContext, SelectedWeb);
            InteropService          interopService          = workflowServicesManager.GetWorkflowInteropService();
            WorkflowInstanceService instanceService         = workflowServicesManager.GetWorkflowInstanceService();

            if (Identity.Instance != null)
            {
                WriteVerbose("Instance object set");
                WriteVerbose("Cancelling workflow with ID: " + Identity.Instance.Id);
                if (Force)
                {
                    instanceService.TerminateWorkflow(Identity.Instance);
                }
                else
                {
                    Identity.Instance.CancelWorkFlow();
                }
                ClientContext.ExecuteQuery();
            }
            else if (Identity.Id != Guid.Empty)
            {
                WriteVerbose("Instance object not set. Looking up site workflows by GUID: " + Identity.Id);
                var allinstances = SelectedWeb.GetWorkflowInstances();
                foreach (var instance in allinstances.Where(instance => instance.Id == Identity.Id))
                {
                    WriteVerbose("Cancelling workflow with ID: " + Identity.Instance.Id);
                    if (Force)
                    {
                        instanceService.TerminateWorkflow(instance);
                    }
                    else
                    {
                        instance.CancelWorkFlow();
                    }
                    ClientContext.ExecuteQuery();
                    break;
                }
            }
        }
Exemple #6
0
        public void TestCheckSig()
        {
            var         engine = GetEngine(true);
            IVerifiable iv     = engine.ScriptContainer;

            byte[]  message    = iv.GetHashData();
            byte[]  privateKey = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
                                   0x01,  0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };
            KeyPair keyPair = new KeyPair(privateKey);
            ECPoint pubkey  = keyPair.PublicKey;

            byte[] signature = Crypto.Default.Sign(message, privateKey, pubkey.EncodePoint(false).Skip(1).ToArray());
            engine.CurrentContext.EvaluationStack.Push(signature);
            engine.CurrentContext.EvaluationStack.Push(pubkey.EncodePoint(false));
            InteropService.Invoke(engine, InteropService.Neo_Crypto_CheckSig).Should().BeTrue();
            engine.CurrentContext.EvaluationStack.Pop().GetBoolean().Should().BeTrue();

            engine.CurrentContext.EvaluationStack.Push(signature);
            engine.CurrentContext.EvaluationStack.Push(new byte[70]);
            InteropService.Invoke(engine, InteropService.Neo_Crypto_CheckSig).Should().BeTrue();
            engine.CurrentContext.EvaluationStack.Pop().GetBoolean().Should().BeFalse();
        }
Exemple #7
0
        public void TestAccount_IsStandard()
        {
            var engine = GetEngine(false, true);
            var hash   = new byte[] { 0x01, 0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01, 0x01 };

            engine.CurrentContext.EvaluationStack.Push(hash);
            InteropService.Invoke(engine, InteropService.Neo_Account_IsStandard).Should().BeTrue();
            engine.CurrentContext.EvaluationStack.Pop().GetBoolean().Should().BeTrue();

            var mockSnapshot = new Mock <Snapshot>();
            var state        = TestUtils.GetContract();

            mockSnapshot.SetupGet(p => p.Contracts).Returns(new TestDataCache <UInt160, ContractState>(state.ScriptHash, state));
            engine = new ApplicationEngine(TriggerType.Application, null, mockSnapshot.Object, 0);
            engine.LoadScript(new byte[] { 0x01 });
            engine.CurrentContext.EvaluationStack.Push(state.ScriptHash.ToArray());
            InteropService.Invoke(engine, InteropService.Neo_Account_IsStandard).Should().BeTrue();
            engine.CurrentContext.EvaluationStack.Pop().GetBoolean().Should().BeFalse();
        }
Exemple #8
0
        public void TestContract_Destroy()
        {
            var engine = GetEngine(false, true);

            InteropService.Invoke(engine, InteropService.Contract.Destroy).Should().BeTrue();

            var snapshot = Blockchain.Singleton.GetSnapshot();
            var state    = TestUtils.GetContract();

            state.Manifest.Features = ContractFeatures.HasStorage;
            var scriptHash  = UInt160.Parse("0xcb9f3b7c6fb1cf2c13a40637c189bdd066a272b4");
            var storageItem = new StorageItem
            {
                Value      = new byte[] { 0x01, 0x02, 0x03, 0x04 },
                IsConstant = false
            };

            var storageKey = new StorageKey
            {
                Id  = 0x43000000,
                Key = new byte[] { 0x01 }
            };

            snapshot.Contracts.Add(scriptHash, state);
            snapshot.Storages.Add(storageKey, storageItem);
            engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0);
            engine.LoadScript(new byte[0]);
            InteropService.Invoke(engine, InteropService.Contract.Destroy).Should().BeTrue();
            engine.Snapshot.Storages.Find(BitConverter.GetBytes(0x43000000)).Any().Should().BeFalse();

            //storages are removed
            snapshot = Blockchain.Singleton.GetSnapshot();
            state    = TestUtils.GetContract();
            snapshot.Contracts.Add(scriptHash, state);
            engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0);
            engine.LoadScript(new byte[0]);
            InteropService.Invoke(engine, InteropService.Contract.Destroy).Should().BeTrue();
            engine.Snapshot.Storages.Find(BitConverter.GetBytes(0x43000000)).Any().Should().BeFalse();
        }
Exemple #9
0
 public void NeoServiceFixedPrices()
 {
     InteropService.GetPrice(InteropService.Neo_Header_GetVersion).Should().Be(1);
     InteropService.GetPrice(InteropService.Neo_Header_GetMerkleRoot).Should().Be(1);
     InteropService.GetPrice(InteropService.Neo_Header_GetNextConsensus).Should().Be(1);
     InteropService.GetPrice(InteropService.Neo_Transaction_GetWitnesses).Should().Be(200);
     InteropService.GetPrice(InteropService.Neo_Transaction_GetScript).Should().Be(1);
     InteropService.GetPrice(InteropService.Neo_Witness_GetVerificationScript).Should().Be(100);
     InteropService.GetPrice(InteropService.Neo_Account_IsStandard).Should().Be(100);
     InteropService.GetPrice(InteropService.Neo_Contract_GetScript).Should().Be(1);
     InteropService.GetPrice(InteropService.Neo_Contract_IsPayable).Should().Be(1);
     InteropService.GetPrice(InteropService.Neo_Storage_Find).Should().Be(1);
     InteropService.GetPrice(InteropService.Neo_Enumerator_Create).Should().Be(1);
     InteropService.GetPrice(InteropService.Neo_Enumerator_Next).Should().Be(1);
     InteropService.GetPrice(InteropService.Neo_Enumerator_Value).Should().Be(1);
     InteropService.GetPrice(InteropService.Neo_Enumerator_Concat).Should().Be(1);
     InteropService.GetPrice(InteropService.Neo_Iterator_Create).Should().Be(1);
     InteropService.GetPrice(InteropService.Neo_Iterator_Key).Should().Be(1);
     InteropService.GetPrice(InteropService.Neo_Iterator_Keys).Should().Be(1);
     InteropService.GetPrice(InteropService.Neo_Iterator_Values).Should().Be(1);
     InteropService.GetPrice(InteropService.Neo_Iterator_Concat).Should().Be(1);
 }
Exemple #10
0
        /// <summary>
        /// Invoke Interop callback
        /// </summary>
        /// <param name="ptr">Method</param>
        /// <param name="size">Size</param>
        /// <returns>Return Interop result</returns>
        byte InternalInvokeInterop(IntPtr ptr, byte size)
        {
            if (InteropService == null)
            {
                return(NeoVM.FALSE);
            }

            string method = Marshal.PtrToStringUTF8(ptr, size);

            try
            {
                if (InteropService.Invoke(method, this))
                {
                    return(NeoVM.TRUE);
                }
            }
            catch
            {
            }

            return(NeoVM.FALSE);
        }
Exemple #11
0
        public void ApplicationEngineVariablePrices()
        {
            // Neo.Contract.Create: f66ca56e (requires push properties on fourth position)
            byte[] SyscallContractCreateHash00 = new byte[] { (byte)OpCode.PUSHDATA1, 0x01, 0x00, (byte)OpCode.PUSHDATA1, 0x02, 0x00, 0x00, (byte)OpCode.SYSCALL, 0xf6, 0x6c, 0xa5, 0x6e };
            using (ApplicationEngine ae = new ApplicationEngine(TriggerType.Application, null, null, 0, testMode: true))
            {
                Debugger debugger = new Debugger(ae);
                ae.LoadScript(SyscallContractCreateHash00);
                debugger.StepInto(); // PUSHDATA1
                debugger.StepInto(); // PUSHDATA1
                InteropService.GetPrice(InteropService.Contract.Create, ae.CurrentContext.EvaluationStack, ae.Snapshot).Should().Be(0_00300000L);
            }

            // System.Storage.Put: e63f1884 (requires push key and value)
            byte[] SyscallStoragePutHash = new byte[] { (byte)OpCode.PUSH3, (byte)OpCode.PUSH3, (byte)OpCode.PUSH0, (byte)OpCode.SYSCALL, 0xe6, 0x3f, 0x18, 0x84 };
            using (ApplicationEngine ae = new ApplicationEngine(TriggerType.Application, null, null, 0, testMode: true))
            {
                Debugger debugger = new Debugger(ae);
                ae.LoadScript(SyscallStoragePutHash);
                debugger.StepInto(); // push 03 (length 1)
                debugger.StepInto(); // push 03 (length 1)
                debugger.StepInto(); // push 00
                Action act = () => InteropService.GetPrice(InteropService.Storage.Put, ae.CurrentContext.EvaluationStack, ae.Snapshot);
                act.Should().Throw <InvalidOperationException>();
            }

            // System.Storage.PutEx: 73e19b3a (requires push key and value)
            byte[] SyscallStoragePutExHash = new byte[] { (byte)OpCode.PUSH3, (byte)OpCode.PUSH3, (byte)OpCode.PUSH0, (byte)OpCode.SYSCALL, 0x73, 0xe1, 0x9b, 0x3a };
            using (ApplicationEngine ae = new ApplicationEngine(TriggerType.Application, null, null, 0, testMode: true))
            {
                Debugger debugger = new Debugger(ae);
                ae.LoadScript(SyscallStoragePutExHash);
                debugger.StepInto(); // push 03 (length 1)
                debugger.StepInto(); // push 03 (length 1)
                debugger.StepInto(); // push 00
                Action act = () => InteropService.GetPrice(InteropService.Storage.Put, ae.CurrentContext.EvaluationStack, ae.Snapshot);
                act.Should().Throw <InvalidOperationException>();
            }
        }
Exemple #12
0
        public void TestAccount_IsStandard()
        {
            var engine = GetEngine(false, true);
            var hash   = new byte[] { 0x01, 0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01, 0x01 };

            engine.CurrentContext.EvaluationStack.Push(hash);
            InteropService.Invoke(engine, InteropService.Neo_Account_IsStandard).Should().BeTrue();
            engine.CurrentContext.EvaluationStack.Pop().ToBoolean().Should().BeTrue();

            var snapshot = Blockchain.Singleton.GetSnapshot();
            var state    = TestUtils.GetContract();

            snapshot.Contracts.Add(state.ScriptHash, state);
            engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0);
            engine.LoadScript(new byte[] { 0x01 });
            engine.CurrentContext.EvaluationStack.Push(state.ScriptHash.ToArray());
            InteropService.Invoke(engine, InteropService.Neo_Account_IsStandard).Should().BeTrue();
            engine.CurrentContext.EvaluationStack.Pop().ToBoolean().Should().BeFalse();
        }
Exemple #13
0
        /// <summary>
        /// check script if it contains wrong Opcode
        /// </summary>
        /// <param name="script"></param>
        /// <returns></returns>
        private async Task CheckBadOpcode(byte[] script)
        {
            // Basic script checks
            using var engine = new ApplicationEngine(TriggerType.Application, null, null, 0, true);
            var context = engine.LoadScript(script);

            while (context.InstructionPointer <= context.Script.Length)
            {
                // Check bad opcodes
                var ci = context.CurrentInstruction;
                if (ci == null || !Enum.IsDefined(typeof(OpCode), ci.OpCode))
                {
                    throw new WsException(ErrorCode.InvalidOpCode, $"OpCode not found at {context.InstructionPointer}-{(byte?)ci?.OpCode:x2}.");
                }
                // Check bad syscalls (NEO2)
                if (ci.OpCode == OpCode.SYSCALL && InteropService.SupportedMethods().All(u => u.Hash != ci.TokenU32))
                {
                    throw new WsException(ErrorCode.InvalidOpCode, $"Syscall not found {ci.TokenU32:x2}. Are you using a NEO2 smartContract?");
                }
                context.InstructionPointer += ci.Size;
            }
        }
 protected override bool OnSysCall(uint method)
 {
     if (callmethod == null)
     {
         callmethod = new Dictionary <uint, InteropDescriptor>()
         {
             { Native_Deploy.Hash, Native_Deploy }
         };
         foreach (var m in InteropService.SupportedMethods())
         {
             callmethod[m] = m;
         }
     }
     if (callmethod.ContainsKey(method) == false)
     {
         throw new Exception($"Syscall not found: {method.ToString("X2")} (using base call)");
     }
     else
     {
         return(base.OnSysCall(method));
     }
 }
Exemple #15
0
        public void TestIterator_Concat()
        {
            var engine = GetEngine();
            var arr1   = new VMArray {
                new byte[] { 0x01 },
                new byte[] { 0x02 }
            };
            var arr2 = new VMArray {
                new byte[] { 0x03 },
                new byte[] { 0x04 }
            };
            var wrapper1 = new ArrayWrapper(arr1);
            var wrapper2 = new ArrayWrapper(arr2);

            engine.CurrentContext.EvaluationStack.Push(new InteropInterface <ArrayWrapper>(wrapper2));
            engine.CurrentContext.EvaluationStack.Push(new InteropInterface <ArrayWrapper>(wrapper1));
            InteropService.Invoke(engine, InteropService.Neo_Iterator_Concat).Should().BeTrue();
            var ret = ((InteropInterface <IIterator>)engine.CurrentContext.EvaluationStack.Pop()).GetInterface <IIterator>();

            ret.Next().Should().BeTrue();
            ret.Value().GetSpan().ToHexString().Should().Be(new byte[] { 0x01 }.ToHexString());
        }
Exemple #16
0
        public void TestContract_Call()
        {
            var mockSnapshot = new Mock <Snapshot>();
            var state        = TestUtils.GetContract();

            state.Manifest.Features = ContractFeatures.HasStorage;
            byte[] method = Encoding.UTF8.GetBytes("method");
            byte[] args   = new byte[0];
            mockSnapshot.SetupGet(p => p.Contracts).Returns(new TestDataCache <UInt160, ContractState>(state.ScriptHash, state));
            var engine = new ApplicationEngine(TriggerType.Application, null, mockSnapshot.Object, 0);

            engine.LoadScript(new byte[] { 0x01 });

            engine.CurrentContext.EvaluationStack.Push(args);
            engine.CurrentContext.EvaluationStack.Push(method);
            engine.CurrentContext.EvaluationStack.Push(state.ScriptHash.ToArray());
            InteropService.Invoke(engine, InteropService.System_Contract_Call).Should().BeTrue();
            engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToHexString().Should().Be(method.ToHexString());
            engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToHexString().Should().Be(args.ToHexString());

            state.Manifest.Permissions[0].Methods = WildCardContainer <string> .Create("a");

            engine.CurrentContext.EvaluationStack.Push(args);
            engine.CurrentContext.EvaluationStack.Push(method);
            engine.CurrentContext.EvaluationStack.Push(state.ScriptHash.ToArray());
            InteropService.Invoke(engine, InteropService.System_Contract_Call).Should().BeFalse();
            state.Manifest.Permissions[0].Methods = WildCardContainer <string> .CreateWildcard();

            engine.CurrentContext.EvaluationStack.Push(args);
            engine.CurrentContext.EvaluationStack.Push(method);
            engine.CurrentContext.EvaluationStack.Push(state.ScriptHash.ToArray());
            InteropService.Invoke(engine, InteropService.System_Contract_Call).Should().BeTrue();

            engine.CurrentContext.EvaluationStack.Push(args);
            engine.CurrentContext.EvaluationStack.Push(method);
            engine.CurrentContext.EvaluationStack.Push(UInt160.Zero.ToArray());
            InteropService.Invoke(engine, InteropService.System_Contract_Call).Should().BeFalse();
        }
Exemple #17
0
        public void TestContract_CreateStandardAccount()
        {
            var engine = GetEngine(true, true);

            byte[] data = "024b817ef37f2fc3d4a33fe36687e592d9f30fe24b3e28187dc8f12b3b3b2b839e".HexToBytes();

            engine.CurrentContext.EvaluationStack.Push(data);
            InteropService.Invoke(engine, InteropService.Contract.CreateStandardAccount).Should().BeTrue();
            engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToArray().Should().BeEquivalentTo(UInt160.Parse("0x2c847208959ec1cc94dd13bfe231fa622a404a8a").ToArray());

            data = "064b817ef37f2fc3d4a33fe36687e592d9f30fe24b3e28187dc8f12b3b3b2b839e".HexToBytes();
            engine.CurrentContext.EvaluationStack.Push(data);
            Assert.ThrowsException <FormatException>(() => InteropService.Invoke(engine, InteropService.Contract.CreateStandardAccount)).Message.Should().BeEquivalentTo("Invalid point encoding 6");

            data = "024b817ef37f2fc3d4a33fe36687e599f30fe24b3e28187dc8f12b3b3b2b839e".HexToBytes();
            engine.CurrentContext.EvaluationStack.Push(data);
            Assert.ThrowsException <FormatException>(() => InteropService.Invoke(engine, InteropService.Contract.CreateStandardAccount)).Message.Should().BeEquivalentTo("Incorrect length for compressed encoding");

            data = "02ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff".HexToBytes();
            engine.CurrentContext.EvaluationStack.Push(data);
            Assert.ThrowsException <ArgumentException>(() => InteropService.Invoke(engine, InteropService.Contract.CreateStandardAccount)).Message.Should().BeEquivalentTo("x value too large in field element");

            data = "020fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff".HexToBytes();
            engine.CurrentContext.EvaluationStack.Push(data);
            Assert.ThrowsException <ArithmeticException>(() => InteropService.Invoke(engine, InteropService.Contract.CreateStandardAccount)).Message.Should().BeEquivalentTo("Invalid point compression");

            data = "044b817ef37f2fc3d4a33fe36687e592d9f30fe24b3e28187dc8f12b3b3b2b839e".HexToBytes();
            engine.CurrentContext.EvaluationStack.Push(data);
            Assert.ThrowsException <FormatException>(() => InteropService.Invoke(engine, InteropService.Contract.CreateStandardAccount)).Message.Should().BeEquivalentTo("Incorrect length for uncompressed/hybrid encoding");

            data = "04ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff".HexToBytes();
            engine.CurrentContext.EvaluationStack.Push(data);
            Assert.ThrowsException <ArgumentException>(() => InteropService.Invoke(engine, InteropService.Contract.CreateStandardAccount)).Message.Should().BeEquivalentTo("x value too large in field element");

            data = "040fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff".HexToBytes();
            engine.CurrentContext.EvaluationStack.Push(data);
            Assert.ThrowsException <ArgumentException>(() => InteropService.Invoke(engine, InteropService.Contract.CreateStandardAccount)).Message.Should().BeEquivalentTo("x value too large in field element");
        }
Exemple #18
0
        public void TestContract_Call()
        {
            var snapshot = Blockchain.Singleton.GetSnapshot();
            var state    = TestUtils.GetContract();

            state.Manifest.Features = ContractFeatures.HasStorage;
            byte[] method = Encoding.UTF8.GetBytes("method");
            byte[] args   = new byte[0];
            snapshot.Contracts.Add(state.ScriptHash, state);
            var engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0);

            engine.LoadScript(new byte[] { 0x01 });

            engine.CurrentContext.EvaluationStack.Push(args);
            engine.CurrentContext.EvaluationStack.Push(method);
            engine.CurrentContext.EvaluationStack.Push(state.ScriptHash.ToArray());
            InteropService.Invoke(engine, InteropService.Contract.Call).Should().BeTrue();
            engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToHexString().Should().Be(method.ToHexString());
            engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToHexString().Should().Be(args.ToHexString());

            state.Manifest.Permissions[0].Methods = WildcardContainer <string> .Create("a");

            engine.CurrentContext.EvaluationStack.Push(args);
            engine.CurrentContext.EvaluationStack.Push(method);
            engine.CurrentContext.EvaluationStack.Push(state.ScriptHash.ToArray());
            InteropService.Invoke(engine, InteropService.Contract.Call).Should().BeFalse();
            state.Manifest.Permissions[0].Methods = WildcardContainer <string> .CreateWildcard();

            engine.CurrentContext.EvaluationStack.Push(args);
            engine.CurrentContext.EvaluationStack.Push(method);
            engine.CurrentContext.EvaluationStack.Push(state.ScriptHash.ToArray());
            InteropService.Invoke(engine, InteropService.Contract.Call).Should().BeTrue();

            engine.CurrentContext.EvaluationStack.Push(args);
            engine.CurrentContext.EvaluationStack.Push(method);
            engine.CurrentContext.EvaluationStack.Push(UInt160.Zero.ToArray());
            InteropService.Invoke(engine, InteropService.Contract.Call).Should().BeFalse();
        }
Exemple #19
0
        public void TestIterator_Create()
        {
            var engine = GetEngine();
            var arr    = new VMArray {
                new byte[] { 0x01 },
                new byte[] { 0x02 }
            };

            engine.CurrentContext.EvaluationStack.Push(arr);
            InteropService.Invoke(engine, InteropService.Neo_Iterator_Create).Should().BeTrue();
            var ret = (InteropInterface <IIterator>)engine.CurrentContext.EvaluationStack.Pop();

            ret.GetInterface <IIterator>().Next();
            ret.GetInterface <IIterator>().Value().GetSpan().ToHexString()
            .Should().Be(new byte[] { 0x01 }.ToHexString());

            var interop = new InteropInterface <object>(1);

            engine.CurrentContext.EvaluationStack.Push(interop);
            InteropService.Invoke(engine, InteropService.Neo_Iterator_Create).Should().BeFalse();

            var map = new Map
            {
                { new Integer(1), new Integer(2) },
                { new Integer(3), new Integer(4) }
            };

            engine.CurrentContext.EvaluationStack.Push(map);
            InteropService.Invoke(engine, InteropService.Neo_Iterator_Create).Should().BeTrue();
            ret = (InteropInterface <IIterator>)engine.CurrentContext.EvaluationStack.Pop();
            ret.GetInterface <IIterator>().Next();
            ret.GetInterface <IIterator>().Key().GetBigInteger().Should().Be(1);
            ret.GetInterface <IIterator>().Value().GetBigInteger().Should().Be(2);

            engine.CurrentContext.EvaluationStack.Push(1);
            InteropService.Invoke(engine, InteropService.Neo_Iterator_Create).Should().BeTrue();
        }
Exemple #20
0
        public void ApplicationEngineVariablePrices()
        {
            // Neo.Contract.Create: f66ca56e (requires push properties on fourth position)
            byte[] SyscallContractCreateHash00 = new byte[] { 0x01, 0x00, 0x02, 0x00, 0x00, 0x68, 0xf6, 0x6c, 0xa5, 0x6e };
            using (ApplicationEngine ae = new ApplicationEngine(TriggerType.Application, null, null, 0, testMode: true))
            {
                Debugger debugger = new Debugger(ae);
                ae.LoadScript(SyscallContractCreateHash00);
                debugger.StepInto(); // PUSHBYTES1
                debugger.StepInto(); // PUSHBYTES2
                InteropService.GetPrice(InteropService.Neo_Contract_Create, ae.CurrentContext.EvaluationStack).Should().Be(0_00300000L);
            }

            // System.Storage.Put: e63f1884 (requires push key and value)
            byte[] SyscallStoragePutHash = new byte[] { 0x53, 0x53, 0x00, 0x68, 0xe6, 0x3f, 0x18, 0x84 };
            using (ApplicationEngine ae = new ApplicationEngine(TriggerType.Application, null, null, 0, testMode: true))
            {
                Debugger debugger = new Debugger(ae);
                ae.LoadScript(SyscallStoragePutHash);
                debugger.StepInto(); // push 03 (length 1)
                debugger.StepInto(); // push 03 (length 1)
                debugger.StepInto(); // push 00
                InteropService.GetPrice(InteropService.System_Storage_Put, ae.CurrentContext.EvaluationStack).Should().Be(200000L);
            }

            // System.Storage.PutEx: 73e19b3a (requires push key and value)
            byte[] SyscallStoragePutExHash = new byte[] { 0x53, 0x53, 0x00, 0x68, 0x73, 0xe1, 0x9b, 0x3a };
            using (ApplicationEngine ae = new ApplicationEngine(TriggerType.Application, null, null, 0, testMode: true))
            {
                Debugger debugger = new Debugger(ae);
                ae.LoadScript(SyscallStoragePutExHash);
                debugger.StepInto(); // push 03 (length 1)
                debugger.StepInto(); // push 03 (length 1)
                debugger.StepInto(); // push 00
                InteropService.GetPrice(InteropService.System_Storage_PutEx, ae.CurrentContext.EvaluationStack).Should().Be(200000L);
            }
        }
Exemple #21
0
        public void TestContract_Destroy()
        {
            var engine = GetEngine(false, true);

            InteropService.Invoke(engine, InteropService.System_Contract_Destroy).Should().BeTrue();

            var mockSnapshot = new Mock <Snapshot>();
            var state        = TestUtils.GetContract();

            state.Manifest.Features = ContractFeatures.HasStorage;
            var scriptHash  = UInt160.Parse("0xcb9f3b7c6fb1cf2c13a40637c189bdd066a272b4");
            var storageItem = new StorageItem
            {
                Value      = new byte[] { 0x01, 0x02, 0x03, 0x04 },
                IsConstant = false
            };

            var storageKey = new StorageKey
            {
                ScriptHash = scriptHash,
                Key        = new byte[] { 0x01 }
            };

            mockSnapshot.SetupGet(p => p.Contracts).Returns(new TestDataCache <UInt160, ContractState>(scriptHash, state));
            mockSnapshot.SetupGet(p => p.Storages).Returns(new TestDataCache <StorageKey, StorageItem>(storageKey, storageItem));
            engine = new ApplicationEngine(TriggerType.Application, null, mockSnapshot.Object, 0);
            engine.LoadScript(new byte[0]);
            InteropService.Invoke(engine, InteropService.System_Contract_Destroy).Should().BeTrue();

            //storages are removed
            mockSnapshot = new Mock <Snapshot>();
            state        = TestUtils.GetContract();
            mockSnapshot.SetupGet(p => p.Contracts).Returns(new TestDataCache <UInt160, ContractState>(scriptHash, state));
            engine = new ApplicationEngine(TriggerType.Application, null, mockSnapshot.Object, 0);
            engine.LoadScript(new byte[0]);
            InteropService.Invoke(engine, InteropService.System_Contract_Destroy).Should().BeTrue();
        }
Exemple #22
0
        public void TestContract_Create()
        {
            var engine = GetEngine(false, true);
            var script = new byte[1024 * 1024 + 1];

            engine.CurrentContext.EvaluationStack.Push(script);
            InteropService.Invoke(engine, InteropService.Neo_Contract_Create).Should().BeFalse();

            string manifestStr = new string(new char[ContractManifest.MaxLength + 1]);

            script = new byte[] { 0x01 };
            engine.CurrentContext.EvaluationStack.Push(manifestStr);
            engine.CurrentContext.EvaluationStack.Push(script);
            InteropService.Invoke(engine, InteropService.Neo_Contract_Create).Should().BeFalse();

            var manifest = ContractManifest.CreateDefault(UInt160.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff01"));

            engine.CurrentContext.EvaluationStack.Push(manifest.ToString());
            engine.CurrentContext.EvaluationStack.Push(script);
            InteropService.Invoke(engine, InteropService.Neo_Contract_Create).Should().BeFalse();

            manifest.Abi.Hash = script.ToScriptHash();
            engine.CurrentContext.EvaluationStack.Push(manifest.ToString());
            engine.CurrentContext.EvaluationStack.Push(script);
            InteropService.Invoke(engine, InteropService.Neo_Contract_Create).Should().BeTrue();

            var snapshot = Blockchain.Singleton.GetSnapshot();
            var state    = TestUtils.GetContract();

            snapshot.Contracts.Add(state.ScriptHash, state);
            engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0);
            engine.LoadScript(new byte[] { 0x01 });
            engine.CurrentContext.EvaluationStack.Push(manifest.ToString());
            engine.CurrentContext.EvaluationStack.Push(state.Script);
            InteropService.Invoke(engine, InteropService.Neo_Contract_Create).Should().BeFalse();
        }
Exemple #23
0
        public void TestContract_Create()
        {
            var engine = GetEngine(false, true);
            var script = new byte[1024 * 1024 + 1];

            engine.CurrentContext.EvaluationStack.Push(script);
            InteropService.Invoke(engine, InteropService.Neo_Contract_Create).Should().BeFalse();

            string manifestStr = new string(new char[ContractManifest.MaxLength + 1]);

            script = new byte[] { 0x01 };
            engine.CurrentContext.EvaluationStack.Push(manifestStr);
            engine.CurrentContext.EvaluationStack.Push(script);
            InteropService.Invoke(engine, InteropService.Neo_Contract_Create).Should().BeFalse();

            var manifest = ContractManifest.CreateDefault(UInt160.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff01"));

            engine.CurrentContext.EvaluationStack.Push(manifest.ToString());
            engine.CurrentContext.EvaluationStack.Push(script);
            InteropService.Invoke(engine, InteropService.Neo_Contract_Create).Should().BeFalse();

            manifest.Abi.Hash = script.ToScriptHash();
            engine.CurrentContext.EvaluationStack.Push(manifest.ToString());
            engine.CurrentContext.EvaluationStack.Push(script);
            InteropService.Invoke(engine, InteropService.Neo_Contract_Create).Should().BeTrue();

            var mockSnapshot = new Mock <Snapshot>();
            var state        = TestUtils.GetContract();

            mockSnapshot.SetupGet(p => p.Contracts).Returns(new TestDataCache <UInt160, ContractState>(state.ScriptHash, state));
            engine = new ApplicationEngine(TriggerType.Application, null, mockSnapshot.Object, 0);
            engine.LoadScript(new byte[] { 0x01 });
            engine.CurrentContext.EvaluationStack.Push(manifest.ToString());
            engine.CurrentContext.EvaluationStack.Push(state.Script);
            InteropService.Invoke(engine, InteropService.Neo_Contract_Create).Should().BeFalse();
        }
        /// <summary>
        /// Invoke Interop callback
        /// </summary>
        /// <param name="ptr">Method</param>
        /// <param name="size">Size</param>
        /// <returns>Return Interop result</returns>
        byte InternalInvokeInterop(IntPtr ptr, byte size)
        {
            if (InteropService == null)
            {
                return(NeoVM.FALSE);
            }

            var method = new byte[size];

            Marshal.Copy(ptr, method, 0, size);

            try
            {
                if (InteropService.Invoke(method, this))
                {
                    return(NeoVM.TRUE);
                }
            }
            catch
            {
            }

            return(NeoVM.FALSE);
        }
Exemple #25
0
        public void TestRuntime_CheckWitness()
        {
            byte[]  privateKey = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
                                   0x01,  0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };
            KeyPair keyPair = new KeyPair(privateKey);
            ECPoint pubkey  = keyPair.PublicKey;

            var engine = GetEngine(true);

            ((Transaction)engine.ScriptContainer).Sender = Contract.CreateSignatureRedeemScript(pubkey).ToScriptHash();

            engine.CurrentContext.EvaluationStack.Push(pubkey.EncodePoint(true));
            InteropService.Invoke(engine, InteropService.Runtime.CheckWitness).Should().BeTrue();
            engine.CurrentContext.EvaluationStack.Peek().GetType().Should().Be(typeof(Neo.VM.Types.Boolean));
            engine.CurrentContext.EvaluationStack.Pop().ToBoolean().Should().Be(false);

            engine.CurrentContext.EvaluationStack.Push(((Transaction)engine.ScriptContainer).Sender.ToArray());
            InteropService.Invoke(engine, InteropService.Runtime.CheckWitness).Should().BeTrue();
            engine.CurrentContext.EvaluationStack.Peek().GetType().Should().Be(typeof(Neo.VM.Types.Boolean));
            engine.CurrentContext.EvaluationStack.Pop().ToBoolean().Should().Be(false);

            engine.CurrentContext.EvaluationStack.Push(new byte[0]);
            InteropService.Invoke(engine, InteropService.Runtime.CheckWitness).Should().BeFalse();
        }
        public static List <string> Analysis(List <byte> scripts, bool raw)
        {
            //初始化所有 OpCode
            var OperandSizePrefixTable = new int[256];
            var OperandSizeTable       = new int[256];

            foreach (FieldInfo field in typeof(OpCode).GetFields(BindingFlags.Public | BindingFlags.Static))
            {
                var attribute = field.GetCustomAttribute <OperandSizeAttribute>();
                if (attribute == null)
                {
                    continue;
                }
                int index = (int)(OpCode)field.GetValue(null);
                OperandSizePrefixTable[index] = attribute.SizePrefix;
                OperandSizeTable[index]       = attribute.Size;
            }
            //初始化所有 InteropService
            var dic = new Dictionary <uint, string>();

            InteropService.SupportedMethods().ToList().ForEach(p => dic.Add(p.Hash, p.Method));

            //解析 Scripts
            var result = new List <string>();

            while (scripts.Count > 0)
            {
                var op = (OpCode)scripts[0];
                var operandSizePrefix = OperandSizePrefixTable[scripts[0]];
                var operandSize       = OperandSizeTable[scripts[0]];
                scripts.RemoveAt(0);

                if (operandSize > 0)
                {
                    var operand = scripts.Take(operandSize).ToArray();
                    if (op.ToString().StartsWith("PUSHINT"))
                    {
                        result.Add(raw ? $"{op.ToString()} {operand.ToHexString()}" : $"{op.ToString()} {new BigInteger(operand)}");
                    }
                    else if (op == OpCode.SYSCALL)
                    {
                        result.Add(raw ? $"{op.ToString()} {operand.ToHexString()}" : $"{op.ToString()} {dic[BitConverter.ToUInt32(operand)]}");
                    }
                    else
                    {
                        result.Add($"{op.ToString()} {operand.ToHexString()}");
                    }
                    scripts.RemoveRange(0, operandSize);
                }
                if (operandSizePrefix > 0)
                {
                    var number = (int)new BigInteger(scripts.Take(operandSizePrefix).ToArray());
                    scripts.RemoveRange(0, operandSizePrefix);
                    var operand = scripts.Take(number).ToArray();

                    result.Add(raw ? $"{op.ToString()} LENGTH:{number} {operand.ToHexString()}" : $"{op.ToString()} {(number == 20 ? new UInt160(operand).ToString() : ToAsciiString(operand))}");
                    scripts.RemoveRange(0, number);
                }
            }
            return(result);
        }
Exemple #27
0
        /// <summary>
        /// Estimate NetworkFee, assuming the witnesses are basic Signature Contract
        /// </summary>
        private long EstimateNetworkFee()
        {
            long networkFee = 0;

            UInt160[] hashes = Tx.GetScriptHashesForVerifying(null);
            int       size   = Transaction.HeaderSize + Tx.Attributes.GetVarSize() + Tx.Script.GetVarSize() + IO.Helper.GetVarSize(hashes.Length);

            // assume the hashes are single Signature
            foreach (var hash in hashes)
            {
                size       += 166;
                networkFee += ApplicationEngine.OpCodePrices[OpCode.PUSHBYTES64] + ApplicationEngine.OpCodePrices[OpCode.PUSHBYTES33] + InteropService.GetPrice(InteropService.Neo_Crypto_ECDsaVerify, null);
            }

            networkFee += size * policyAPI.GetFeePerByte();
            return(networkFee);
        }
Exemple #28
0
        public void TestStorage_Put()
        {
            var engine = GetEngine(false, true);

            engine.CurrentContext.EvaluationStack.Push(1);
            InteropService.Invoke(engine, InteropService.System_Storage_Put).Should().BeFalse();

            //CheckStorageContext fail
            var key   = new byte[] { 0x01 };
            var value = new byte[] { 0x02 };

            engine.CurrentContext.EvaluationStack.Push(value);
            engine.CurrentContext.EvaluationStack.Push(key);
            var state          = TestUtils.GetContract();
            var storageContext = new StorageContext
            {
                ScriptHash = state.ScriptHash,
                IsReadOnly = false
            };

            engine.CurrentContext.EvaluationStack.Push(new InteropInterface <StorageContext>(storageContext));
            InteropService.Invoke(engine, InteropService.System_Storage_Put).Should().BeFalse();

            //key.Length > MaxStorageKeySize
            key   = new byte[InteropService.MaxStorageKeySize + 1];
            value = new byte[] { 0x02 };
            engine.CurrentContext.EvaluationStack.Push(value);
            engine.CurrentContext.EvaluationStack.Push(key);
            engine.CurrentContext.EvaluationStack.Push(new InteropInterface <StorageContext>(storageContext));
            InteropService.Invoke(engine, InteropService.System_Storage_Put).Should().BeFalse();

            //value.Length > MaxStorageValueSize
            key   = new byte[] { 0x01 };
            value = new byte[ushort.MaxValue + 1];
            engine.CurrentContext.EvaluationStack.Push(value);
            engine.CurrentContext.EvaluationStack.Push(key);
            engine.CurrentContext.EvaluationStack.Push(new InteropInterface <StorageContext>(storageContext));
            InteropService.Invoke(engine, InteropService.System_Storage_Put).Should().BeFalse();

            //context.IsReadOnly
            key   = new byte[] { 0x01 };
            value = new byte[] { 0x02 };
            storageContext.IsReadOnly = true;
            engine.CurrentContext.EvaluationStack.Push(value);
            engine.CurrentContext.EvaluationStack.Push(key);
            engine.CurrentContext.EvaluationStack.Push(new InteropInterface <StorageContext>(storageContext));
            InteropService.Invoke(engine, InteropService.System_Storage_Put).Should().BeFalse();

            //storage value is constant
            var mockSnapshot = new Mock <Snapshot>();

            state.Manifest.Features = ContractFeatures.HasStorage;

            var storageKey = new StorageKey
            {
                ScriptHash = state.ScriptHash,
                Key        = new byte[] { 0x01 }
            };
            var storageItem = new StorageItem
            {
                Value      = new byte[] { 0x01, 0x02, 0x03, 0x04 },
                IsConstant = true
            };

            mockSnapshot.SetupGet(p => p.Contracts).Returns(new TestDataCache <UInt160, ContractState>(state.ScriptHash, state));
            mockSnapshot.SetupGet(p => p.Storages).Returns(new TestDataCache <StorageKey, StorageItem>(storageKey, storageItem));
            engine = new ApplicationEngine(TriggerType.Application, null, mockSnapshot.Object, 0);
            engine.LoadScript(new byte[] { 0x01 });
            key   = new byte[] { 0x01 };
            value = new byte[] { 0x02 };
            storageContext.IsReadOnly = false;
            engine.CurrentContext.EvaluationStack.Push(value);
            engine.CurrentContext.EvaluationStack.Push(key);
            engine.CurrentContext.EvaluationStack.Push(new InteropInterface <StorageContext>(storageContext));
            InteropService.Invoke(engine, InteropService.System_Storage_Put).Should().BeFalse();

            //success
            storageItem.IsConstant = false;
            engine.CurrentContext.EvaluationStack.Push(value);
            engine.CurrentContext.EvaluationStack.Push(key);
            engine.CurrentContext.EvaluationStack.Push(new InteropInterface <StorageContext>(storageContext));
            InteropService.Invoke(engine, InteropService.System_Storage_Put).Should().BeTrue();

            //value length == 0
            key   = new byte[] { 0x01 };
            value = new byte[0];
            engine.CurrentContext.EvaluationStack.Push(value);
            engine.CurrentContext.EvaluationStack.Push(key);
            engine.CurrentContext.EvaluationStack.Push(new InteropInterface <StorageContext>(storageContext));
            InteropService.Invoke(engine, InteropService.System_Storage_Put).Should().BeTrue();
        }
Exemple #29
0
        public void TestStorage_Put()
        {
            var engine = GetEngine(false, true);

            engine.CurrentContext.EvaluationStack.Push(1);
            InteropService.Invoke(engine, InteropService.Storage.Put).Should().BeFalse();

            //CheckStorageContext fail
            var key   = new byte[] { 0x01 };
            var value = new byte[] { 0x02 };

            engine.CurrentContext.EvaluationStack.Push(value);
            engine.CurrentContext.EvaluationStack.Push(key);
            var state          = TestUtils.GetContract();
            var storageContext = new StorageContext
            {
                ScriptHash = state.ScriptHash,
                IsReadOnly = false
            };

            engine.CurrentContext.EvaluationStack.Push(new InteropInterface(storageContext));
            InteropService.Invoke(engine, InteropService.Storage.Put).Should().BeFalse();

            //key.Length > MaxStorageKeySize
            key   = new byte[InteropService.Storage.MaxKeySize + 1];
            value = new byte[] { 0x02 };
            engine.CurrentContext.EvaluationStack.Push(value);
            engine.CurrentContext.EvaluationStack.Push(key);
            engine.CurrentContext.EvaluationStack.Push(new InteropInterface(storageContext));
            InteropService.Invoke(engine, InteropService.Storage.Put).Should().BeFalse();

            //value.Length > MaxStorageValueSize
            key   = new byte[] { 0x01 };
            value = new byte[ushort.MaxValue + 1];
            engine.CurrentContext.EvaluationStack.Push(value);
            engine.CurrentContext.EvaluationStack.Push(key);
            engine.CurrentContext.EvaluationStack.Push(new InteropInterface(storageContext));
            InteropService.Invoke(engine, InteropService.Storage.Put).Should().BeFalse();

            //context.IsReadOnly
            key   = new byte[] { 0x01 };
            value = new byte[] { 0x02 };
            storageContext.IsReadOnly = true;
            engine.CurrentContext.EvaluationStack.Push(value);
            engine.CurrentContext.EvaluationStack.Push(key);
            engine.CurrentContext.EvaluationStack.Push(new InteropInterface(storageContext));
            InteropService.Invoke(engine, InteropService.Storage.Put).Should().BeFalse();

            //storage value is constant
            var snapshot = Blockchain.Singleton.GetSnapshot();

            state.Manifest.Features = ContractFeatures.HasStorage;

            var storageKey = new StorageKey
            {
                ScriptHash = state.ScriptHash,
                Key        = new byte[] { 0x01 }
            };
            var storageItem = new StorageItem
            {
                Value      = new byte[] { 0x01, 0x02, 0x03, 0x04 },
                IsConstant = true
            };

            snapshot.Contracts.Add(state.ScriptHash, state);
            snapshot.Storages.Add(storageKey, storageItem);
            engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0);
            engine.LoadScript(new byte[] { 0x01 });
            key   = new byte[] { 0x01 };
            value = new byte[] { 0x02 };
            storageContext.IsReadOnly = false;
            engine.CurrentContext.EvaluationStack.Push(value);
            engine.CurrentContext.EvaluationStack.Push(key);
            engine.CurrentContext.EvaluationStack.Push(new InteropInterface(storageContext));
            InteropService.Invoke(engine, InteropService.Storage.Put).Should().BeFalse();

            //success
            storageItem.IsConstant = false;
            engine.CurrentContext.EvaluationStack.Push(value);
            engine.CurrentContext.EvaluationStack.Push(key);
            engine.CurrentContext.EvaluationStack.Push(new InteropInterface(storageContext));
            InteropService.Invoke(engine, InteropService.Storage.Put).Should().BeTrue();

            //value length == 0
            key   = new byte[] { 0x01 };
            value = new byte[0];
            engine.CurrentContext.EvaluationStack.Push(value);
            engine.CurrentContext.EvaluationStack.Push(key);
            engine.CurrentContext.EvaluationStack.Push(new InteropInterface(storageContext));
            InteropService.Invoke(engine, InteropService.Storage.Put).Should().BeTrue();
        }
Exemple #30
0
 public ApplicationEngine(TriggerType trigger, IScriptContainer container, IScriptTable table, InteropService service, Fixed8 gas, bool testMode = false)
     : base(container, Cryptography.Crypto.Default, table, service)
 {
     this.gas_amount = gas_free + gas.GetData();
     this.testMode   = testMode;
     this.Trigger    = trigger;
     if (table is CachedScriptTable)
     {
         this.script_table = (CachedScriptTable)table;
     }
 }