public void Wiggle_has_no_min_value()
        {
            Queue <int> randoms = new Queue <int>(new List <int> {
                Clique.WiggleTime / 2, Clique.WiggleTime, Clique.WiggleTime * 2, Clique.WiggleTime * 3
            });
            ICryptoRandom cryptoRandom = Substitute.For <ICryptoRandom>();

            cryptoRandom.NextInt(Arg.Any <int>()).Returns(ci => randoms.Dequeue());

            Snapshot snapshot = new Snapshot(1, Keccak.Zero, new SortedList <Address, long>(AddressComparer.Instance)
            {
                { TestItem.AddressA, 1 },
                { TestItem.AddressB, 2 },
                { TestItem.AddressC, 3 },
                { TestItem.AddressD, 4 }
            });

            ISnapshotManager snapshotManager = Substitute.For <ISnapshotManager>();

            snapshotManager.GetOrCreateSnapshot(Arg.Any <long>(), Arg.Any <Keccak>()).Returns(snapshot);
            WiggleRandomizer randomizer = new WiggleRandomizer(cryptoRandom, snapshotManager);

            BlockHeader header1 = Build.A.BlockHeader.WithNumber(1).TestObject;
            BlockHeader header2 = Build.A.BlockHeader.WithNumber(2).TestObject;
            BlockHeader header3 = Build.A.BlockHeader.WithNumber(3).TestObject;
            int         wiggle  = randomizer.WiggleFor(header1);

            Assert.AreEqual(Clique.WiggleTime / 2, wiggle);

            wiggle = randomizer.WiggleFor(header2);
            Assert.AreEqual(Clique.WiggleTime, wiggle);

            wiggle = randomizer.WiggleFor(header3);
            Assert.AreEqual(Clique.WiggleTime * 2, wiggle);
        }
Example #2
0
        public StateManager(IStorageManager storageManager, IRocksDbContext dbContext)
        {
            _balanceManager =
                new SnapshotManager <IBalanceSnapshot, BalanceSnapshot>(storageManager,
                                                                        (uint)RepositoryType.BalanceRepository);
            _contractManager =
                new SnapshotManager <IContractSnapshot, ContractSnapshot>(storageManager,
                                                                          (uint)RepositoryType.ContractRepository);
            _storageManager =
                new SnapshotManager <IStorageSnapshot, StorageSnapshot>(storageManager,
                                                                        (uint)RepositoryType.StorageRepository);
            _transactionManager =
                new SnapshotManager <ITransactionSnapshot, TransactionSnapshot>(storageManager,
                                                                                (uint)RepositoryType.TransactionRepository);
            _blockManager =
                new SnapshotManager <IBlockSnapshot, BlockSnapshot>(storageManager,
                                                                    (uint)RepositoryType.BlockRepository);
            _eventManager =
                new SnapshotManager <IEventSnapshot, EventSnapshot>(storageManager,
                                                                    (uint)RepositoryType.EventRepository);
            _validatorManager =
                new SnapshotManager <IValidatorSnapshot, ValidatorSnapshot>(storageManager,
                                                                            (uint)RepositoryType.ValidatorRepository);

            LastApprovedSnapshot = new BlockchainSnapshot(
                _balanceManager.LastApprovedSnapshot,
                _contractManager.LastApprovedSnapshot,
                _storageManager.LastApprovedSnapshot,
                _transactionManager.LastApprovedSnapshot,
                _blockManager.LastApprovedSnapshot,
                _eventManager.LastApprovedSnapshot,
                _validatorManager.LastApprovedSnapshot
                );
            _dbContext = dbContext;
        }
        public static TSnapshot FindSnapshot <TSnapshot>(this ISnapshotManager snapshotManager, string title, string category = null)
            where TSnapshot : ISnapshot
        {
            Argument.IsNotNull(() => snapshotManager);

            return((TSnapshot)FindSnapshot(snapshotManager, title, category));
        }
        public void Wiggle_is_fine()
        {
            Queue <int> randoms        = new(new List <int> {
                100, 600, 1000, 2000, 50
            });
            ICryptoRandom cryptoRandom = Substitute.For <ICryptoRandom>();

            cryptoRandom.NextInt(Arg.Any <int>()).Returns(ci => randoms.Dequeue());

            Snapshot snapshot = new(1, Keccak.Zero, new SortedList <Address, long>(AddressComparer.Instance)
            {
                { TestItem.AddressA, 1 },
                { TestItem.AddressB, 2 },
                { TestItem.AddressC, 3 },
                { TestItem.AddressD, 4 }
            });
            ISnapshotManager snapshotManager = Substitute.For <ISnapshotManager>();

            snapshotManager.GetOrCreateSnapshot(Arg.Any <long>(), Arg.Any <Keccak>()).Returns(snapshot);
            WiggleRandomizer randomizer = new(cryptoRandom, snapshotManager);

            BlockHeader header1 = Build.A.BlockHeader.WithNumber(1).TestObject;

            for (int i = 0; i < 5; i++)
            {
                Assert.AreEqual(100, randomizer.WiggleFor(header1));
            }
        }
