Example #1
0
        private static ApplicationEngine GetEngine(bool hasContainer = false, bool hasSnapshot = false)
        {
            var tx       = TestUtils.GetTransaction();
            var snapshot = TestBlockchain.GetStore().GetSnapshot().Clone();
            ApplicationEngine engine;

            if (hasContainer && hasSnapshot)
            {
                engine = new ApplicationEngine(TriggerType.Application, tx, snapshot, 0);
            }
            else if (hasContainer && !hasSnapshot)
            {
                engine = new ApplicationEngine(TriggerType.Application, tx, null, 0);
            }
            else if (!hasContainer && hasSnapshot)
            {
                engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0);
            }
            else
            {
                engine = new ApplicationEngine(TriggerType.Application, null, null, 0);
            }
            engine.LoadScript(new byte[] { 0x01 });
            return(engine);
        }
Example #2
0
        public void TestSetup()
        {
            TestBlockchain.InitializeMockNeoSystem();

            var rand       = new Random();
            var mockWallet = new Mock <Wallet>();

            mockWallet.Setup(p => p.GetAccount(It.IsAny <UInt160>())).Returns <UInt160>(p => new TestWalletAccount(p));

            // Create dummy validators

            _validatorKeys = new KeyPair[7];
            for (int x = 0; x < _validatorKeys.Length; x++)
            {
                var pk = new byte[32];
                rand.NextBytes(pk);

                _validatorKeys[x] = new KeyPair(pk);
            }

            _context = new ConsensusContext(mockWallet.Object, TestBlockchain.GetStore())
            {
                Validators = _validatorKeys.Select(u => u.PublicKey).ToArray()
            };
            _context.Reset(0);
        }
Example #3
0
        public void TestSignMulti()
        {
            txManager = new TransactionManager(rpcClientMock.Object, sender);

            var multiContract = Contract.CreateMultiSigContract(2, keyPair1.PublicKey, keyPair2.PublicKey);

            // Cosigner needs multi signature
            Cosigner[] cosigners = new Cosigner[1]
            {
                new Cosigner
                {
                    Account = multiContract.ScriptHash,
                    Scopes  = WitnessScope.Global
                }
            };

            byte[] script = new byte[1];
            txManager.MakeTransaction(script, null, cosigners, 0_10000000)
            .AddMultiSig(keyPair1, 2, keyPair1.PublicKey, keyPair2.PublicKey)
            .AddMultiSig(keyPair2, 2, keyPair1.PublicKey, keyPair2.PublicKey)
            .AddSignature(keyPair1)
            .Sign();

            var store    = TestBlockchain.GetStore();
            var snapshot = store.GetSnapshot();

            var tx = txManager.Tx;

            Assert.IsTrue(tx.VerifyWitnesses(snapshot, tx.NetworkFee));
        }
        public void Init()
        {
            _store = TestBlockchain.GetStore();
            var snapshot = _store.GetSnapshot();

            _block  = Blockchain.GenesisBlock;
            _engine = new TestEngine(snapshot: snapshot);
            _engine.AddEntryScript("./TestClasses/Contract_Blockchain.cs");
        }
