Exemplo n.º 1
0
        public void AddVotingBlock(RegistryConfidenceBlock confidenceBlock)
        {
            if (confidenceBlock == null)
            {
                throw new ArgumentNullException(nameof(confidenceBlock));
            }

            _logger.Debug($"AddVotingBlock - Adding ConfidenceBlock of round {confidenceBlock.BlockHeight} with BitMask {confidenceBlock.BitMask.ToHexString()}");

            //if (confidenceBlock.SyncBlockHeight <= _lastCompletedSyncHeight)
            if (_lastCompletedRound > 1 && confidenceBlock.BlockHeight <= _lastCompletedRound && confidenceBlock.BlockHeight != 1 || _lastCompletedRound == 1 && confidenceBlock.BlockHeight == 1)
            {
                _logger.Error($"AddVotingBlock - Received ConfidenceBlock with Round {confidenceBlock.BlockHeight} violates last completed Round {_lastCompletedRound}. BitMask: {confidenceBlock.BitMask.ToHexString()}");
                return;
            }

            lock (_syncRound)
            {
                if (!_roundDescriptors.ContainsKey(confidenceBlock.BlockHeight))
                {
                    RoundDescriptor roundDescriptor = new RoundDescriptor(_transactionHashKey);
                    roundDescriptor.AddVotingBlock(confidenceBlock);
                    _roundDescriptors.Add(confidenceBlock.BlockHeight, roundDescriptor);
                }
                else
                {
                    _roundDescriptors[confidenceBlock.BlockHeight].AddVotingBlock(confidenceBlock);
                }

                _logger.Debug($"AddVotingBlock - Number of voting blocks for round {confidenceBlock.BlockHeight} = {_roundDescriptors[confidenceBlock.BlockHeight].VotingBlocks.Count}");
            }
        }
Exemplo n.º 2
0
        public void RegistryConfidenceBlockParserTest()
        {
            ulong syncBlockHeight = 1;
            uint  nonce           = 4;

            byte[] powHash     = BinaryHelper.GetPowHash(1234);
            ushort version     = 1;
            ulong  blockHeight = 9;

            byte[] prevHash = null;

            Random randNum       = new Random();
            ushort bitMaskLength = 375;

            byte[] bitMask       = Enumerable.Repeat(0, bitMaskLength).Select(i => (byte)randNum.Next(0, 255)).ToArray();
            byte[] expectedProof = Enumerable.Repeat(0, 16).Select(i => (byte)randNum.Next(0, 255)).ToArray();
            byte[] expectedReferencedBodyHash = BinaryHelper.GetDefaultHash(473826643);

            byte[] body;

            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    bw.Write((ushort)bitMask.Length);
                    bw.Write(bitMask);
                    bw.Write(expectedProof);
                    bw.Write(expectedReferencedBodyHash);
                }

                body = ms.ToArray();
            }

            byte[] packet = BinaryHelper.GetSignedPacket(
                PacketType.Registry,
                syncBlockHeight,
                nonce, powHash, version,
                BlockTypes.Registry_ConfidenceBlock, blockHeight, prevHash, body, _privateKey, out byte[] expectedSignature);

            RegistryConfidenceBlockParser registryFullBlockParser = new RegistryConfidenceBlockParser(_identityKeyProvidersRegistry);
            RegistryConfidenceBlock       block = (RegistryConfidenceBlock)registryFullBlockParser.Parse(packet);

            Assert.Equal(syncBlockHeight, block.SyncBlockHeight);
            Assert.Equal(nonce, block.Nonce);
            Assert.Equal(powHash, block.PowHash);
            Assert.Equal(version, block.Version);
            Assert.Equal(blockHeight, block.BlockHeight);

            Assert.Equal(bitMask, block.BitMask);
            Assert.Equal(expectedProof, block.ConfidenceProof);
            Assert.Equal(expectedReferencedBodyHash, block.ReferencedBlockHash);

            Assert.Equal(_publicKey, block.Signer.Value.ToArray());
            Assert.Equal(expectedSignature, block.Signature.ToArray());
        }
