public void Should_allocate_by_speed_post_merge()
    {
        ulong[]           totalDifficulties = { 1, 3, 2 };
        int[]             averageSpeed      = { 5, 8, 10 };
        PublicKey[]       publicKeys        = { TestItem.PublicKeyA, TestItem.PublicKeyB, TestItem.PublicKeyC };
        PeerInfo[]        peers             = new PeerInfo[3];
        INodeStatsManager _nodeStatsManager = Substitute.For <INodeStatsManager>();

        for (int i = 0; i < 3; i++)
        {
            ISyncPeer syncPeer = Substitute.For <ISyncPeer>();
            syncPeer.IsInitialized.Returns(true);
            Node node = new Node(publicKeys[i], "192.168.1.18", i);
            syncPeer.Node.Returns(node);
            syncPeer.TotalDifficulty.Returns(new UInt256(totalDifficulties[i]));
            peers[i] = new PeerInfo(syncPeer);
            peers[i].HeadNumber.Returns(1);
            INodeStats nodeStats = Substitute.For <INodeStats>();
            nodeStats.GetAverageTransferSpeed(Arg.Any <TransferSpeedType>()).Returns(averageSpeed[i]);
            _nodeStatsManager.GetOrAdd(peers[i].SyncPeer.Node).Returns(nodeStats);
        }
        IPoSSwitcher poSSwitcher = Substitute.For <IPoSSwitcher>();

        poSSwitcher.TerminalTotalDifficulty.Returns(new UInt256(1));
        poSSwitcher.HasEverReachedTerminalBlock().Returns(true);

        IBeaconPivot beaconPivot = Substitute.For <IBeaconPivot>();

        IPeerAllocationStrategy mergePeerAllocationStrategy =
            (new MergeBlocksSyncPeerAllocationStrategyFactory(poSSwitcher, beaconPivot, Substitute.For <ILogManager>())).Create(new BlocksRequest());
        IBlockTree _blockTree = Substitute.For <IBlockTree>();
        PeerInfo?  info       = mergePeerAllocationStrategy.Allocate(null, peers, _nodeStatsManager, _blockTree);

        Assert.AreEqual(info, peers[2]);    // peer with highest highest speed
    }
 public Persister ReadPersist(PeerInfo peer)
 {
     lock (_lockObject)
     {
         return(Peer.MyState.PersistedStates.FirstOrDefault(p => p.Key == peer.Id).Value);
     }
 }
        protected override async Task Dispatch(
            PeerInfo peerInfo,
            HeadersSyncBatch batch,
            CancellationToken cancellationToken)
        {
            ISyncPeer peer = peerInfo.SyncPeer;

            batch.ResponseSourcePeer = peerInfo;
            batch.MarkSent();

            try
            {
                batch.Response = await peer.GetBlockHeaders(batch.StartNumber, batch.RequestSize, 0, cancellationToken);
            }
            catch (TimeoutException)
            {
                if (Logger.IsDebug)
                {
                    Logger.Debug($"{batch} - request block header timeout {batch.RequestTime:F2}");
                }
                return;
            }
            if (batch.RequestTime > 1000)
            {
                if (Logger.IsDebug)
                {
                    Logger.Debug($"{batch} - peer is slow {batch.RequestTime:F2}");
                }
            }
        }
 public void Persist(PeerInfo peer)
 {
     lock (_lockObject)
     {
         Peer.MyState.PersistedStates[peer.Id] = peer.PersistedState;
     }
 }
        protected override async Task Dispatch(PeerInfo peerInfo, BodiesSyncBatch batch, CancellationToken cancellationToken)
        {
            ISyncPeer peer = peerInfo.SyncPeer;

            batch.ResponseSourcePeer = peerInfo;
            batch.MarkSent();
            var hashes = batch.Infos.Where(i => i != null).Select(i => i !.BlockHash).ToArray();
            Task <BlockBody[]> getBodiesTask = peer.GetBlockBodies(hashes, cancellationToken);
            await getBodiesTask.ContinueWith(
                (t, state) =>
            {
                BodiesSyncBatch batchLocal = (BodiesSyncBatch)state !;
                if (t.IsCompletedSuccessfully)
                {
                    if (batchLocal.RequestTime > 1000)
                    {
                        if (Logger.IsDebug)
                        {
                            Logger.Debug($"{batchLocal} - peer is slow {batchLocal.RequestTime:F2}");
                        }
                    }

                    batchLocal.Response = t.Result;
                }
            }, batch);
        }