Example #5
0
        public void System_ExecutionEngine_GetScriptContainer()
        {
            var snapshot = TestBlockchain.GetStore().GetSnapshot();

            using (var script = new ScriptBuilder())
            {
                script.EmitSysCall(InteropService.System_ExecutionEngine_GetScriptContainer);

                // Without tx

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

                Assert.AreEqual(engine.Execute(), VMState.HALT);
                Assert.AreEqual(1, engine.ResultStack.Count);
                Assert.IsTrue(engine.ResultStack.Peek().IsNull);

                // With tx

                script.EmitSysCall(InteropService.Neo_Json_Serialize);

                var tx = new Transaction()
                {
                    Script          = new byte[] { 0x01 },
                    Attributes      = new TransactionAttribute[0],
                    Cosigners       = new Cosigner[0],
                    NetworkFee      = 0x02,
                    SystemFee       = 0x03,
                    Nonce           = 0x04,
                    ValidUntilBlock = 0x05,
                    Version         = 0x06,
                    Witnesses       = new Witness[] { new Witness()
                                                      {
                                                          VerificationScript = new byte[] { 0x07 }
                                                      } },
                    Sender = UInt160.Parse("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"),
                };

                engine = new ApplicationEngine(TriggerType.Application, tx, snapshot, 0, true);
                engine.LoadScript(script.ToArray());

                Assert.AreEqual(engine.Execute(), VMState.HALT);
                Assert.AreEqual(1, engine.ResultStack.Count);
                Assert.IsInstanceOfType(engine.ResultStack.Peek(), typeof(ByteArray));
                Assert.AreEqual(engine.ResultStack.Pop().GetByteArray().ToHexString(),
                                @"5b225c75303032426b53415959527a4c4b69685a676464414b50596f754655737a63544d7867445a6572584a3172784c37303d222c362c342c225c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f5c2f383d222c332c322c352c2241513d3d225d");
                Assert.AreEqual(0, engine.ResultStack.Count);
            }
        }
Example #6
0
        public void System_ExecutionEngine_GetScriptContainer()
        {
            var snapshot = TestBlockchain.GetStore().GetSnapshot();

            using (var script = new ScriptBuilder())
            {
                script.EmitSysCall(InteropService.System_ExecutionEngine_GetScriptContainer);

                // Without tx

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

                Assert.AreEqual(engine.Execute(), VMState.HALT);
                Assert.AreEqual(1, engine.ResultStack.Count);
                Assert.IsTrue(engine.ResultStack.Peek().IsNull);

                // With tx

                script.EmitSysCall(InteropService.Neo_Json_Serialize);

                var tx = new Transaction()
                {
                    Script          = new byte[] { 0x01 },
                    Attributes      = new TransactionAttribute[0],
                    Cosigners       = new Cosigner[0],
                    NetworkFee      = 0x02,
                    SystemFee       = 0x03,
                    Nonce           = 0x04,
                    ValidUntilBlock = 0x05,
                    Version         = 0x06,
                    Witnesses       = new Witness[] { new Witness()
                                                      {
                                                          VerificationScript = new byte[] { 0x07 }
                                                      } },
                    Sender = UInt160.Parse("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"),
                };

                engine = new ApplicationEngine(TriggerType.Application, tx, snapshot, 0, true);
                engine.LoadScript(script.ToArray());

                Assert.AreEqual(engine.Execute(), VMState.HALT);
                Assert.AreEqual(1, engine.ResultStack.Count);
                Assert.IsInstanceOfType(engine.ResultStack.Peek(), typeof(ByteArray));
                Assert.AreEqual(engine.ResultStack.Pop().GetByteArray().ToHexString(),
                                @"5b2266613434383036313834373332636138613136363037356430306133643861326531353462333337313333333138303336356561643732373561663132666264222c362c342c2266666666666666666666666666666666666666666666666666666666666666666666666666666666222c332c322c352c223031225d");
                Assert.AreEqual(0, engine.ResultStack.Count);
            }
        }
Example #7
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);
            _unit.LoadPolicy(TestBlockchain.GetStore().GetSnapshot());

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

            _unit.VerifiedCount.ShouldBeEquivalentTo(0);
            _unit.UnVerifiedCount.ShouldBeEquivalentTo(0);
            _unit.Count.ShouldBeEquivalentTo(0);
        }
Example #8
0
        private Witness PrepareDummyWitness(int maxAccounts)
        {
            var store    = TestBlockchain.GetStore();
            var wallet   = TestUtils.GenerateTestWallet();
            var snapshot = store.GetSnapshot();

            // Prepare

            var address        = new WalletAccount[maxAccounts];
            var wallets        = new NEP6Wallet[maxAccounts];
            var walletsUnlocks = new IDisposable[maxAccounts];

            for (int x = 0; x < maxAccounts; x++)
            {
                wallets[x]        = TestUtils.GenerateTestWallet();
                walletsUnlocks[x] = wallets[x].Unlock("123");
                address[x]        = wallets[x].CreateAccount();
            }

            // Generate multisignature

            var multiSignContract = Contract.CreateMultiSigContract(maxAccounts, address.Select(a => a.GetKey().PublicKey).ToArray());

            for (int x = 0; x < maxAccounts; x++)
            {
                wallets[x].CreateAccount(multiSignContract, address[x].GetKey());
            }

            // Sign

            var data = new ContractParametersContext(new DummyVerificable(multiSignContract.ScriptHash));

            for (int x = 0; x < maxAccounts; x++)
            {
                Assert.IsTrue(wallets[x].Sign(data));
            }

            Assert.IsTrue(data.Completed);
            return(data.GetWitnesses()[0]);
        }