Exemplo n.º 3
0
        protected override Memory <byte> ParseSigned(ushort version, Memory <byte> spanBody, out SignedPacketBase syncedBlockBase)
        {
            if (version == 1)
            {
                RegistryConfidenceBlock registryConfidenceBlock = new RegistryConfidenceBlock();
                ushort bitMaskLength = BinaryPrimitives.ReadUInt16LittleEndian(spanBody.Span);
                registryConfidenceBlock.BitMask             = spanBody.Slice(2, bitMaskLength).ToArray();
                registryConfidenceBlock.ConfidenceProof     = spanBody.Slice(2 + bitMaskLength, Globals.TRANSACTION_KEY_HASH_SIZE).ToArray();
                registryConfidenceBlock.ReferencedBlockHash = spanBody.Slice(2 + bitMaskLength + Globals.TRANSACTION_KEY_HASH_SIZE, Globals.DEFAULT_HASH_SIZE).ToArray();

                syncedBlockBase = registryConfidenceBlock;

                return(spanBody.Slice(2 + bitMaskLength + Globals.TRANSACTION_KEY_HASH_SIZE + Globals.DEFAULT_HASH_SIZE));
            }

            throw new BlockVersionNotSupportedException(version, BlockType);
        }
Exemplo n.º 4
0
        private RegistryConfidenceBlock GetConfidence(RegistryShortBlock transactionsShortBlock)
        {
            _registryMemPool.EnqueueTransactionsShortBlock(transactionsShortBlock);

            byte[] proof = _registryMemPool.GetConfidenceMask(transactionsShortBlock, out byte[] bitMask);

            SynchronizationDescriptor synchronizationDescriptor           = _synchronizationContext.LastBlockDescriptor;
            RegistryConfidenceBlock   transactionsRegistryConfidenceBlock = new RegistryConfidenceBlock()
            {
                SyncBlockHeight     = transactionsShortBlock.SyncBlockHeight,
                Nonce               = transactionsShortBlock.Nonce,
                PowHash             = transactionsShortBlock.PowHash,
                BlockHeight         = transactionsShortBlock.BlockHeight,
                ReferencedBlockHash = _defaulHashCalculation.CalculateHash(transactionsShortBlock.RawData),
                BitMask             = bitMask,
                ConfidenceProof     = proof
            };

            _logger.Debug($"BitMask of Confidence for RegistryShortBlock at round {transactionsShortBlock.BlockHeight} with {transactionsShortBlock.TransactionHeaderHashes.Count} hashes is {transactionsRegistryConfidenceBlock.BitMask.ToHexString()}");

            return(transactionsRegistryConfidenceBlock);
        }
Exemplo n.º 5
0
        private void SendConfidence(RegistryConfidenceBlock transactionsRegistryConfidenceBlock)
        {
            ISerializer confidenceBlockSerializer = _signatureSupportSerializersFactory.Create(transactionsRegistryConfidenceBlock);

            _tcpCommunicationService.PostMessage(_registryGroupState.SyncLayerNode, confidenceBlockSerializer);
        }
Exemplo n.º 6
0
        public void RegistryConfidenceBlockSerializerTest()
        {
            ulong syncBlockHeight = 1;
            uint  nonce           = 4;

            byte[] powHash     = BinaryBuilder.GetPowHash(1234);
            ushort version     = 1;
            ulong  blockHeight = 9;

            byte[] prevHash = null;

            Random randNum       = new Random();
            ushort bitMaskLength = 375;

            byte[] bitMask       = Enumerable.Repeat(0, bitMaskLength).Select(i => (byte)randNum.Next(0, 255)).ToArray();
            byte[] expectedProof = Enumerable.Repeat(0, 16).Select(i => (byte)randNum.Next(0, 255)).ToArray();
            byte[] expectedReferencedBodyHash = BinaryBuilder.GetDefaultHash(473826643);

            byte[] body;

            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    bw.Write((ushort)bitMask.Length);
                    bw.Write(bitMask);
                    bw.Write(expectedProof);
                    bw.Write(expectedReferencedBodyHash);
                }

                body = ms.ToArray();
            }

            byte[] expectedPacket = BinaryBuilder.GetSignedPacket(
                PacketType.Registry,
                syncBlockHeight,
                nonce, powHash, version,
                BlockTypes.Registry_ConfidenceBlock, blockHeight, prevHash, body, _privateKey, out byte[] expectedSignature);

            RegistryConfidenceBlock block = new RegistryConfidenceBlock
            {
                SyncBlockHeight     = syncBlockHeight,
                Nonce               = nonce,
                PowHash             = powHash,
                BlockHeight         = blockHeight,
                BitMask             = bitMask,
                ConfidenceProof     = expectedProof,
                ReferencedBlockHash = expectedReferencedBodyHash
            };

            RegistryConfidenceBlockSerializer serializer = new RegistryConfidenceBlockSerializer(_cryptoService, _identityKeyProvidersRegistry, _hashCalculationRepository);

            serializer.Initialize(block);

            byte[] actualPacket = serializer.GetBytes();

            Trace.WriteLine(expectedPacket.ToHexString());
            Trace.WriteLine(actualPacket.ToHexString());

            Assert.Equal(expectedPacket, actualPacket);
        }
