Ejemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="interceptor"></param>
        /// <returns></returns>
        public ISession OpenSession(IInterceptor interceptor)
        {
            long timestamp = Timestamper.Next();

            // specify true for autoClose because NHibernate has responsibility for
            // the IDbConnection.
            return(OpenSession(null, true, timestamp, interceptor));
        }
Ejemplo n.º 2
0
        // TODO: Try to understand what this is for and how it's used.
        public long NextTimestamp()
        {
            if (_logger.IsDebugEnabled)
            {
                _logger.DebugFormat("NextTimestamp() invoked in region '{0}'.", _regionAlphaNumeric);
            }

            return(Timestamper.Next());
        }
Ejemplo n.º 3
0
        private async Task AddBlockInternal(params Transaction[] transactions)
        {
            await _oneAtATime.WaitOneAsync(CancellationToken.None);

            foreach (Transaction transaction in transactions)
            {
                TxPool.AddTransaction(transaction, TxHandlingOptions.None);
            }

            Timestamper.Add(TimeSpan.FromSeconds(1));
            BlockProducer.BuildNewBlock();
        }
Ejemplo n.º 4
0
        public void epoch_timestamp_in_seconds_and_milliseconds_should_be_valid()
        {
            var utcNow                      = DateTime.UtcNow;
            var timestamper                 = new Timestamper(utcNow);
            var epochSeconds                = timestamper.EpochSeconds;
            var epochMilliseconds           = timestamper.EpochMilliseconds;
            var unixUtcUntilNowSeconds      = (ulong)utcNow.Subtract(Jan1St1970).TotalSeconds;
            var unixUtcUntilNowMilliseconds = (ulong)utcNow.Subtract(Jan1St1970).TotalMilliseconds;

            epochSeconds.Should().Be(unixUtcUntilNowSeconds);
            epochMilliseconds.Should().Be(unixUtcUntilNowMilliseconds);
        }
Ejemplo n.º 5
0
        public void AsyncOperationsThrow()
        {
            var      cache    = new HashtableCacheProvider().BuildCache("region", new Dictionary <string, string>());
            var      strategy = CreateCache(cache);
            CacheKey key      = CreateCacheKey("key");
            var      stamp    = Timestamper.Next();

            Assert.ThrowsAsync <InvalidOperationException>(
                () =>
                strategy.PutAsync(key, "value", stamp, 0, null, false, default(CancellationToken)));
            Assert.ThrowsAsync <InvalidOperationException>(() => strategy.GetAsync(key, stamp, default(CancellationToken)));
        }
Ejemplo n.º 6
0
        public void should_mark_transaction_as_removable()
        {
            var utcNow           = DateTime.UtcNow;
            var validator        = GetValidator();
            var timestamp        = new Timestamper(utcNow);
            var transaction1     = GetTransaction(utcNow, 5);
            var transaction2     = GetTransaction(utcNow, 600);
            var transaction3     = GetTransaction(utcNow, 1000);
            var currentTimestamp = new UInt256(timestamp.EpochSeconds);

            validator.IsRemovable(currentTimestamp, transaction1.Timestamp).Should().BeFalse();
            validator.IsRemovable(currentTimestamp, transaction2.Timestamp).Should().BeFalse();
            validator.IsRemovable(currentTimestamp, transaction3.Timestamp).Should().BeTrue();
        }
Ejemplo n.º 7
0
        public void VerifyIncrease()
        {
            long currentTicks = 0;
            long newTicks     = 0;

            // the Timestampper will only generate 4095 increasing identifiers per millisecond.
            for (int i = 0; i < 4095; i++)
            {
                newTicks = Timestamper.Next();
                if ((newTicks - currentTicks) == 0)
                {
                    Assert.Fail("diff was " + (newTicks - currentTicks) + ".  It should always increase.  Loop i=" + i +
                                " with currentTicks = " + currentTicks + " and newTicks = " + newTicks);
                }
                currentTicks = newTicks;
            }
        }