Example #9
0
        public void TestReVerifyTopUnverifiedTransactionsIfNeeded()
        {
            NeoSystem TheNeoSystem = TestBlockchain.InitializeMockNeoSystem();
            var       s            = Blockchain.Singleton.Height;

            _unit = new MemoryPool(TheNeoSystem, 600);
            _unit.LoadPolicy(TestBlockchain.GetStore().GetSnapshot());
            AddTransaction(CreateTransaction(100000001));
            AddTransaction(CreateTransaction(100000001));
            AddTransaction(CreateTransaction(100000001));
            AddTransaction(CreateTransaction(1));
            _unit.VerifiedCount.Should().Be(4);
            _unit.UnVerifiedCount.Should().Be(0);

            _unit.InvalidateVerifiedTransactions();
            _unit.VerifiedCount.Should().Be(0);
            _unit.UnVerifiedCount.Should().Be(4);

            AddTransactions(511); // Max per block currently is 512
            _unit.VerifiedCount.Should().Be(511);
            _unit.UnVerifiedCount.Should().Be(4);

            var result = _unit.ReVerifyTopUnverifiedTransactionsIfNeeded(1, Blockchain.Singleton.GetSnapshot());

            result.Should().BeTrue();
            _unit.VerifiedCount.Should().Be(512);
            _unit.UnVerifiedCount.Should().Be(3);

            result = _unit.ReVerifyTopUnverifiedTransactionsIfNeeded(2, Blockchain.Singleton.GetSnapshot());
            result.Should().BeTrue();
            _unit.VerifiedCount.Should().Be(514);
            _unit.UnVerifiedCount.Should().Be(1);

            result = _unit.ReVerifyTopUnverifiedTransactionsIfNeeded(3, Blockchain.Singleton.GetSnapshot());
            result.Should().BeFalse();
            _unit.VerifiedCount.Should().Be(515);
            _unit.UnVerifiedCount.Should().Be(0);
        }
Example #10
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 Neo.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.Emit(OpCode.PUSHNULL);
                    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);
        }
Example #11
0
        public void System_Runtime_GetInvocationCounter()
        {
            ContractState contractA, contractB, contractC;
            var           snapshot  = TestBlockchain.GetStore().GetSnapshot();
            var           contracts = (TestDataCache <UInt160, ContractState>)snapshot.Contracts;

            // Create dummy contracts

            using (var script = new ScriptBuilder())
            {
                script.EmitSysCall(InteropService.System_Runtime_GetInvocationCounter);

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

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

                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

            using (var 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 */
                }
                );
            }
        }