Exemplo n.º 7
0
 public void AddVotingBlock(RegistryConfidenceBlock registryConfidenceBlock)
 {
     VotingBlocks.Add(registryConfidenceBlock);
 }
Exemplo n.º 8
0
        public void GetMostConfidentFullBlockTest()
        {
            List <RegistryFullBlock>  registryFullBlocks    = new List <RegistryFullBlock>();
            List <RegistryShortBlock> registryShortBlocks   = new List <RegistryShortBlock>();
            Dictionary <IKey, int>    votesPerShortBlockKey = new Dictionary <IKey, int>();

            int   fullBlockCount  = 10;
            int   votersCount     = 100;
            ulong syncBlockHeight = 1;
            ulong blockHeight     = 12;
            uint  nonce           = 0;

            byte[]           powHash = BinaryBuilder.GetPowHash(1234);
            IHashCalculation hashCalculationTransactionKey = new MurMurHashCalculation();

            IHashCalculation              hashCalculationDefault             = new Keccak256HashCalculation();
            IHashCalculation              hashCalculationMurMur              = new MurMurHashCalculation();
            ISerializersFactory           signatureSupportSerializersFactory = Substitute.For <ISerializersFactory>();
            IHashCalculationsRepository   hashCalculationsRepository         = Substitute.For <IHashCalculationsRepository>();
            IIdentityKeyProvider          identityKeyProviderTransactionKey  = Substitute.For <IIdentityKeyProvider>();
            IIdentityKeyProvidersRegistry identityKeyProvidersRegistry       = Substitute.For <IIdentityKeyProvidersRegistry>();
            ICryptoService          cryptoService          = GetRandomCryptoService();
            ILoggerService          loggerService          = Substitute.For <ILoggerService>();
            IStatesRepository       statesRepository       = Substitute.For <IStatesRepository>();
            ISynchronizationContext synchronizationContext = new Wist.Core.Synchronization.SynchronizationContext(loggerService);

            statesRepository.GetInstance <ISynchronizationContext>().ReturnsForAnyArgs(synchronizationContext);

            identityKeyProviderTransactionKey.GetKey(null).ReturnsForAnyArgs(c => new Key16(c.ArgAt <Memory <byte> >(0)));

            identityKeyProvidersRegistry.GetInstance("DefaultHash").Returns(new DefaultHashKeyProvider());
            identityKeyProvidersRegistry.GetTransactionsIdenityKeyProvider().Returns(identityKeyProviderTransactionKey);

            hashCalculationsRepository.Create(HashType.Keccak256).Returns(hashCalculationDefault);
            hashCalculationsRepository.Create(HashType.MurMur).Returns(hashCalculationMurMur);

            signatureSupportSerializersFactory.Create(null).ReturnsForAnyArgs(c =>
            {
                RegistryShortBlockSerializer registryShortBlockSerializer = new RegistryShortBlockSerializer(cryptoService, identityKeyProvidersRegistry, hashCalculationsRepository);
                registryShortBlockSerializer.Initialize(c.Arg <SignedBlockBase>());
                return(registryShortBlockSerializer);
            });

            SyncRegistryMemPool syncRegistryMemPool = new SyncRegistryMemPool(signatureSupportSerializersFactory, hashCalculationsRepository, identityKeyProvidersRegistry, cryptoService, statesRepository, loggerService);

            for (int i = 0; i < fullBlockCount; i++)
            {
                ICryptoService cryptoService1 = GetRandomCryptoService();
                ushort         expectedCount  = 1000;

                SortedList <ushort, ITransactionRegistryBlock> transactionHeaders = GetTransactionHeaders(syncBlockHeight, blockHeight, nonce, expectedCount);
                SortedList <ushort, IKey> transactionHeaderKeys = GetTransactionHeaderKeys(hashCalculationTransactionKey, transactionHeaders);

                RegistryShortBlock registryShortBlock = new RegistryShortBlock
                {
                    SyncBlockHeight         = syncBlockHeight,
                    BlockHeight             = blockHeight,
                    Nonce                   = nonce,
                    PowHash                 = powHash,
                    TransactionHeaderHashes = transactionHeaderKeys
                };

                RegistryShortBlockSerializer registryShortBlockSerializer = new RegistryShortBlockSerializer(cryptoService1, identityKeyProvidersRegistry, hashCalculationsRepository);
                registryShortBlockSerializer.Initialize(registryShortBlock);
                registryShortBlockSerializer.FillBodyAndRowBytes();

                RegistryFullBlock registryFullBlock = new RegistryFullBlock
                {
                    SyncBlockHeight    = syncBlockHeight,
                    BlockHeight        = blockHeight,
                    Nonce              = nonce,
                    PowHash            = powHash,
                    TransactionHeaders = transactionHeaders,
                    ShortBlockHash     = hashCalculationDefault.CalculateHash(registryShortBlock.RawData)
                };

                RegistryFullBlockSerializer serializer = new RegistryFullBlockSerializer(cryptoService1, identityKeyProvidersRegistry, hashCalculationsRepository);
                serializer.Initialize(registryFullBlock);
                serializer.FillBodyAndRowBytes();

                registryFullBlocks.Add(registryFullBlock);
                registryShortBlocks.Add(registryShortBlock);
            }

            foreach (RegistryFullBlock fullBlock in registryFullBlocks)
            {
                syncRegistryMemPool.AddCandidateBlock(fullBlock);
            }

            Random random = new Random();

            for (int i = 0; i < votersCount; i++)
            {
                ICryptoService cryptoService2 = GetRandomCryptoService();

                foreach (var registryShortBlock in registryShortBlocks)
                {
                    byte[] hashBytes     = hashCalculationDefault.CalculateHash(registryShortBlock.RawData);
                    Random randNum       = new Random();
                    byte[] bitMask       = Enumerable.Repeat(0, registryShortBlock.TransactionHeaderHashes.Count).Select(j => (byte)randNum.Next(0, 255)).ToArray();
                    byte[] expectedProof = Enumerable.Repeat(0, 16).Select(j => (byte)randNum.Next(0, 255)).ToArray();
                    IKey   shortBlockKey = new Key32(hashBytes);
                    long   vote          = GetConfidence(bitMask);
                    if (!votesPerShortBlockKey.ContainsKey(shortBlockKey))
                    {
                        votesPerShortBlockKey.Add(shortBlockKey, (ushort)vote);
                    }
                    else
                    {
                        votesPerShortBlockKey[shortBlockKey] += (ushort)vote;
                    }

                    RegistryConfidenceBlock registryConfidenceBlock = new RegistryConfidenceBlock
                    {
                        SyncBlockHeight     = syncBlockHeight,
                        BlockHeight         = blockHeight,
                        Nonce               = nonce,
                        PowHash             = powHash,
                        ReferencedBlockHash = hashBytes,
                        BitMask             = bitMask,
                        ConfidenceProof     = expectedProof
                    };

                    RegistryConfidenceBlockSerializer registryConfidenceBlockSerializer = new RegistryConfidenceBlockSerializer(cryptoService2, identityKeyProvidersRegistry, hashCalculationsRepository);
                    registryConfidenceBlockSerializer.Initialize(registryConfidenceBlock);
                    registryConfidenceBlockSerializer.FillBodyAndRowBytes();

                    syncRegistryMemPool.AddVotingBlock(registryConfidenceBlock);
                }
            }

            IKey expectedMostConfidentKey = votesPerShortBlockKey.OrderByDescending(kv => kv.Value).Select(kv => kv.Key).First();

            RegistryFullBlock actualFullBlock = syncRegistryMemPool.GetMostConfidentFullBlock(blockHeight);
            IKey actualMostConfidentKey       = new Key32(actualFullBlock.ShortBlockHash);

            Assert.Equal(expectedMostConfidentKey, actualMostConfidentKey);
        }