public void BuildDeltaCheckForAccuracy()
        {
            var transactions = Enumerable.Range(0, 20).Select(i =>
            {
                var transaction = TransactionHelper.GetPublicTransaction(
                    amount: (uint)i,
                    receiverPublicKey: i.ToString(),
                    transactionFees: (ulong)_random.Next(),
                    timestamp: _random.Next(),
                    signature: i.ToString());
                return(transaction);
            }).ToList();

            var transactionRetriever = Substitute.For <IDeltaTransactionRetriever>();

            transactionRetriever.GetMempoolTransactionsByPriority().Returns(transactions);

            var selectedTransactions = transactions.Where(t => t.IsPublicTransaction && t.HasValidEntries()).ToArray();

            var expectedCoinBase = new CoinbaseEntry
            {
                Amount            = selectedTransactions.Sum(t => t.SummedEntryFees()).ToUint256ByteString(),
                ReceiverPublicKey = _producerId.PublicKey.ToByteString()
            };

            var salt = BitConverter.GetBytes(
                _randomFactory.GetDeterministicRandomFromSeed(_previousDeltaHash.ToArray()).NextInt());

            var rawAndSaltedEntriesBySignature = selectedTransactions.SelectMany(
                t => t.PublicEntries.Select(e => new
            {
                RawEntry             = e,
                SaltedAndHashedEntry = _hashProvider.ComputeMultiHash(e.ToByteArray().Concat(salt))
            }));

            var shuffledEntriesBytes = rawAndSaltedEntriesBySignature
                                       .OrderBy(v => v.SaltedAndHashedEntry.ToArray(), ByteUtil.ByteListComparer.Default)
                                       .SelectMany(v => v.RawEntry.ToByteArray())
                                       .ToArray();

            var signaturesInOrder = selectedTransactions
                                    .Select(p => p.Signature.ToByteArray())
                                    .OrderBy(s => s, ByteUtil.ByteListComparer.Default)
                                    .SelectMany(b => b)
                                    .ToArray();

            var expectedBytesToHash = shuffledEntriesBytes.Concat(signaturesInOrder)
                                      .Concat(expectedCoinBase.ToByteArray()).ToArray();

            var deltaBuilder = new DeltaBuilder(transactionRetriever, _randomFactory, _hashProvider, _peerSettings, _cache, _dateTimeProvider, _logger);
            var candidate    = deltaBuilder.BuildCandidateDelta(_previousDeltaHash);

            ValidateDeltaCandidate(candidate, expectedBytesToHash);

            _cache.Received(1).AddLocalDelta(Arg.Is(candidate), Arg.Any <Delta>());
        }
Ejemplo n.º 2
0
        public async Task AddAsync_Should_Save_File_In_Subfolder_With_Hash_As_Name()
        {
            _fileSystem.File.Create(Arg.Any <string>()).Returns(new MemoryStream());

            var contentBytes  = BitConverter.GetBytes(123456);
            var contentStream = contentBytes.ToMemoryStream();

            var expectedCid = _hashProvider.ComputeMultiHash(contentBytes).CreateCid();

            var cid = await _dfs.AddAsync(contentStream);

            cid.Should().Be(expectedCid);
        }
