Exemple #1
0
 public static byte[] CreateMultiSigRedeemScript(int m, params ECPoint[] publicKeys)
 {
     if (!(1 <= m && m <= publicKeys.Length && publicKeys.Length <= 1024))
     {
         throw new ArgumentException();
     }
     using (ScriptBuilder sb = new ScriptBuilder())
     {
         sb.EmitPush(m);
         foreach (ECPoint publicKey in publicKeys.OrderBy(p => p))
         {
             sb.EmitPush(publicKey.EncodePoint(true));
         }
         sb.EmitPush(publicKeys.Length);
         sb.Emit(OpCode.CHECKMULTISIG);
         return(sb.ToArray());
     }
 }
Exemple #2
0
        private void TestEmit(DebugInformationFormat format)
        {
            var script      = CSharpScript.Create("1 + 2", options: ScriptOptions.Default.WithEmitDebugInformation(true));
            var compilation = script.GetCompilation();
            var emitOptions = ScriptBuilder.GetEmitOptions(emitDebugInformation: true).WithDebugInformationFormat(format);

            var peStream   = new MemoryStream();
            var pdbStream  = new MemoryStream();
            var emitResult = ScriptBuilder.Emit(peStream, pdbStream, compilation, emitOptions, cancellationToken: default);

            peStream.Position  = 0;
            pdbStream.Position = 0;

            PdbValidation.ValidateDebugDirectory(
                peStream,
                portablePdbStreamOpt: (format == DebugInformationFormat.PortablePdb) ? pdbStream : null,
                pdbPath: compilation.AssemblyName + ".pdb",
                hashAlgorithm: default,
Exemple #3
0
        public void Test_Optimize_StaticMath_ABS()
        {
            using (var scriptBefore = new ScriptBuilder())
            {
                scriptBefore.Emit(VM.OpCode.PUSH0);
                scriptBefore.Emit(VM.OpCode.ABS);

                using (var scriptAfter = new ScriptBuilder())
                {
                    scriptAfter.EmitPush(0);

                    var optimized = NefOptimizeTool.Optimize(scriptBefore.ToArray(), Array.Empty <int>(), OptimizeParserType.DELETE_CONST_EXECUTION);
                    CollectionAssert.AreEqual(scriptAfter.ToArray(), optimized);
                }
            }

            using (var scriptBefore = new ScriptBuilder())
            {
                scriptBefore.EmitPush(1);
                scriptBefore.Emit(VM.OpCode.ABS);

                using (var scriptAfter = new ScriptBuilder())
                {
                    scriptAfter.EmitPush(1);

                    var optimized = NefOptimizeTool.Optimize(scriptBefore.ToArray(), Array.Empty <int>(), OptimizeParserType.DELETE_CONST_EXECUTION);
                    CollectionAssert.AreEqual(scriptAfter.ToArray(), optimized);
                }
            }

            using (var scriptBefore = new ScriptBuilder())
            {
                scriptBefore.EmitPush(-1);
                scriptBefore.Emit(VM.OpCode.ABS);

                using (var scriptAfter = new ScriptBuilder())
                {
                    scriptAfter.EmitPush(1);

                    var optimized = NefOptimizeTool.Optimize(scriptBefore.ToArray(), Array.Empty <int>(), OptimizeParserType.DELETE_CONST_EXECUTION);
                    CollectionAssert.AreEqual(scriptAfter.ToArray(), optimized);
                }
            }
        }
        /// <summary>
        /// MINT TOKENS
        /// </summary>
        /// <returns></returns>
        public static bool MintTokens()
        {
            ExecutionEngine engine = new ExecutionEngine(scriptContainer, Crypto.Default, null, service);

            engine.LoadScript(File.ReadAllBytes(Helper.CONTRACT_ADDRESS));

            using (ScriptBuilder sb = new ScriptBuilder())
            {
                sb.EmitPush(0);
                sb.Emit(OpCode.PACK);
                sb.EmitPush(Helper.OPERATION_MINT_TOKENS);
                engine.LoadScript(sb.ToArray());
            }

            engine.Execute();

            Assert.AreEqual(engine.State, VMState.HALT);
            return(engine.EvaluationStack.Peek().GetBoolean());
        }
Exemple #5
0
 public static byte[] CreateMultiSigRedeemScript(int m, params ECPoint[] publicKeys)
 {
     if (!(1 <= m && m <= publicKeys.Length && publicKeys.Length <= 1024))
     {
         throw new ArgumentException();
     }
     using (ScriptBuilder sb = new ScriptBuilder())
     {
         sb.EmitPush(m);
         foreach (ECPoint publicKey in publicKeys.OrderBy(p => p))
         {
             sb.EmitPush(publicKey.EncodePoint(true));
         }
         sb.EmitPush(publicKeys.Length);
         sb.Emit(OpCode.PUSHNULL);
         sb.EmitSysCall(InteropService.Neo_Crypto_ECDsaCheckMultiSig);
         return(sb.ToArray());
     }
 }
Exemple #6
0
        private Transaction MakeTransaction(List <TransferRequestModel> transfers)
        {
            var lookup = transfers.ToLookup(t => new
            {
                t.Sender,
                t.Asset
            });

            using var sb = new ScriptBuilder();
            var snapshot = Helpers.GetDefaultSnapshot();

            foreach (var transferRequests in lookup)
            {
                var        sender    = transferRequests.Key.Sender;
                var        assetHash = transferRequests.Key.Asset;
                BigInteger amount    = 0;
                transferRequests.ForEach(t => amount += t.Amount.Value);
                Console.WriteLine($"Transfer[{transferRequests.Key.Asset}]:{transferRequests.Key.Sender}=>{amount}");
                var balance = sender.GetBalanceOf(assetHash, snapshot).Value;
                if (balance < amount)
                {
                    //balance not enough
                    return(null);
                }
                foreach (var transfer in transferRequests)
                {
                    sb.EmitDynamicCall(assetHash, "transfer", sender, transfer.Receiver, transfer.Amount.Value, null);
                    sb.Emit(OpCode.ASSERT);
                }
            }

            var script    = sb.ToArray();
            var senders   = transfers.Select(t => t.Sender).ToHashSet();
            var cosigners = senders.Select(p =>
                                           new Signer()
            {
                // default access for transfers should be valid only for first invocation
                Scopes  = WitnessScope.CalledByEntry,
                Account = p
            }).ToArray();

            return(CurrentWallet.MakeTransaction(snapshot, script, null, cosigners, new TransactionAttribute[0]));
        }
Exemple #7
0
        public void FeeIsSignatureContract_TestScope_NoScopeFAULT()
        {
            var wallet   = TestUtils.GenerateTestWallet();
            var snapshot = Blockchain.Singleton.GetSnapshot();

            // no password on this wallet
            using (var unlock = wallet.Unlock(""))
            {
                var acc = wallet.CreateAccount();

                // Fake balance

                var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash);

                var entry = snapshot.Storages.GetAndChange(key, () => new StorageItem(new Nep5AccountState()));

                entry.GetInteroperable <Nep5AccountState>().Balance = 10000 * NativeContract.GAS.Factor;

                // Make transaction
                // Manually creating script

                byte[] script;
                using (ScriptBuilder sb = new ScriptBuilder())
                {
                    // self-transfer of 1e-8 GAS
                    System.Numerics.BigInteger value = (new BigDecimal(1, 8)).Value;
                    sb.EmitAppCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value);
                    sb.Emit(OpCode.ASSERT);
                    script = sb.ToArray();
                }

                // trying with no scope
                var attributes = new TransactionAttribute[] { };

                // using this...

                // expects FAULT on execution of 'transfer' Application script
                // due to lack of a valid witness validation
                Transaction tx = null;
                Assert.ThrowsException <InvalidOperationException>(() => tx = wallet.MakeTransaction(script, acc.ScriptHash, attributes));
                Assert.IsNull(tx);
            }
        }
