Beispiel #1
0
 private void UpdateState(List <DeltaIndexDao> deltaIndexes) => deltaIndexes.ForEach(x =>
 {
     if (_deltaHashProvider.TryUpdateLatestHash(_previousHash, x.Cid))
     {
         _previousHash = x.Cid;
     }
 });
        public override void HandleBroadcast(IObserverDto <ProtocolMessage> messageDto)
        {
            try
            {
                var deserialised = messageDto.Payload.FromProtocolMessage <DeltaDfsHashBroadcast>();

                var previousHash = _hashProvider.Cast(deserialised.PreviousDeltaDfsHash.ToByteArray());
                if (previousHash == null)
                {
                    Logger.Error($"PreviousDeltaDfsHash is not a valid hash");
                    return;
                }

                var newHash = _hashProvider.Cast(deserialised.DeltaDfsHash.ToByteArray());
                if (newHash == null)
                {
                    Logger.Error($"DeltaDfsHash is not a valid hash");
                    return;
                }

                _deltaHashProvider.TryUpdateLatestHash(previousHash, newHash);
            }
            catch (Exception exception)
            {
                Logger.Error(exception, "Failed to update latest delta hash from incoming broadcast message.");
            }
        }
        public void StartProducing()
        {
            _constructionProducingSubscription = _cycleEventsProvider.PhaseChanges
                                                 .Where(p => p.Name == PhaseName.Construction && p.Status == PhaseStatus.Producing)
                                                 .Select(p => _deltaBuilder.BuildCandidateDelta(p.PreviousDeltaDfsHash))
                                                 .Subscribe(c =>
            {
                _deltaVoter.OnNext(c);
                _deltaHub.BroadcastCandidate(c);
            });

            _campaigningProductionSubscription = _cycleEventsProvider.PhaseChanges
                                                 .Where(p => p.Name == PhaseName.Campaigning && p.Status == PhaseStatus.Producing)
                                                 .Select(p =>
            {
                _deltaVoter.TryGetFavouriteDelta(p.PreviousDeltaDfsHash, out var favourite);
                return(favourite);
            })
                                                 .Where(f => f != null)
                                                 .Subscribe(f =>
            {
                _deltaHub.BroadcastFavouriteCandidateDelta(f);
                _deltaElector.OnNext(f);
            });

            _votingProductionSubscription = _cycleEventsProvider.PhaseChanges
                                            .Where(p => p.Name == PhaseName.Voting && p.Status == PhaseStatus.Producing)
                                            .Select(p => _deltaElector.GetMostPopularCandidateDelta(p.PreviousDeltaDfsHash))
                                            .Where(c => c != null)
                                            .Select(c =>
            {
                _deltaCache.TryGetLocalDelta(c, out var delta);
                return(delta);
            })
                                            .Where(d => d != null)
                                            .Subscribe(d =>
            {
                _logger.Information("New Delta following {deltaHash} published",
                                    d.PreviousDeltaDfsHash);

                var newCid = _deltaHub.PublishDeltaToDfsAndBroadcastAddressAsync(d)
                             .ConfigureAwait(false).GetAwaiter().GetResult();
                var previousHash = _hashProvider.Cast(d.PreviousDeltaDfsHash.ToByteArray());

                _deltaHashProvider.TryUpdateLatestHash(previousHash, newCid.Hash);
            });
        }
        public override void HandleBroadcast(IObserverDto <ProtocolMessage> messageDto)
        {
            if (!_syncState.IsSynchronized)
            {
                return;
            }

            try
            {
                var deserialised = messageDto.Payload.FromProtocolMessage <DeltaDfsHashBroadcast>();

                var previousHash = deserialised.PreviousDeltaDfsHash.ToByteArray().ToCid();
                if (previousHash == null)
                {
                    Logger.Error("PreviousDeltaDfsHash is not a valid hash");
                    return;
                }

                var newHash = deserialised.DeltaDfsHash.ToByteArray().ToCid();
                if (newHash == null)
                {
                    Logger.Error("DeltaDfsHash is not a valid hash");
                    return;
                }

                var messagePoaNode = _peerRepository.GetPeersByIpAndPublicKey(messageDto.Payload.PeerId.Ip, messageDto.Payload.PeerId.PublicKey).FirstOrDefault();
                if (messagePoaNode == null)
                {
                    Logger.Error($"Message from IP address '{messageDto.Payload.PeerId.Ip}' with public key '{messageDto.Payload.PeerId.PublicKey}' is not found in producer node list.");
                    return;
                }

                _deltaHashProvider.TryUpdateLatestHash(previousHash, newHash);
            }
            catch (Exception exception)
            {
                Logger.Error(exception, "Failed to update latest delta hash from incoming broadcast message.");
            }
        }