Ejemplo n.º 3
0
        public void InitMappers(IMapperConfigurationExpression cfg)
        {
            cfg.AllowNullDestinationValues = true;

            cfg.CreateMap <PublicEntry, PublicEntryDao>()
            .ForMember(d => d.Id, opt => opt.MapFrom(src => _hashProvider.ComputeMultiHash(src.ToByteArray())))
            .ForMember(d => d.Amount,
                       opt => opt.ConvertUsing(new ByteStringToUInt256StringConverter(), s => s.Amount))
            .ForMember(e => e.Data, opt => opt.ConvertUsing <ByteStringToBase32Converter, ByteString>())
            .ForMember(d => d.ReceiverAddress,
                       opt => opt.ConvertUsing(new ByteStringToBase32Converter(), s => s.ReceiverAddress))
            .ForMember(d => d.SenderAddress,
                       opt => opt.ConvertUsing(new ByteStringToBase32Converter(), s => s.SenderAddress))
            .ForMember(d => d.TransactionFees,
                       opt => opt.ConvertUsing(new ByteStringToUInt256StringConverter(), s => s.TransactionFees));

            cfg.CreateMap <PublicEntryDao, PublicEntry>()
            .ForMember(d => d.Amount,
                       opt => opt.ConvertUsing(new UInt256StringToByteStringConverter(), s => s.Amount))
            .ForMember(e => e.Data, opt => opt.ConvertUsing <Base32ToByteStringFormatter, string>())
            .ForMember(d => d.ReceiverAddress,
                       opt => opt.ConvertUsing(new Base32ToByteStringFormatter(), s => s.ReceiverAddress))
            .ForMember(d => d.SenderAddress,
                       opt => opt.ConvertUsing(new Base32ToByteStringFormatter(), s => s.SenderAddress))
            .ForMember(d => d.TransactionFees,
                       opt => opt.ConvertUsing(new UInt256StringToByteStringConverter(), s => s.TransactionFees));

            cfg.CreateMap <DateTime, Timestamp>().ConvertUsing(s => s.ToTimestamp());
            cfg.CreateMap <Timestamp, DateTime>().ConvertUsing(s => s.ToDateTime());
        }
Ejemplo n.º 4
0
 public RawEntryWithSaltedAndHashedEntry(PublicEntry rawEntry,
                                         byte[] salt,
                                         IHashProvider hashProvider)
 {
     RawEntry             = rawEntry;
     SaltedAndHashedEntry = hashProvider.ComputeMultiHash(rawEntry, salt).ToArray();
 }
Ejemplo n.º 5
0
        public void Generate_Genesis_Hash()
        {
            var emptyDelta = new Delta();
            var hash       = _hashProvider.ComputeMultiHash(emptyDelta.ToByteArray()).ToCid();

            TestContext.WriteLine(hash);
        }
Ejemplo n.º 6
0
        public void Generate_Genesis_Hash()
        {
            var emptyDelta = new Delta();
            var hash       = _hashProvider.ComputeMultiHash(emptyDelta.ToByteArray()).ToBase32();

            Output.WriteLine(hash);
        }