Example #5
0
        public CompanySnapshotProvider(Project project, ISnapshotManager snapshotManager, IServiceLocator serviceLocator)
            : base(snapshotManager, serviceLocator)
        {
            Argument.IsNotNull(() => project);

            _project = project;
        }
        public void Returns_zero_for_in_turn_blocks()
        {
            Queue <int> randoms        = new(new List <int> {
                Consensus.Clique.Clique.WiggleTime / 2, Consensus.Clique.Clique.WiggleTime, Consensus.Clique.Clique.WiggleTime * 2, Consensus.Clique.Clique.WiggleTime * 3
            });
            ICryptoRandom cryptoRandom = Substitute.For <ICryptoRandom>();

            cryptoRandom.NextInt(Arg.Any <int>()).Returns(ci => randoms.Dequeue());

            Snapshot snapshot = new(1, Keccak.Zero, new SortedList <Address, long>(AddressComparer.Instance)
            {
                { TestItem.AddressA, 1 },
                { TestItem.AddressB, 2 },
                { TestItem.AddressC, 3 },
                { TestItem.AddressD, 4 }
            });

            ISnapshotManager snapshotManager = Substitute.For <ISnapshotManager>();

            snapshotManager.GetOrCreateSnapshot(Arg.Any <long>(), Arg.Any <Keccak>()).Returns(snapshot);
            WiggleRandomizer randomizer = new(cryptoRandom, snapshotManager);

            BlockHeader header1 = Build.A.BlockHeader.WithNumber(1).WithDifficulty(Consensus.Clique.Clique.DifficultyInTurn).TestObject;
            int         wiggle  = randomizer.WiggleFor(header1);

            Assert.AreEqual(0, wiggle);
        }
        public CliqueBlockProducer(IPendingTxSelector pendingTxSelector,
                                   IBlockchainProcessor blockchainProcessor,
                                   IStateProvider stateProvider,
                                   IBlockTree blockTree,
                                   ITimestamper timestamper,
                                   ICryptoRandom cryptoRandom,
                                   ISnapshotManager snapshotManager,
                                   ISealer cliqueSealer,
                                   Address address,
                                   ICliqueConfig config,
                                   ILogManager logManager)
        {
            _logger            = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
            _pendingTxSelector = pendingTxSelector ?? throw new ArgumentNullException(nameof(pendingTxSelector));
            _processor         = blockchainProcessor ?? throw new ArgumentNullException(nameof(blockchainProcessor));
            _blockTree         = blockTree ?? throw new ArgumentNullException(nameof(blockTree));
            _stateProvider     = stateProvider ?? throw new ArgumentNullException(nameof(stateProvider));
            _timestamper       = timestamper ?? throw new ArgumentNullException(nameof(timestamper));
            _cryptoRandom      = cryptoRandom ?? throw new ArgumentNullException(nameof(cryptoRandom));
            _sealer            = cliqueSealer ?? throw new ArgumentNullException(nameof(cliqueSealer));
            _snapshotManager   = snapshotManager ?? throw new ArgumentNullException(nameof(snapshotManager));
            _config            = config ?? throw new ArgumentNullException(nameof(config));
            _address           = address ?? throw new ArgumentNullException(nameof(address));
            _wiggle            = new WiggleRandomizer(_cryptoRandom, _snapshotManager);

            _timer.AutoReset = false;
            _timer.Elapsed  += TimerOnElapsed;
            _timer.Interval  = 100;
            _timer.Start();
        }
