public void Handle(RegisterPeerCommand message)
        {
            if (_blacklistedMachines.Contains(Context !.Originator.SenderMachineName !))
            {
                throw new InvalidOperationException($"Peer {Context.SenderId} on host {Context.Originator.SenderMachineName} is not allowed to register on this directory");
            }

            var peerTimestampUtc = message.Peer.TimestampUtc;

            if (!peerTimestampUtc.HasValue)
            {
                throw new InvalidOperationException("The TimestampUtc must be provided when registering");
            }

            var utcNow = SystemDateTime.UtcNow;

            if (_configuration.MaxAllowedClockDifferenceWhenRegistering != null && peerTimestampUtc.Value > utcNow + _configuration.MaxAllowedClockDifferenceWhenRegistering)
            {
                throw new InvalidOperationException($"The client provided timestamp [{peerTimestampUtc}] is too far ahead of the the server's current time [{utcNow}]");
            }

            var stopwatch      = Stopwatch.StartNew();
            var peerDescriptor = message.Peer;

            peerDescriptor.Peer.IsUp         = true;
            peerDescriptor.Peer.IsResponding = true;

            var existingPeer = _peerRepository.Get(peerDescriptor.PeerId);

            if (IsPeerInConflict(existingPeer, peerDescriptor))
            {
                throw new DomainException(DirectoryErrorCodes.PeerAlreadyExists, string.Format("Peer {0} already exists (running on {1})", peerDescriptor.PeerId, existingPeer.Peer.EndPoint));
            }

            _peerRepository.RemoveAllDynamicSubscriptionsForPeer(peerDescriptor.PeerId, DateTime.SpecifyKind(peerDescriptor.TimestampUtc !.Value, DateTimeKind.Utc));
            _peerRepository.AddOrUpdatePeer(peerDescriptor);
            _bus.Publish(new PeerStarted(peerDescriptor));

            var registredPeerDescriptors = _peerRepository.GetPeers(loadDynamicSubscriptions: true);

            _bus.Reply(new RegisterPeerResponse(registredPeerDescriptors.ToArray()));
            _speedReporter.ReportRegistrationDuration(stopwatch.Elapsed);
        }
        public IActionResult Get(int id)
        {
            Peer peer = _dataRepository.Get(id);

            if (peer == null)
            {
                return(NotFound("The Peer record couldn't be found."));
            }
            return(Ok(peer));
        }
Exemple #3
0
        private void DeltaHeightOnNext(ProtocolMessage protocolMessage)
        {
            var peerId          = protocolMessage.PeerId;
            var latestDeltaHash = protocolMessage.FromProtocolMessage <LatestDeltaHashResponse>();

            var peer = _peerRepository.Get(peerId);

            if (peer != null)
            {
                peer.Touch();
                _peerRepository.Update(peer);
            }

            DeltaHeightRanker.Add(peerId, latestDeltaHash);
        }
        public static bool SetPeerRespondingState(this IPeerRepository repository, PeerId peerId, bool isResponding, DateTime timestampUtc)
        {
            var peer = repository.Get(peerId);

            if (peer == null || peer.TimestampUtc > timestampUtc)
            {
                return(false);
            }

            peer.Peer.IsResponding = isResponding;
            peer.TimestampUtc      = timestampUtc;
            repository.AddOrUpdatePeer(peer);

            return(true);
        }
Exemple #5
0
        private void PopulatePeers(int count)
        {
            var peerList = new List <Peer>();

            for (var i = 10; i < count + 10; i++)
            {
                var peer = new Peer
                {
                    PeerId = PeerIdHelper.GetPeerId(i.ToString())
                };
                peerList.Add(peer);
                _peers.Get(peer.DocumentId).Returns(peer);
            }

            _peers.AsQueryable().Returns(peerList.AsQueryable());
        }
        public static PeerDescriptor UpdatePeerSubscriptions(this IPeerRepository repository, PeerId peerId, Subscription[] subscriptions, DateTime?timestampUtc)
        {
            var peerDescriptor = repository.Get(peerId);

            if (peerDescriptor == null)
            {
                throw new InvalidOperationException(string.Format("The specified Peer ({0}) does not exist.", peerId));
            }

            if (peerDescriptor.TimestampUtc > timestampUtc)
            {
                return(null);
            }

            peerDescriptor.TimestampUtc  = timestampUtc;
            peerDescriptor.Subscriptions = subscriptions;
            repository.AddOrUpdatePeer(peerDescriptor);

            return(peerDescriptor);
        }
