/// <summary>Initializes a new instance of the <see cref="PeerCountRequestObserver" /> class.</summary>
 /// <param name="peerSettings"></param>
 /// <param name="peerRepository">The peer discovery.</param>
 /// <param name="logger">The logger.</param>
 public PeerCountRequestObserver(IPeerSettings peerSettings,
                                 IPeerRepository peerRepository,
                                 ILogger logger) :
     base(logger, peerSettings)
 {
     _peerRepository = peerRepository;
 }
Exemple #2
0
 public PeerBlackListingRequestObserver(IPeerSettings peerSettings,
                                        ILogger logger,
                                        IPeerRepository peerRepository)
     : base(logger, peerSettings)
 {
     _peerRepository = peerRepository;
 }
Exemple #3
0
 public PeerReputationRequestObserver(IPeerSettings peerSettings,
                                      ILogger logger,
                                      IPeerRepository peerRepository)
     : base(logger, peerSettings)
 {
     _peerRepository = peerRepository;
 }
Exemple #4
0
 public PingResponseObserver(IPeerChallengeRequest peerChallengeRequest, IPeerRepository peerRepository, ILogger logger)
     : base(logger)
 {
     _peerChallengeRequest  = peerChallengeRequest;
     _peerRepository        = peerRepository;
     ResponseMessageSubject = new ReplaySubject <IPeerClientMessageDto>(1);
 }
Exemple #5
0
        public CatalystNodePoa(IKeySigner keySigner,
                               IPeerService peer,
                               IConsensus consensus,
                               IDfsService dfsService,
                               ILedger ledger,
                               ILogger logger,
                               IPeerClient peerClient,
                               IPeerSettings peerSettings,
                               IMempool <PublicEntryDao> memPool,
                               ISynchroniser synchronizer,
                               IPeerRepository peerRepository,
                               IContract contract = null)
        {
            Guard.Argument(peerRepository, nameof(peerRepository)).NotNull();

            _peer           = peer;
            _peerClient     = peerClient;
            _peerSettings   = peerSettings;
            Consensus       = consensus;
            _dfsService     = dfsService;
            _ledger         = ledger;
            _keySigner      = keySigner;
            _logger         = logger;
            _memPool        = memPool;
            _contract       = contract;
            _synchronizer   = synchronizer;
            _peerRepository = peerRepository;

            var privateKey = keySigner.KeyStore.KeyStoreDecrypt(KeyRegistryTypes.DefaultKey);

            _publicKey = keySigner.CryptoContext.GetPublicKeyFromPrivateKey(privateKey);
        }
Exemple #6
0
        public PoaTestNode(string name,
                           IPrivateKey privateKey,
                           IPeerSettings nodeSettings,
                           IDfsService dfsService,
                           IEnumerable <PeerId> knownPeerIds,
                           IFileSystem parentTestFileSystem)
        {
            Name          = name;
            _nodeSettings = nodeSettings;

            _nodeDirectory = parentTestFileSystem.GetCatalystDataDir();

            _dfsService = dfsService;

            _rpcSettings = RpcSettingsHelper.GetRpcServerSettings(nodeSettings.Port + 100);
            _nodePeerId  = nodeSettings.PeerId;

            _memPool        = new Mempool(new MempoolService(new InMemoryRepository <PublicEntryDao, string>()));
            _peerRepository = new PeerRepository(new InMemoryRepository <Peer, string>());
            var peersInRepo = knownPeerIds.Select(p => new Peer
            {
                PeerId    = p,
                IsPoaNode = true,
                LastSeen  = DateTime.UtcNow
            }).ToList();

            _peerRepository.Add(peersInRepo);

            _deltaByNumber = new DeltaByNumberRepository(new InMemoryRepository <DeltaByNumber, string>());

            _containerProvider = new ContainerProvider(new[]
            {
                Constants.NetworkConfigFile(NetworkType.Devnet),
                Constants.SerilogJsonConfigFile
            }
                                                       .Select(f => Path.Combine(Constants.ConfigSubFolder, f)), parentTestFileSystem, TestContext.CurrentContext);

            RegisterNodeDependencies(_containerProvider.ContainerBuilder,
                                     excludedModules: new List <Type>
            {
                typeof(ApiModule),
                typeof(RpcServerModule)
            }
                                     );
            _containerProvider.ConfigureContainerBuilder(true, true);
            OverrideContainerBuilderRegistrations();

            _scope = _containerProvider.Container.BeginLifetimeScope(Name);
            _node  = _scope.Resolve <ICatalystNode>();

            var keyStore    = _scope.Resolve <IKeyStore>();
            var keyRegistry = _scope.Resolve <IKeyRegistry>();

            keyRegistry.RemoveItemFromRegistry(KeyRegistryTypes.DefaultKey);
            keyRegistry.AddItemToRegistry(KeyRegistryTypes.DefaultKey, privateKey);

            keyStore.KeyStoreEncryptAsync(privateKey, nodeSettings.NetworkType, KeyRegistryTypes.DefaultKey)
            .ConfigureAwait(false).GetAwaiter()
            .GetResult();
        }
