private void CreateAndDistributeCombinedBlock(RegistryFullBlock transactionsFullBlockMostConfident) { lock (_synchronizationContext) { SynchronizationRegistryCombinedBlock lastCombinedBlock = (SynchronizationRegistryCombinedBlock)_synchronizationChainDataService.GetAllLastBlocksByType(BlockTypes.Synchronization_RegistryCombinationBlock).Single(); byte[] prevHash = lastCombinedBlock != null?_defaultTransactionHashCalculation.CalculateHash(lastCombinedBlock.RawData) : new byte[Globals.DEFAULT_HASH_SIZE]; byte[] fullBlockHash = _defaultTransactionHashCalculation.CalculateHash(transactionsFullBlockMostConfident?.RawData ?? new byte[Globals.DEFAULT_HASH_SIZE]); //TODO: For initial POC there will be only one participant at Synchronization Layer, thus combination of FullBlocks won't be implemented fully SynchronizationRegistryCombinedBlock synchronizationRegistryCombinedBlock = new SynchronizationRegistryCombinedBlock { SyncBlockHeight = _synchronizationContext.LastBlockDescriptor?.BlockHeight ?? 0, PowHash = _powCalculation.CalculateHash(_synchronizationContext.LastBlockDescriptor?.Hash ?? new byte[Globals.DEFAULT_HASH_SIZE]), BlockHeight = ++_synchronizationContext.LastRegistrationCombinedBlockHeight, HashPrev = prevHash, ReportedTime = DateTime.Now, BlockHashes = new byte[][] { fullBlockHash } }; ISerializer combinedBlockSerializer = _signatureSupportSerializersFactory.Create(synchronizationRegistryCombinedBlock); combinedBlockSerializer.FillBodyAndRowBytes(); IEnumerable <IKey> storageLayerKeys = _nodesResolutionService.GetStorageNodeKeys(combinedBlockSerializer); _communicationService.PostMessage(storageLayerKeys, combinedBlockSerializer); _synchronizationChainDataService.Add(synchronizationRegistryCombinedBlock); } }
public void RegisterTransactionForConsent(TransactionConsentRequest consentRequest) { _consentRequests.AddOrUpdate(consentRequest.TransactionId, consentRequest, (k, v) => consentRequest); byte[] confirmHash = _hashCalculation.CalculateHash(Encoding.UTF8.GetBytes(consentRequest.TransactionId)); byte[] declineHash = _hashCalculation.CalculateHash(confirmHash); _consentRequestsByConfirmKey.AddOrUpdate(confirmHash.ToHexString(), consentRequest.TransactionId, (k, v) => confirmHash.ToHexString()); _consentRequestsByDeclineKey.AddOrUpdate(declineHash.ToHexString(), consentRequest.TransactionId, (k, v) => declineHash.ToHexString()); _consentsPerRegistration.AddOrUpdate(consentRequest.RegistrationCommitment, new List <string> { consentRequest.TransactionId }, (k, v) => { v.Add(consentRequest.TransactionId); return(v); }); }
protected byte[] GetRandomTargetAddress() { byte[] seedTarget = "1F0B7DBB567EFC99060EC69DD60130B4364E36B7A88248DD234285B3860F63C3".HexStringToByteArray();// GetRandomSeed(); byte[] targetKeyBytes = _cryptoService.GetPublicKeyFromSeed(seedTarget); byte[] targetHash = _hashCalculation.CalculateHash(targetKeyBytes); return(targetHash); }
private void FinalizeTransaction(long pos, long bodyLength) { _memoryStream.Seek(pos, SeekOrigin.Begin); byte[] body = _binaryReader.ReadBytes((int)bodyLength); RingSignature[] ringSignatures = _block.Signatures; // _cryptoService.Sign(body, _block.KeyImage.Value.ToArray(), _block.PublicKeys, _prevSecretKey, _prevSecretKeyIndex); _binaryWriter.Write((ushort)ringSignatures.Length); foreach (IKey key in _block.PublicKeys) { _binaryWriter.Write(key.ArraySegment.Array, key.ArraySegment.Offset, key.ArraySegment.Count); } foreach (var signature in ringSignatures) { _binaryWriter.Write(signature.C); _binaryWriter.Write(signature.R); } Memory <byte> memory = _memoryStream.ToArray(); _block.RawData = memory; _block.BodyBytes = memory.Slice((int)pos, (int)bodyLength); //_block.NonHeaderBytes = memory.Slice((int)pos); byte[] hash = _transactionKeyHashCalculation.CalculateHash(_block.RawData.ToArray()); _block.Key = _transactionKeyIdentityKeyProvider.GetKey(hash); }
public void InitializeAccountBased(byte[] seed) { _isConfidential = false; _secretKey = seed; _publicSpendKey = _cryptoService.GetPublicKeyFromSeed(_secretKey); _publicSpendKeyHash = _defaultHashCalculation.CalculateHash(_publicSpendKey); }
public override Task <TransactionalBlockEssense> GetLastTransactionalBlock(TransactionalBlockRequest request, ServerCallContext context) { if (request.PublicKey == null) { throw new ArgumentNullException(nameof(request.PublicKey)); } byte[] keyBytes = request.PublicKey.ToByteArray(); if (keyBytes.Length != Globals.NODE_PUBLIC_KEY_SIZE) { throw new ArgumentException($"Public key size must be of {Globals.NODE_PUBLIC_KEY_SIZE} bytes"); } IKey key = _identityKeyProvider.GetKey(keyBytes); TransactionalBlockBase transactionalBlockBase = (TransactionalBlockBase)_transactionalDataService.GetLastBlock(key); TransactionalBlockEssense transactionalBlockEssense = new TransactionalBlockEssense { Height = transactionalBlockBase?.BlockHeight ?? 0, //TODO: need to reconsider hash calculation here since it is potential point of DoS attack Hash = ByteString.CopyFrom(transactionalBlockBase != null ? _hashCalculation.CalculateHash(transactionalBlockBase.RawData) : new byte[Globals.DEFAULT_HASH_SIZE]), UpToDateFunds = transactionalBlockBase?.UptodateFunds ?? 0 }; return(Task.FromResult(transactionalBlockEssense)); }
public BlockBase CreateRegisterBlock(TransactionalBlockBase transactionalBlock, byte[] target) { RegistryRegisterBlock registerBlock = new RegistryRegisterBlock { SyncBlockHeight = transactionalBlock.SyncBlockHeight, BlockHeight = transactionalBlock.BlockHeight, Nonce = transactionalBlock.Nonce, PowHash = transactionalBlock.PowHash, ReferencedPacketType = transactionalBlock.PacketType, ReferencedBlockType = transactionalBlock.BlockType, ReferencedTarget = target ?? new byte[32], ReferencedBodyHash = _hashCalculation.CalculateHash(transactionalBlock.RawData) }; return(registerBlock); }
public IKey GetKey() { byte[] hash = _transactionKeyHashCalculation.CalculateHash(_blockBase.RawData); IKey key = _transactionKeyIdentityKeyProvider.GetKey(hash); return(key); }
protected byte[] GetPowHash(byte[] hash, ulong nonce) { BigInteger bigInteger = new BigInteger(hash); bigInteger += nonce; byte[] hashNonce = bigInteger.ToByteArray(); byte[] powHash = _proofOfWorkCalculation.CalculateHash(hashNonce); return(powHash); }
public void DeferredBroadcast(ushort round, Action onBroadcasted) { if (_synchronizationContext == null) { return; } //if (_synchronizationContext.LastBlockDescriptor != null && _synchronizationContext.LastBlockDescriptor.BlockHeight - 1 > _lastLaunchedSyncBlockOrder) //{ // _syncProducingCancellation?.Cancel(); // _syncProducingCancellation = null; //} int delay = 1; if (_syncProducingCancellation != null) { delay = Math.Max((int)(60000 * round - (DateTime.Now - (_synchronizationContext.LastBlockDescriptor?.UpdateTime ?? DateTime.Now)).TotalMilliseconds), 0); } _syncProducingCancellation = new CancellationTokenSource(); //if (delay > 0) { Task.Delay(delay, _syncProducingCancellation.Token) .ContinueWith(t => { try { SynchronizationDescriptor synchronizationDescriptor = _synchronizationContext.LastBlockDescriptor; SynchronizationProducingBlock synchronizationBlock = new SynchronizationProducingBlock { SyncBlockHeight = synchronizationDescriptor?.BlockHeight ?? 0, BlockHeight = (synchronizationDescriptor?.BlockHeight ?? 0) + 1, ReportedTime = synchronizationDescriptor?.MedianTime.AddMinutes(1) ?? DateTime.Now, Round = round, HashPrev = synchronizationDescriptor?.Hash ?? new byte[Globals.DEFAULT_HASH_SIZE], PowHash = _proofOfWorkCalculation.CalculateHash(synchronizationDescriptor?.Hash ?? new byte[Globals.DEFAULT_HASH_SIZE]) }; using (ISerializer serializer = _serializersFactory.Create(synchronizationBlock)) { serializer.SerializeBody(); _nodeContext.SigningService.Sign(synchronizationBlock); _communicationService.PostMessage(_synchronizationGroupState.GetAllNeighbors(), serializer); _lastLaunchedSyncBlockOrder = synchronizationBlock.BlockHeight; } } finally { onBroadcasted.Invoke(); } }, _syncProducingCancellation.Token, TaskContinuationOptions.NotOnCanceled, TaskScheduler.Current); } }
public override async Task GetDeltaSyncBlocks(ByHeightRequest request, IServerStreamWriter <SyncBlockDescriptor> responseStream, ServerCallContext context) { IEnumerable <PacketBase> blocks = _syncChainDataService.GetAll(new BlockTypeLowHeightKey(BlockTypes.Synchronization_ConfirmedBlock, request.Height)); foreach (PacketBase block in blocks) { await responseStream.WriteAsync(new SyncBlockDescriptor { Height = ((SynchronizationConfirmedBlock)block).SyncBlockHeight, Hash = ByteString.CopyFrom(_hashCalculation.CalculateHash(((SynchronizationConfirmedBlock)block).RawData)) //TODO: !!! need to change hash calculation in place to reading from database, otherwise DoS attack is allowed }); } }
private static SortedList <ushort, IKey> GetTransactionHeaderKeys(IHashCalculation hashCalculationTransactionKey, SortedList <ushort, ITransactionRegistryBlock> transactionHeaders) { SortedList <ushort, IKey> transactionHeaderKeys = new SortedList <ushort, IKey>(transactionHeaders.Count); foreach (ushort order in transactionHeaders.Keys) { ITransactionRegistryBlock registryRegisterBlock = transactionHeaders[order]; byte[] hashBytes = hashCalculationTransactionKey.CalculateHash(registryRegisterBlock.RawData); IKey key = new Key16(hashBytes); transactionHeaderKeys.Add(order, key); } return(transactionHeaderKeys); }
public void StoreIncomingTransactionalBlock(ulong syncBlockHeight, ulong combinedRegistryBlockHeight, ulong blockHeight, ushort blockType, Span <byte> owner, ulong tagId, Span <byte> content, Span <byte> target) { TransactionalIncomingBlock transactionalIncomingBlock = new TransactionalIncomingBlock { SyncBlockHeight = syncBlockHeight, CombinedRegistryBlockHeight = combinedRegistryBlockHeight, Height = blockHeight, BlockType = blockType, TagId = tagId, Content = content.ToArray(), Owner = GetOrAddIdentity(owner), Target = GetOrAddIdentity(target), ThisBlockHash = GetOrAddBlockHash(_hashCalculation.CalculateHash(content.ToArray())), IsVerified = true, IsCorrect = true, IsTransition = false }; lock (_sync) { _dataContext.TransactionalIncomingBlocks.Add(transactionalIncomingBlock); _dataContext.SaveChanges(); } }
private void SendTransactionsBlocks(Tuple <RegistryFullBlock, RegistryShortBlock> tuple) { RegistryFullBlock transactionsFullBlock = tuple.Item1; RegistryShortBlock transactionsShortBlock = tuple.Item2; ISerializer fullBlockSerializer = _signatureSupportSerializersFactory.Create(transactionsFullBlock); ISerializer shortBlockSerializer = _signatureSupportSerializersFactory.Create(transactionsShortBlock); shortBlockSerializer.FillBodyAndRowBytes(); transactionsFullBlock.ShortBlockHash = _hashCalculation.CalculateHash(transactionsShortBlock.RawData); _logger.Debug($"Sending FullBlock with {transactionsFullBlock.TransactionHeaders.Count} transactions and ShortBlock with {transactionsShortBlock.TransactionHeaderHashes.Count} hashes at round {transactionsFullBlock.BlockHeight}"); _tcpCommunicationService.PostMessage(_registryGroupState.SyncLayerNode, fullBlockSerializer); _tcpCommunicationService.PostMessage(_registryGroupState.GetAllNeighbors(), shortBlockSerializer); }
public IActionResult CalculateFileHash() { var file = Request.Form.Files[0]; if (file.Length > 0) { using var stream = new MemoryStream(); file.CopyTo(stream); byte[] hash = _hashCalculation.CalculateHash(stream.ToArray()); return(Ok(new { documentName = file.FileName, hash = hash.ToHexString() })); } else { return(BadRequest()); } }
private void SendTransactionsBlocks(RegistryFullBlock transactionsFullBlock, RegistryShortBlock transactionsShortBlock) { ISerializer fullBlockSerializer = _serializersFactory.Create(transactionsFullBlock); ISerializer shortBlockSerializer = _serializersFactory.Create(transactionsShortBlock); shortBlockSerializer.SerializeBody(); _nodeContext.SigningService.Sign(transactionsShortBlock); shortBlockSerializer.SerializeFully(); transactionsFullBlock.ShortBlockHash = _hashCalculation.CalculateHash(transactionsShortBlock.RawData); fullBlockSerializer.SerializeBody(); _nodeContext.SigningService.Sign(transactionsFullBlock); _logger.Debug($"Sending FullBlock with {transactionsFullBlock.StateWitnesses.Length + transactionsFullBlock.UtxoWitnesses.Length} transactions and ShortBlock with {transactionsShortBlock.WitnessStateKeys.Length + transactionsShortBlock.WitnessUtxoKeys.Length} keys at round {transactionsFullBlock.BlockHeight}"); _tcpCommunicationService.PostMessage(_registryGroupState.SyncLayerNode, fullBlockSerializer); _tcpCommunicationService.PostMessage(_registryGroupState.GetAllNeighbors(), shortBlockSerializer); }
private RegistryFullBlock ProduceTransactionsFullBlock(SortedList <ushort, RegistryRegisterBlock> transactionStateWitnesses, SortedList <ushort, RegistryRegisterUtxoConfidential> transactionUtxoWitnesses, SynchronizationDescriptor synchronizationDescriptor, int round) { ulong syncBlockHeight = synchronizationDescriptor?.BlockHeight ?? 0; byte[] hash = synchronizationDescriptor?.Hash ?? new byte[Globals.DEFAULT_HASH_SIZE]; byte[] pow = _powCalculation.CalculateHash(hash); _logger.Debug($"ProduceTransactionsFullBlock synchronizationDescriptor[{syncBlockHeight}].Hash = {hash.ToHexString()}; POW = {pow.ToHexString()}"); RegistryFullBlock transactionsFullBlock = new RegistryFullBlock { SyncBlockHeight = syncBlockHeight, PowHash = pow, BlockHeight = (ulong)(round * _registryConfiguration.TotalNodes + _registryConfiguration.Position + 1), StateWitnesses = transactionStateWitnesses.Select(t => t.Value).ToArray(), UtxoWitnesses = transactionUtxoWitnesses.Select(t => t.Value).ToArray() }; return(transactionsFullBlock); }
public void AddCandidateBlock(RegistryFullBlock transactionsFullBlock) { if (transactionsFullBlock == null) { throw new ArgumentNullException(nameof(transactionsFullBlock)); } _logger.Debug($"Adding candidate block of round {transactionsFullBlock.BlockHeight} with {transactionsFullBlock.StateWitnesses.Length + transactionsFullBlock.UtxoWitnesses.Length} transactions"); byte[] hash = _defaultTransactionHashCalculation.CalculateHash(transactionsFullBlock.RawData); if (_registryCombinedBlocks.Any(b => b.BlockHashes.Any(h => h.Equals32(hash)))) { return; } lock (_registryBlocks) { _registryBlocks.Add(transactionsFullBlock); } }
private void FinalizeTransaction(long pos, long bodyLength) { _memoryStream.Seek(pos, SeekOrigin.Begin); byte[] body = _binaryReader.ReadBytes((int)bodyLength); byte[] signature = _cryptoService.Sign(body); byte[] signer = _cryptoService.PublicKey.Value.ToArray(); _binaryWriter.Write(signature); _binaryWriter.Write(_cryptoService.PublicKey.Value.ToArray()); Memory <byte> memory = _memoryStream.ToArray(); _block.Signature = memory.Slice(memory.Length - signature.Length - signer.Length, signature.Length); _block.Signer = _cryptoService.PublicKey; _block.RawData = memory; _block.BodyBytes = memory.Slice((int)pos, (int)bodyLength); //_block.NonHeaderBytes = memory.Slice((int)pos); byte[] hash = _transactionKeyHashCalculation.CalculateHash(_block.RawData.ToArray()); _block.Key = _transactionKeyIdentityKeyProvider.GetKey(hash); }
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); }
private RegistryFullBlock ProduceTransactionsFullBlock(SortedList <ushort, ITransactionRegistryBlock> transactionRegisterBlocks) { SynchronizationDescriptor synchronizationDescriptor = _synchronizationContext.LastBlockDescriptor; ulong syncBlockHeight = synchronizationDescriptor?.BlockHeight ?? 0; byte[] hash = synchronizationDescriptor?.Hash ?? new byte[Globals.DEFAULT_HASH_SIZE]; byte[] pow = _powCalculation.CalculateHash(hash); _logger.Debug($"ProduceTransactionsFullBlock synchronizationDescriptor[{syncBlockHeight}].Hash = {hash.ToHexString()}; POW = {pow.ToHexString()}"); RegistryFullBlock transactionsFullBlock = new RegistryFullBlock { SyncBlockHeight = syncBlockHeight, PowHash = pow, BlockHeight = (ulong)_registryGroupState.Round, TransactionHeaders = transactionRegisterBlocks }; //_nodeCountersService.RegistryBlockLastSize.RawValue = transactionRegisterBlocks.Count; //_nodeCountersService.RegistryBlockLastSize.NextSample(); return(transactionsFullBlock); }
public void Add(PacketBase item) { if (item is RegistryFullBlock block) { //TODO: shardId must be taken from somewhere DataAccessService.Instance.AddRegistryFullBlock(block.SyncBlockHeight, block.BlockHeight, block.StateWitnesses.Length + block.UtxoWitnesses.Length, block.RawData.ToArray(), _defaultHashCalculation.CalculateHash(block.RawData)); } }
private void ProcessBlocks(CancellationToken ct) { foreach (SynchronizationConfirmedBlock synchronizationBlock in _synchronizationBlocks.GetConsumingEnumerable(ct)) { if ((_synchronizationContext.LastBlockDescriptor?.BlockHeight ?? 0) >= synchronizationBlock.BlockHeight) { continue; } _synchronizationContext.UpdateLastSyncBlockDescriptor(new SynchronizationDescriptor(synchronizationBlock.BlockHeight, _hashCalculation.CalculateHash(synchronizationBlock.RawData), synchronizationBlock.ReportedTime, DateTime.Now, synchronizationBlock.Round)); _chainDataService.Add(synchronizationBlock); IPacketProvider packetProvider = _rawPacketProvidersFactory.Create(synchronizationBlock); _communicationService.PostMessage(_neighborhoodState.GetAllNeighbors(), packetProvider); } }
protected override void InitializeInner() { _logger.Info("Starting Synchronization Initializer"); try { SynchronizationConfirmedBlock synchronizationConfirmedBlock = (SynchronizationConfirmedBlock)_chainDataService.GetAllLastBlocksByType(BlockTypes.Synchronization_ConfirmedBlock).Single(); if (synchronizationConfirmedBlock != null) { _synchronizationContext.UpdateLastSyncBlockDescriptor(new SynchronizationDescriptor(synchronizationConfirmedBlock.BlockHeight, _hashCalculation.CalculateHash(synchronizationConfirmedBlock.RawData), synchronizationConfirmedBlock.ReportedTime, DateTime.Now, synchronizationConfirmedBlock.Round)); } SynchronizationRegistryCombinedBlock combinedBlock = (SynchronizationRegistryCombinedBlock)_chainDataService.GetAllLastBlocksByType(BlockTypes.Synchronization_RegistryCombinationBlock).Single(); if (combinedBlock != null) { _synchronizationContext.LastRegistrationCombinedBlockHeight = combinedBlock.BlockHeight; } } finally { _logger.Info("Synchronization Initializer completed"); } }
public void Add(BlockBase item) { if (item is RegistryFullBlock block) { //TODO: shardId must be taken from somewhere DataAccessService.Instance.AddRegistryFullBlock(block.SyncBlockHeight, block.BlockHeight, block.TransactionHeaders?.Count ?? 0, block.RawData.ToArray(), _defaultHashCalculation.CalculateHash(block.RawData)); } }
public override void Start() { byte[] seedTarget = GetRandomSeed(); byte[] targetKeyBytes = Ed25519.PublicKeyFromSeed(seedTarget); byte[] targetHash = CryptoHelper.ComputeHash(targetKeyBytes); //IHash hash = HashFactory.Crypto.CreateTiger_4_192(); //List<byte[]> seeds = new List<byte[]>(); //List<byte[]> hashes = new List<byte[]>(); //byte[] seed1 = GetRandomSeed(); //BigInteger bigInteger1 = new BigInteger(seed1); //bool found = false; //Stopwatch stopwatch1 = Stopwatch.StartNew(); //for (int i = 0; i < 10000000; i++) //{ // bigInteger1 += 1; // byte[] calc = hash.ComputeBytes(bigInteger1.ToByteArray()).GetBytes(); // if(calc[0] == 0 && calc[1] == 0 && calc[2] == 0 ) // { // found = true; // break; // } //} //long elapsed = stopwatch1.ElapsedMilliseconds; ulong index = _synchronizationContext.LastBlockDescriptor?.BlockHeight ?? 0; byte[] syncHash = _synchronizationContext.LastBlockDescriptor?.Hash ?? new byte[Globals.DEFAULT_HASH_SIZE]; BigInteger bigInteger = new BigInteger(syncHash); ulong nonce = 1234; bigInteger += nonce; byte[] hashNonce = bigInteger.ToByteArray(); byte[] powHash = _proofOfWorkCalculation.CalculateHash(hashNonce); ulong count = 0; Stopwatch stopwatch = Stopwatch.StartNew(); do { RegistryRegisterBlock transactionRegisterBlock = new RegistryRegisterBlock { SyncBlockHeight = index, BlockHeight = count, Signer = _key, Nonce = 1234, PowHash = powHash, ReferencedPacketType = PacketType.Transactional, ReferencedBlockType = BlockTypes.Transaction_TransferFunds, ReferencedBodyHash = new byte[Globals.DEFAULT_HASH_SIZE], ReferencedTarget = targetHash }; ISerializer signatureSupportSerializer = _serializersFactory.Create(transactionRegisterBlock); _communicationService.PostMessage(_keyTarget, signatureSupportSerializer); _loadCountersService.SentMessages.Increment(); count++; } while (!_cancellationToken.IsCancellationRequested); }
public byte[] ComputeTransactionKey(byte[] bytes) => _transactionKeyCalculation.CalculateHash(bytes);
public void Initialize(CancellationToken cancellationToken) { if (_isInitialized) { return; } lock (_sync) { if (_isInitialized) { return; } _logger.Info("Initialization Started"); try { _communicationService.Init(new Network.Communication.SocketSettings(_communicationConfiguration.MaxConnections, _communicationConfiguration.ReceiveBufferSize, _communicationConfiguration.ListeningPort, System.Net.Sockets.AddressFamily.InterNetwork)); if (_dataAccessService.GetLastSyncBlock(out ulong syncBlockHeight, out byte[] syncBlockHash)) { _lastSyncDescriptor = new Entities.SyncBlockDescriptor(syncBlockHeight, syncBlockHash); } else { _lastSyncDescriptor = new Entities.SyncBlockDescriptor(0, new byte[32]); } if (_dataAccessService.GetLastRegistryCombinedBlock(out ulong combinedBlockHeight, out byte[] combinedBlockContent)) { _lastCombinedBlockDescriptor = new RegistryCombinedBlockDescriptor(combinedBlockHeight, combinedBlockContent, _defaultHashCalculation.CalculateHash(combinedBlockContent)); } else { _lastCombinedBlockDescriptor = new RegistryCombinedBlockDescriptor(0, null, new byte[32]); } foreach (string nodeDescriptor in _synchronizerConfiguration.Nodes) { string[] pair = nodeDescriptor.Split(':'); byte[] keyBytes = pair[0].HexStringToByteArray(); IKey nodeKey = _identityKeyProvider.GetKey(keyBytes); IPAddress ipAddress = IPAddress.Parse(pair[1]); NodeAddress nodeAddress = new NodeAddress(nodeKey, ipAddress); _nodesResolutionService.UpdateSingleNode(nodeAddress); } IKey syncNodeKey = _identityKeyProvider.GetKey(_synchronizerConfiguration.SyncNodeKey.HexStringToByteArray()); _registryNodeKey = _identityKeyProvider.GetKey(_synchronizerConfiguration.RegistryNodeKey.HexStringToByteArray()); _storageNodeKey = _identityKeyProvider.GetKey(_synchronizerConfiguration.StorageNodeKey.HexStringToByteArray()); IPAddress syncNodeAddress = _nodesResolutionService.ResolveNodeAddress(syncNodeKey); IPAddress storageNodeAddress = _nodesResolutionService.ResolveNodeAddress(_storageNodeKey); Channel syncLayerChannel = new Channel(syncNodeAddress.ToString(), 5050, ChannelCredentials.Insecure); Channel storageLayerChannel = new Channel(storageNodeAddress.ToString(), 5050, ChannelCredentials.Insecure); _syncLayerSyncManagerClient = new SyncManager.SyncManagerClient(syncLayerChannel); _storageLayerSyncManagerClient = new TransactionalChainManager.TransactionalChainManagerClient(storageLayerChannel); _cancellationToken = cancellationToken; _isInitialized = true; _logger.Info($"Last Sync Block Height = {_lastSyncDescriptor.Height}; Last Registry Combined Block Height = {_lastCombinedBlockDescriptor.Height}"); } catch (Exception ex) { _logger.Error("Failure during initializtion", ex); } finally { _logger.Info("Initialization completed"); } } }
public RegistryShortBlock GetRegistryShortBlockByHash(ulong syncBlockHeight, ulong round, byte[] hash) { if (!_transactionsShortBlocks.ContainsKey(syncBlockHeight)) { return(null); } if (!_transactionsShortBlocks[syncBlockHeight].ContainsKey(round)) { return(null); } RegistryShortBlock registryShortBlock = _transactionsShortBlocks[syncBlockHeight][round].FirstOrDefault(s => _hashCalculation.CalculateHash(s.RawData).Equals32(hash)); return(registryShortBlock); }
private bool CheckSyncPOW(SyncedBlockBase syncedBlockBase) { ulong syncBlockHeight = syncedBlockBase.SyncBlockHeight; uint nonce = syncedBlockBase.Nonce; byte[] powHash = syncedBlockBase.PowHash; byte[] baseHash; byte[] baseSyncHash; if (syncedBlockBase.PacketType != PacketType.Synchronization) { //TODO: make difficulty check dynamic //if (powHash[0] != 0 || powHash[1] != 0) //{ // return false; //} BigInteger bigInteger; baseSyncHash = new byte[Globals.DEFAULT_HASH_SIZE + 1]; // Adding extra 0 byte for avoiding negative values of BigInteger lock (_synchronizationContext) { byte[] buf; if (_synchronizationContext.LastBlockDescriptor != null || _synchronizationContext.PrevBlockDescriptor != null) { buf = (syncBlockHeight == _synchronizationContext.LastBlockDescriptor?.BlockHeight) ? _synchronizationContext.LastBlockDescriptor.Hash : _synchronizationContext.PrevBlockDescriptor.Hash; } else { _log.Warning("CheckSyncPOW - BOTH LastBlockDescriptor and PrevBlockDescriptor are NULL"); buf = new byte[Globals.DEFAULT_HASH_SIZE]; } Array.Copy(buf, 0, baseSyncHash, 0, buf.Length); } bigInteger = new BigInteger(baseSyncHash); bigInteger += nonce; baseHash = bigInteger.ToByteArray().Take(Globals.DEFAULT_HASH_SIZE).ToArray(); } else { lock (_synchronizationContext) { if (_synchronizationContext.LastBlockDescriptor == null) { baseSyncHash = new byte[Globals.DEFAULT_HASH_SIZE]; } else { baseSyncHash = (syncBlockHeight == _synchronizationContext.LastBlockDescriptor.BlockHeight) ? _synchronizationContext.LastBlockDescriptor.Hash : _synchronizationContext.PrevBlockDescriptor.Hash; } } baseHash = baseSyncHash; } byte[] computedHash = _proofOfWorkCalculation.CalculateHash(baseHash); if (!computedHash.Equals24(powHash)) { _log.Error($"Computed HASH differs from obtained one. PacketType is {syncedBlockBase.PacketType}, BlockType is {syncedBlockBase.BlockType}. Reported SyncBlockHeight is {syncedBlockBase.SyncBlockHeight}, Nonce is {syncedBlockBase.Nonce}, POW is {syncedBlockBase.PowHash.ToHexString()}. Hash of SyncBlock is {baseSyncHash.ToHexString()}, after adding Nonce is {baseHash.ToHexString()}, computed POW Hash is {computedHash.ToHexString()}"); return(false); } return(true); }