Exemple #8
0
        public void TestSetAndIsInitializedIsTrue()
        {
            // test is_initialized (expect false)
            ExecutionEngine engine = LoadContract("HubContract");

            using (ScriptBuilder sb = new ScriptBuilder()) {
                sb.EmitPush(0);
                sb.Emit(OpCode.PACK);
                sb.EmitPush("is_initialized");
                ExecuteScript(engine, sb);
            }
            var result = engine.EvaluationStack.Peek().GetBoolean();

            Assert.False(result);

            // initialize
            ExecutionEngine engine1 = LoadContract("HubContract");

            using (ScriptBuilder sb = new ScriptBuilder()) {
                // initialize the contract, get back the stored blobs
                sb.EmitPush(new byte[] { 7, 8, 9 });
                sb.EmitPush(new byte[] { 4, 5, 6 });
                sb.EmitPush(new byte[] { 1, 2, 3 });
                sb.EmitPush(3);
                sb.Emit(OpCode.PACK);
                sb.EmitPush("initialize"); // operation
                ExecuteScript(engine1, sb);
            }

            // test is_initialized (expect true)
            ExecutionEngine engine2 = LoadContract("HubContract");

            using (ScriptBuilder sb = new ScriptBuilder()) {
                sb.EmitPush(0);
                sb.Emit(OpCode.PACK);
                sb.EmitPush("is_initialized");
                ExecuteScript(engine2, sb);
            }
            var result2 = engine2.EvaluationStack.Peek().GetBoolean();

            Assert.True(result2);
        }