Example #8
0
 public EventSource(IEventSender eventSender, IEventStore eventStore, ISnapshotManager snapshotManager, IServiceProvider serviceProvider)
 {
     this.serviceProvider = serviceProvider;
     this.eventSender     = eventSender;
     this.eventStore      = eventStore;
     this.snapshotManager = snapshotManager;
 }
        public CliqueBlockProducer(
            ITxSource txSource,
            IBlockchainProcessor blockchainProcessor,
            IStateProvider stateProvider,
            IBlockTree blockTree,
            ITimestamper timestamper,
            ICryptoRandom cryptoRandom,
            ISnapshotManager snapshotManager,
            ISealer cliqueSealer,
            IGasLimitCalculator gasLimitCalculator,
            ISpecProvider?specProvider,
            ICliqueConfig config,
            ILogManager logManager)
        {
            _logger             = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
            _txSource           = txSource ?? throw new ArgumentNullException(nameof(txSource));
            _processor          = blockchainProcessor ?? throw new ArgumentNullException(nameof(blockchainProcessor));
            _blockTree          = blockTree ?? throw new ArgumentNullException(nameof(blockTree));
            _stateProvider      = stateProvider ?? throw new ArgumentNullException(nameof(stateProvider));
            _timestamper        = timestamper ?? throw new ArgumentNullException(nameof(timestamper));
            _cryptoRandom       = cryptoRandom ?? throw new ArgumentNullException(nameof(cryptoRandom));
            _sealer             = cliqueSealer ?? throw new ArgumentNullException(nameof(cliqueSealer));
            _gasLimitCalculator = gasLimitCalculator ?? throw new ArgumentNullException(nameof(gasLimitCalculator));
            _specProvider       = specProvider ?? throw new ArgumentNullException(nameof(specProvider));
            _snapshotManager    = snapshotManager ?? throw new ArgumentNullException(nameof(snapshotManager));
            _config             = config ?? throw new ArgumentNullException(nameof(config));
            _wiggle             = new WiggleRandomizer(_cryptoRandom, _snapshotManager);

            _timer.AutoReset = false;
            _timer.Elapsed  += TimerOnElapsed;
            _timer.Interval  = 100;
            _timer.Start();
        }
Example #10
0
        private void SetSnapshotManager(ISnapshotManager snapshotManager)
        {
            var previousSnapshotManager = _snapshotManager;

            if (ReferenceEquals(snapshotManager, previousSnapshotManager))
            {
                return;
            }

            if (previousSnapshotManager is not null)
            {
                previousSnapshotManager.Loaded           -= OnSnapshotsLoaded;
                previousSnapshotManager.SnapshotsChanged -= OnSnapshotsChanged;
            }

            Log.Debug($"Updating current snapshot manager with scope '{snapshotManager?.Scope}' to new instance with '{snapshotManager?.Snapshots.Count() ?? 0}' snapshots");

            _snapshotManager = snapshotManager;

            if (snapshotManager is not null)
            {
                snapshotManager.Loaded           += OnSnapshotsLoaded;
                snapshotManager.SnapshotsChanged += OnSnapshotsChanged;
            }
        }