Exemple #7
0
        public Web3EthApi(IStateReader stateReader,
                          IDeltaResolver deltaResolver,
                          IDeltaCache deltaCache,
                          IDeltaExecutor executor,
                          IStorageProvider storageProvider,
                          IStateProvider stateProvider,
                          ITransactionRepository receipts,
                          ITransactionReceivedEvent transactionReceived,
                          IPeerRepository peerRepository,
                          IMempool <PublicEntryDao> mempoolRepository,
                          IDfsService dfsService,
                          IHashProvider hashProvider,
                          SyncState syncState,
                          IMapperProvider mapperProvider,
                          IPeerSettings peerSettings)
        {
            _receipts            = receipts;
            _transactionReceived = transactionReceived ?? throw new ArgumentNullException(nameof(transactionReceived));
            HashProvider         = hashProvider;
            _peerId            = peerSettings.PeerId;
            _mempoolRepository = mempoolRepository;
            PeerRepository     = peerRepository;
            _mapperProvider    = mapperProvider;

            StateReader     = stateReader ?? throw new ArgumentNullException(nameof(stateReader));
            DeltaResolver   = deltaResolver ?? throw new ArgumentNullException(nameof(deltaResolver));
            DeltaCache      = deltaCache ?? throw new ArgumentNullException(nameof(deltaCache));
            Executor        = executor ?? throw new ArgumentNullException(nameof(executor));
            StorageProvider = storageProvider ?? throw new ArgumentNullException(nameof(storageProvider));
            StateProvider   = stateProvider ?? throw new ArgumentNullException(nameof(stateProvider));
            DfsService      = dfsService;
            SyncState       = syncState;
        }
 public GetPeerInfoRequestObserver(IPeerSettings peerSettings,
                                   ILogger logger,
                                   IPeerRepository peerRepository)
     : base(logger, peerSettings)
 {
     _peerRepository = peerRepository;
 }
 public GetNeighbourRequestObserver(IPeerSettings peerSettings,
                                    IPeerRepository repository,
                                    ILogger logger)
     : base(logger, peerSettings)
 {
     _repository = repository;
 }
Exemple #10
0
 public PoaDiscovery(IPeerSettings peerSettings, IPeerRepository peerRepository, IFileSystem fileSystem, ILogger logger)
 {
     _peerSettings   = peerSettings;
     _peerRepository = peerRepository;
     _fileSystem     = fileSystem;
     _logger         = logger;
 }
 public GetNeighbourRequestObserverTests()
 {
     _testScheduler        = new TestScheduler();
     _subbedLogger         = Substitute.For <ILogger>();
     _subbedPeerRepository = Substitute.For <IPeerRepository>();
     _peerId = PeerIdHelper.GetPeerId("testPeer");
 }
        public DeadPeerDetector(IBus bus, IPeerRepository peerRepository, IDirectoryConfiguration configuration)
        {
            _bus            = bus;
            _peerRepository = peerRepository;
            _configuration  = configuration;

            TaskScheduler = TaskScheduler.Current;
        }
 public FavouriteDeltaObserver(IDeltaElector deltaElector, SyncState syncState, IPeerRepository peerRepository, IHashProvider hashProvider, ILogger logger)
     : base(logger)
 {
     _deltaElector   = deltaElector;
     _syncState      = syncState;
     _hashProvider   = hashProvider;
     _peerRepository = peerRepository;
 }
 public DirectoryCommandsHandler(IBus bus, IPeerRepository peerRepository, IDirectoryConfiguration configuration, IDirectorySpeedReporter speedReporter)
 {
     _bus                 = bus;
     _peerRepository      = peerRepository;
     _configuration       = configuration;
     _speedReporter       = speedReporter;
     _blacklistedMachines = configuration.BlacklistedMachines.ToHashSet(StringComparer.OrdinalIgnoreCase);
 }