Example #6
0
        public void onReceiveClosest(PeerInfo pInfo)
        {
            if (mCurrentTargetGUID != pInfo.getGUID && mPreviousGUID != pInfo.getGUID)
            {
                mPreviousGUID = pInfo.getGUID;

                IPEndPoint   remotePoint = new IPEndPoint(IPAddress.Parse(pInfo.getIP()), pInfo.getPORT());
                UDPResponder responder   = new UDPResponder(remotePoint, mOwner.getRoutingTable.MyInfo.getPORT());
                responder.sendRequestClosest(mOwner.getGUID, mCurrentTargetGUID);
            }
            else
            {
                if (mCurrentTargetGUID != pInfo.getGUID)
                {
                    //IPEndPoint remotePoint = new IPEndPoint(IPAddress.Parse(pInfo.getIP()), pInfo.getPORT());
                    //UDPResponder responder = new UDPResponder(remotePoint, mOwner.getRoutingTable.MyInfo.getPORT());
                    //responder.sendRequestJoin(mCurrentTargetGUID, mOwner.getRoutingTable.MyInfo);
                    mOwner.addPeerInfo(pInfo);
                }
                else
                {
                    //IPEndPoint remotePoint = new IPEndPoint(IPAddress.Parse(pInfo.getIP()), pInfo.getPORT());
                    //UDPResponder responder = new UDPResponder(remotePoint, mOwner.getRoutingTable.MyInfo.getPORT());
                    //responder.sendRequestJoin(mOwner.getRoutingTable.MyInfo.getGUID, mOwner.getRoutingTable.MyInfo);
                    mOwner.addPeerInfo(pInfo);
                }
            }
        }
