Exemple #1
0
        public void TestCachedFind_Last()
        {
            var snapshot = TestBlockchain.GetStore().GetSnapshot();
            var storages = snapshot.Storages;
            var cache    = new CloneCache <StorageKey, StorageItem>(storages);

            storages.DeleteWhere((k, v) => k.ScriptHash == UInt160.Zero);

            storages.Add
            (
                new StorageKey()
            {
                Key = new byte[] { 0x00, 0x01 }, ScriptHash = UInt160.Zero
            },
                new StorageItem()
            {
                IsConstant = false, Value = new byte[] { }
            }
            );
            storages.Add
            (
                new StorageKey()
            {
                Key = new byte[] { 0x01, 0x01 }, ScriptHash = UInt160.Zero
            },
                new StorageItem()
            {
                IsConstant = false, Value = new byte[] { }
            }
            );
            cache.Add
            (
                new StorageKey()
            {
                Key = new byte[] { 0x00, 0x02 }, ScriptHash = UInt160.Zero
            },
                new StorageItem()
            {
                IsConstant = false, Value = new byte[] { }
            }
            );
            cache.Add
            (
                new StorageKey()
            {
                Key = new byte[] { 0x01, 0x02 }, ScriptHash = UInt160.Zero
            },
                new StorageItem()
            {
                IsConstant = false, Value = new byte[] { }
            }
            );

            CollectionAssert.AreEqual(
                cache.Find(new byte[21]).Select(u => u.Key.Key[1]).ToArray(),
                new byte[] { 0x01, 0x02 }
                );

            storages.DeleteWhere((k, v) => k.ScriptHash == UInt160.Zero);
        }
Exemple #2
0
        public void TestCachedFind_Last()
        {
            var snapshot = TestBlockchain.GetTestSnapshot();
            var storages = snapshot.CreateSnapshot();
            var cache    = new ClonedCache(storages);

            storages.Add
            (
                new StorageKey()
            {
                Key = new byte[] { 0x00, 0x01 }, Id = 0
            },
                new StorageItem()
            {
                Value = new byte[] { }
            }
            );
            storages.Add
            (
                new StorageKey()
            {
                Key = new byte[] { 0x01, 0x01 }, Id = 0
            },
                new StorageItem()
            {
                Value = new byte[] { }
            }
            );
            cache.Add
            (
                new StorageKey()
            {
                Key = new byte[] { 0x00, 0x02 }, Id = 0
            },
                new StorageItem()
            {
                Value = new byte[] { }
            }
            );
            cache.Add
            (
                new StorageKey()
            {
                Key = new byte[] { 0x01, 0x02 }, Id = 0
            },
                new StorageItem()
            {
                Value = new byte[] { }
            }
            );
            CollectionAssert.AreEqual(cache.Find(new byte[5]).Select(u => u.Key.Key[1]).ToArray(),
                                      new byte[] { 0x01, 0x02 }
                                      );
        }
Exemple #3
0
        public void TestSetup()
        {
            // protect against external changes on TimeProvider
            TimeProvider.ResetToDefault();

            NeoSystem TheNeoSystem = TestBlockchain.InitializeMockNeoSystem();

            // Create a MemoryPool with capacity of 100
            _unit = new MemoryPool(TheNeoSystem, 100);

            // Verify capacity equals the amount specified
            _unit.Capacity.ShouldBeEquivalentTo(100);

            _unit.VerifiedCount.ShouldBeEquivalentTo(0);
            _unit.UnVerifiedCount.ShouldBeEquivalentTo(0);
            _unit.Count.ShouldBeEquivalentTo(0);
        }
Exemple #4
0
 public void TestSetup()
 {
     TestBlockchain.InitializeMockNeoSystem();
     Store = TestBlockchain.GetStore();
 }