Exemple #15
0
        public void OneTimeSetUp()
        {
            _container = new Container(configuration => configuration.AddRegistry <BusRegistry>());

            _bus = BusFactory.Create("TestE2E", "tcp://localhost:8080", "tcp://localhost:8080", _container);

            _directoryRepository = _container.GetInstance <IPeerRepository>();
        }
        /// <summary>Executes the test case.</summary>
        /// <param name="fakePeers">The fake peers.</param>
        /// <param name="withPublicKey">if set to <c>true</c> [send message to handler with the public key].</param>
        private void ExecuteTestCase(IReadOnlyCollection <string> fakePeers, bool withPublicKey)
        {
            var             testScheduler      = new TestScheduler();
            IPeerRepository peerRepository     = Substitute.For <IPeerRepository>();
            Peer            targetPeerToDelete = null;
            var             fakePeerList       = fakePeers.ToList().Select(fakePeer =>
            {
                var peer = new Peer
                {
                    Reputation = 0,
                    LastSeen   = DateTime.Now.Subtract(TimeSpan.FromSeconds(fakePeers.ToList().IndexOf(fakePeer))),
                    PeerId     = PeerIdHelper.GetPeerId(fakePeer)
                };

                if (targetPeerToDelete == null)
                {
                    targetPeerToDelete = peer;
                }

                return(peer);
            }).ToList();

            peerRepository.FindAll(Arg.Any <ISpecification <Peer> >()).Returns(withPublicKey ? new List <Peer> {
                targetPeerToDelete
            } : fakePeerList);

            // Build a fake remote endpoint
            _fakeContext.Channel.RemoteAddress.Returns(EndpointBuilder.BuildNewEndPoint("192.0.0.1", 42042));

            var peerId = PeerIdHelper.GetPeerId("sender");

            var removePeerRequest = new RemovePeerRequest
            {
                PeerIp    = targetPeerToDelete.PeerId.Ip,
                PublicKey = withPublicKey ? targetPeerToDelete.PeerId.PublicKey : ByteString.Empty
            };

            var protocolMessage = removePeerRequest.ToProtocolMessage(peerId);

            var messageStream = MessageStreamHelper.CreateStreamWithMessage(_fakeContext, testScheduler, protocolMessage);

            var peerSettings = peerId.ToSubstitutedPeerSettings();
            var handler      = new RemovePeerRequestObserver(peerSettings, peerRepository, _logger);

            handler.StartObserving(messageStream);

            testScheduler.Start();

            var receivedCalls = _fakeContext.Channel.ReceivedCalls().ToList();

            receivedCalls.Count().Should().Be(1);

            var sentResponseDto = (IMessageDto <ProtocolMessage>)receivedCalls[0].GetArguments().Single();

            var signResponseMessage = sentResponseDto.Content.FromProtocolMessage <RemovePeerResponse>();

            signResponseMessage.DeletedCount.Should().Be(withPublicKey ? 1 : (uint)fakePeers.Count);
        }
        public DeadPeerDetector(IBus bus, IPeerRepository peerRepository, IDirectoryConfiguration configuration)
        {
            _bus = bus;
            _peerRepository = peerRepository;
            _configuration = configuration;

            TaskScheduler = TaskScheduler.Current;
            ExceptionHandler = ex => _logger.ErrorFormat("MainLoop error: {0}", ex);
        }
 public void Init()
 {
     _peerRepository = Substitute.For <IPeerRepository>();
     _peerClient     = Substitute.For <IPeerClient>();
     _testPeer       = new Peer
     {
         PeerId = PeerIdHelper.GetPeerId("TestPeer")
     };
 }
        public DeltaHeightRanker(IPeerRepository peerRepository, int maxPeersInStore = 100, double threshold = 0.5, IScheduler scheduler = null)
        {
            _peerRepository  = peerRepository;
            _maxPeersInStore = maxPeersInStore;
            _threshold       = threshold;

            _foundDeltaHeightSubject = new ReplaySubject <DeltaIndex>(1, scheduler ?? Scheduler.Default);
            FoundDeltaHeight         = _foundDeltaHeightSubject.AsObservable();
        }
Exemple #20
0
 public CandidateDeltaObserver(IDeltaVoter deltaVoter, IDeltaIndexService deltaIndexService, SyncState syncState, IPeerRepository peerRepository, IHashProvider provider, ILogger logger)
     : base(logger)
 {
     _deltaVoter        = deltaVoter;
     _deltaIndexService = deltaIndexService;
     _syncState         = syncState;
     _peerRepository    = peerRepository;
     _hashProvider      = provider;
 }
 public PeerHeartbeatCheckerTests()
 {
     _peerRepository = Substitute.For <IPeerRepository>();
     _peerClient     = Substitute.For <IPeerClient>();
     _testPeer       = new Peer
     {
         PeerId = PeerIdHelper.GetPeerId("TestPeer")
     };
 }
Exemple #22
0
 //todo add unit tests
 public PeerSyncManagerUnitTests()
 {
     _hashProvider             = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("keccak-256"));
     _peerService              = Substitute.For <IPeerService>();
     _peerClient               = Substitute.For <IPeerClient>();
     _peerRepository           = new PeerRepository(new InMemoryRepository <Peer, string>());
     _deltaHeightReplaySubject = new ReplaySubject <IObserverDto <ProtocolMessage> >(1);
     _peerService.MessageStream.Returns(_deltaHeightReplaySubject.AsObservable());
 }