Ejemplo n.º 8
0
        public void epoch_timestamp_in_seconds_and_milliseconds_should_be_valid()
        {
            // very strange fail once:
            // Failed epoch_timestamp_in_seconds_and_milliseconds_should_be_valid [317 ms]
            // Error Message:
            // Expected value to be 1613321574133UL, but found 1613321574132UL.

            DateTime     utcNow                      = DateTime.UtcNow;
            ITimestamper timestamper                 = new Timestamper(utcNow);
            ulong        epochSeconds                = timestamper.UnixTime.Seconds;
            ulong        epochMilliseconds           = timestamper.UnixTime.Milliseconds;
            ulong        unixUtcUntilNowSeconds      = (ulong)utcNow.Subtract(Jan1St1970).TotalSeconds;
            ulong        unixUtcUntilNowMilliseconds = (ulong)utcNow.Subtract(Jan1St1970).TotalMilliseconds;

            epochSeconds.Should().Be(unixUtcUntilNowSeconds);
            epochMilliseconds.Should().Be(unixUtcUntilNowMilliseconds);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Generate a timestamp
 /// </summary>
 /// <returns>a timestamp</returns>
 public long NextTimestamp()
 {
     return(Timestamper.Next());
 }
Ejemplo n.º 10
0
        public async Task Can_process_mined_blocks()
        {
            int timeMultiplier = 1; // for debugging

            TimeSpan miningDelay = TimeSpan.FromMilliseconds(50 * timeMultiplier);

            /* logging & instrumentation */
//            OneLoggerLogManager logger = new OneLoggerLogManager(new SimpleConsoleLogger(true));
            ILogManager logManager = NullLogManager.Instance;
            ILogger     logger     = logManager.GetClassLogger();

            /* spec */
            FakeSealer sealer = new FakeSealer(miningDelay);

            RopstenSpecProvider specProvider = RopstenSpecProvider.Instance;

            /* state & storage */
            StateDb         codeDb          = new StateDb();
            StateDb         stateDb         = new StateDb();
            StateProvider   stateProvider   = new StateProvider(stateDb, codeDb, logManager);
            StorageProvider storageProvider = new StorageProvider(stateDb, stateProvider, logManager);

            /* store & validation */

            EthereumEcdsa        ecdsa                = new EthereumEcdsa(specProvider, logManager);
            MemDb                receiptsDb           = new MemDb();
            MemDb                traceDb              = new MemDb();
            TxPool               txPool               = new TxPool(NullTxStorage.Instance, Timestamper.Default, ecdsa, specProvider, new TxPoolConfig(), stateProvider, logManager);
            IReceiptStorage      receiptStorage       = new PersistentReceiptStorage(receiptsDb, specProvider, logManager);
            var                  blockInfoDb          = new MemDb();
            BlockTree            blockTree            = new BlockTree(new MemDb(), new MemDb(), blockInfoDb, new ChainLevelInfoRepository(blockInfoDb), specProvider, txPool, logManager);
            Timestamper          timestamper          = new Timestamper();
            DifficultyCalculator difficultyCalculator = new DifficultyCalculator(specProvider);
            HeaderValidator      headerValidator      = new HeaderValidator(blockTree, sealer, specProvider, logManager);
            OmmersValidator      ommersValidator      = new OmmersValidator(blockTree, headerValidator, logManager);
            TxValidator          txValidator          = new TxValidator(ChainId.Ropsten);
            BlockValidator       blockValidator       = new BlockValidator(txValidator, headerValidator, ommersValidator, specProvider, logManager);

            TestTransactionsGenerator generator = new TestTransactionsGenerator(txPool, ecdsa, TimeSpan.FromMilliseconds(5 * timeMultiplier), NullLogManager.Instance);

            generator.Start();

            /* blockchain processing */
            BlockhashProvider    blockhashProvider = new BlockhashProvider(blockTree, LimboLogs.Instance);
            VirtualMachine       virtualMachine    = new VirtualMachine(stateProvider, storageProvider, blockhashProvider, specProvider, logManager);
            TransactionProcessor processor         = new TransactionProcessor(specProvider, stateProvider, storageProvider, virtualMachine, logManager);
            RewardCalculator     rewardCalculator  = new RewardCalculator(specProvider);
            BlockProcessor       blockProcessor    = new BlockProcessor(specProvider, blockValidator, rewardCalculator,
                                                                        processor, stateDb, codeDb, traceDb, stateProvider, storageProvider, txPool, receiptStorage, logManager);
            BlockchainProcessor blockchainProcessor = new BlockchainProcessor(blockTree, blockProcessor, new TxSignaturesRecoveryStep(ecdsa, NullTxPool.Instance, LimboLogs.Instance), logManager, false, false);

            /* load ChainSpec and init */
            ChainSpecLoader loader = new ChainSpecLoader(new EthereumJsonSerializer());
            string          path   = "chainspec.json";

            logManager.GetClassLogger().Info($"Loading ChainSpec from {path}");
            ChainSpec chainSpec = loader.Load(File.ReadAllText(path));

            foreach (var allocation in chainSpec.Allocations)
            {
                stateProvider.CreateAccount(allocation.Key, allocation.Value.Balance);
                if (allocation.Value.Code != null)
                {
                    Keccak codeHash = stateProvider.UpdateCode(allocation.Value.Code);
                    stateProvider.UpdateCodeHash(allocation.Key, codeHash, specProvider.GenesisSpec);
                }
            }

            stateProvider.Commit(specProvider.GenesisSpec);
            chainSpec.Genesis.Header.StateRoot = stateProvider.StateRoot; // TODO: shall it be HeaderSpec and not BlockHeader?
            chainSpec.Genesis.Header.Hash      = BlockHeader.CalculateHash(chainSpec.Genesis.Header);
            if (chainSpec.Genesis.Hash != new Keccak("0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d"))
            {
                throw new Exception("Unexpected genesis hash");
            }

            /* start processing */
            blockTree.SuggestBlock(chainSpec.Genesis);
            blockchainProcessor.Start();

            MinedBlockProducer minedBlockProducer = new MinedBlockProducer(difficultyCalculator, txPool, blockchainProcessor, sealer, blockTree, timestamper, NullLogManager.Instance);

            minedBlockProducer.Start();

            ManualResetEventSlim manualResetEvent = new ManualResetEventSlim(false);

            blockTree.NewHeadBlock += (sender, args) =>
            {
                if (args.Block.Number == 6)
                {
                    manualResetEvent.Set();
                }
            };

            manualResetEvent.Wait(miningDelay * 12 * timeMultiplier);
            await minedBlockProducer.StopAsync();

            int previousCount = 0;
            int totalTx       = 0;

            for (int i = 0; i < 6; i++)
            {
                Block block = blockTree.FindBlock(i, BlockTreeLookupOptions.None);
                logger.Info($"Block {i} with {block.Transactions.Length} txs");

                ManualResetEventSlim blockProcessedEvent = new ManualResetEventSlim(false);
                blockchainProcessor.ProcessingQueueEmpty += (sender, args) => blockProcessedEvent.Set();
                blockchainProcessor.SuggestBlock(block, ProcessingOptions.ForceProcessing | ProcessingOptions.StoreReceipts | ProcessingOptions.ReadOnlyChain);
                blockProcessedEvent.Wait(1000);

                Tracer tracer = new Tracer(blockchainProcessor, receiptStorage, blockTree, new MemDb());

                int currentCount = receiptsDb.Keys.Count;
                logger.Info($"Current count of receipts {currentCount}");
                logger.Info($"Previous count of receipts {previousCount}");

                if (block.Transactions.Length > 0)
                {
                    GethLikeTxTrace trace = tracer.Trace(block.Transactions[0].Hash, GethTraceOptions.Default);
                    Assert.AreSame(GethLikeTxTrace.QuickFail, trace);
                    Assert.AreNotEqual(previousCount, currentCount, $"receipts at block {i}");
                    totalTx += block.Transactions.Length;
                }

                previousCount = currentCount;
            }

            Assert.AreNotEqual(0, totalTx, "no tx in blocks");
        }
Ejemplo n.º 11
0
 /// <inheritdoc />
 public override long NextTimestamp()
 {
     return(Timestamper.Next());
 }
        public async Task DoTestCacheAsync(ICacheProvider cacheProvider, CancellationToken cancellationToken = default(CancellationToken))
        {
            ICache cache = cacheProvider.BuildCache(typeof(String).FullName, new Dictionary <string, string>());

            long longBefore = Timestamper.Next();

            await(Task.Delay(15, cancellationToken));

            long before = Timestamper.Next();

            await(Task.Delay(15, cancellationToken));

            ICacheConcurrencyStrategy ccs = new ReadWriteCache();

            ccs.Cache = cache;

            // cache something
            CacheKey fooKey = CreateCacheKey("foo");

            Assert.IsTrue(await(ccs.PutAsync(fooKey, "foo", before, null, null, false, cancellationToken)));

            await(Task.Delay(15, cancellationToken));

            long after = Timestamper.Next();

            Assert.IsNull(await(ccs.GetAsync(fooKey, longBefore, cancellationToken)));
            Assert.AreEqual("foo", await(ccs.GetAsync(fooKey, after, cancellationToken)));
            Assert.IsFalse(await(ccs.PutAsync(fooKey, "foo", before, null, null, false, cancellationToken)));

            // update it;

            ISoftLock fooLock = await(ccs.LockAsync(fooKey, null, cancellationToken));

            Assert.IsNull(await(ccs.GetAsync(fooKey, after, cancellationToken)));
            Assert.IsNull(await(ccs.GetAsync(fooKey, longBefore, cancellationToken)));
            Assert.IsFalse(await(ccs.PutAsync(fooKey, "foo", before, null, null, false, cancellationToken)));

            await(Task.Delay(15, cancellationToken));

            long whileLocked = Timestamper.Next();

            Assert.IsFalse(await(ccs.PutAsync(fooKey, "foo", whileLocked, null, null, false, cancellationToken)));

            await(Task.Delay(15, cancellationToken));

            await(ccs.ReleaseAsync(fooKey, fooLock, cancellationToken));

            Assert.IsNull(await(ccs.GetAsync(fooKey, after, cancellationToken)));
            Assert.IsNull(await(ccs.GetAsync(fooKey, longBefore, cancellationToken)));
            Assert.IsFalse(await(ccs.PutAsync(fooKey, "bar", whileLocked, null, null, false, cancellationToken)));
            Assert.IsFalse(await(ccs.PutAsync(fooKey, "bar", after, null, null, false, cancellationToken)));

            await(Task.Delay(15, cancellationToken));

            long longAfter = Timestamper.Next();

            Assert.IsTrue(await(ccs.PutAsync(fooKey, "baz", longAfter, null, null, false, cancellationToken)));
            Assert.IsNull(await(ccs.GetAsync(fooKey, after, cancellationToken)));
            Assert.IsNull(await(ccs.GetAsync(fooKey, whileLocked, cancellationToken)));

            await(Task.Delay(15, cancellationToken));

            long longLongAfter = Timestamper.Next();

            Assert.AreEqual("baz", await(ccs.GetAsync(fooKey, longLongAfter, cancellationToken)));

            // update it again, with multiple locks

            ISoftLock fooLock1 = await(ccs.LockAsync(fooKey, null, cancellationToken));
            ISoftLock fooLock2 = await(ccs.LockAsync(fooKey, null, cancellationToken));

            Assert.IsNull(await(ccs.GetAsync(fooKey, longLongAfter, cancellationToken)));

            await(Task.Delay(15, cancellationToken));

            whileLocked = Timestamper.Next();

            Assert.IsFalse(await(ccs.PutAsync(fooKey, "foo", whileLocked, null, null, false, cancellationToken)));

            await(Task.Delay(15, cancellationToken));

            await(ccs.ReleaseAsync(fooKey, fooLock2, cancellationToken));

            await(Task.Delay(15, cancellationToken));

            long betweenReleases = Timestamper.Next();

            Assert.IsFalse(await(ccs.PutAsync(fooKey, "bar", betweenReleases, null, null, false, cancellationToken)));
            Assert.IsNull(await(ccs.GetAsync(fooKey, betweenReleases, cancellationToken)));

            await(Task.Delay(15, cancellationToken));

            await(ccs.ReleaseAsync(fooKey, fooLock1, cancellationToken));

            Assert.IsFalse(await(ccs.PutAsync(fooKey, "bar", whileLocked, null, null, false, cancellationToken)));

            await(Task.Delay(15, cancellationToken));

            longAfter = Timestamper.Next();

            Assert.IsTrue(await(ccs.PutAsync(fooKey, "baz", longAfter, null, null, false, cancellationToken)));
            Assert.IsNull(await(ccs.GetAsync(fooKey, whileLocked, cancellationToken)));

            await(Task.Delay(15, cancellationToken));

            longLongAfter = Timestamper.Next();

            Assert.AreEqual("baz", await(ccs.GetAsync(fooKey, longLongAfter, cancellationToken)));
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Generate a timestamp
 /// </summary>
 /// <returns></returns>
 public virtual long NextTimestamp()
 {
     return(Timestamper.Next());
 }
Ejemplo n.º 14
0
        public void DoTestCache(ICacheProvider cacheProvider)
        {
            ICache cache = cacheProvider.BuildCache(typeof(String).FullName, new Dictionary <string, string>());

            long longBefore = Timestamper.Next();

            Thread.Sleep(15);

            long before = Timestamper.Next();

            Thread.Sleep(15);

            ICacheConcurrencyStrategy ccs = new ReadWriteCache();

            ccs.Cache = cache;

            // cache something
            CacheKey fooKey = CreateCacheKey("foo");

            Assert.IsTrue(ccs.Put(fooKey, "foo", before, null, null, false));

            Thread.Sleep(15);

            long after = Timestamper.Next();

            Assert.IsNull(ccs.Get(fooKey, longBefore));
            Assert.AreEqual("foo", ccs.Get(fooKey, after));
            Assert.IsFalse(ccs.Put(fooKey, "foo", before, null, null, false));

            // update it;

            ISoftLock fooLock = ccs.Lock(fooKey, null);

            Assert.IsNull(ccs.Get(fooKey, after));
            Assert.IsNull(ccs.Get(fooKey, longBefore));
            Assert.IsFalse(ccs.Put(fooKey, "foo", before, null, null, false));

            Thread.Sleep(15);

            long whileLocked = Timestamper.Next();

            Assert.IsFalse(ccs.Put(fooKey, "foo", whileLocked, null, null, false));

            Thread.Sleep(15);

            ccs.Release(fooKey, fooLock);

            Assert.IsNull(ccs.Get(fooKey, after));
            Assert.IsNull(ccs.Get(fooKey, longBefore));
            Assert.IsFalse(ccs.Put(fooKey, "bar", whileLocked, null, null, false));
            Assert.IsFalse(ccs.Put(fooKey, "bar", after, null, null, false));

            Thread.Sleep(15);

            long longAfter = Timestamper.Next();

            Assert.IsTrue(ccs.Put(fooKey, "baz", longAfter, null, null, false));
            Assert.IsNull(ccs.Get(fooKey, after));
            Assert.IsNull(ccs.Get(fooKey, whileLocked));

            Thread.Sleep(15);

            long longLongAfter = Timestamper.Next();

            Assert.AreEqual("baz", ccs.Get(fooKey, longLongAfter));

            // update it again, with multiple locks

            ISoftLock fooLock1 = ccs.Lock(fooKey, null);
            ISoftLock fooLock2 = ccs.Lock(fooKey, null);

            Assert.IsNull(ccs.Get(fooKey, longLongAfter));

            Thread.Sleep(15);

            whileLocked = Timestamper.Next();

            Assert.IsFalse(ccs.Put(fooKey, "foo", whileLocked, null, null, false));

            Thread.Sleep(15);

            ccs.Release(fooKey, fooLock2);

            Thread.Sleep(15);

            long betweenReleases = Timestamper.Next();

            Assert.IsFalse(ccs.Put(fooKey, "bar", betweenReleases, null, null, false));
            Assert.IsNull(ccs.Get(fooKey, betweenReleases));

            Thread.Sleep(15);

            ccs.Release(fooKey, fooLock1);

            Assert.IsFalse(ccs.Put(fooKey, "bar", whileLocked, null, null, false));

            Thread.Sleep(15);

            longAfter = Timestamper.Next();

            Assert.IsTrue(ccs.Put(fooKey, "baz", longAfter, null, null, false));
            Assert.IsNull(ccs.Get(fooKey, whileLocked));

            Thread.Sleep(15);

            longLongAfter = Timestamper.Next();

            Assert.AreEqual("baz", ccs.Get(fooKey, longLongAfter));
        }
 /// <inheritdoc />
 public override long NextTimestamp() => Timestamper.Next();