Exemple #9
0
        public static byte[] GenerateScript(UInt160 scriptHash, object[] args, byte[] nonce)
        {
            using (var sb = new ScriptBuilder())
            {
                var items = new Stack <object>();

                if (args != null)
                {
                    foreach (var item in args)
                    {
                        items.Push(item);
                    }
                }

                while (items.Count > 0)
                {
                    var item = items.Pop();
                    EmitObject(sb, item);
                }

                sb.EmitAppCall(scriptHash, false);

                if (nonce == null)
                {
                    var timestamp = DateTime.UtcNow.ToTimestamp();
                    nonce = BitConverter.GetBytes(timestamp);
                }

                if (nonce.Length > 0)
                {
                    sb.Emit(OpCode.RET);
                    sb.EmitPush(nonce);
                }

                var bytes = sb.ToArray();

                string hex = bytes.ByteToHex();
                //System.IO.File.WriteAllBytes(@"D:\code\Crypto\neo-debugger-tools\ICO-Template\bin\Debug\inputs.avm", bytes);

                return(bytes);
            }
        }
Exemple #10
0
        /// <summary>
        /// Creates the multiple public key redeem contract ('multisig account')
        /// </summary>
        /// <returns>The multiple public key redeem contract.</returns>
        /// <param name="numberOfRequiredPublicKeys">Number of required public keys.</param>
        /// <param name="publicKeys">Public keys.</param>
        public static Contract CreateMultiplePublicKeyRedeemContract(int numberOfRequiredPublicKeys, ECPoint[] publicKeys)
        {
            if (!((1 <= numberOfRequiredPublicKeys) &&
                  (numberOfRequiredPublicKeys <= publicKeys.Length) &&
                  (publicKeys.Length <= 1024)))
            {
                throw new ArgumentException("Invalid public keys. ");
            }

            byte[] contractHexCode;

            using (ScriptBuilder sb = new ScriptBuilder())
            {
                sb.EmitPush(numberOfRequiredPublicKeys);
                foreach (ECPoint publicKey in publicKeys.OrderBy(p => p))
                {
                    sb.EmitPush(publicKey.EncodedData);
                }
                sb.EmitPush(publicKeys.Length);
                sb.Emit(EVMOpCode.CHECKMULTISIG);
                contractHexCode = sb.ToArray();
            }

            ContractParameterType returnType = ContractParameterType.Void;

            ContractParameterType[] parameters = Enumerable.Repeat(ContractParameterType.Signature, numberOfRequiredPublicKeys).ToArray();

            Code contractCode = new Code
            {
                Script     = contractHexCode,
                ScriptHash = contractHexCode.ToScriptHash(),
                ReturnType = returnType,
                Parameters = parameters
            };

            Contract contract = new Contract
            {
                Code = contractCode
            };

            return(contract);
        }
        private void ProcessSwitch(ScriptBuilder sb)
        {
            if (Arguments.Length != 1)
            {
                throw new CompilerException(LineNumber, ERR_INCORRECT_NUMBER);
            }

            byte dest_reg;

            if (Arguments[0].IsRegister())
            {
                dest_reg = Arguments[0].AsRegister();
            }
            else
            {
                throw new CompilerException(LineNumber, ERR_INVALID_ARGUMENT);
            }

            sb.Emit(this._opcode.Value, new byte[] { dest_reg });
        }
        private void Process1Reg(ScriptBuilder sb)
        {
            if (Arguments.Length != 1)
            {
                throw new CompilerException(LineNumber, ERR_INCORRECT_NUMBER);
            }

            if (Arguments[0].IsRegister())
            {
                var reg = Arguments[0].AsRegister();
                sb.Emit(this._opcode.Value, new[]
                {
                    reg
                });
            }
            else
            {
                throw new CompilerException(LineNumber, ERR_INVALID_ARGUMENT);
            }
        }
        public void Test_CombinedRules()
        {
            using (var scriptBefore = new ScriptBuilder())
            using (var scriptAfter = new ScriptBuilder())
            {
                scriptBefore.Emit(VM.OpCode.PUSH1);
                scriptBefore.Emit(VM.OpCode.NOP);
                scriptBefore.Emit(VM.OpCode.PUSH0);
                scriptBefore.Emit(VM.OpCode.NOP);
                scriptBefore.Emit(VM.OpCode.EQUAL);
                scriptBefore.Emit(VM.OpCode.PUSH0);
                scriptBefore.Emit(VM.OpCode.EQUAL);

                var optimized = NefOptimizeTool.Optimize(scriptBefore.ToArray(), OptimizeParserType.DELETE_USELESS_EQUAL, OptimizeParserType.DELETE_NOP);

                scriptAfter.Emit(VM.OpCode.PUSH1);

                CollectionAssert.AreEqual(scriptAfter.ToArray(), optimized);
            }
        }