Exemple #5
0
        public void ConsensusService_Primary_Sends_PrepareRequest_After_OnStart()
        {
            TestProbe subscriber = CreateTestProbe();
            var       mockWallet = new Mock <Wallet>();

            mockWallet.Setup(p => p.GetAccount(It.IsAny <UInt160>())).Returns <UInt160>(p => new TestWalletAccount(p));
            ConsensusContext context = new ConsensusContext(mockWallet.Object, TestBlockchain.GetStore());

            int timeIndex  = 0;
            var timeValues = new[] {
                //new DateTime(1968, 06, 01, 0, 0, 15, DateTimeKind.Utc), // For tests here
                new DateTime(1968, 06, 01, 0, 0, 1, DateTimeKind.Utc),                               // For receiving block
                new DateTime(1968, 06, 01, 0, 0, (int)Blockchain.SecondsPerBlock, DateTimeKind.Utc), // For Initialize
                new DateTime(1968, 06, 01, 0, 0, 15, DateTimeKind.Utc),                              // unused
                new DateTime(1968, 06, 01, 0, 0, 15, DateTimeKind.Utc)                               // unused
            };

            //TimeProvider.Current.UtcNow.ToTimestamp().Should().Be(4244941711); //1968-06-01 00:00:15

            Console.WriteLine($"time 0: {timeValues[0].ToString()} 1: {timeValues[1].ToString()} 2: {timeValues[2].ToString()} 3: {timeValues[3].ToString()}");

            var timeMock = new Mock <TimeProvider>();

            timeMock.SetupGet(tp => tp.UtcNow).Returns(() => timeValues[timeIndex])
            .Callback(() => timeIndex++);
            //new DateTime(1968, 06, 01, 0, 0, 15, DateTimeKind.Utc));
            TimeProvider.Current = timeMock.Object;

            //public void Log(string message, LogLevel level)
            // TODO: create ILogPlugin for Tests

            /*
             * mockConsensusContext.Setup(mr => mr.Log(It.IsAny<string>(), It.IsAny<LogLevel>()))
             *           .Callback((string message, LogLevel level) => {
             *                           Console.WriteLine($"CONSENSUS LOG: {message}");
             *                                                     }
             *                    );
             */

            // Creating proposed block
            Header header = new Header();

            TestUtils.SetupHeaderWithValues(header, UInt256.Zero, out UInt256 merkRootVal, out UInt160 val160, out uint timestampVal, out uint indexVal, out Witness scriptVal);
            header.Size.Should().Be(101);

            Console.WriteLine($"header {header} hash {header.Hash} timstamp {timestampVal}");

            timestampVal.Should().Be(4244941696); //1968-06-01 00:00:00
                                                  // check basic ConsensusContext
                                                  //mockConsensusContext.Object.block_received_time.ToTimestamp().Should().Be(4244941697); //1968-06-01 00:00:01

            // ============================================================================
            //                      creating ConsensusService actor
            // ============================================================================

            TestActorRef <ConsensusService> actorConsensus = ActorOfAsTestActorRef <ConsensusService>(
                Akka.Actor.Props.Create(() => (ConsensusService)Activator.CreateInstance(typeof(ConsensusService), BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { subscriber, subscriber, context }, null))
                );

            Console.WriteLine("will trigger OnPersistCompleted!");
            actorConsensus.Tell(new Blockchain.PersistCompleted
            {
                Block = new Block
                {
                    Version       = header.Version,
                    PrevHash      = header.PrevHash,
                    MerkleRoot    = header.MerkleRoot,
                    Timestamp     = header.Timestamp,
                    Index         = header.Index,
                    NextConsensus = header.NextConsensus
                }
            });

            // OnPersist will not launch timer, we need OnStart

            Console.WriteLine("will start consensus!");
            actorConsensus.Tell(new ConsensusService.Start
            {
                IgnoreRecoveryLogs = true
            });

            Console.WriteLine("OnTimer should expire!");
            Console.WriteLine("Waiting for subscriber message!");
            // Timer should expire in one second (block_received_time at :01, initialized at :02)

            var answer = subscriber.ExpectMsg <LocalNode.SendDirectly>();

            Console.WriteLine($"MESSAGE 1: {answer}");
            //var answer2 = subscriber.ExpectMsg<LocalNode.SendDirectly>(); // expects to fail!

            // ============================================================================
            //                      finalize ConsensusService actor
            // ============================================================================

            //Thread.Sleep(4000);
            Sys.Stop(actorConsensus);
            TimeProvider.ResetToDefault();

            Assert.AreEqual(1, 1);
        }