Example #7
0
        /// <summary>
        /// Searches for Bluetooth peers
        /// </summary>
        /// <param name="options"></param>
        public async void discoverDevices(string options)
        {
            try
            {
                PeerFinder.Start();
                discoveredPeers = await PeerFinder.FindAllPeersAsync();

                PeerInfo[] peerInfo = new PeerInfo[discoveredPeers.Count];

                for (int i = 0; i < discoveredPeers.Count; i++)
                {
                    var peer = discoveredPeers[i];

                    //TODO It seems PeerInformation.HostName property sometimes returns null. Check what is the cause.
                    string hostName = peer.HostName == null ? "Unknown host" : peer.HostName.DisplayName;
                    peerInfo[i] = new PeerInfo(peer.DisplayName, hostName);
                }

                this.DispatchCommandResult(discoveredPeers.Count > 0
                                               ? new PluginResult(PluginResult.Status.OK, JsonHelper.Serialize(peerInfo))
                                               : new PluginResult(PluginResult.Status.ERROR, "No devices were found"));
            }
            catch (Exception)
            {
                this.DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error occurred while discovering devices"));
            }
        }
        public void Can_write_report_update_with_allocations()
        {
            ISyncPeer        syncPeer     = Substitute.For <ISyncPeer>();
            IEthSyncPeerPool syncPeerPool = Substitute.For <IEthSyncPeerPool>();
            PeerInfo         peer1        = new PeerInfo(syncPeer);

            peer1.IsInitialized = false;

            PeerInfo peer2 = new PeerInfo(syncPeer);

            peer2.IsInitialized = true;

            PeerInfo[] peers = new PeerInfo[] { peer1, peer2 };
            syncPeerPool.PeerCount.Returns(peers.Length);

            syncPeerPool.AllPeers.Returns(peers);
            syncPeerPool.Allocations.Returns(peers.Select(p => new SyncPeerAllocation(p, "desc")));

            SyncPeersReport report = new SyncPeersReport(syncPeerPool, Substitute.For <INodeStatsManager>(), NoErrorLimboLogs.Instance);

            report.Write();

            peer1.IsInitialized = true;
            report.Write();
        }
        protected override async Task Dispatch(PeerInfo peerInfo, WitnessBlockSyncBatch request, CancellationToken cancellationToken)
        {
            ISyncPeer peer = peerInfo.SyncPeer;

            if (peer.TryGetSatelliteProtocol <IWitnessPeer>("wit", out var witnessProtocolHandler) && witnessProtocolHandler != null)
            {
                var getNodeDataTask = witnessProtocolHandler.GetBlockWitnessHashes(request.BlockHash, cancellationToken);
                await getNodeDataTask.ContinueWith(
                    (t, state) =>
                {
                    if (t.IsFaulted)
                    {
                        if (Logger.IsTrace)
                        {
                            Logger.Error("DEBUG/ERROR Error after dispatching the state sync request", t.Exception);
                        }
                    }

                    WitnessBlockSyncBatch batchLocal = (WitnessBlockSyncBatch)state !;
                    if (t.IsCompletedSuccessfully)
                    {
                        batchLocal.Response = t.Result;
                    }
                }, request, cancellationToken);
            }
            else
            {
                if (Logger.IsError)
                {
                    Logger.Error($"Couldn't get witness protocol from {peer.Node}.");
                }
            }
        }
Example #10
0
        public async Task Can_sync_with_peer_when_it_times_out_on_full_batch()
        {
            BlockDownloader blockDownloader = new BlockDownloader(_blockTree, TestBlockValidator.AlwaysValid, TestSealValidator.AlwaysValid, NullSyncReport.Instance, new InMemoryReceiptStorage(), RopstenSpecProvider.Instance, LimboLogs.Instance);

            ISyncPeer syncPeer = Substitute.For <ISyncPeer>();

            syncPeer.GetBlockHeaders(Arg.Any <long>(), Arg.Any <int>(), Arg.Any <int>(), Arg.Any <CancellationToken>())
            .Returns(async ci => await _responseBuilder.BuildHeaderResponse(ci.ArgAt <long>(0), ci.ArgAt <int>(1), Response.AllCorrect | Response.TimeoutOnFullBatch));

            syncPeer.GetBlocks(Arg.Any <IList <Keccak> >(), Arg.Any <CancellationToken>())
            .Returns(ci => _responseBuilder.BuildBlocksResponse(ci.ArgAt <IList <Keccak> >(0), Response.AllCorrect | Response.TimeoutOnFullBatch));

            PeerInfo peerInfo = new PeerInfo(syncPeer);

            peerInfo.TotalDifficulty = UInt256.MaxValue;
            peerInfo.HeadNumber      = SyncBatchSize.Max * 2 + 32;

            await blockDownloader.DownloadHeaders(peerInfo, SyncModeSelector.FullSyncThreshold, CancellationToken.None).ContinueWith(t => { });

            await blockDownloader.DownloadHeaders(peerInfo, SyncModeSelector.FullSyncThreshold, CancellationToken.None);

            Assert.AreEqual(Math.Max(0, peerInfo.HeadNumber - SyncModeSelector.FullSyncThreshold), _blockTree.BestSuggestedHeader.Number);

            peerInfo.HeadNumber *= 2;
            await blockDownloader.DownloadBlocks(peerInfo, 0, CancellationToken.None).ContinueWith(t => { });

            await blockDownloader.DownloadBlocks(peerInfo, 0, CancellationToken.None);

            Assert.AreEqual(Math.Max(0, peerInfo.HeadNumber), _blockTree.BestSuggestedHeader.Number);
        }