Exemple #14
0
        public void TestGetReservationRecipient()
        {
            ExecutionEngine engine = LoadContract("HubContract");

            using (ScriptBuilder sb = new ScriptBuilder()) {
                sb.EmitPush(new byte[] {
                    0xFF, 0xFF, 0xFF, 0x7F,    // timestamp is 4 bytes
                    0xFF, 0xFF, 0xFF, 0x7F, 0, // value is 5 bytes
                    5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1,
                });
                sb.EmitPush(1);
                sb.Emit(OpCode.PACK);
                sb.EmitPush("test_reservation_getRecipient"); // operation
                ExecuteScript(engine, sb);
            }

            var expected = new byte[] { 5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1 };
            var result   = engine.EvaluationStack.Peek().GetByteArray();

            Assert.Equal(expected, result);
        }
Exemple #15
0
        public static bool TransferToken(string fromSH, string toSH, int value)
        {
            ExecutionEngine engine = new ExecutionEngine(scriptContainer, Crypto.Default, null, service);

            engine.LoadScript(File.ReadAllBytes(CONTRACT_ADDRESS));

            using (ScriptBuilder sb = new ScriptBuilder())
            {
                sb.EmitPush(value);
                sb.EmitPush(UInt160.Parse(toSH));
                sb.EmitPush(UInt160.Parse(fromSH));
                sb.EmitPush(3);
                sb.Emit(OpCode.PACK);
                sb.EmitPush("transfer");
                engine.LoadScript(sb.ToArray());
            }

            engine.Execute();
            Assert.AreEqual(engine.State, VMState.HALT);
            return(engine.EvaluationStack.Peek().GetBoolean());
        }