Beispiel #5
0
        public void StartProducing()
        {
            Task.Delay(_cycleEventsProvider.GetTimeSpanUntilNextCycleStart()).Wait();

            _constructionProducingSubscription = _cycleEventsProvider.PhaseChanges
               .Where(p => p.Name.Equals(PhaseName.Construction) && p.Status.Equals(PhaseStatus.Producing))
               .Select(p => _deltaBuilder.BuildCandidateDelta(p.PreviousDeltaDfsHash))
               .Where(c => c != null)
               .Subscribe(c =>
                {
                    _deltaVoter.OnNext(c);
                    _deltaHub.BroadcastCandidate(c);
                });

            _campaigningProductionSubscription = _cycleEventsProvider.PhaseChanges
               .Where(p => p.Name.Equals(PhaseName.Campaigning) && p.Status.Equals(PhaseStatus.Producing))
               .Select(p =>
                {
                    _deltaVoter.TryGetFavouriteDelta(p.PreviousDeltaDfsHash, out var favourite);
                    return favourite;
                })
               .Where(f => f != null)
               .Subscribe(f =>
                {
                    _deltaHub.BroadcastFavouriteCandidateDelta(f);
                    _deltaElector.OnNext(f);
                });

            _votingProductionSubscription = _cycleEventsProvider.PhaseChanges
               .Where(p => p.Name.Equals(PhaseName.Voting) && p.Status.Equals(PhaseStatus.Producing))
               .Select(p => _deltaElector.GetMostPopularCandidateDelta(p.PreviousDeltaDfsHash))
               .Where(c => c != null)
               .Select(c =>
                {
                    _deltaCache.TryGetLocalDelta(c, out var delta);
                    return delta;
                })
               .Where(d => d != null)
               .Subscribe(async d =>
                {
                    // here were some importnt changes for Web3 so need to have a look if I can delete the comments
                    // <<<<<<< HEAD
                    //                     var newCid = _deltaHub.PublishDeltaToDfsAndBroadcastAddressAsync(d)
                    //                        .ConfigureAwait(false).GetAwaiter().GetResult();
                    //                     _deltaCache.AddLocalDelta(newCid, d);
                    //                     
                    //                     var previousHash = d.PreviousDeltaDfsHash.ToByteArray().ToCid();
                    //                     
                    //                     _logger.Information("New Delta following {deltaHash} published with new cid {newCid}", 
                    //                         d.PreviousDeltaDfsHash, newCid);
                    //
                    //                     _deltaHashProvider.TryUpdateLatestHash(previousHash, newCid);
                    // =======

                    _logger.Information("New Delta following {deltaHash} published",
                        d.PreviousDeltaDfsHash);

                    var newHashCid = _deltaHub.PublishDeltaToDfsAndBroadcastAddressAsync(d)
                       .ConfigureAwait(false).GetAwaiter().GetResult();
                    var previousHashCid = d.PreviousDeltaDfsHash.ToByteArray().ToCid();

                    _deltaHashProvider.TryUpdateLatestHash(previousHashCid, newHashCid);
                });
        }