Example #11
0
        public CliqueBlockProducer(ITransactionPool transactionPool,
                                   IBlockchainProcessor blockchainProcessor,
                                   IBlockTree blockTree,
                                   ITimestamp timestamp,
                                   ICryptoRandom cryptoRandom,
                                   IStateProvider stateProvider,
                                   ISnapshotManager snapshotManager,
                                   ISealer cliqueSealer,
                                   Address address,
                                   ICliqueConfig config,
                                   ILogManager logManager)
        {
            _logger          = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
            _transactionPool = transactionPool ?? throw new ArgumentNullException(nameof(transactionPool));
            _processor       = blockchainProcessor ?? throw new ArgumentNullException(nameof(blockchainProcessor));
            _blockTree       = blockTree ?? throw new ArgumentNullException(nameof(blockTree));
            _stateProvider   = stateProvider ?? throw new ArgumentNullException(nameof(stateProvider));
            _timestamp       = timestamp ?? throw new ArgumentNullException(nameof(timestamp));
            _cryptoRandom    = cryptoRandom ?? throw new ArgumentNullException(nameof(cryptoRandom));
            _sealer          = cliqueSealer ?? throw new ArgumentNullException(nameof(cliqueSealer));
            _snapshotManager = snapshotManager ?? throw new ArgumentNullException(nameof(snapshotManager));
            _config          = config ?? throw new ArgumentNullException(nameof(config));
            _address         = address ?? throw new ArgumentNullException(nameof(address));

            _timer.AutoReset = false;
            _timer.Elapsed  += TimerOnElapsed;
            _timer.Interval  = 100;
            _timer.Start();
        }
        public void Can_ask_for_block_signer_when_hash_is_null()
        {
            ISnapshotManager snapshotManager = Substitute.For <ISnapshotManager>();
            IBlockFinder     blockFinder     = Substitute.For <IBlockFinder>();
            CliqueRpcModule  rpcModule       = new(Substitute.For <ICliqueBlockProducer>(), snapshotManager, blockFinder);

            rpcModule.clique_getBlockSigner(null).Result.ResultType.Should().Be(ResultType.Failure);
        }
        public static void AddProvider <TSnapshotProvider>(this ISnapshotManager snapshotManager)
            where TSnapshotProvider : ISnapshotProvider
        {
            Argument.IsNotNull(() => snapshotManager);

            var snapshotProvider = TypeFactory.Default.CreateInstance <TSnapshotProvider>();

            snapshotManager.AddProvider(snapshotProvider);
        }
 public DataHarmonizationManager(IDataHarmonizationLogManager logManager, ILicenseRepository licenseRepository, IDataHarmonizationQueueService dataHarmonizationQueueService,
                                 ILicenseProductService licenseProductService, ISnapshotManager snapshotManager)
 {
     _dataHarmonizationQueueService = dataHarmonizationQueueService;
     _snapshotManager       = snapshotManager;
     _licenseProductService = licenseProductService;
     _licenseRepository     = licenseRepository;
     _logManager            = logManager;
 }
        public UpdateTransformSystem(Contexts contexts, ISnapshotManager snapshotManager,
                                     IMatchTimeStorage matchTimeStorage)
        {
            this.snapshotManager  = snapshotManager;
            this.matchTimeStorage = matchTimeStorage;
            gameContext           = contexts.serverGame;
            var matcher = ServerGameMatcher.AllOf(ServerGameMatcher.Transform).NoneOf(ServerGameMatcher.HealthBar);

            withTransformGroup = contexts.serverGame.GetGroup(matcher);
        }
        public static ISnapshot FindSnapshot(this ISnapshotManager snapshotManager, string title, string category = null)
        {
            Argument.IsNotNull(() => snapshotManager);
            Argument.IsNotNullOrWhitespace(() => title);

            return((from snapshot in snapshotManager.Snapshots
                    where string.Equals(snapshot.Title, title, StringComparison.OrdinalIgnoreCase) &&
                    string.Equals(snapshot.Category, category, StringComparison.OrdinalIgnoreCase)
                    select snapshot).FirstOrDefault());
        }
Example #17
0
 public RepositoryEx(
     IStoreEvents eventStore,
     IConstructAggregatesEx factory,
     IDetectConflicts conflictDetector,
     IIdentityConverter identityConverter,
     NEventStore.Logging.ILog logger)
     : base(eventStore, factory, conflictDetector, identityConverter, logger)
 {
     SnapshotManager = NullSnapshotManager.Instance; //Default behavior is avoid snapshot entirely.
 }
        public void Can_ask_for_block_signer_when_block_is_unknown()
        {
            ISnapshotManager snapshotManager = Substitute.For <ISnapshotManager>();
            IBlockFinder     blockFinder     = Substitute.For <IBlockFinder>();

            blockFinder.FindHeader(Arg.Any <Keccak>()).Returns((BlockHeader)null);
            CliqueRpcModule rpcModule = new(Substitute.For <ICliqueBlockProducer>(), snapshotManager, blockFinder);

            rpcModule.clique_getBlockSigner(Keccak.Zero).Result.ResultType.Should().Be(ResultType.Failure);
        }