Exemple #16
0
        public static BigInteger TotalSupply(this NativeContract contract, StoreView snapshot)
        {
            var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot);

            engine.LoadScript(contract.Script);

            var script = new ScriptBuilder();

            script.EmitPush(0);
            script.Emit(OpCode.PACK);
            script.EmitPush("totalSupply");
            engine.LoadScript(script.ToArray());

            engine.Execute().Should().Be(VMState.HALT);

            var result = engine.ResultStack.Pop();

            result.Should().BeOfType(typeof(VM.Types.Integer));

            return(result.GetInteger());
        }
        public void TestCreateTravelValidationCarrySpaceTooHigh()
        {
            ExecutionEngine engine = LoadContract("HubContract");

            // failure case: carrySpace is too high below.

            using (ScriptBuilder sb = new ScriptBuilder()) {
                sb.EmitPush(128);        // args[3] - carrySpace
                sb.EmitPush(1);          // args[2] - repRequired
                sb.EmitPush(1);          // args[1] - expiry
                sb.EmitPush(ScriptHash); // args[0] - owner
                sb.EmitPush(4);
                sb.Emit(OpCode.PACK);
                sb.EmitPush("test_travel_create"); // operation
                ExecuteScript(engine, sb);
            }

            var result = engine.EvaluationStack.Peek().GetByteArray();

            Assert.Equal(new byte[] { }, result);
        }
Exemple #18
0
        internal static ECPoint[] Check_GetValidators(Snapshot snapshot)
        {
            var engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, true);

            engine.LoadScript(NativeContract.NEO.Script);

            var script = new ScriptBuilder();

            script.EmitPush(0);
            script.Emit(OpCode.PACK);
            script.EmitPush("getValidators");
            engine.LoadScript(script.ToArray());

            engine.Execute().Should().Be(VMState.HALT);

            var result = engine.ResultStack.Pop();

            result.Should().BeOfType(typeof(VM.Types.Array));

            return((result as VM.Types.Array).Select(u => u.GetByteArray().AsSerializable <ECPoint>()).ToArray());
        }
Exemple #19
0
        public static string Symbol(this NativeContract contract)
        {
            var engine = ApplicationEngine.Create(TriggerType.Application, null, null);

            engine.LoadScript(contract.Script);

            var script = new ScriptBuilder();

            script.EmitPush(0);
            script.Emit(OpCode.PACK);
            script.EmitPush("symbol");
            engine.LoadScript(script.ToArray());

            engine.Execute().Should().Be(VMState.HALT);

            var result = engine.ResultStack.Pop();

            result.Should().BeOfType(typeof(VM.Types.ByteString));

            return(result.GetString());
        }
Exemple #20
0
        public static BigInteger Decimals(this NativeContract contract)
        {
            var engine = new ApplicationEngine(TriggerType.Application, null, null, 0);

            engine.LoadScript(contract.Script);

            var script = new ScriptBuilder();

            script.EmitPush(0);
            script.Emit(OpCode.PACK);
            script.EmitPush("decimals");
            engine.LoadScript(script.ToArray());

            engine.Execute().Should().Be(VMState.HALT);

            var result = engine.ResultStack.Pop();

            result.Should().BeOfType(typeof(VM.Types.Integer));

            return((result as VM.Types.Integer).GetBigInteger());
        }
