/// <summary> /// Waits for sent event, if the message is TCP and sent by me. /// </summary> /// <param name="timeout">The timeout.</param> internal void WaitForSentEvent(int timeout) { if (mMessage.MessageType == MessageTypeEnum.Tcp && NetworkManager.Instance.InternalLocalhost.Id.Equals(mMessage.SenderId)) { // csak a saját TCP üzeneteimre lehet várakozni lock (mLockObject) { if (mWatch == null) { mWatch = Stopwatch.StartNew(); } if (mSentEvent == null) { mSentEvent = new ManualResetEvent(false); } } if (mSentEvent.WaitOne(timeout) && IsSuccess) { // replytime feljegyzése NetworkPeerRemote networkPeer = (NetworkPeerRemote)NetworkPeerContext.GetNetworkPeerById(mMessage.TargetId); networkPeer.Session.ReplyTime = ReplyTime; } } else { IsSuccess = true; } }
public void SetPeerContext(IPeerContext peerContext) { _networkPeerContext = peerContext as NetworkPeerContext ?? throw new ArgumentException("Expected NetworkPeerContext", nameof(peerContext));; _deserializationContext.SetInitiator(_networkPeerContext.Direction == PeerConnectionDirection.Outbound); LightningEndpoint?lightningEndpoint = null; if (peerContext.Direction == PeerConnectionDirection.Outbound) { OutgoingConnectionEndPoint endpoint = peerContext.Features.Get <OutgoingConnectionEndPoint>(); if (endpoint == null || !endpoint.Items.TryGetValue(nameof(LightningEndpoint), out object?res)) { _logger.LogError("Remote connection was not found "); throw new ApplicationException("Initiator connection must have a public key of the remote node"); } if (res == null) { _logger.LogError("Remote connection type is invalid"); throw new ApplicationException("Remote connection type is invalid"); } lightningEndpoint = (LightningEndpoint)res; } _handshakeProtocol = new HandshakeWithNoiseProtocol(_nodeContext, lightningEndpoint?.NodePubKey, _handshakeProcessor); _networkPeerContext.SetHandshakeProtocol(_handshakeProtocol); }
public override PongMessage DeserializeMessage(ref SequenceReader <byte> reader, int protocolVersion, NetworkPeerContext peerContext) { ushort bytesLen = reader.ReadUShort(true); return(new PongMessage { BytesLen = bytesLen, Ignored = reader.ReadBytes(bytesLen).ToArray() }); }
public override ErrorMessage DeserializeMessage(ref SequenceReader <byte> reader, int protocolVersion, NetworkPeerContext peerContext) { var channelId = reader.ReadBytes(32).ToArray(); ushort len = reader.ReadUShort(true); return(new ErrorMessage { ChannelId = channelId, Len = len, Data = reader.ReadBytes(len).ToArray() }); }
protected BaseMessageSerializerTests(BaseMessageSerializer <TMessage> serializer) { this.serializer = serializer; context = new NetworkPeerContext( //TODO David change this when moved to interface new Mock <ILogger>().Object, new Mock <IEventBus>().Object, PeerConnectionDirection.Inbound, //TODO create a random enum generator _random.Next(int.MaxValue).ToString(), // string peerId, new Mock <IPEndPoint>((long)_random.Next(int.MaxValue), 9735).Object, new Mock <IPEndPoint>((long)_random.Next(int.MaxValue), 9735).Object, new Mock <IPEndPoint>((long)_random.Next(int.MaxValue), 9735).Object, new Mock <INetworkMessageWriter>().Object ); }
public TransportMessageSerializer( ILogger <TransportMessageSerializer> logger, INetworkMessageSerializerManager networkMessageSerializerManager, NodeContext nodeContext, IHandshakeProcessor handshakeProcessor) { _logger = logger; _networkMessageSerializerManager = networkMessageSerializerManager; _nodeContext = nodeContext; _handshakeProcessor = handshakeProcessor; _deserializationContext = new DeserializationContext(); //initialized by SetPeerContext _networkPeerContext = null !; _handshakeProtocol = null !; }
public override void SerializeMessage(PingMessage message, int protocolVersion, NetworkPeerContext peerContext, IBufferWriter <byte> output) { output.WriteUShort(message.NumPongBytes, true); output.WriteUShort(message.BytesLen, true); output.WriteBytes(message.Ignored); }
public override InitMessage DeserializeMessage(ref SequenceReader <byte> reader, int protocolVersion, NetworkPeerContext peerContext) { var message = new InitMessage(); ushort len = reader.ReadUShort(true); message.GlobalFeatures = reader.ReadBytes(len).ToArray(); len = reader.ReadUShort(true); message.Features = reader.ReadBytes(len).ToArray(); return(message); }
public override void SerializeMessage(InitMessage message, int protocolVersion, NetworkPeerContext peerContext, IBufferWriter <byte> output) { output.WriteUShort((ushort)message.GlobalFeatures.Length, true); output.Write(message.GlobalFeatures); output.WriteUShort((ushort)message.Features.Length, true); output.Write(message.Features); }
public override void SerializeMessage(ErrorMessage message, int protocolVersion, NetworkPeerContext peerContext, IBufferWriter <byte> output) { output.WriteBytes(message.ChannelId); output.WriteUShort(message.Len, true); output.WriteBytes(message.Data); }
private void Callback(IAsyncResult result) { try { UdpBroadcastMessage message = null; IPEndPoint ep = mBroadcastEp; using (MemoryStream ms = new MemoryStream(mUdpClient.EndReceive(result, ref ep))) { ms.Position = 0; message = mMessageFormatter.Read(ms); ms.SetLength(0); } if (LOGGER.IsInfoEnabled) { LOGGER.Info(string.Format("BROADCAST_SERVER, a broadcast message arrived from '{0}'.", message.SenderId)); } if (NetworkManager.Instance.InternalLocalhost.Id.Equals(message.SenderId)) { if (LOGGER.IsInfoEnabled) { LOGGER.Info("BROADCAST_SERVER, this broadcast message arrived from me."); } } else { if (NetworkManager.Instance.NetworkContextRuleManager.CheckSeparation(NetworkManager.Instance.InternalLocalhost.NetworkContext.Name, message.NetworkContextName)) { // láthatom ezt a context-et, megpróbálok rácsatlakozni INetworkPeerRemote peer = NetworkPeerContext.GetNetworkPeerById(message.SenderId); if (peer == null || (peer != null && peer.Distance != 1)) { // nincs közvetlen kapcsolatom ilyen peer-el mThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(ConnectionTask), message); } else { if (LOGGER.IsInfoEnabled) { LOGGER.Info(string.Format("BROADCAST_SERVER, this is a known peer with direct network connection. No need to establish a new. PeerId: '{0}'.", peer.Id)); } } } else { if (LOGGER.IsInfoEnabled) { LOGGER.Info(string.Format("BROADCAST_SERVER, network context separation is active between '{0}' and '{1}'.", NetworkManager.Instance.InternalLocalhost.NetworkContext.Name, message.NetworkContextName)); } } } } catch (Exception ex) { if (LOGGER.IsErrorEnabled) { LOGGER.Error(string.Format("BROADCAST_SERVER, failed to receive a broadcast message. Reason: {0}", ex.Message)); } } finally { BeginReceive(); } }
private static void ConnectionTask(object state) { UdpBroadcastMessage message = (UdpBroadcastMessage)state; if (LOGGER.IsDebugEnabled) { LOGGER.Debug(string.Format("BROADCAST_SERVER, processing message of sender, id: {0}", message.SenderId)); } if (message.TCPServers != null && message.TCPServers.Length > 0) { foreach (AddressEndPoint ep in message.TCPServers) { if (ep.AddressFamily == AddressFamily.InterNetwork || (ep.AddressFamily == AddressFamily.InterNetworkV6 && NetworkManager.Instance.InternalConfiguration.Settings.EnableIPV6)) { try { if (LOGGER.IsInfoEnabled) { LOGGER.Info(string.Format("BROADCAST_SERVER, connecting to [{0}] with address [{1}] and port {2}.", message.SenderId, ep.Host, ep.Port)); } Synapse.NetworkStream stream = NetworkManager.Instance.InternalNetworkManager.Connect(ep); stream.SendBufferSize = NetworkManager.Instance.InternalConfiguration.Settings.DefaultLowLevelSocketSendBufferSize; stream.ReceiveBufferSize = NetworkManager.Instance.InternalConfiguration.Settings.DefaultLowLevelSocketReceiveBufferSize; stream.NoDelay = NetworkManager.Instance.InternalConfiguration.Settings.DefaultLowLevelNoDelay; NetworkPeerRemote remotePeer = NetworkManager.Instance.ProcessConnection(stream, NetworkManager.Instance.InternalConfiguration.Settings.DefaultConnectionTimeoutInMS, true, !NetworkManager.Instance.InternalConfiguration.Settings.EnableMultipleConnectionWithNetworkPeers); if (NetworkManager.Instance.IsShutdown) { stream.Close(); break; } if (remotePeer != null && remotePeer.Id.Equals(message.SenderId)) { // létrejött a kapcsolat, tovább nem próbálkozunk if (LOGGER.IsInfoEnabled) { LOGGER.Info(string.Format("BROADCAST_SERVER, successfully connected to '{0}' on TCP server.", message.SenderId)); } break; } } catch (Exception ex) { if (LOGGER.IsErrorEnabled) { LOGGER.Error(string.Format("BROADCAST_SERVER, failed to connect to [{0}] with address [{1}] and port {2}. Reason: {3}", message.SenderId, ep.Host, ep.Port, ex.Message)); } } } else { if (LOGGER.IsInfoEnabled) { LOGGER.Info(string.Format("BROADCAST_SERVER, connecting to [{0}] with address [{1}] not allowed. IPV6 protocol disabled.", message.SenderId, ep.Host)); } } } } INetworkPeerRemote peer = NetworkPeerContext.GetNetworkPeerById(message.SenderId); if (peer == null || (peer != null && peer.Distance != 1)) { if (message.NATGateways != null && message.NATGateways.Length > 0) { foreach (AddressEndPoint ep in message.NATGateways) { if (ep.AddressFamily == AddressFamily.InterNetwork || (ep.AddressFamily == AddressFamily.InterNetworkV6 && NetworkManager.Instance.InternalConfiguration.Settings.EnableIPV6)) { try { if (LOGGER.IsInfoEnabled) { LOGGER.Info(string.Format("BROADCAST_SERVER, connecting to [{0}] with NAT address [{1}] and port {2}.", message.SenderId, ep.Host, ep.Port)); } Synapse.NetworkStream stream = NetworkManager.Instance.InternalNetworkManager.Connect(ep); stream.SendBufferSize = NetworkManager.Instance.InternalConfiguration.Settings.DefaultLowLevelSocketSendBufferSize; stream.ReceiveBufferSize = NetworkManager.Instance.InternalConfiguration.Settings.DefaultLowLevelSocketReceiveBufferSize; stream.NoDelay = NetworkManager.Instance.InternalConfiguration.Settings.DefaultLowLevelNoDelay; NetworkPeerRemote remotePeer = NetworkManager.Instance.ProcessConnection(stream, NetworkManager.Instance.InternalConfiguration.Settings.DefaultConnectionTimeoutInMS, true, !NetworkManager.Instance.InternalConfiguration.Settings.EnableMultipleConnectionWithNetworkPeers); if (NetworkManager.Instance.IsShutdown) { stream.Close(); break; } if (remotePeer != null && remotePeer.Id.Equals(message.SenderId)) { // létrejött a kapcsolat, tovább nem próbálkozunk if (LOGGER.IsInfoEnabled) { LOGGER.Info(string.Format("BROADCAST_SERVER, successfully connected to '{0}' on NAT address.", message.SenderId)); } break; } } catch (Exception ex) { if (LOGGER.IsErrorEnabled) { LOGGER.Error(string.Format("BROADCAST_SERVER, failed to connect to [{0}] with address [{1}] and port {2}. Reason: {3}", message.SenderId, ep.Host, ep.Port, ex.Message)); } } } else { if (LOGGER.IsInfoEnabled) { LOGGER.Info(string.Format("BROADCAST_SERVER, connecting to [{0}] with address [{1}] not allowed. IPV6 protocol disabled.", message.SenderId, ep.Host)); } } } } } }