Example #12
0
        public void System_Blockchain_GetBlock()
        {
            var tx = new Transaction()
            {
                Script          = new byte[] { 0x01 },
                Attributes      = new TransactionAttribute[0],
                Cosigners       = new Cosigner[0],
                NetworkFee      = 0x02,
                SystemFee       = 0x03,
                Nonce           = 0x04,
                ValidUntilBlock = 0x05,
                Version         = 0x06,
                Witnesses       = new Witness[] { new Witness()
                                                  {
                                                      VerificationScript = new byte[] { 0x07 }
                                                  } },
                Sender = UInt160.Parse("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"),
            };

            var block = new Block()
            {
                Index     = 1,
                Timestamp = 2,
                Version   = 3,
                Witness   = new Witness()
                {
                    InvocationScript   = new byte[0],
                    VerificationScript = new byte[0]
                },
                PrevHash      = UInt256.Zero,
                MerkleRoot    = UInt256.Zero,
                NextConsensus = UInt160.Zero,
                ConsensusData = new ConsensusData()
                {
                    Nonce = 1, PrimaryIndex = 1
                },
                Transactions = new Transaction[] { tx }
            };

            var snapshot = TestBlockchain.GetStore().GetSnapshot();

            using (var script = new ScriptBuilder())
            {
                script.EmitPush(block.Hash.ToArray());
                script.EmitSysCall(InteropService.System_Blockchain_GetBlock);

                // Without block

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

                Assert.AreEqual(engine.Execute(), VMState.HALT);
                Assert.AreEqual(1, engine.ResultStack.Count);
                Assert.IsTrue(engine.ResultStack.Peek().IsNull);

                // With block

                var blocks = (TestDataCache <UInt256, TrimmedBlock>)snapshot.Blocks;
                var txs    = (TestDataCache <UInt256, TransactionState>)snapshot.Transactions;
                blocks.Add(block.Hash, block.Trim());
                txs.Add(tx.Hash, new TransactionState()
                {
                    Transaction = tx, BlockIndex = block.Index, VMState = VMState.HALT
                });

                script.EmitSysCall(InteropService.Neo_Json_Serialize);
                engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, true);
                engine.LoadScript(script.ToArray());

                Assert.AreEqual(engine.Execute(), VMState.HALT);
                Assert.AreEqual(1, engine.ResultStack.Count);
                Assert.IsInstanceOfType(engine.ResultStack.Peek(), typeof(ByteArray));
                Assert.AreEqual(engine.ResultStack.Pop().GetByteArray().ToHexString(),
                                "5b22556168355c2f4b6f446d39723064555950636353714346745a30594f726b583164646e7334366e676e3962383d222c332c22414141414141414141414141414141414141414141414141414141414141414141414141414141414141413d222c22414141414141414141414141414141414141414141414141414141414141414141414141414141414141413d222c322c312c224141414141414141414141414141414141414141414141414141413d222c315d");
                Assert.AreEqual(0, engine.ResultStack.Count);

                // Clean
                blocks.Delete(block.Hash);
                txs.Delete(tx.Hash);
            }
        }
Example #13
0
        public void FeeIsMultiSigContract()
        {
            var store    = TestBlockchain.GetStore();
            var walletA  = TestUtils.GenerateTestWallet();
            var walletB  = TestUtils.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(verificationGas, 2000540);
                    Assert.AreEqual(sizeGas, 358000);
                    Assert.AreEqual(verificationGas + sizeGas, 2358540);
                    Assert.AreEqual(tx.NetworkFee, 2358540);
                }
        }
Example #14
0
 public void TestSetup()
 {
     uut   = new Transaction();
     store = TestBlockchain.GetStore();
 }
Example #15
0
 public void Initialize()
 {
     system = TestBlockchain.InitializeMockNeoSystem();
     store  = TestBlockchain.GetStore();
     Blockchain.Singleton.MemPool.TryAdd(txSample.Hash, txSample);
 }
Example #16
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(1980, 06, 01, 0, 0, 1, 001, DateTimeKind.Utc),                                           // For receiving block
                new DateTime(1980, 06, 01, 0, 0, (int)Blockchain.MillisecondsPerBlock / 1000, 100, DateTimeKind.Utc), // For Initialize
                new DateTime(1980, 06, 01, 0, 0, 15, 001, DateTimeKind.Utc),                                          // unused
                new DateTime(1980, 06, 01, 0, 0, 15, 001, 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 ulong timestampVal, out uint indexVal, out Witness scriptVal);
            header.Size.Should().Be(105);

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

            timestampVal.Should().Be(328665601001);    // GMT: Sunday, June 1, 1980 12:00:01.001 AM
                                                       // 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);
        }
 public void TestSetup()
 {
     TestBlockchain.InitializeMockNeoSystem();
     Store = TestBlockchain.GetStore();
 }
Example #18
0
 public void TestSetup()
 {
     store = TestBlockchain.GetStore();
 }