Exemple #6
0
 public void TestSetup()
 {
     TestBlockchain.InitializeMockNeoSystem();
 }
Exemple #7
0
        public void FeeIsMultiSigContract()
        {
            var store    = TestBlockchain.GetStore();
            var walletA  = GenerateTestWallet();
            var walletB  = GenerateTestWallet();
            var snapshot = store.GetSnapshot();

            using (var unlockA = walletA.Unlock("123"))
                using (var unlockB = walletB.Unlock("123"))
                {
                    var a = walletA.CreateAccount();
                    var b = walletB.CreateAccount();

                    var multiSignContract = Contract.CreateMultiSigContract(2,
                                                                            new ECPoint[]
                    {
                        a.GetKey().PublicKey,
                        b.GetKey().PublicKey
                    });

                    walletA.CreateAccount(multiSignContract, a.GetKey());
                    var acc = walletB.CreateAccount(multiSignContract, b.GetKey());

                    // Fake balance

                    var key   = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash);
                    var entry = snapshot.Storages.GetAndChange(key, () => new StorageItem
                    {
                        Value = new Nep5AccountState().ToByteArray()
                    });

                    entry.Value = new Nep5AccountState()
                    {
                        Balance = 10000 * NativeContract.GAS.Factor
                    }
                    .ToByteArray();

                    // Make transaction

                    var tx = walletA.MakeTransaction(new TransferOutput[]
                    {
                        new TransferOutput()
                        {
                            AssetId    = NativeContract.GAS.Hash,
                            ScriptHash = acc.ScriptHash,
                            Value      = new BigDecimal(1, 8)
                        }
                    }, acc.ScriptHash);

                    Assert.IsNotNull(tx);

                    // Sign

                    var data = new ContractParametersContext(tx);
                    Assert.IsTrue(walletA.Sign(data));
                    Assert.IsTrue(walletB.Sign(data));
                    Assert.IsTrue(data.Completed);

                    tx.Witnesses = data.GetWitnesses();

                    // Fast check

                    Assert.IsTrue(tx.VerifyWitnesses(snapshot, tx.NetworkFee));

                    // Check

                    long verificationGas = 0;
                    foreach (var witness in tx.Witnesses)
                    {
                        using (ApplicationEngine engine = new ApplicationEngine(TriggerType.Verification, tx, snapshot, tx.NetworkFee, false))
                        {
                            engine.LoadScript(witness.VerificationScript);
                            engine.LoadScript(witness.InvocationScript);
                            Assert.AreEqual(VMState.HALT, engine.Execute());
                            Assert.AreEqual(1, engine.ResultStack.Count);
                            Assert.IsTrue(engine.ResultStack.Pop().GetBoolean());
                            verificationGas += engine.GasConsumed;
                        }
                    }

                    var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot);
                    Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas);
                }
        }
Exemple #8
0
 public void TestSetup()
 {
     uut   = new Transaction();
     store = TestBlockchain.GetStore();
 }