Exemple #7
0
        /// <summary>
        ///     Basic method to handle ping messages.
        /// </summary>
        /// <param name="pingRequest"></param>
        /// <param name="channelHandlerContext"></param>
        /// <param name="senderPeerId"></param>
        /// <param name="correlationId"></param>
        /// <returns><see cref="PingResponse"/></returns>
        protected override PingResponse HandleRequest(PingRequest pingRequest,
                                                      IChannelHandlerContext channelHandlerContext,
                                                      PeerId senderPeerId,
                                                      ICorrelationId correlationId)
        {
            Guard.Argument(pingRequest, nameof(pingRequest)).NotNull();
            Guard.Argument(channelHandlerContext, nameof(channelHandlerContext)).NotNull();
            Guard.Argument(senderPeerId, nameof(senderPeerId)).NotNull();

            Logger.Debug("message content is {0} IP: {1} PeerId: {2}", pingRequest, senderPeerId.Ip, senderPeerId);

            var peer = _peerRepository.Get(senderPeerId);

            if (peer == null)
            {
                _peerRepository.Add(new Peer
                {
                    PeerId   = senderPeerId,
                    LastSeen = DateTime.UtcNow
                });
            }

            return(new PingResponse());
        }
        public PoaTestNode(string name,
                           IPrivateKey privateKey,
                           IPeerSettings nodeSettings,
                           IEnumerable <PeerId> knownPeerIds,
                           IFileSystem parentTestFileSystem,
                           ITestOutputHelper output)
        {
            Name          = name;
            _nodeSettings = nodeSettings;

            _nodeDirectory = parentTestFileSystem.GetCatalystDataDir().SubDirectoryInfo(Name);
            var nodeFileSystem = Substitute.ForPartsOf <FileSystem>();

            nodeFileSystem.GetCatalystDataDir().Returns(_nodeDirectory);

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

            var baseDfsFolder = Path.Combine(parentTestFileSystem.GetCatalystDataDir().FullName, "dfs");
            var hashProvider  = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("blake2b-256"));

            _dfs = new DevDfs(parentTestFileSystem, hashProvider, baseDfsFolder);

            _memPool        = new Mempool(new TestMempoolRepository(new InMemoryRepository <TransactionBroadcastDao, string>()));
            _peerRepository = Substitute.For <IPeerRepository>();
            var peersInRepo = knownPeerIds.Select(p => new Peer
            {
                PeerId = p
            }).ToList();

            _peerRepository.AsQueryable().Returns(peersInRepo.AsQueryable());
            _peerRepository.GetAll().Returns(peersInRepo);
            _peerRepository.Get(Arg.Any <string>()).Returns(ci =>
            {
                return(peersInRepo.First(p => p.DocumentId.Equals((string)ci[0])));
            });

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

            Program.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.AddItemToRegistry(KeyRegistryTypes.DefaultKey, privateKey);

            keyStore.KeyStoreEncryptAsync(privateKey, nodeSettings.NetworkType, KeyRegistryTypes.DefaultKey).ConfigureAwait(false).GetAwaiter()
            .GetResult();
        }
 public Peer?GetPeer(PeerId peerId)
 {
     return(_peerRepository.Get(peerId)?.Peer);
 }
Exemple #10
0
 public PeerDescriptor GetPeerDescriptor(PeerId peerId)
 {
     return(_peerRepository.Get(peerId));
 }