Beispiel #6
0
        public void Init()
        {
            _cancellationToken = new CancellationToken();

            _manualResetEventSlim = new ManualResetEventSlim(false);

            _testScheduler = new TestScheduler();
            _hashProvider  = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("keccak-256"));

            _peerSettings = Substitute.For <IPeerSettings>();
            _peerSettings.PeerId.Returns(PeerIdHelper.GetPeerId());

            _deltaDfsReader = Substitute.For <IDeltaDfsReader>();
            _deltaDfsReader.TryReadDeltaFromDfs(Arg.Any <Cid>(), out Arg.Any <Delta>()).Returns(x => true);

            _deltaCache = Substitute.For <IDeltaCache>();
            _deltaCache.GenesisHash.Returns("bafk2bzacecji5gcdd6lxsoazgnbg46c3vttjwwkptiw27enachziizhhkir2w".ToCid());

            _ledger = Substitute.For <ILedger>();

            _peerService = Substitute.For <IPeerService>();

            _deltaHashProvider = new DeltaHashProvider(_deltaCache, Substitute.For <IDeltaIndexService>(), Substitute.For <ILogger>());

            _deltaIndexService = new DeltaIndexService(new InMemoryRepository <DeltaIndexDao, string>());
            _deltaIndexService.Add(new DeltaIndexDao {
                Cid = _hashProvider.ComputeUtf8MultiHash("0").ToCid(), Height = 0
            });

            _peerClient = Substitute.For <IPeerClient>();
            ModifyPeerClient <LatestDeltaHashRequest>((request, senderPeerIdentifier) =>
            {
                var deltaHeightResponse = new LatestDeltaHashResponse
                {
                    DeltaIndex = new DeltaIndex
                    {
                        Cid = _hashProvider.ComputeUtf8MultiHash(_syncTestHeight.ToString()).ToCid().ToArray()
                              .ToByteString(),
                        Height = (uint)_syncTestHeight
                    }
                };

                _deltaHeightReplaySubject.OnNext(new ObserverDto(Substitute.For <IChannelHandlerContext>(),
                                                                 deltaHeightResponse.ToProtocolMessage(senderPeerIdentifier, CorrelationId.GenerateCorrelationId())));
            });

            ModifyPeerClient <DeltaHistoryRequest>((request, senderPeerIdentifier) =>
            {
                var data = GenerateSampleData((int)request.Height, (int)request.Range, (int)_syncTestHeight);
                _deltaIndexService.Add(data.DeltaIndex.Select(x => DeltaIndexDao.ToDao <DeltaIndex>(x, _mapperProvider)));

                _deltaHistoryReplaySubject.OnNext(new ObserverDto(Substitute.For <IChannelHandlerContext>(),
                                                                  data
                                                                  .ToProtocolMessage(senderPeerIdentifier, CorrelationId.GenerateCorrelationId())));
            });

            _peerRepository = new PeerRepository(new InMemoryRepository <Peer, string>());
            Enumerable.Repeat(new Peer {
                PeerId = PeerIdHelper.GetPeerId()
            }, 5).ToList().ForEach(_peerRepository.Add);

            _deltaHeightReplaySubject  = new ReplaySubject <IObserverDto <ProtocolMessage> >(1);
            _deltaHistoryReplaySubject = new ReplaySubject <IObserverDto <ProtocolMessage> >(1);

            var mergeMessageStreams = _deltaHeightReplaySubject.AsObservable()
                                      .Merge(_deltaHistoryReplaySubject.AsObservable());

            _peerService.MessageStream.Returns(mergeMessageStreams);

            _deltaHashProvider = Substitute.For <IDeltaHashProvider>();
            _deltaHashProvider.TryUpdateLatestHash(Arg.Any <Cid>(), Arg.Any <Cid>()).Returns(true);

            _mapperProvider = new TestMapperProvider();

            _userOutput = Substitute.For <IUserOutput>();

            _deltaHeightWatcher = new DeltaHeightWatcher(_peerClient, _peerRepository, _peerService, minimumPeers: 0);

            var dfsService = Substitute.For <IDfsService>();

            _peerSyncManager = new PeerSyncManager(_peerClient, _peerRepository,
                                                   _peerService, _userOutput, _deltaHeightWatcher, Substitute.For <IDfsService>(), 0.7, 0);
        }