Exemple #9
0
        public void System_Runtime_GetInvocationCounter()
        {
            var snapshot  = TestBlockchain.GetStore().GetSnapshot();
            var contracts = (TestDataCache <UInt160, ContractState>)snapshot.Contracts;

            // Call System.Runtime.GetInvocationCounter syscall

            var script = new ScriptBuilder();

            script.EmitSysCall(InteropService.System_Runtime_GetInvocationCounter);

            // Init A,B,C contracts
            // First two drops is for drop method and arguments

            var contractA = new ContractState()
            {
                Script = new byte[] { (byte)OpCode.DROP, (byte)OpCode.DROP }.Concat(script.ToArray()).ToArray()
            };
            var contractB = new ContractState()
            {
                Script = new byte[] { (byte)OpCode.DROP, (byte)OpCode.DROP, (byte)OpCode.NOP }.Concat(script.ToArray()).ToArray()
            };
            var contractC = new ContractState()
            {
                Script = new byte[] { (byte)OpCode.DROP, (byte)OpCode.DROP, (byte)OpCode.NOP, (byte)OpCode.NOP }.Concat(script.ToArray()).ToArray()
            };

            contracts.DeleteWhere((a, b) => a.ToArray().SequenceEqual(contractA.ScriptHash.ToArray()));
            contracts.DeleteWhere((a, b) => a.ToArray().SequenceEqual(contractB.ScriptHash.ToArray()));
            contracts.DeleteWhere((a, b) => a.ToArray().SequenceEqual(contractC.ScriptHash.ToArray()));
            contracts.Add(contractA.ScriptHash, contractA);
            contracts.Add(contractB.ScriptHash, contractB);
            contracts.Add(contractC.ScriptHash, contractC);

            // Call A,B,B,C

            script = new ScriptBuilder();
            script.EmitSysCall(InteropService.System_Contract_Call, contractA.ScriptHash.ToArray(), "dummyMain", 0);
            script.EmitSysCall(InteropService.System_Contract_Call, contractB.ScriptHash.ToArray(), "dummyMain", 0);
            script.EmitSysCall(InteropService.System_Contract_Call, contractB.ScriptHash.ToArray(), "dummyMain", 0);
            script.EmitSysCall(InteropService.System_Contract_Call, contractC.ScriptHash.ToArray(), "dummyMain", 0);

            // Execute

            var engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, true);

            engine.LoadScript(script.ToArray());
            Assert.AreEqual(engine.Execute(), VMState.HALT);

            // Check the results

            CollectionAssert.AreEqual
            (
                engine.ResultStack.Select(u => (int)((VM.Types.Integer)u).GetBigInteger()).ToArray(),
                new int[]
            {
                1,     /* A */
                1,     /* B */
                2,     /* B */
                1      /* C */
            }
            );
        }
Exemple #10
0
 public void Setup()
 {
     neoSystem = TestBlockchain.InitializeMockNeoSystem();
 }