Ejemplo n.º 7
0
        public async Task KeyStoreEncryptAsync(IPrivateKey privateKey,
                                               NetworkType networkType,
                                               KeyRegistryTypes keyIdentifier)
        {
            try
            {
                var publicKeyHash = _hashProvider.ComputeMultiHash(privateKey.GetPublicKey().Bytes).ToArray()
                                    .ToByteString();
                var address = new Address
                {
                    PublicKeyHash = publicKeyHash,
                    AccountType   = AccountType.PublicAccount,
                    NetworkType   = networkType
                };

                var securePassword = _passwordManager.RetrieveOrPromptPassword(_defaultNodePassword,
                                                                               "Please create a password for this node");

                var password = StringFromSecureString(securePassword);

                var json = EncryptAndGenerateDefaultKeyStoreAsJson(
                    password,
                    _cryptoContext.ExportPrivateKey(privateKey),
                    address.RawBytes.ToBase32());

                _passwordManager.AddPasswordToRegistry(_defaultNodePassword, securePassword);

                await _fileSystem.WriteTextFileToCddSubDirectoryAsync(keyIdentifier.Name, Constants.KeyStoreDataSubDir,
                                                                      json);
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Serializes the <paramref name="message"/>, appends suffix and returns the hash of it.
        /// </summary>
        /// <param name="provider">The hash provider.</param>
        /// <param name="message">The protocol message.</param>
        /// <param name="suffix">The suffix that should be appended to the message. </param>
        /// <returns></returns>
        public static MultiHash ComputeMultiHash(this IHashProvider provider, IMessage message, byte[] suffix)
        {
            ProtoPreconditions.CheckNotNull(message, nameof(message));
            var calculateSize = message.CalculateSize();

            var required = calculateSize + suffix.Length;
            var array    = ArrayPool <byte> .Shared.Rent(required);

            try
            {
                using (var output = new CodedOutputStream(array))
                {
                    message.WriteTo(output);
                }

                suffix.CopyTo(array, calculateSize);

                var result = provider.ComputeMultiHash(array, 0, required);
                return(result);
            }
            finally
            {
                ArrayPool <byte> .Shared.Return(array);
            }
        }
Ejemplo n.º 9
0
        public static CandidateDeltaBroadcast GetCandidateDelta(IHashProvider hashProvider,
                                                                MultiHash previousDeltaHash = null,
                                                                MultiHash hash    = null,
                                                                PeerId producerId = null)
        {
            var candidateHash = hash ?? hashProvider.ComputeMultiHash(ByteUtil.GenerateRandomByteArray(32));
            var previousHash  = previousDeltaHash ?? hashProvider.ComputeMultiHash(ByteUtil.GenerateRandomByteArray(32));
            var producer      = producerId
                                ?? PeerIdHelper.GetPeerId(publicKey: ByteUtil.GenerateRandomByteArray(32));

            return(new CandidateDeltaBroadcast
            {
                Hash = candidateHash.ToArray().ToByteString(),
                PreviousDeltaDfsHash = previousHash.ToArray().ToByteString(),
                ProducerId = producer
            });
        }
Ejemplo n.º 10
0
        public void BuildDeltaCheckForAccuracy()
        {
            var transactions = Enumerable.Range(0, 20).Select(i =>
            {
                var transaction = TransactionHelper.GetPublicTransaction(
                    (uint)i,
                    receiverPublicKey: i.ToString(),
                    transactionFees: (ulong)_random.Next(),
                    timestamp: _random.Next(),
                    signature: i.ToString());
                return(transaction.PublicEntry);
            }).ToList();

            var transactionRetriever = BuildRetriever(transactions);
            var selectedTransactions = BuildSelectedTransactions(transactions);

            var salt = BitConverter.GetBytes(_randomFactory.GetDeterministicRandomFromSeed(_previousDeltaHash.ToArray())
                                             .NextInt());

            var rawAndSaltedEntriesBySignature = selectedTransactions.Select(e =>
            {
                var publicEntriesProtoBuff = e;
                return(new
                {
                    RawEntry = publicEntriesProtoBuff,
                    SaltedAndHashedEntry =
                        _hashProvider.ComputeMultiHash(publicEntriesProtoBuff.ToByteArray().Concat(salt))
                });
            });

            var shuffledEntriesBytes = rawAndSaltedEntriesBySignature
                                       .OrderBy(v => v.SaltedAndHashedEntry.ToArray(), ByteUtil.ByteListComparer.Default)
                                       .SelectMany(v => v.RawEntry.ToByteArray())
                                       .ToArray();

            var expectedBytesToHash = BuildExpectedBytesToHash(selectedTransactions, shuffledEntriesBytes);

            var deltaBuilder = new DeltaBuilder(transactionRetriever, _randomFactory, _hashProvider, _peerSettings,
                                                _cache, _dateTimeProvider, _stateProvider, _deltaExecutor, _logger);
            var candidate = deltaBuilder.BuildCandidateDelta(_previousDeltaHash);

            ValidateDeltaCandidate(candidate, expectedBytesToHash);

            _cache.Received(1).AddLocalDelta(Arg.Is(candidate), Arg.Any <Delta>());
        }
Ejemplo n.º 11
0
        public static CandidateDeltaBroadcast GetCandidateDelta(IHashProvider hashProvider,
                                                                Cid previousDeltaHash = null,
                                                                Cid hash          = null,
                                                                PeerId producerId = null)
        {
            var candidateHash = hash ??
                                hashProvider.ComputeMultiHash(ByteUtil.GenerateRandomByteArray(32)).CreateCid();
            var previousHash = previousDeltaHash ??
                               hashProvider.ComputeMultiHash(ByteUtil.GenerateRandomByteArray(32)).CreateCid();
            var producer = producerId
                           ?? PeerIdHelper.GetPeerId(ByteUtil.GenerateRandomByteArray(32));

            return(new CandidateDeltaBroadcast
            {
                Hash = MultiBase.Decode(candidateHash).ToByteString(),
                PreviousDeltaDfsHash = MultiBase.Decode(previousHash).ToByteString(),
                ProducerId = producer
            });
        }
        public void GetFavouriteDelta_should_return_null_on_unknown_previous_delta_hash()
        {
            using (var realCache = new MemoryCache(new MemoryCacheOptions()))
            {
                _voter = new DeltaVoter(realCache, _producersProvider, _peerSettings, _logger);

                AddCandidatesToCacheAndVote(10, 500, realCache);

                var found = _voter.TryGetFavouriteDelta(_hashProvider.ComputeMultiHash(ByteUtil.GenerateRandomByteArray(32)), out var favouriteCandidate);

                found.Should().BeFalse();
                favouriteCandidate.Should().BeNull();
            }
        }
Ejemplo n.º 13
0
        public DeltaHashProviderTests(ITestOutputHelper output) : base(output)
        {
            _deltaCache = Substitute.For <IDeltaCache>();
            _logger     = new LoggerConfiguration()
                          .MinimumLevel.Verbose()
                          .WriteTo.TestOutput(output)
                          .CreateLogger()
                          .ForContext(MethodBase.GetCurrentMethod().DeclaringType);

            _hashProvider = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("blake2b-256"));

            _deltaCache.GenesisHash.Returns(
                _hashProvider.ComputeMultiHash(new Delta().ToByteArray()).CreateCid());
        }
Ejemplo n.º 14
0
        /// <inheritdoc />
        public async Task <Cid> AddAsync(Stream content,
                                         string name = "",
                                         CancellationToken cancellationToken = default)
        {
            var cid      = _hashProvider.ComputeMultiHash(content).CreateCid();
            var filePath = Path.Combine(_baseFolder.FullName, cid);

            using (var file = _fileSystem.File.Create(filePath))
            {
                content.Position = 0;
                await content.CopyToAsync(file, cancellationToken).ConfigureAwait(false);
            }

            return(cid);
        }
Ejemplo n.º 15
0
        /// <param name="deltaHeightRequest"></param>
        /// <param name="channelHandlerContext"></param>
        /// <param name="senderPeerId"></param>
        /// <param name="correlationId"></param>
        /// <returns></returns>
        protected override DeltaHistoryResponse HandleRequest(DeltaHistoryRequest deltaHeightRequest,
                                                              IChannelHandlerContext channelHandlerContext,
                                                              PeerId senderPeerId,
                                                              ICorrelationId correlationId)
        {
            Guard.Argument(deltaHeightRequest, nameof(deltaHeightRequest)).NotNull();
            Guard.Argument(channelHandlerContext, nameof(channelHandlerContext)).NotNull();
            Guard.Argument(senderPeerId, nameof(senderPeerId)).NotNull();

            Logger.Debug("PeerId: {0} requests: {1} deltas from height: {2}", senderPeerId, deltaHeightRequest.Range, deltaHeightRequest.Height);

            // @TODO actually get this from some where for now provide a bunch of fake linked deltas
            /////////////////////////////////////////////////////////////////////////////////////////////////////
            var response      = new DeltaHistoryResponse();
            var lastDeltaHash = _hashProvider.ComputeMultiHash(ByteUtil.GenerateRandomByteArray(32));

            for (uint x = 0; x < deltaHeightRequest.Range; x++)
            {
                var delta = new Delta
                {
                    PreviousDeltaDfsHash = lastDeltaHash.Digest.ToByteString()
                };

                var index = new DeltaIndex
                {
                    Height = deltaHeightRequest.Height,
                    Cid    = delta.ToByteString()
                };

                response.Result.Add(index);
                lastDeltaHash = _hashProvider.ComputeMultiHash(ByteUtil.GenerateRandomByteArray(32));
            }
            /////////////////////////////////////////////////////////////////////////////////////////////////////

            return(response);
        }
Ejemplo n.º 16
0
        public void Init()
        {
            this.Setup(TestContext.CurrentContext);

            _deltaCache = Substitute.For <IDeltaCache>();
            _logger     = new LoggerConfiguration()
                          .MinimumLevel.Verbose()
                          .WriteTo.NUnitOutput()
                          .CreateLogger()
                          .ForContext(MethodBase.GetCurrentMethod().DeclaringType);

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

            _deltaCache.GenesisHash.Returns(
                _hashProvider.ComputeMultiHash(new Delta().ToByteArray()).ToCid());
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Serializes the <paramref name="message"/> returns the hash of it.
        /// </summary>
        /// <param name="provider">The hash provider.</param>
        /// <param name="message">The protocol message.</param>
        /// <returns></returns>
        public static MultiHash ComputeMultiHash(this IHashProvider provider, IMessage message)
        {
            ProtoPreconditions.CheckNotNull(message, nameof(message));
            var required = message.CalculateSize();

            var array = ArrayPool <byte> .Shared.Rent(required);

            using (var output = new CodedOutputStream(array))
            {
                message.WriteTo(output);
            }

            var result = provider.ComputeMultiHash(array, 0, required);

            ArrayPool <byte> .Shared.Return(array);

            return(result);
        }
        public DeltaVoterTests()
        {
            _hashProvider = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("blake2b-256"));

            _cache = Substitute.For <IMemoryCache>();

            _previousDeltaHash = _hashProvider.ComputeMultiHash(ByteUtil.GenerateRandomByteArray(32));

            _producerIds = "1234"
                           .Select((c, i) => PeerIdHelper.GetPeerId(c.ToString()))
                           .Shuffle();
            _producersProvider = Substitute.For <IDeltaProducersProvider>();
            _producersProvider.GetDeltaProducersFromPreviousDelta(Arg.Any <MultiHash>())
            .Returns(_producerIds);

            _localIdentifier = PeerIdHelper.GetPeerId("myself, a producer");
            _peerSettings    = _localIdentifier.ToSubstitutedPeerSettings();
            _logger          = Substitute.For <ILogger>();
        }
        public IList <PeerId> GetDeltaProducersFromPreviousDelta(MultiHash previousDeltaHash)
        {
            Guard.Argument(previousDeltaHash, nameof(previousDeltaHash)).NotNull();

            var previousDeltaHashAsString = previousDeltaHash.ToBase32();

            if (_producersByPreviousDelta.TryGetValue(GetCacheKey(previousDeltaHashAsString),
                                                      out IList <PeerId> cachedPeerIdsInPriorityOrder))
            {
                _logger.Information("Retrieved favourite delta producers for successor of {0} from cache.",
                                    previousDeltaHashAsString);
                return(cachedPeerIdsInPriorityOrder);
            }

            _logger.Information("Calculating favourite delta producers for the successor of {0}.",
                                previousDeltaHashAsString);

            var allPeers = PeerRepository.GetAll().Concat(new[] { _selfAsPeer });

            var peerIdsInPriorityOrder = allPeers.Select(p =>
            {
                var array   = p.PeerId.ToByteArray().Concat(previousDeltaHash.ToArray()).ToArray();
                var ranking = _hashProvider.ComputeMultiHash(array).ToArray();
                return(new
                {
                    p.PeerId,
                    ranking
                });
            })
                                         .OrderBy(h => h.ranking, ByteUtil.ByteListMinSizeComparer.Default)
                                         .Select(h => h.PeerId)
                                         .ToList();

            _logger.Information("Adding favourite delta producers for the successor of {0} to cache.",
                                previousDeltaHashAsString);
            _logger.Debug("Favourite producers are, in that order, [{0}]", string.Join(", ", peerIdsInPriorityOrder));
            _producersByPreviousDelta.Set(GetCacheKey(previousDeltaHashAsString), peerIdsInPriorityOrder,
                                          _cacheEntryOptions);

            return(peerIdsInPriorityOrder);
        }
Ejemplo n.º 20
0
        public DeltaCache(IHashProvider hashProvider,
                          IMemoryCache memoryCache,
                          IDeltaDfsReader dfsReader,
                          IDeltaCacheChangeTokenProvider changeTokenProvider,
                          IStorageProvider storageProvider,
                          IStateProvider stateProvider,
                          ISnapshotableDb stateDb,
                          IDeltaIndexService deltaIndexService,
                          ILogger logger)
        {
            _deltaIndexService = deltaIndexService;

            stateProvider.CreateAccount(TruffleTestAccount, 1_000_000_000.Kat());
            stateProvider.CreateAccount(CatalystTruffleTestAccount, 1_000_000_000.Kat());

            storageProvider.Commit();
            stateProvider.Commit(CatalystGenesisSpec.Instance);

            storageProvider.CommitTrees();
            stateProvider.CommitTree();

            stateDb.Commit();

            var genesisDelta = new Delta
            {
                TimeStamp = Timestamp.FromDateTime(DateTime.UnixEpoch),
                StateRoot = ByteString.CopyFrom(stateProvider.StateRoot.Bytes),
            };


            GenesisHash = hashProvider.ComputeMultiHash(genesisDelta).ToCid();

            _dfsReader    = dfsReader;
            _logger       = logger;
            _entryOptions = () => new MemoryCacheEntryOptions()
                            .AddExpirationToken(changeTokenProvider.GetChangeToken())
                            .RegisterPostEvictionCallback(EvictionCallback);

            _memoryCache = memoryCache;
            _memoryCache.Set(GenesisHash, genesisDelta);
        }
Ejemplo n.º 21
0
        public DeltaCache(IHashProvider hashProvider,
                          IMemoryCache memoryCache,
                          IDeltaDfsReader dfsReader,
                          IDeltaCacheChangeTokenProvider changeTokenProvider,
                          ILogger logger)
        {
            var genesisDelta = new Delta {
                TimeStamp = Timestamp.FromDateTime(DateTime.MinValue.ToUniversalTime())
            };

            GenesisHash = hashProvider.ComputeMultiHash(genesisDelta).CreateCid();

            _dfsReader    = dfsReader;
            _logger       = logger;
            _entryOptions = () => new MemoryCacheEntryOptions()
                            .AddExpirationToken(changeTokenProvider.GetChangeToken())
                            .RegisterPostEvictionCallback(EvictionCallback);

            _memoryCache = memoryCache;
            _memoryCache.Set(GenesisHash, genesisDelta);
        }
Ejemplo n.º 22
0
        public static Delta GetDelta(IHashProvider hashProvider,
                                     MultiHash previousDeltaHash = null,
                                     byte[] merkleRoot           = default,
                                     byte[] merklePoda           = default,
                                     DateTime?timestamp          = default)
        {
            var previousHash     = previousDeltaHash ?? hashProvider.ComputeMultiHash(ByteUtil.GenerateRandomByteArray(32));
            var root             = merkleRoot ?? ByteUtil.GenerateRandomByteArray(32);
            var poda             = merklePoda ?? ByteUtil.GenerateRandomByteArray(32);
            var nonNullTimestamp = Timestamp.FromDateTime(timestamp?.ToUniversalTime() ?? DateTime.Now.ToUniversalTime());

            var delta = new Delta
            {
                PreviousDeltaDfsHash = previousHash.ToArray().ToByteString(),
                MerkleRoot           = root.ToByteString(),
                MerklePoda           = poda.ToByteString(),
                TimeStamp            = nonNullTimestamp
            };

            return(delta);
        }
        public PoaDeltaProducersProviderTests()
        {
            var hashingAlgorithm = HashingAlgorithm.GetAlgorithmMetadata("blake2b-256");

            _hashProvider = new HashProvider(hashingAlgorithm);

            var peerSettings = PeerIdHelper.GetPeerId("TEST").ToSubstitutedPeerSettings();

            _selfAsPeer = new Peer {
                PeerId = peerSettings.PeerId
            };
            var rand = new Random();

            _peers = Enumerable.Range(0, 5)
                     .Select(_ =>
            {
                var peerIdentifier = PeerIdHelper.GetPeerId(rand.Next().ToString());
                var peer           = new Peer {
                    PeerId = peerIdentifier
                };
                return(peer);
            }).ToList();

            var logger = Substitute.For <ILogger>();

            var peerRepository = Substitute.For <IPeerRepository>();

            peerRepository.GetAll().Returns(_ => _peers);

            _previousDeltaHash       = _hashProvider.ComputeMultiHash(ByteUtil.GenerateRandomByteArray(32));
            _previousDeltaHashString = _previousDeltaHash.ToBase32();

            _producersByPreviousDelta = Substitute.For <IMemoryCache>();

            _poaDeltaProducerProvider = new PoaDeltaProducersProvider(peerRepository,
                                                                      peerSettings,
                                                                      _producersByPreviousDelta,
                                                                      _hashProvider,
                                                                      logger);
        }
        public void Init()
        {
            _hashProvider = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("keccak-256"));

            var peerSettings = PeerIdHelper.GetPeerId("TEST").ToSubstitutedPeerSettings();

            _selfAsPeer = new Peer {
                PeerId = peerSettings.PeerId
            };
            var rand = new Random();

            _peers = Enumerable.Range(0, 5)
                     .Select(_ =>
            {
                var peerIdentifier = PeerIdHelper.GetPeerId(rand.Next().ToString());
                var peer           = new Peer {
                    PeerId = peerIdentifier, LastSeen = DateTime.UtcNow
                };
                return(peer);
            }).ToList();

            var logger = Substitute.For <ILogger>();

            var peerRepository = Substitute.For <IPeerRepository>();

            peerRepository.GetActivePoaPeers().Returns(_ => _peers);

            _previousDeltaHash =
                _hashProvider.ComputeMultiHash(ByteUtil.GenerateRandomByteArray(32)).ToCid();

            _producersByPreviousDelta = Substitute.For <IMemoryCache>();

            _poaDeltaProducerProvider = new PoaDeltaProducersProvider(peerRepository,
                                                                      peerSettings,
                                                                      _producersByPreviousDelta,
                                                                      _hashProvider,
                                                                      logger);
        }
        public void GetDeltaProducersFromPreviousDelta_when_not_cached_should_store_and_return_an_ordered_list()
        {
            _producersByPreviousDelta.TryGetValue(Arg.Any <string>(), out Arg.Any <object>()).Returns(false);

            var peers = _peers.Concat(new[] { _selfAsPeer });

            var expectedProducers = peers.Select(p =>
            {
                var bytesToHash = p.PeerId.ToByteArray()
                                  .Concat(_previousDeltaHash.ToArray()).ToArray();
                var ranking = _hashProvider.ComputeMultiHash(bytesToHash).ToArray();
                return(new
                {
                    PeerIdentifier = p.PeerId,
                    ranking
                });
            })
                                    .OrderBy(h => h.ranking, ByteUtil.ByteListMinSizeComparer.Default)
                                    .Select(h => h.PeerIdentifier)
                                    .ToList();

            var producers = _poaDeltaProducerProvider.GetDeltaProducersFromPreviousDelta(_previousDeltaHash);

            _producersByPreviousDelta.Received(1).TryGetValue(Arg.Is <string>(s => s.EndsWith(_previousDeltaHashString)),
                                                              out Arg.Any <object>());
            _producersByPreviousDelta.Received(1)
            .CreateEntry(Arg.Is <string>(s => s.EndsWith(_previousDeltaHashString)));

            producers.Should().OnlyHaveUniqueItems();

            for (var i = 0; i < expectedProducers.Count; i++)
            {
                producers[i].ToByteArray()
                .Should().BeEquivalentTo(expectedProducers[i].ToByteArray());
            }
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Gets the hash out of the public entry.
 /// </summary>
 /// <param name="entry">The entry.</param>
 /// <param name="hashProvider">The hash provider.</param>
 /// <returns>The hash value.</returns>
 public static Keccak GetHash(this PublicEntry entry, IHashProvider hashProvider)
 {
     return(new Keccak(hashProvider.ComputeMultiHash(entry).Digest));
 }
 public RawEntryWithSaltedAndHashedEntry(PublicEntry rawEntry, IEnumerable <byte> salt, IHashProvider hashProvider)
 {
     RawEntry             = rawEntry;
     SaltedAndHashedEntry = hashProvider.ComputeMultiHash(rawEntry.ToByteArray().Concat(salt)).ToArray();
 }
        ///<inheritdoc />
        public CandidateDeltaBroadcast BuildCandidateDelta(MultiHash previousDeltaHash)
        {
            _logger.Debug("Building candidate delta locally");

            var allTransactions = _transactionRetriever.GetMempoolTransactionsByPriority();

            Guard.Argument(allTransactions, nameof(allTransactions))
            .NotNull("Mempool content returned null, check the mempool is actively running");

            var includedTransactions = GetValidTransactionsForDelta(allTransactions);
            var salt = GetSaltFromPreviousDelta(previousDeltaHash);

            var rawAndSaltedEntriesBySignature = includedTransactions.SelectMany(
                t => t.PublicEntries.Select(e => new RawEntryWithSaltedAndHashedEntry(e, salt, _hashProvider)));

            // (Eα;Oα)
            var shuffledEntriesBytes = rawAndSaltedEntriesBySignature
                                       .OrderBy(v => v.SaltedAndHashedEntry, ByteUtil.ByteListComparer.Default)
                                       .SelectMany(v => v.RawEntry.ToByteArray())
                                       .ToArray();

            // dn
            var signaturesInOrder = includedTransactions
                                    .Select(p => p.Signature.ToByteArray())
                                    .OrderBy(s => s, ByteUtil.ByteListComparer.Default)
                                    .SelectMany(b => b)
                                    .ToArray();

            // xf
            var summedFees = includedTransactions.Sum(t => t.SummedEntryFees());

            //∆Ln,j = L(f/E) + dn + E(xf, j)
            var coinbaseEntry = new CoinbaseEntry
            {
                Amount            = summedFees.ToUint256ByteString(),
                ReceiverPublicKey = _producerUniqueId.PublicKey.ToByteString()
            };
            var globalLedgerStateUpdate = shuffledEntriesBytes
                                          .Concat(signaturesInOrder)
                                          .Concat(coinbaseEntry.ToByteArray())
                                          .ToArray();

            //hj
            var candidate = new CandidateDeltaBroadcast
            {
                // h∆j
                Hash = _hashProvider.ComputeMultiHash(globalLedgerStateUpdate).ToArray().ToByteString(),

                // Idj
                ProducerId           = _producerUniqueId,
                PreviousDeltaDfsHash = previousDeltaHash.ToArray().ToByteString()
            };

            _logger.Debug("Building full delta locally");

            var producedDelta = new Delta
            {
                PreviousDeltaDfsHash = previousDeltaHash.ToArray().ToByteString(),
                MerkleRoot           = candidate.Hash,
                CoinbaseEntries      = { coinbaseEntry },
                PublicEntries        = { includedTransactions.SelectMany(t => t.PublicEntries) },
                TimeStamp            = Timestamp.FromDateTime(_dateTimeProvider.UtcNow)
            };

            _logger.Debug("Adding local candidate delta");

            _deltaCache.AddLocalDelta(candidate, producedDelta);

            return(candidate);
        }
Ejemplo n.º 29
0
 public (byte[], bool) Run(byte[] inputData)
 {
     return(_hashProvider.ComputeMultiHash(inputData).Digest, true);
 }