Exemple #23
0
        public ReputationManager(IPeerRepository peerRepository, ILogger logger, IScheduler scheduler = null)
        {
            var observableScheduler = scheduler ?? Scheduler.Default;

            _logger         = logger;
            PeerRepository  = peerRepository;
            ReputationEvent = new ReplaySubject <IPeerReputationChange>(0, observableScheduler);
            ReputationEventStream.Subscribe(OnNext, OnError, OnCompleted);
        }
        public ReputationManager(IPeerRepository peerRepository, ILogger logger)
        {
            _logger         = logger;
            PeerRepository  = peerRepository;
            ReputationEvent = new ReplaySubject <IPeerReputationChange>(0);

            ReputationEventStream
            .SubscribeOn(NewThreadScheduler.Default)
            .Subscribe(OnNext, OnError, OnCompleted);
        }
Exemple #25
0
        public DiscoveryTestBuilder WithPeerRepository(IPeerRepository peerRepository = default, bool mock = false)
        {
            _peerRepository = peerRepository == default(IPeerRepository) && mock == false
                ? Substitute.For <IPeerRepository>()
                : peerRepository == null
                    ? _peerRepository = DiscoveryHelper.MockPeerRepository()
                    : _peerRepository = peerRepository;

            return(this);
        }
Exemple #26
0
 public void Init()
 {
     _hashProvider       = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("keccak-256"));
     _deltaHashProvider  = Substitute.For <IDeltaHashProvider>();
     _fakeChannelContext = Substitute.For <IChannelHandlerContext>();
     _syncState          = new SyncState {
         IsSynchronized = true, IsRunning = true
     };
     _logger         = Substitute.For <ILogger>();
     _peerRepository = Substitute.For <IPeerRepository>();
 }
        public DeltaDfsHashObserver(IDeltaHashProvider deltaHashProvider,
                                    SyncState syncState,
                                    IPeerRepository peerRepository,
                                    ILogger logger)
            : base(logger)
        {
            Guard.Argument(peerRepository, nameof(peerRepository)).NotNull();

            _syncState         = syncState;
            _deltaHashProvider = deltaHashProvider;
            _peerRepository    = peerRepository;
        }
Exemple #28
0
        public void Init()
        {
            _logger      = Substitute.For <ILogger>();
            _fakeContext = Substitute.For <IChannelHandlerContext>();

            var fakeChannel = Substitute.For <IChannel>();

            _fakeContext.Channel.Returns(fakeChannel);

            _peerRepository = new PeerRepository(new InMemoryRepository <Peer, string>());
            _peerRepository.Add(GetPeerTestData());
        }
Exemple #29
0
        public BroadcastManagerTests()
        {
            _senderPeerId = PeerIdHelper.GetPeerId("sender");
            _keySigner    = Substitute.For <IKeySigner>();
            var fakeSignature = Substitute.For <ISignature>();

            _keySigner.Sign(Arg.Any <byte[]>(), default).ReturnsForAnyArgs(fakeSignature);
            _keySigner.CryptoContext.SignatureLength.Returns(64);
            _peers        = Substitute.For <IPeerRepository>();
            _cache        = new MemoryCache(new MemoryCacheOptions());
            _peerSettings = _senderPeerId.ToSubstitutedPeerSettings();
        }
Exemple #30
0
 public PeerHeartbeatChecker(ILogger logger,
                             IPeerRepository peerRepository,
                             IPeerChallengeRequest peerChallengeRequest,
                             int checkHeartbeatIntervalSeconds,
                             int maxNonResponsiveCounter)
 {
     _logger = logger;
     _nonResponsivePeerMap    = new ConcurrentDictionary <string, int>();
     _peerRepository          = peerRepository;
     _maxNonResponsiveCounter = maxNonResponsiveCounter;
     _peerChallengeRequest    = peerChallengeRequest;
     _checkHeartbeatInterval  = TimeSpan.FromSeconds(checkHeartbeatIntervalSeconds);
 }
Exemple #31
0
 public HastingsDiscovery(ILogger logger,
                          IPeerRepository peerRepository,
                          IDns dns,
                          IPeerSettings peerSettings,
                          IPeerClient peerClient,
                          IPeerMessageCorrelationManager peerMessageCorrelationManager,
                          ICancellationTokenProvider cancellationTokenProvider,
                          IEnumerable <IPeerClientObservable> peerClientObservables,
                          bool autoStart                                   = true,
                          int peerDiscoveryBurnIn                          = 10,
                          IHastingsOriginator stepProposal                 = default,
                          IHastingsCareTaker hastingsCareTaker             = default,
                          int millisecondsTimeout                          = 10_000,