Exemple #11
0
        public void Runtime_GetNotifications_Test()
        {
            UInt160 scriptHash2;
            var     snapshot = TestBlockchain.GetStore().GetSnapshot();

            using (var script = new ScriptBuilder())
            {
                // Drop arguments

                script.Emit(VM.OpCode.TOALTSTACK);
                script.Emit(VM.OpCode.DROP);
                script.Emit(VM.OpCode.FROMALTSTACK);

                // Notify method

                script.EmitSysCall(InteropService.System_Runtime_Notify);

                // Add return

                script.EmitPush(true);

                // Mock contract

                scriptHash2 = script.ToArray().ToScriptHash();

                snapshot.Contracts.Delete(scriptHash2);
                snapshot.Contracts.Add(scriptHash2, new Ledger.ContractState()
                {
                    Script   = script.ToArray(),
                    Manifest = ContractManifest.CreateDefault(scriptHash2),
                });
            }

            // Wrong length

            using (var engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, true))
                using (var script = new ScriptBuilder())
                {
                    // Retrive

                    script.EmitPush(1);
                    script.EmitSysCall(InteropService.System_Runtime_GetNotifications);

                    // Execute

                    engine.LoadScript(script.ToArray());

                    Assert.AreEqual(VMState.FAULT, engine.Execute());
                }

            // All test

            using (var engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, true))
                using (var script = new ScriptBuilder())
                {
                    // Notification 1 -> 13

                    script.EmitPush(13);
                    script.EmitSysCall(InteropService.System_Runtime_Notify);

                    // Call script

                    script.EmitAppCall(scriptHash2, "test");

                    // Drop return

                    script.Emit(OpCode.DROP);

                    // Receive all notifications

                    script.EmitPush(UInt160.Zero.ToArray());
                    script.EmitSysCall(InteropService.System_Runtime_GetNotifications);

                    // Execute

                    engine.LoadScript(script.ToArray());
                    var currentScriptHash = engine.EntryScriptHash;

                    Assert.AreEqual(VMState.HALT, engine.Execute());
                    Assert.AreEqual(1, engine.ResultStack.Count);
                    Assert.AreEqual(2, engine.Notifications.Count);

                    Assert.IsInstanceOfType(engine.ResultStack.Peek(), typeof(VM.Types.Array));

                    var array = (VM.Types.Array)engine.ResultStack.Pop();

                    // Check syscall result

                    AssertNotification(array[1], scriptHash2, "test");
                    AssertNotification(array[0], currentScriptHash, 13);

                    // Check notifications

                    Assert.AreEqual(scriptHash2, engine.Notifications[1].ScriptHash);
                    Assert.AreEqual("test", engine.Notifications[1].State.GetString());

                    Assert.AreEqual(currentScriptHash, engine.Notifications[0].ScriptHash);
                    Assert.AreEqual(13, engine.Notifications[0].State.GetBigInteger());
                }

            // Script notifications

            using (var engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, true))
                using (var script = new ScriptBuilder())
                {
                    // Notification 1 -> 13

                    script.EmitPush(13);
                    script.EmitSysCall(InteropService.System_Runtime_Notify);

                    // Call script

                    script.EmitAppCall(scriptHash2, "test");

                    // Drop return

                    script.Emit(OpCode.DROP);

                    // Receive all notifications

                    script.EmitPush(scriptHash2.ToArray());
                    script.EmitSysCall(InteropService.System_Runtime_GetNotifications);

                    // Execute

                    engine.LoadScript(script.ToArray());
                    var currentScriptHash = engine.EntryScriptHash;

                    Assert.AreEqual(VMState.HALT, engine.Execute());
                    Assert.AreEqual(1, engine.ResultStack.Count);
                    Assert.AreEqual(2, engine.Notifications.Count);

                    Assert.IsInstanceOfType(engine.ResultStack.Peek(), typeof(VM.Types.Array));

                    var array = (VM.Types.Array)engine.ResultStack.Pop();

                    // Check syscall result

                    AssertNotification(array[0], scriptHash2, "test");

                    // Check notifications

                    Assert.AreEqual(scriptHash2, engine.Notifications[1].ScriptHash);
                    Assert.AreEqual("test", engine.Notifications[1].State.GetString());

                    Assert.AreEqual(currentScriptHash, engine.Notifications[0].ScriptHash);
                    Assert.AreEqual(13, engine.Notifications[0].State.GetBigInteger());
                }

            // Clean storage

            snapshot.Contracts.Delete(scriptHash2);
        }
Exemple #12
0
        public static void SetupTestBlockchain(UInt256 assetId)
        {
            Blockchain testBlockchain = new TestBlockchain(assetId);

            Blockchain.RegisterBlockchain(testBlockchain);
        }
Exemple #13
0
 public static void TestSetup(TestContext ctx)
 {
     testBlockchain = TestBlockchain.InitializeMockNeoSystem();
 }
Exemple #14
0
        private void setupTestBlockchain(UInt256 assetId)
        {
            Blockchain testBlockchain = new TestBlockchain(assetId);

            Blockchain.RegisterBlockchain(testBlockchain);
        }