Example #19
0
 /// <summary>
 /// Sets up the engine to use the last-in-first-out optimized snapshot storage,
 /// suitable for fast reading of recent data.
 /// </summary>
 /// <param name="formatter">
 /// Specifies a <see cref="IFormatter<TInputStream, TOutputStream>"/> which
 /// will be used for serialization and deserialization.
 /// </param>
 /// <param name="options">
 /// If not null, overrides the default <see cref="FilesystemStorageOptions"/>.
 /// </param>
 /// <param name="zeroPaddingBytes">
 /// Specifies maximum free space at the start of the file for future
 /// snapshots. When there is no free space left for writing, the file
 /// expands by specified byte count and rewrites.
 /// <para>
 /// If the number is too small, rewrites may appear often.
 /// </para>
 /// <para>
 /// If the number is big, files will be bigger and may consist
 /// of big unused space depending on how many data is being written.
 /// </para>
 /// </param>
 public DiffstoreBuilder <TKey, TValue> WithLastFirstOptimizedSnapshots(
     IFileSystem fileSystem           = null,
     FilesystemStorageOptions options = null,
     int zeroPaddingBytes             = 256)
 {
     (fileSystem, options) = PrepareFileStorage(fileSystem, options);
     sm = new BinaryLIFOSnapshotManager <TKey, TValue>(options,
                                                       fileSystem, zeroPaddingBytes);
     return(this);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="SnapshotProviderBase" /> class.
        /// </summary>
        /// <param name="snapshotManager">The snapshot manager.</param>
        /// <param name="serviceLocator">The service locator.</param>
        protected SnapshotProviderBase(ISnapshotManager snapshotManager, IServiceLocator serviceLocator)
        {
            Argument.IsNotNull(() => snapshotManager);
            Argument.IsNotNull(() => serviceLocator);

            ServiceLocator = serviceLocator;

            SnapshotManager = snapshotManager;

            Name = GetType().Name;
        }
Example #21
0
        public RibbonViewModel(ISnapshotManager snapshotManager, IUIVisualizerService uiVisualizerService, IMessageService messageService)
        {
            _snapshotManager     = snapshotManager;
            _uiVisualizerService = uiVisualizerService;
            _messageService      = messageService;

            CreateSnapshot   = new TaskCommand(OnCreateSnapshotExecuteAsync, OnCreateSnapshotCanExecute);
            CleanupSnapshots = new TaskCommand(OnCleanupSnapshotsExecuteAsync);

            Title = "Orc.Snapshots example";
        }
Example #22
0
 public InputSystem(Joystick forMovement, Joystick forAttack,
                    ClientInputMessagesHistory clientInputMessagesHistory, ISnapshotManager snapshotManager,
                    IMatchTimeStorage matchTimeStorage, LastInputIdStorage lastInputIdStorage)
 {
     movementJoystick = forMovement;
     attackJoystick   = forAttack;
     this.clientInputMessagesHistory = clientInputMessagesHistory;
     this.snapshotManager            = snapshotManager;
     this.matchTimeStorage           = matchTimeStorage;
     this.lastInputIdStorage         = lastInputIdStorage;
 }
Example #23
0
        public ShowNotificationOnSnapshotEventsWatcher(ISnapshotManager snapshotManager, INotificationService notificationService)
        {
            Argument.IsNotNull(() => snapshotManager);
            Argument.IsNotNull(() => notificationService);

            _snapshotManager     = snapshotManager;
            _notificationService = notificationService;

            _snapshotManager.Loaded           += OnSnapshotManagerLoaded;
            _snapshotManager.SnapshotCreated  += OnSnapshotManagerSnapshotCreated;
            _snapshotManager.SnapshotRestored += OnSnapshotManagerSnapshotRestored;
        }
        public static async Task <ISnapshot> CreateSnapshotAndSaveAsync(this ISnapshotManager snapshotManager, string title, string category = null)
        {
            Argument.IsNotNull(() => snapshotManager);
            Argument.IsNotNullOrWhitespace(() => title);

            var snapshot = await snapshotManager.CreateSnapshotAsync(title, category);

            snapshotManager.Add(snapshot);
            await snapshotManager.SaveAsync();

            return(snapshot);
        }
Example #25
0
        public CliqueSealer(ISigner signer, ICliqueConfig config, ISnapshotManager snapshotManager, ILogManager logManager)
        {
            _logger          = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
            _snapshotManager = snapshotManager ?? throw new ArgumentNullException(nameof(snapshotManager));
            _config          = config ?? throw new ArgumentNullException(nameof(config));
            _signer          = signer ?? throw new ArgumentNullException(nameof(signer));

            if (config.Epoch == 0)
            {
                config.Epoch = Clique.DefaultEpochLength;
            }
        }
        internal DefaultViewManager(IEventManager eventManager, ISnapshotManager snapshotManager, bool disposeDependencies)
        {
            Guard.Against.Null(() => eventManager);
            Guard.Against.Null(() => snapshotManager);

            this.eventManager    = eventManager;
            this.snapshotManager = snapshotManager;

            var task = new Task(() => this.Run(this.cancellationTokenSource.Token));

            task.ContinueWith(t => this.cancellationTokenSource.Dispose(), TaskContinuationOptions.ExecuteSynchronously);
            task.Start();
        }
Example #27
0
        public CliqueSealer(IBasicWallet wallet, ICliqueConfig config, ISnapshotManager snapshotManager, Address sealerAddress, ILogManager logManager)
        {
            _logger          = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
            _snapshotManager = snapshotManager ?? throw new ArgumentNullException(nameof(snapshotManager));
            _sealerAddress   = sealerAddress ?? throw new ArgumentNullException(nameof(sealerAddress));
            _config          = config ?? throw new ArgumentNullException(nameof(config));
            _wallet          = wallet ?? throw new ArgumentNullException(nameof(wallet));

            if (config.Epoch == 0)
            {
                config.Epoch = Clique.DefaultEpochLength;
            }
        }
        public void Can_ask_for_block_signer()
        {
            ISnapshotManager snapshotManager = Substitute.For <ISnapshotManager>();
            IBlockFinder     blockFinder     = Substitute.For <IBlockFinder>();
            BlockHeader      header          = Build.A.BlockHeader.TestObject;

            blockFinder.FindHeader(Arg.Any <Keccak>()).Returns(header);
            snapshotManager.GetBlockSealer(header).Returns(TestItem.AddressA);
            CliqueRpcModule rpcModule = new(Substitute.For <ICliqueBlockProducer>(), snapshotManager, blockFinder);

            rpcModule.clique_getBlockSigner(Keccak.Zero).Result.ResultType.Should().Be(ResultType.Success);
            rpcModule.clique_getBlockSigner(Keccak.Zero).Data.Should().Be(TestItem.AddressA);
        }
        public SnapshotsCleanupViewModel(ISnapshotManager snapshotManager, ILanguageService languageService)
        {
            Argument.IsNotNull(() => snapshotManager);
            Argument.IsNotNull(() => languageService);

            _snapshotManager = snapshotManager;

            Snapshots = new List <SnapshotCleanup>(from snapshot in _snapshotManager.Snapshots
                                                   select new SnapshotCleanup(snapshot));

            MaxSnapshotAge = 7;

            Title = languageService.GetString("Snapshots_CleanupTitle");
        }
Example #30
0
 public AggregateRepository(IEventStore eventStore,
                            ISnapshotManager snapshotManager,
                            ISerializationManager serializeManager,
                            IEventPublisher eventPublisher,
                            ICommitNotifier commitNotifier,
                            IIntegrityValidator integrityValidator)
 {
     _eventStore         = eventStore;
     _snapshotManager    = snapshotManager;
     _serializeManager   = serializeManager;
     _eventPublisher     = eventPublisher;
     _commitNotifier     = commitNotifier;
     _integrityValidator = integrityValidator;
 }