Exemple #21
0
        public static string Name(this NativeContract contract)
        {
            var engine = new ApplicationEngine(TriggerType.Application, null, null, 0);

            engine.LoadScript(contract.Script);

            var script = new ScriptBuilder();

            script.EmitPush(0);
            script.Emit(OpCode.PACK);
            script.EmitPush("name");
            engine.LoadScript(script.ToArray());

            engine.Execute().Should().Be(VMState.HALT);

            var result = engine.ResultStack.Pop();

            result.Should().BeOfType(typeof(VM.Types.ByteArray));

            return(Encoding.UTF8.GetString((result as VM.Types.ByteArray).GetByteArray()));
        }
        public void Test_Optimize_JMP_LNext()
        {
            using var scriptBefore = new ScriptBuilder();
            scriptBefore.Emit(VM.OpCode.JMP_L, ToJumpLArg(5));       // ───┐
            scriptBefore.Emit(VM.OpCode.PUSH1);                      // <──┘

            // useshortaddress before deleteuselessjmp
            var optimized = NefOptimizeTool.Optimize(scriptBefore.ToArray(), new OptimizeParserType[] { OptimizeParserType.USE_SHORT_ADDRESS, OptimizeParserType.DELETE_USERLESS_JMP });

            using var scriptAfter = new ScriptBuilder();
            scriptAfter.Emit(VM.OpCode.PUSH1);
            CollectionAssert.AreEqual(scriptAfter.ToArray(), optimized);

            // deleteuselessjmp before useshortaddress
            optimized = NefOptimizeTool.Optimize(scriptBefore.ToArray(), new OptimizeParserType[] { OptimizeParserType.DELETE_USERLESS_JMP, OptimizeParserType.USE_SHORT_ADDRESS });
            CollectionAssert.AreEqual(scriptAfter.ToArray(), optimized);

            // use deleteuselessjmp only
            optimized = NefOptimizeTool.Optimize(scriptBefore.ToArray(), new OptimizeParserType[] { OptimizeParserType.DELETE_USERLESS_JMP });
            CollectionAssert.AreEqual(scriptAfter.ToArray(), optimized);
        }
        public void Check_CommitteeBonus()
        {
            var snapshot = Blockchain.Singleton.GetSnapshot();

            snapshot.PersistingBlock = new Block {
                Index = 0
            };

            using (ScriptBuilder sb = new ScriptBuilder())
            {
                sb.EmitAppCall(NativeContract.NEO.Hash, "onPersist");
                sb.Emit(OpCode.RET);
                ApplicationEngine engine = ApplicationEngine.Create(TriggerType.System, null, snapshot, (long)(20 * NativeContract.GAS.Factor));
                engine.LoadScript(sb.ToArray());
                engine.Execute();
                engine.State.Should().Be(VM.VMState.HALT);

                var committee = Blockchain.StandbyCommittee.OrderBy(p => p).ToArray();
                NativeContract.GAS.BalanceOf(snapshot, Contract.CreateSignatureContract(committee[0]).ScriptHash.ToArray()).Should().Be(25000000);
                NativeContract.GAS.BalanceOf(snapshot, Contract.CreateSignatureContract(committee[1]).ScriptHash.ToArray()).Should().Be(0);
            }
        }
        public static BigInteger BalanceOf(this NativeContract contract, StoreView snapshot, byte[] account)
        {
            var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot);

            engine.LoadScript(contract.Script, CallFlags.All, contract.Hash);

            var script = new ScriptBuilder();

            script.EmitPush(account);
            script.EmitPush(1);
            script.Emit(OpCode.PACK);
            script.EmitPush("balanceOf");
            engine.LoadScript(script.ToArray());

            engine.Execute().Should().Be(VMState.HALT);

            var result = engine.ResultStack.Pop();

            result.Should().BeOfType(typeof(VM.Types.Integer));

            return(result.GetInteger());
        }
Exemple #25
0
        public static NEP5AssetItem GetBalance(UInt160 nep5ScriptHash, IList <UInt160> accountScriptHashes)
        {
            byte[] script;
            using (var builder = new ScriptBuilder())
            {
                foreach (var accountScriptHash in accountScriptHashes)
                {
                    builder.EmitAppCall(nep5ScriptHash, "balanceOf", accountScriptHash);
                }
                builder.Emit(OpCode.DEPTH, OpCode.PACK);
                builder.EmitAppCall(nep5ScriptHash, "decimals");
                builder.EmitAppCall(nep5ScriptHash, "name");
                script = builder.ToArray();
            }

            var engine = ApplicationEngine.Run(script);

            if (engine.State.HasFlag(VMState.FAULT))
            {
                return(null);
            }

            var name     = engine.EvaluationStack.Pop().GetString();
            var decimals = (byte)engine.EvaluationStack.Pop().GetBigInteger();
            var amount   = engine.EvaluationStack.Pop().GetArray().Aggregate(BigInteger.Zero, (x, y) => x + y.GetBigInteger());

            var balance = new BigDecimal();

            if (amount != 0)
            {
                balance = new BigDecimal(amount, decimals);
            }

            // TODO Set issuer
            return(new NEP5AssetItem(nep5ScriptHash, balance)
            {
                Name = name
            });
        }
