private async Task SetChainBlockIndexAsync(long blockHeight, Hash blockHash) { await _chainBlockIndexes.SetAsync(ChainId.ToStorageKey() + KernelConstants.StorageKeySeparator + blockHeight.ToStorageKey(), new ChainBlockIndex() { BlockHash = blockHash }); }
private async Task SetChainBlockIndexesAsync(IDictionary <long, Hash> blockIndexes) { var prefix = ChainId.ToStorageKey() + KernelConstants.StorageKeySeparator; await _chainBlockIndexes.SetAllAsync(blockIndexes.ToDictionary(d => prefix + d.Key.ToStorageKey(), d => new ChainBlockIndex { BlockHash = d.Value })); }
public override int GetHashCode() { int hash = 1; if (Hash.Length != 0) { hash ^= Hash.GetHashCode(); } if (From.Length != 0) { hash ^= From.GetHashCode(); } if (To.Length != 0) { hash ^= To.GetHashCode(); } if (Value.Length != 0) { hash ^= Value.GetHashCode(); } if (Nonce != 0UL) { hash ^= Nonce.GetHashCode(); } if (Timestamp != 0L) { hash ^= Timestamp.GetHashCode(); } if (data_ != null) { hash ^= Data.GetHashCode(); } if (ChainId != 0) { hash ^= ChainId.GetHashCode(); } if (GasPrice.Length != 0) { hash ^= GasPrice.GetHashCode(); } if (GasLimit.Length != 0) { hash ^= GasLimit.GetHashCode(); } if (Alg != 0) { hash ^= Alg.GetHashCode(); } if (Sign.Length != 0) { hash ^= Sign.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
// ReSharper restore StringLiteralTypo public async Task ExecuteAsync__Should_Calculate_InCorrect_Checksum( string addressWithChecksum) { var chainId = new ChainId(42); var strategy = new RootstockAddChecksumStrategy(chainId, HashCalculator.Keccak256); var rawAddress = addressWithChecksum.ToLowerInvariant(); (await strategy.ExecuteAsync(rawAddress)) .Should() .NotBe(addressWithChecksum); }
private async Task SetChainBlockLinksAsync(IList <ChainBlockLink> chainBlockLinks) { var prefix = ChainId.ToStorageKey() + KernelConstants.StorageKeySeparator; await _chainBlockLinks.SetAllAsync(chainBlockLinks.ToDictionary(l => prefix + l.BlockHash.ToStorageKey(), l => l)); foreach (var chainBlockLink in chainBlockLinks) { _chainBlockLinkCacheProvider.SetChainBlockLink(chainBlockLink); } }
public async Task InitNetworkProtocol() { var(getFromAPi, _) = _api.ForNetwork; INetworkConfig networkConfig = _api.Config <INetworkConfig>(); IInitConfig initConfig = _api.Config <IInitConfig>(); if (_isOn) { string instanceId = $"{_ethStatsConfig.Name}-{Keccak.Compute(getFromAPi.Enode!.Info)}"; if (_logger.IsInfo) { _logger.Info($"Initializing ETH Stats for the instance: {instanceId}, server: {_ethStatsConfig.Server}"); } MessageSender sender = new(instanceId, _api.LogManager); const int reconnectionInterval = 5000; const string api = "no"; const string client = "0.1.1"; const bool canUpdateHistory = false; string node = ClientVersion.Description; int port = networkConfig.P2PPort; string network = _api.SpecProvider !.ChainId.ToString(); string protocol = $"{P2PProtocolInfoProvider.DefaultCapabilitiesToString()}"; _ethStatsClient = new EthStatsClient( _ethStatsConfig.Server, reconnectionInterval, sender, _api.LogManager); _ethStatsIntegration = new EthStatsIntegration( _ethStatsConfig.Name !, node, port, network, protocol, api, client, _ethStatsConfig.Contact !, canUpdateHistory, _ethStatsConfig.Secret !, _ethStatsClient, sender, getFromAPi.TxPool, getFromAPi.BlockTree, getFromAPi.PeerManager, getFromAPi.GasPriceOracle, getFromAPi.EthSyncingInfo !, initConfig.IsMining, getFromAPi.LogManager); await _ethStatsIntegration.InitAsync(); } }
public MailMessage(MimeMessage message, int folder = 1, bool unread = false, string chainId = "", string streamId = "") { if (message == null) { throw new ArgumentNullException("message"); } Date = IsDateCorrect(message.Date.UtcDateTime) ? message.Date.UtcDateTime : DateTime.UtcNow; MimeMessageId = (string.IsNullOrEmpty(message.MessageId) ? MailUtil.CreateMessageId() : message.MessageId) .Trim(new[] { '<', '>' }); ChainId = string.IsNullOrEmpty(chainId) ? MimeMessageId : chainId; MimeReplyToId = ChainId.Equals(MimeMessageId) ? null : message.InReplyTo.Trim('<', '>'); ReplyTo = message.ReplyTo.ToString(); From = message.From.ToString(); FromEmail = message.From != null && message.From.Mailboxes != null && message.From.Mailboxes.Any() ? message.From.Mailboxes.First().Address : ""; ToList = message.To.Mailboxes.Select(s => new MailAddress(s.Address, s.Name)).ToList(); To = string.Join(", ", message.To.Mailboxes.Select(s => s.ToString())); CcList = message.Cc.Mailboxes.Select(s => new MailAddress(s.Address, s.Name)).ToList(); Cc = string.Join(", ", message.Cc.Mailboxes.Select(s => s.ToString())); Bcc = string.Join(", ", message.Bcc.Mailboxes.Select(s => s.ToString())); Subject = message.Subject ?? string.Empty; Important = message.Importance == MessageImportance.High || message.Priority == MessagePriority.Urgent; TextBodyOnly = false; Introduction = ""; Attachments = new List <MailAttachment>(); HtmlBodyStream = new MemoryStream(); ExtractMainParts(message); Size = HtmlBodyStream.Length > 0 ? HtmlBodyStream.Length : HtmlBody.Length; HeaderFieldNames = new NameValueCollection(); message.Headers .ToList() .ForEach(h => HeaderFieldNames.Add(h.Field, h.Value)); Folder = folder; IsNew = unread; StreamId = string.IsNullOrEmpty(streamId) ? MailUtil.CreateStreamId() : streamId; LoadCalendarInfo(message); }
private byte[] GetSignatureData() { var rawBlock = new BlockHeader { ChainId = ChainId?.Clone(), Index = Index, PreviousBlockHash = PreviousBlockHash?.Clone(), MerkleTreeRootOfTransactions = MerkleTreeRootOfTransactions?.Clone(), MerkleTreeRootOfWorldState = MerkleTreeRootOfWorldState?.Clone(), Bloom = Bloom, SideChainBlockHeadersRoot = SideChainBlockHeadersRoot?.Clone(), SideChainTransactionsRoot = MerkleTreeRootOfTransactions?.Clone() }; if (Index > GlobalConfig.GenesisBlockHeight) { rawBlock.Time = Time?.Clone(); } return(rawBlock.ToByteArray()); }
public async Task <Chain> CreateAsync(Hash genesisBlock) { var chain = await _chains.GetAsync(ChainId.ToStorageKey()); if (chain != null) { throw new InvalidOperationException("chain already exists"); } chain = new Chain() { Id = ChainId, LongestChainHeight = AElfConstants.GenesisBlockHeight, LongestChainHash = genesisBlock, BestChainHeight = AElfConstants.GenesisBlockHeight, BestChainHash = genesisBlock, GenesisBlockHash = genesisBlock, LastIrreversibleBlockHash = genesisBlock, LastIrreversibleBlockHeight = AElfConstants.GenesisBlockHeight, Branches = { { genesisBlock.ToStorageKey(), AElfConstants.GenesisBlockHeight } } }; await SetChainBlockLinkAsync(new ChainBlockLink() { BlockHash = genesisBlock, Height = AElfConstants.GenesisBlockHeight, PreviousBlockHash = Hash.Empty, IsLinked = true, IsIrreversibleBlock = true }); await SetChainBlockIndexAsync(AElfConstants.GenesisBlockHeight, genesisBlock); await _chains.SetAsync(ChainId.ToStorageKey(), chain); return(chain); }
private async Task <bool> ValidateProtocol(string protocol, Peer peer, ProtocolInitializedEventArgs eventArgs) { //TODO add validation for clientId - e.g. get only ethereumJ clients switch (protocol) { case Protocol.P2P: var args = (P2PProtocolInitializedEventArgs)eventArgs; if (args.P2PVersion < 4 || args.P2PVersion > 5) { if (_logger.IsInfoEnabled) { _logger.Info($"Initiating disconnect with peer: {peer.Node.Id}, incorrect P2PVersion: {args.P2PVersion}"); } await peer.Session.InitiateDisconnectAsync(DisconnectReason.IncompatibleP2PVersion); return(false); } if (!args.Capabilities.Any(x => x.ProtocolCode == Protocol.Eth && x.Version == 62)) { if (_logger.IsInfoEnabled) { _logger.Info($"Initiating disconnect with peer: {peer.Node.Id}, no Eth62 capability, supported capabilities: [{string.Join(",", args.Capabilities.Select(x => $"{x.ProtocolCode}v{x.Version}"))}]"); } //TODO confirm disconnect reason await peer.Session.InitiateDisconnectAsync(DisconnectReason.Other); return(false); } //if (args.ClientId.Contains("Geth") || args.ClientId.Contains("Parity") || args.ClientId.Contains("Gnekonium")) //{ // if (_logger.IsInfoEnabled) // { // _logger.Info($"Initiating disconnect, rejecting client: {args.ClientId}, id: {peer.Node.Id}"); // } // await peer.Session.InitiateDisconnectAsync(DisconnectReason.Other); // return false; //} break; case Protocol.Eth: var ethArgs = (Eth62ProtocolInitializedEventArgs)eventArgs; if (ethArgs.ChainId != _synchronizationManager.ChainId) { if (_logger.IsInfoEnabled) { _logger.Info($"Initiating disconnect with peer: {peer.Node.Id}, different chainId: {ChainId.GetChainName((int)ethArgs.ChainId)}, our chainId: {ChainId.GetChainName(_synchronizationManager.ChainId)}"); } //TODO confirm disconnect reason await peer.Session.InitiateDisconnectAsync(DisconnectReason.Other); return(false); } if (ethArgs.GenesisHash != _synchronizationManager.Genesis.Hash) { if (_logger.IsInfoEnabled) { _logger.Info($"Initiating disconnect with peer: {peer.Node.Id}, different genesis hash: {ethArgs.GenesisHash}, our: {_synchronizationManager.Genesis.Hash}"); } //TODO confirm disconnect reason await peer.Session.InitiateDisconnectAsync(DisconnectReason.Other); return(false); } break; } return(true); }
public override string ToString() { return($"{ChainId.ToString().Substring(30)}-{Id}"); }
public override bool Equals(object obj) { Store storeObj = (Store)obj; return(StoreId.Equals(storeObj.StoreId) && ChainId.Equals(storeObj.ChainId)); }
public async Task SetChainBlockLinkAsync(ChainBlockLink chainBlockLink) { await _chainBlockLinks.SetAsync(ChainId.ToStorageKey() + KernelConstants.StorageKeySeparator + chainBlockLink.BlockHash.ToStorageKey(), chainBlockLink); _chainBlockLinkCacheProvider.SetChainBlockLink(chainBlockLink); }
private async Task <List <ChainBlockLink> > GetChainBlockLinksAsync(IList <string> blockHashes) { var prefix = ChainId.ToStorageKey() + KernelConstants.StorageKeySeparator; return(await _chainBlockLinks.GetAllAsync(blockHashes.Select(h => prefix + h).ToList())); }
public void DumpStats(IReadOnlyCollection <INodeStats> nodes, bool logEventDetails) { var eventTypes = Enum.GetValues(typeof(NodeStatsEventType)).OfType <NodeStatsEventType>().Where(x => !x.ToString().Contains("Discovery")) .OrderBy(x => x).ToArray(); var eventStats = eventTypes.Select(x => new { EventType = x.ToString(), Count = nodes.Count(y => y.DidEventHappen(x)) }).ToArray(); var chains = nodes.Where(x => x.EthNodeDetails != null).GroupBy(x => x.EthNodeDetails.ChainId).Select( x => new { ChainName = ChainId.GetChainName((int)x.Key), Count = x.Count() }).ToArray(); var clients = nodes.Where(x => x.P2PNodeDetails != null).Select(x => x.P2PNodeDetails.ClientId).GroupBy(x => x).Select( x => new { ClientId = x.Key, Count = x.Count() }).ToArray(); var remoteDisconnect = nodes.Count(x => x.EventHistory.Any(y => y.DisconnectDetails != null && y.DisconnectDetails.DisconnectType == DisconnectType.Remote)); var sb = new StringBuilder(); sb.AppendLine($"Session stats | {DateTime.Now.ToString(DetailedTimeDateFormat)} | Peers: {nodes.Count}"); sb.AppendLine($"Peers count with each EVENT:{Environment.NewLine}" + $"{string.Join(Environment.NewLine, eventStats.Select(x => $"{x.EventType.ToString()}:{x.Count}"))}{Environment.NewLine}" + $"Remote disconnect: {remoteDisconnect}{Environment.NewLine}{Environment.NewLine}" + $"CHAINS: {Environment.NewLine}" + $"{string.Join(Environment.NewLine, chains.Select(x => $"{x.ChainName}:{x.Count}"))}{Environment.NewLine}{Environment.NewLine}" + $"CLIENTS:{Environment.NewLine}" + $"{string.Join(Environment.NewLine, clients.Select(x => $"{x.ClientId}:{x.Count}"))}{Environment.NewLine}"); var peersWithLatencyStats = nodes.Where(x => x.LatencyHistory.Any()).ToArray(); if (peersWithLatencyStats.Any()) { var latencyLog = GetLatencyComparisonLog(peersWithLatencyStats); sb.AppendLine(latencyLog); } if (_statsConfig.CaptureNodeStatsEventHistory && logEventDetails) { sb.AppendLine($"All peers ({nodes.Count}):"); sb.AppendLine($"{string.Join(Environment.NewLine, nodes.Select(GetNodeLog))}{Environment.NewLine}"); var peersWithEvents = nodes.Where(x => x.EventHistory.Any(y => y.EventType != NodeStatsEventType.NodeDiscovered)).ToArray(); sb.AppendLine($"Logging {peersWithEvents.Length} peers log event histories"); foreach (var peer in peersWithEvents) { LogPeerEventHistory(peer); } } else { sb.AppendLine($"Detailed session log disabled, CaptureNodeStatsEventHistory: {_statsConfig.CaptureNodeStatsEventHistory}, logEventDetails: {logEventDetails}"); } sb.AppendLine(); var generalFilePath = Path.Combine(_eventLogsDirectoryPath, "generalStats.log"); var content = sb.ToString(); File.AppendAllText(generalFilePath, content); if (_logger.IsTrace) { _logger.Trace(content); } }
public override string ToString() { return($"/{ChainId.DumpHex()}/{ContractAddress.DumpHex()}/{string.Join("/", Path)}"); }
public bool DisconnectOnInvalid(string protocol, ISession session, ProtocolInitializedEventArgs eventArgs) { switch (protocol) { case Protocol.P2P: var args = (P2PProtocolInitializedEventArgs)eventArgs; if (!ValidateP2PVersion(args.P2PVersion)) { if (_logger.IsTrace) { _logger.Trace($"Initiating disconnect with peer: {session.RemoteNodeId}, incorrect P2PVersion: {args.P2PVersion}"); } _nodeStatsManager.ReportFailedValidation(session.Node, CompatibilityValidationType.P2PVersion); Disconnect(session, DisconnectReason.IncompatibleP2PVersion); return(false); } if (!ValidateCapabilities(args.Capabilities)) { if (_logger.IsTrace) { _logger.Trace($"Initiating disconnect with peer: {session.RemoteNodeId}, no Eth62 capability, supported capabilities: [{string.Join(",", args.Capabilities.Select(x => $"{x.ProtocolCode}v{x.Version}"))}]"); } _nodeStatsManager.ReportFailedValidation(session.Node, CompatibilityValidationType.Capabilities); Disconnect(session, DisconnectReason.UselessPeer); return(false); } break; case Protocol.Eth: var ethArgs = (EthProtocolInitializedEventArgs)eventArgs; if (!ValidateChainId(ethArgs.ChainId)) { if (_logger.IsTrace) { _logger.Trace($"Initiating disconnect with peer: {session.RemoteNodeId}, different chainId: {ChainId.GetChainName((int) ethArgs.ChainId)}, our chainId: {ChainId.GetChainName(_blockTree.ChainId)}"); } _nodeStatsManager.ReportFailedValidation(session.Node, CompatibilityValidationType.ChainId); Disconnect(session, DisconnectReason.UselessPeer); return(false); } if (ethArgs.GenesisHash != _blockTree.Genesis.Hash) { if (_logger.IsTrace) { _logger.Trace($"Initiating disconnect with peer: {session.RemoteNodeId}, different genesis hash: {ethArgs.GenesisHash}, our: {_blockTree.Genesis.Hash}"); } _nodeStatsManager.ReportFailedValidation(session.Node, CompatibilityValidationType.DifferentGenesis); Disconnect(session, DisconnectReason.BreachOfProtocol); return(false); } break; } return(true); }
public DeltaTaskData() { ChainId = Guid.NewGuid(); FieldWithCommonName = new[] { ChainId.GetHashCode() }; }
public override int GetHashCode() { return(this.Chain.Protein.GetHashCode() + ChainId.GetHashCode() + ResidueSeq.GetHashCode()); }
public AlphaTaskData() { ChainId = Guid.NewGuid(); FieldWithCommonName = ChainId.GetHashCode(); }
public string ToJsonHex() { var data = "['" + Nonce.ToHex() + "','" + GasPrice.ToHex() + "','" + GasLimit.ToHex() + "','" + ReceiveAddress.ToHex() + "','" + Value.ToHex() + "','" + ToHex(Data) + "','" + ChainId.ToHex() + "','" + RHash.ToHex() + "','" + SHash.ToHex() + "'"; if (Signature != null) { data = data + ", '" + Signature.V.ToHex() + "', '" + Signature.R.ToHex() + "', '" + Signature.S.ToHex() + "'"; } return(data + "]"); }
public GammaTaskData() { ChainId = Guid.NewGuid(); FieldWithCommonName = ChainId.ToString(); }
public async Task RemoveChainBlockLinkAsync(Hash blockHash) { await _chainBlockLinks.RemoveAsync(ChainId.ToStorageKey() + KernelConstants.StorageKeySeparator + blockHash.ToStorageKey()); _chainBlockLinkCacheProvider.RemoveChainBlockLink(blockHash); }
public async Task <Chain> GetAsync() { var chain = await _chains.GetAsync(ChainId.ToStorageKey()); return(chain); }
public async Task <ChainBlockIndex> GetChainBlockIndexAsync(long blockHeight) { return(await _chainBlockIndexes.GetAsync(ChainId.ToStorageKey() + KernelConstants.StorageKeySeparator + blockHeight.ToStorageKey())); }
private async Task <ChainBlockLink> GetChainBlockLinkAsync(string blockHash) { return(await _chainBlockLinks.GetAsync(ChainId.ToStorageKey() + KernelConstants.StorageKeySeparator + blockHash)); }
public BigInteger GetChainIdAsBigInteger() { return(ChainId.ToBigIntegerFromRLPDecoded()); }
private StringBuilder BuildNodeStats(INodeStats nodeStats) { var sb = new StringBuilder(); sb.AppendLine(); sb.AppendLine($"NodeEventHistory | {DateTime.Now.ToString(DetailedTimeDateFormat)}, {GetNodeLog(nodeStats)}"); if (nodeStats.P2PNodeDetails != null) { sb.AppendLine($"P2P details: ClientId: {nodeStats.P2PNodeDetails.ClientId}, P2PVersion: {nodeStats.P2PNodeDetails.P2PVersion}, Capabilities: {GetCapabilities(nodeStats.P2PNodeDetails)}"); } if (nodeStats.EthNodeDetails != null) { sb.AppendLine($"Eth62 details: ChainId: {ChainId.GetChainName((int) nodeStats.EthNodeDetails.ChainId)}, TotalDifficulty: {nodeStats.EthNodeDetails.TotalDifficulty}"); } foreach (var statsEvent in nodeStats.EventHistory.OrderBy(x => x.EventDate).ToArray()) { sb.Append($"{statsEvent.EventDate.ToString(DetailedTimeDateFormat)} | {statsEvent.EventType}"); if (statsEvent.ConnectionDirection.HasValue) { sb.Append($" | {statsEvent.ConnectionDirection.Value.ToString()}"); } if (statsEvent.P2PNodeDetails != null) { sb.Append($" | {statsEvent.P2PNodeDetails.ClientId} | v{statsEvent.P2PNodeDetails.P2PVersion} | {GetCapabilities(statsEvent.P2PNodeDetails)}"); } if (statsEvent.EthNodeDetails != null) { sb.Append($" | {ChainId.GetChainName((int) statsEvent.EthNodeDetails.ChainId)} | TotalDifficulty:{statsEvent.EthNodeDetails.TotalDifficulty}"); } if (statsEvent.DisconnectDetails != null) { sb.Append($" | {statsEvent.DisconnectDetails.DisconnectReason.ToString()} | {statsEvent.DisconnectDetails.DisconnectType.ToString()}"); } if (statsEvent.SyncNodeDetails != null && (statsEvent.SyncNodeDetails.NodeBestBlockNumber.HasValue || statsEvent.SyncNodeDetails.OurBestBlockNumber.HasValue)) { sb.Append($" | NodeBestBlockNumber: {statsEvent.SyncNodeDetails.NodeBestBlockNumber} | OurBestBlockNumber: {statsEvent.SyncNodeDetails.OurBestBlockNumber}"); } sb.AppendLine(); } sb.AppendLine(); sb.AppendLine("Latency averages:"); var averageLatencies = GetAverageLatencies(nodeStats); foreach (var latency in averageLatencies.Where(x => x.Value.HasValue)) { sb.AppendLine($"{latency.Key.ToString()} = {latency.Value}"); } if (nodeStats.LatencyHistory.Any()) { sb.AppendLine("Latency events:"); foreach (var statsEvent in nodeStats.LatencyHistory.OrderBy(x => x.StatType).ThenBy(x => x.CaptureTime).ToArray()) { sb.AppendLine($"{statsEvent.StatType.ToString()} | {statsEvent.CaptureTime.ToString(DetailedTimeDateFormat)} | {statsEvent.Latency}"); } } return(sb); }
public bool DisconnectOnInvalid(string protocol, ISession session, ProtocolInitializedEventArgs eventArgs) { switch (protocol) { case Protocol.P2P: P2PProtocolInitializedEventArgs args = (P2PProtocolInitializedEventArgs)eventArgs; if (!ValidateP2PVersion(args.P2PVersion)) { if (_logger.IsTrace) { _logger.Trace($"Initiating disconnect with peer: {session.RemoteNodeId}, incorrect P2PVersion: {args.P2PVersion}"); } _nodeStatsManager.ReportFailedValidation(session.Node, CompatibilityValidationType.P2PVersion); Disconnect(session, DisconnectReason.IncompatibleP2PVersion, $"p2p.{args.P2PVersion}"); if (session.Node.IsStatic && _logger.IsWarn) { _logger.Warn($"Disconnected an invalid static node: {session.Node.Host}:{session.Node.Port}, reason: {DisconnectReason.IncompatibleP2PVersion}"); } return(false); } if (!ValidateCapabilities(args.Capabilities)) { if (_logger.IsTrace) { _logger.Trace($"Initiating disconnect with peer: {session.RemoteNodeId}, no Eth62 capability, supported capabilities: [{string.Join(",", args.Capabilities.Select(x => $"{x.ProtocolCode}v{x.Version}"))}]"); } _nodeStatsManager.ReportFailedValidation(session.Node, CompatibilityValidationType.Capabilities); Disconnect(session, DisconnectReason.UselessPeer, "capabilities"); if (session.Node.IsStatic && _logger.IsWarn) { _logger.Warn($"Disconnected an invalid static node: {session.Node.Host}:{session.Node.Port}, reason: {DisconnectReason.UselessPeer} (capabilities)"); } return(false); } break; case Protocol.Eth: case Protocol.Les: SyncPeerProtocolInitializedEventArgs syncPeerArgs = (SyncPeerProtocolInitializedEventArgs)eventArgs; if (!ValidateChainId(syncPeerArgs.ChainId)) { if (_logger.IsTrace) { _logger.Trace($"Initiating disconnect with peer: {session.RemoteNodeId}, different chainId: {ChainId.GetChainName((int) syncPeerArgs.ChainId)}, our chainId: {ChainId.GetChainName(_blockTree.ChainId)}"); } _nodeStatsManager.ReportFailedValidation(session.Node, CompatibilityValidationType.ChainId); Disconnect(session, DisconnectReason.UselessPeer, $"invalid chain id - {syncPeerArgs.ChainId}"); if (session.Node.IsStatic && _logger.IsWarn) { _logger.Warn($"Disconnected an invalid static node: {session.Node.Host}:{session.Node.Port}, reason: {DisconnectReason.UselessPeer} (invalid chain id - {syncPeerArgs.ChainId})"); } return(false); } if (syncPeerArgs.GenesisHash != _blockTree.Genesis.Hash) { if (_logger.IsTrace) { _logger.Trace($"Initiating disconnect with peer: {session.RemoteNodeId}, different genesis hash: {syncPeerArgs.GenesisHash}, our: {_blockTree.Genesis.Hash}"); } _nodeStatsManager.ReportFailedValidation(session.Node, CompatibilityValidationType.DifferentGenesis); Disconnect(session, DisconnectReason.BreachOfProtocol, "invalid genesis"); if (session.Node.IsStatic && _logger.IsWarn) { _logger.Warn($"Disconnected an invalid static node: {session.Node.Host}:{session.Node.Port}, reason: {DisconnectReason.BreachOfProtocol} (invalid genesis)"); } return(false); } break; } return(true); }
public MailMessage(MimeMessage message, int folder = 1, bool unread = false, string chainId = "", string streamId = "") { if (message == null) { throw new ArgumentNullException("message"); } Date = IsDateCorrect(message.Date.UtcDateTime) ? message.Date.UtcDateTime : DateTime.UtcNow; MimeMessageId = (string.IsNullOrEmpty(message.MessageId) ? MailUtil.CreateMessageId() : message.MessageId) .Trim(new[] { '<', '>' }); ChainId = string.IsNullOrEmpty(chainId) ? MimeMessageId : chainId; MimeReplyToId = ChainId.Equals(MimeMessageId) ? null : message.InReplyTo.Trim(new[] { '<', '>' }); ReplyTo = message.ReplyTo.ToString(); From = message.From.ToString(); FromEmail = message.From != null && message.From.Mailboxes != null && message.From.Mailboxes.Any() ? message.From.Mailboxes.First().Address : ""; ToList = message.To.Mailboxes.Select(s => new MailAddress(s.Address, s.Name)).ToList(); To = string.Join(", ", message.To.Mailboxes.Select(s => s.ToString())); CcList = message.Cc.Mailboxes.Select(s => new MailAddress(s.Address, s.Name)).ToList(); Cc = string.Join(", ", message.Cc.Mailboxes.Select(s => s.ToString())); Bcc = string.Join(", ", message.Bcc.Mailboxes.Select(s => s.ToString())); Subject = message.Subject ?? string.Empty; Important = message.Importance == MessageImportance.High || message.Priority == MessagePriority.Urgent; TextBodyOnly = false; if (message.HtmlBody == null && message.TextBody == null) { HtmlBody = ""; Introduction = ""; IsBodyCorrupted = true; var messagePart = new MessagePart { Message = message, ContentDisposition = new ContentDisposition { FileName = "message.eml" } }; LoadAttachments(new List <MimeEntity> { messagePart }); } else { SetHtmlBodyAndIntroduction(message); } Size = HtmlBody.Length; HeaderFieldNames = new NameValueCollection(); if (message.Headers.Any()) { foreach (var header in message.Headers) { HeaderFieldNames.Add(header.Field, header.Value); } } Folder = folder; IsNew = unread; StreamId = string.IsNullOrEmpty(streamId) ? MailUtil.CreateStreamId() : streamId; LoadAttachments(message.Attachments); LoadEmbeddedAttachments(message); LoadCalendarInfo(message); }