Example #11
0
        public void Can_keep_changing_in_fast_sync()
        {
            IEthSyncPeerPool syncPeerPool = Substitute.For <IEthSyncPeerPool>();
            ISyncPeer        syncPeer     = Substitute.For <ISyncPeer>();

            syncPeer.TotalDifficultyOnSessionStart.Returns((UInt256)(1024 * 1024));

            PeerInfo peerInfo1 = new PeerInfo(syncPeer)
            {
                HeadNumber = 0, IsInitialized = true
            };

            syncPeerPool.AllPeers.Returns(new[] { peerInfo1 });
            syncPeerPool.UsefulPeers.Returns(new[] { peerInfo1 });
            syncPeerPool.PeerCount.Returns(1);

            SyncConfig syncConfig = new SyncConfig();

            syncConfig.FastSync = true;
            ISyncProgressResolver syncProgressResolver = Substitute.For <ISyncProgressResolver>();

            SyncModeSelector selector = new SyncModeSelector(syncProgressResolver, syncPeerPool, syncConfig, LimboLogs.Instance);

            Assert.AreEqual(SyncMode.Headers, selector.Current);

            (long BestRemote, long BestLocalHeader, long BestLocalFullBlock, long BestLocalState, SyncMode ExpectedState, string Description)[] states =
Example #12
0
        private static IPeer CreatePeer(string ip = NetworkTestConstants.FakeIpEndpoint)
        {
            var peerMock = new Mock <IPeer>();

            var keyPair = CryptoHelper.GenerateKeyPair();
            var pubkey  = keyPair.PublicKey.ToHex();

            var peerInfo = new PeerInfo
            {
                Pubkey          = pubkey,
                ProtocolVersion = KernelConstants.ProtocolVersion,
                ConnectionTime  = TimestampHelper.GetUtcNow().Seconds,
                IsInbound       = true
            };

            if (!IpEndpointHelper.TryParse(ip, out var endpoint))
            {
                throw new Exception($"Endpoint {ip} could not be parsed.");
            }

            peerMock.Setup(p => p.RemoteEndpoint).Returns(endpoint);
            peerMock.Setup(p => p.Info).Returns(peerInfo);

            return(peerMock.Object);
        }
Example #13
0
        public async Task Throws_on_incorrect_receipts_root()
        {
            InMemoryReceiptStorage inMemoryReceiptStorage = new InMemoryReceiptStorage();
            BlockDownloader        blockDownloader        = new BlockDownloader(_blockTree, TestBlockValidator.AlwaysValid, TestSealValidator.AlwaysValid, NullSyncReport.Instance, inMemoryReceiptStorage, RopstenSpecProvider.Instance, LimboLogs.Instance);

            ISyncPeer            syncPeer             = Substitute.For <ISyncPeer>();
            Task <BlockHeader[]> buildHeadersResponse = null;

            syncPeer.GetBlockHeaders(Arg.Any <long>(), Arg.Any <int>(), Arg.Any <int>(), Arg.Any <CancellationToken>())
            .Returns(ci => buildHeadersResponse = _responseBuilder.BuildHeaderResponse(ci.ArgAt <long>(0), ci.ArgAt <int>(1), Response.AllCorrect));

            Task <BlockBody[]> buildBlocksResponse = null;

            syncPeer.GetBlocks(Arg.Any <IList <Keccak> >(), Arg.Any <CancellationToken>())
            .Returns(ci => buildBlocksResponse = _responseBuilder.BuildBlocksResponse(ci.ArgAt <IList <Keccak> >(0), Response.AllCorrect | Response.WithTransactions));

            syncPeer.GetReceipts(Arg.Any <IList <Keccak> >(), Arg.Any <CancellationToken>())
            .Returns(ci => _responseBuilder.BuildReceiptsResponse(buildHeadersResponse.Result, buildBlocksResponse.Result, Response.IncorrectReceiptRoot).Result);

            PeerInfo peerInfo = new PeerInfo(syncPeer)
            {
                TotalDifficulty = UInt256.MaxValue, HeadNumber = 1
            };
            await blockDownloader.DownloadHeaders(peerInfo, SyncModeSelector.FullSyncThreshold, CancellationToken.None);

            peerInfo.HeadNumber *= 2;

            Func <Task> action = async() => await blockDownloader.DownloadBlocks(peerInfo, 0, CancellationToken.None, BlockDownloader.DownloadOptions.DownloadWithReceipts);

            action.Should().Throw <EthSynchronizationException>();
        }
        protected override async Task Dispatch(
            PeerInfo peerInfo,
            HeadersSyncBatch batch,
            CancellationToken cancellationToken)
        {
            ISyncPeer peer = peerInfo.SyncPeer;

            batch.ResponseSourcePeer = peerInfo;
            batch.MarkSent();
            Task <BlockHeader[]> getHeadersTask
                = peer.GetBlockHeaders(batch.StartNumber, batch.RequestSize, 0, cancellationToken);

            await getHeadersTask.ContinueWith(
                (t, state) =>
            {
                HeadersSyncBatch batchLocal = (HeadersSyncBatch)state !;
                if (t.IsCompletedSuccessfully)
                {
                    if (batchLocal.RequestTime > 1000)
                    {
                        if (Logger.IsDebug)
                        {
                            Logger.Debug($"{batchLocal} - peer is slow {batchLocal.RequestTime:F2}");
                        }
                    }

                    batchLocal.Response = t.Result;
                }
            }, batch);
        }
Example #15
0
        public void Cannot_allocate_subcontext_of_sleeping()
        {
            PeerInfo peerInfo = new PeerInfo(Substitute.For <ISyncPeer>());

            peerInfo.PutToSleep(AllocationContexts.Blocks, DateTime.MinValue);
            peerInfo.CanBeAllocated(AllocationContexts.Bodies).Should().BeFalse();
        }
Example #16
0
        private void addNew(string newIP)
        {
            int port = NetworkManager.DEFAULT_PORT;

            string[] serverPort = newIP.Split(':');
            if (serverPort.Length > 1)
            {
                ushort newPort = 0;
                if (ushort.TryParse(serverPort[1], out newPort))
                {
                    port = newPort;
                }
            }

            PeerInfo newInfo = new PeerInfo(serverPort[0], port);

            //bool alreadyExists = false;
            //foreach (ContactInfo info in DiagManager.Instance.CurSettings.ContactList)
            //{
            //    if (info.UUID == newID)
            //    {
            //        alreadyExists = true;
            //        break;
            //    }
            //}

            DiagManager.Instance.CurSettings.PeerList.Add(newInfo);
            DiagManager.Instance.SaveSettings(DiagManager.Instance.CurSettings);
            MenuManager.Instance.ReplaceMenu(new PeersMenu(action));
        }
Example #17
0
        public async Task Can_cancel_adding_headers()
        {
            BlockDownloader blockDownloader = new BlockDownloader(_blockTree, new SlowHeaderValidator(), TestSealValidator.AlwaysValid, NullSyncReport.Instance, new InMemoryReceiptStorage(), RopstenSpecProvider.Instance, LimboLogs.Instance);

            ISyncPeer syncPeer = Substitute.For <ISyncPeer>();

            syncPeer.GetBlockHeaders(Arg.Any <long>(), Arg.Any <int>(), Arg.Any <int>(), Arg.Any <CancellationToken>())
            .Returns(ci => _responseBuilder.BuildHeaderResponse(ci.ArgAt <long>(0), ci.ArgAt <int>(1), Response.AllCorrect));

            syncPeer.GetBlocks(Arg.Any <IList <Keccak> >(), Arg.Any <CancellationToken>())
            .Returns(ci => _responseBuilder.BuildBlocksResponse(ci.ArgAt <IList <Keccak> >(0), Response.AllCorrect));

            PeerInfo peerInfo = new PeerInfo(syncPeer);

            peerInfo.TotalDifficulty = UInt256.MaxValue;
            peerInfo.HeadNumber      = 1000;

            CancellationTokenSource cancellation = new CancellationTokenSource();

            cancellation.CancelAfter(1000);
            Task task = blockDownloader.DownloadHeaders(peerInfo, SyncModeSelector.FullSyncThreshold, cancellation.Token);
            await task.ContinueWith(t => Assert.True(t.IsCanceled, "headers"));

            peerInfo.HeadNumber *= 2;
            cancellation         = new CancellationTokenSource();
            cancellation.CancelAfter(1000);
            task = blockDownloader.DownloadHeaders(peerInfo, SyncModeSelector.FullSyncThreshold, cancellation.Token);
            await task.ContinueWith(t => Assert.True(t.IsCanceled, "blocks"));
        }
Example #18
0
        protected override async Task Dispatch(
            PeerInfo bestPeer,
            BlocksRequest?blocksRequest,
            CancellationToken cancellation)
        {
            if (blocksRequest == null)
            {
                if (Logger.IsWarn)
                {
                    Logger.Warn($"NULL received for dispatch in {nameof(BlockDownloader)}");
                }
                return;
            }

            if (!_blockTree.CanAcceptNewBlocks)
            {
                return;
            }
            CancellationTokenSource linkedCancellation =
                CancellationTokenSource.CreateLinkedTokenSource(
                    cancellation,
                    _allocationWithCancellation.Cancellation.Token);

            try
            {
                SyncEvent?.Invoke(this, new SyncEventArgs(bestPeer.SyncPeer, Synchronization.SyncEvent.Started));
                if ((blocksRequest.Options & DownloaderOptions.WithBodies) == DownloaderOptions.WithBodies)
                {
                    if (Logger.IsDebug)
                    {
                        Logger.Debug("Downloading bodies");
                    }
                    await DownloadBlocks(bestPeer, blocksRequest, linkedCancellation.Token).ContinueWith(t => HandleSyncRequestResult(t, bestPeer));

                    if (Logger.IsDebug)
                    {
                        Logger.Debug("Finished downloading bodies");
                    }
                }
                else
                {
                    if (Logger.IsDebug)
                    {
                        Logger.Debug("Downloading headers");
                    }
                    await DownloadHeaders(bestPeer, blocksRequest, linkedCancellation.Token).ContinueWith(t => HandleSyncRequestResult(t, bestPeer));

                    if (Logger.IsDebug)
                    {
                        Logger.Debug("Finished downloading headers");
                    }
                }
            }
            finally
            {
                _allocationWithCancellation.Dispose();
                linkedCancellation.Dispose();
            }
        }
Example #19
0
        private void btnBootstrap_Click(object sender, EventArgs e)
        {
            PeerInfo peer1 = new PeerInfo();

            peer1.Id       = PeerId.CalculateId("peer1");
            peer1.EndPoint = new IPEndPoint(GetHostAddresses(txtBootstrapIP.Text), Convert.ToInt32(txtPort.Text));
            client.BootstrapPeers.Add(peer1);
        }
Example #20
0
 public void SyncWithPeer(PeerInfo peerIp, int timeout)
 {
     _syncer             = new Syncer(Id);
     _remoteEndpoint     = _syncer.SyncWithPeer(peerIp, timeout, _udpClient);
     _peer               = peerIp;
     IsTunnelEstablished = true;
     StartPinger();
 }
Example #21
0
 void OnDeletedPeer(PeerInfo peer)
 {
     if (peers.Contains(peer))
     {
         peers.Remove(peer);
     }
     this.Invoke(new dgvUpdate(ReBindDataSource));
 }
Example #22
0
 public void WaitForSyncFromPeer(PeerInfo peerIp, int timeout)
 {
     _syncer             = new Syncer(Id);
     _remoteEndpoint     = _syncer.WaitForSyncFromPeer(peerIp, timeout, _udpClient);
     _peer               = peerIp;
     IsTunnelEstablished = true;
     StartCheckerForPings();
 }
Example #23
0
 public PeerFileSlice(string fileName, PeerInfo owner, int startIndex, int endIndex, byte[] fileSlice)
 {
     Name            = fileName;
     Owner           = owner;
     this.StartIndex = startIndex;
     this.EndIndex   = endIndex;
     Slice           = fileSlice;
 }
Example #24
0
 public void ConnectToPeer(PeerInfo peerInfo)
 {
     // Called by ReconnectToPeer and Setup in PhotonApplication
     if (Server.ConnectToServerTcp(peerInfo.MasterEndPoint, "Master", peerInfo) == false)
     {
         Log.Warn("Connection refused");
     }
 }
Example #25
0
 public void ReconnectToPeer(PeerInfo peerInfo)
 {
     peerInfo.NumTries++;
     if (peerInfo.NumTries < peerInfo.MaxTries)
     {
         var timer = new Timer(o => ConnectToPeer(peerInfo), null, peerInfo.ConnectRetryIntervalSeconds * 1000, 0);
     }
 }
Example #26
0
 public OutboundPhotonPeer(PhotonApplication application
                           , PeerInfo peerInfo)
     : base(application)
 {
     _application = application;
     _peerInfo    = peerInfo;
     SetPrivateCustomTypeCache(new TypeCache().GetCache());
 }
        private static PeerInfo BuildPeer(bool initialized)
        {
            ISyncPeer syncPeer = Substitute.For <ISyncPeer>();
            PeerInfo  peer     = new PeerInfo(syncPeer);

            syncPeer.IsInitialized.Returns(initialized);
            return(peer);
        }
Example #28
0
        public PeerInfo Allocate(PeerInfo currentPeer, IEnumerable <PeerInfo> peers, INodeStatsManager nodeStatsManager, IBlockTree blockTree)
        {
            IPeerAllocationStrategy strategy = _priority ? _fastest : _slowest;

            peers = _minNumber == null ? peers : peers.Where(p => p.HeadNumber > _minNumber);
            PeerInfo allocated = strategy.Allocate(currentPeer, peers, nodeStatsManager, blockTree);

            return(allocated);
        }
        /// <summary>
        /// Do connect to the peer.
        /// </summary>
        /// <param name="peerInfo">MGF.Implementation.PeerInfo.</param>
        public void ConnectToPeer(PeerInfo peerInfo)
        {
            var outbound = new OutboundPhotonPeer(Server, peerInfo);

            if (outbound.ConnectTcp(peerInfo.MasterEndPoint, peerInfo.ApplicationName, TypeCache.SerializePeerInfo(peerInfo)) == false)
            {
                Log.Warn("Connection refused");
            }
        }
Example #30
0
        public void Can_allocate()
        {
            PeerInfo peerInfo = new PeerInfo(Substitute.For <ISyncPeer>());

            peerInfo.IsAllocated(_contexts).Should().BeFalse();
            peerInfo.TryAllocate(_contexts);
            peerInfo.IsAllocated(_contexts).Should().BeTrue();
            peerInfo.CanBeAllocated(_contexts).Should().BeFalse();
        }
Example #31
0
 public static IPeer CreateFromPeerInfo(PeerInfo info)
 {
     using (info)
     {
         return new Peer
         {
             EndPoint = info.EndPoint.ToString()
         };
     }
 }
        private void _listener_ReceivedPeerInfo(IPEndPoint peerEP, byte[] challenge, BinaryID recvHMAC, bool isReply)
        {
            if (PeerDiscovered != null)
            {
                BinaryID foundNetworkID = null;

                lock (_trackedNetworkIDs)
                {
                    foreach (BinaryID networkID in _trackedNetworkIDs)
                    {
                        using (HMACSHA256 hmacSHA256 = new HMACSHA256(networkID.ID))
                        {
                            BinaryID computedHmac = new BinaryID(hmacSHA256.ComputeHash(challenge));

                            if (computedHmac.Equals(recvHMAC))
                            {
                                foundNetworkID = networkID;
                                break;
                            }
                        }
                    }
                }

                if (foundNetworkID != null)
                {
                    PeerInfo peerInfo = new PeerInfo(peerEP, foundNetworkID);

                    bool peerInCache;

                    if (_peerInfoCache.Contains(peerInfo))
                    {
                        PeerInfo existingPeerInfo = _peerInfoCache[_peerInfoCache.IndexOf(peerInfo)];

                        if (existingPeerInfo.IsExpired())
                        {
                            peerInCache = false;
                            _peerInfoCache.Remove(existingPeerInfo);
                        }
                        else
                        {
                            peerInCache = true;
                        }
                    }
                    else
                    {
                        peerInCache = false;
                    }

                    if (!peerInCache)
                    {
                        _peerInfoCache.Add(peerInfo);

                        PeerDiscovered(this, peerEP, foundNetworkID);
                    }

                    if (!isReply)
                        ThreadPool.QueueUserWorkItem(AnnounceAsync, new object[] { foundNetworkID, new IPAddress[] { peerEP.Address }, 1, true });
                }
            }
        }
Example #33
0
 static DataGridViewRow GetPeerListRow(PeerInfo peer)
 {
     DataGridViewRow row = new DataGridViewRow();
     DataGridViewTextBoxCell cellHost = new DataGridViewTextBoxCell();
     DataGridViewTextBoxCell cellPort = new DataGridViewTextBoxCell();
     DataGridViewTextBoxCell cellShare = new DataGridViewTextBoxCell();
     cellHost.Value = peer.Host;
     cellPort.Value = peer.Port;
     cellShare.Value = peer.Share;
     row.Cells.Add(cellHost);
     row.Cells.Add(cellPort);
     row.Cells.Add(cellShare);
     row.Tag = peer;
     return row;
 }
Example #34
0
        /// <summary>
        /// Searches for Bluetooth peers
        /// </summary>
        /// <param name="options"></param>
        public async void discoverDevices(string options)
        {
            try
            {                
                discoveredPeers = await PeerFinder.FindAllPeersAsync();
                PeerInfo[] peerInfo = new PeerInfo[discoveredPeers.Count];

                for (int i = 0; i < discoveredPeers.Count; i++)
                {
                    var peer = discoveredPeers[i];
                    
                    //TODO It seems PeerInformation.HostName property sometimes returns null. Check what is the cause.
                    string hostName = peer.HostName == null ? "Unknown host" : peer.HostName.DisplayName;
                    peerInfo[i] = new PeerInfo(peer.DisplayName, hostName);                   
                }

                this.DispatchCommandResult(discoveredPeers.Count > 0
                                               ? new PluginResult(PluginResult.Status.OK, JsonHelper.Serialize(peerInfo))
                                               : new PluginResult(PluginResult.Status.ERROR, "No devices were found"));
            }
            catch (Exception)
            {
                this.DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error occurred while discovering devices"));
            }            
        }
            public bool Equals(PeerInfo obj)
            {
                if (ReferenceEquals(null, obj))
                    return false;

                if (ReferenceEquals(this, obj))
                    return true;

                if (!_peerEP.Equals(obj._peerEP))
                    return false;

                if (!_networkID.Equals(obj._networkID))
                    return false;

                return true;
            }