Exemple #26
0
        public void TestCreateReservation()
        {
            ExecutionEngine engine = LoadContract("HubContract");

            using (ScriptBuilder sb = new ScriptBuilder()) {
                sb.EmitPush(new byte[] { 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5 }); // args[2]
                sb.EmitPush(2147483647);                                                                // args[1] - value
                sb.EmitPush(2147483647);                                                                // args[0] - timestamp
                sb.EmitPush(3);
                sb.Emit(OpCode.PACK);
                sb.EmitPush("test_reservation_create"); // operation
                ExecuteScript(engine, sb);
            }

            var result = engine.EvaluationStack.Peek().GetByteArray();

            Assert.Equal(new byte[] {
                0xFF, 0xFF, 0xFF, 0x7F,    // timestamp is 4 bytes
                0xFF, 0xFF, 0xFF, 0x7F, 0, // value is 5 bytes
                1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5,
            }, result);
        }
Exemple #27
0
        public static BigInteger BalanceOf(this NativeContract contract, Persistence.Snapshot snapshot, byte[] account)
        {
            var engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, true);

            engine.LoadScript(contract.Script);

            var script = new ScriptBuilder();

            script.EmitPush(account);
            script.EmitPush(1);
            script.Emit(OpCode.PACK);
            script.EmitPush("balanceOf");
            engine.LoadScript(script.ToArray());

            engine.Execute().Should().Be(VMState.HALT);

            var result = engine.ResultStack.Pop();

            result.Should().BeOfType(typeof(VM.Types.Integer));

            return((result as VM.Types.Integer).GetBigInteger());
        }
Exemple #28
0
        public void TestGetReservationExpiry()
        {
            ExecutionEngine engine = LoadContract("HubContract");

            var reservation = new byte[] {
                0xFF, 0xFF, 0xFF, 0x7F,    // timestamp is 4 bytes
                0xFF, 0xFF, 0xFF, 0x7F, 0, // value is 5 bytes
                5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1,
            };

            using (ScriptBuilder sb = new ScriptBuilder()) {
                sb.EmitPush(reservation); // args[0]
                sb.EmitPush(1);
                sb.Emit(OpCode.PACK);
                sb.EmitPush("test_reservation_getExpiry"); // operation
                ExecuteScript(engine, sb);
            }

            var result = engine.EvaluationStack.Peek().GetBigInteger();

            Assert.Equal(2147483647, result);
        }
Exemple #29
0
        public void TestGetDemandLookupKey()
        {
            ExecutionEngine engine = LoadContract("HubContract");

            using (ScriptBuilder sb = new ScriptBuilder()) {
                // input is a city pair hash160
                sb.EmitPush(ScriptHash);
                sb.EmitPush(Demand);
                sb.EmitPush(2);
                sb.Emit(OpCode.PACK);
                sb.EmitPush("test_demand_getLookupKey"); // operation
                ExecuteScript(engine, sb);
            }
            var expected = new byte[] {
                1, 0, 0, 0, // nowTime
                1, 0, 0, 0, // expiry
                1           // STORAGE_KEY_SUFFIX_DEMAND
            }.Concat(ScriptHash).ToArray();
            var result = engine.EvaluationStack.Peek().GetByteArray();

            Assert.Equal(expected, result);
        }
        public void TestCreateTravel()
        {
            ExecutionEngine engine = LoadContract("HubContract");

            // private fun travel_create(pickupCityHash: Hash160, destCityHash: Hash160,
            //                            repRequired: BigInteger, carrySpace: BigInteger): Travel {

            using (ScriptBuilder sb = new ScriptBuilder()) {
                sb.EmitPush(2);          // args[3] - carrySpace
                sb.EmitPush(1);          // args[2] - repRequired
                sb.EmitPush(1);          // args[1] - expiry
                sb.EmitPush(ScriptHash); // args[0] - owner
                sb.EmitPush(4);
                sb.Emit(OpCode.PACK);
                sb.EmitPush("test_travel_create"); // operation
                ExecuteScript(engine, sb);
            }

            var result = engine.EvaluationStack.Peek().GetByteArray();

            Assert.Equal(Travel, result);
        }