public static PeerAddress Decode(IByteReader stream) { PeerAddress decodedPeerAddress = new PeerAddress(); decodedPeerAddress.Ip = PeerAddressIp.Decode(stream); decodedPeerAddress.Port = Uint32.Decode(stream); decodedPeerAddress.NumFailures = Uint32.Decode(stream); return decodedPeerAddress; }
/// <summary> /// Decodes a message object. /// The format looks as follows: 28 bit P2P version, 4 bit message type, 32 bit message ID, 8 bit message command, /// 160 bit senderSocket ID, 16 bit senderSocket TCP port, 16 bit senderSocket UDP port, 160 bit recipientSocket ID, 32 bit content types, 8 bit options. /// In total, the header is of size 58 bytes. /// </summary> /// <param name="buffer">The buffer to decode from.</param> /// <param name="recipientSocket">The recipientSocket of the message.</param> /// <param name="senderSocket">The senderSocket of the packet, which has been set in the socket class.</param> // TODO check if true /// <returns>The partial message where only the header fields are set.</returns> public static Message DecodeHeader(AlternativeCompositeByteBuf buffer, IPEndPoint recipientSocket, IPEndPoint senderSocket) { Logger.Debug("Decode message. Recipient: {0}, Sender: {1}", recipientSocket, senderSocket); var message = new Message(); int versionAndType = buffer.ReadInt(); // 4 message.SetVersion(versionAndType >> 4); message.SetType((Message.MessageType)(versionAndType & Utils.Utils.Mask0F)); // TODO does this work? (2x) message.SetMessageId(buffer.ReadInt()); // 8 message.SetCommand(buffer.ReadByte()); // 9 // TODO check conversion with Java version var senderId = ReadId(buffer); // 29 int tcpPort = buffer.ReadUShort(); // 31 // TODO check if should be read as short (same as encode) int udpPort = buffer.ReadUShort(); // 33 var recipientId = ReadId(buffer); // 53 int contentTypes = buffer.ReadInt(); // 57 int options = buffer.ReadUByte(); // 58 // TODO check if should be read as unsigned/signed message.SetRecipient(new PeerAddress(recipientId, recipientSocket)); message.HasContent(contentTypes != 0); message.SetContentType(DecodeContentTypes(contentTypes, message)); message.SetOptions(options & Utils.Utils.Mask0F); // set the address as we see it, important for port forwarding identification int senderOptions = options >> 4; var pa = new PeerAddress(senderId, senderSocket.Address, tcpPort, udpPort, senderOptions); message.SetSender(pa); message.SetSenderSocket(senderSocket); message.SetRecipientSocket(recipientSocket); return message; }
/// <summary> /// Sends data directly to a peer. Make sure you have set up a reply handler. /// This is an RPC. /// </summary> /// <param name="remotePeer">The remote peer to store the data.</param> /// <param name="sendDirectBuilder"></param> /// <returns></returns> public RequestHandler SendInternal(PeerAddress remotePeer, ISendDirectBuilder sendDirectBuilder) { var message = CreateRequestMessage(remotePeer, Rpc.Commands.DirectData.GetNr(), sendDirectBuilder.IsRaw ? Message.Message.MessageType.Request1 : Message.Message.MessageType.Request2); var tcsResponse = new TaskCompletionSource<Message.Message>(message); if (sendDirectBuilder.IsSign) { message.SetPublicKeyAndSign(sendDirectBuilder.KeyPair); } message.SetStreaming(sendDirectBuilder.IsStreaming); if (sendDirectBuilder.IsRaw) { message.SetBuffer(sendDirectBuilder.Buffer); } else { try { sbyte[] me = Utils.Utils.EncodeObject(sendDirectBuilder.Object); message.SetBuffer(new Message.Buffer(Unpooled.WrappedBuffer(me))); } catch (Exception ex) { tcsResponse.SetException(ex); } } return new RequestHandler(tcsResponse, PeerBean, ConnectionBean, sendDirectBuilder); }
public static PeerAddress CreateAddress(Number160 idSender, String inetSender, int tcpPortSender, int udpPortSender, bool firewallUdp, bool firewallTcp) { IPAddress inetSend = IPAddress.Parse(inetSender); // TODO correct port var peerSocketAddress = new PeerSocketAddress(inetSend, tcpPortSender, udpPortSender); var n1 = new PeerAddress(idSender, peerSocketAddress, firewallTcp, firewallUdp, false, PeerAddress.EmptyPeerSocketAddresses); return n1; }
public void TestPeerAddressRoundtrip() { // copied verbatim from https://en.bitcoin.it/wiki/Protocol_specification#Network_address const string fromSpec = "010000000000000000000000000000000000ffff0a000001208d"; var pa = new PeerAddress(NetworkParameters.ProdNet(), Hex.Decode(fromSpec), 0, 0); var reserialized = Utils.BytesToHexString(pa.BitcoinSerialize()); Assert.AreEqual(reserialized, fromSpec); }
public Buffer Reply(PeerAddress sender, Buffer requestBuffer, bool complete) { Console.WriteLine("{0}.", ++_counter); Console.WriteLine("Request from {0}.", sender); Console.WriteLine("Buffer Size : {0}", Convenient.ToHumanReadable(requestBuffer.Length)); // server returns just OK if same buffer is returned return requestBuffer; }
/// <summary> /// Creates a request requestMessage and fills it with peer bean and connection bean parameters. /// </summary> /// <param name="recipient">The recipient of this requestMessage.</param> /// <param name="name">The command type.</param> /// <param name="type">The request type.</param> /// <returns>The created request requestMessage.</returns> public Message.Message CreateRequestMessage(PeerAddress recipient, sbyte name, Message.Message.MessageType type) { return new Message.Message() .SetRecipient(recipient) .SetSender(PeerBean.ServerPeerAddress) .SetCommand(name) .SetType(type) .SetVersion(ConnectionBean.P2PId); }
public static PeerAddress[] CreateDummyAddresses(int size, int portTcp, int portUdp) { var pa = new PeerAddress[size]; for (int i = 0; i < size; i++) { pa[i] = CreateAddress(i + 1, portTcp, portUdp); } return pa; }
/// <summary> /// Creates a new future object and creates a timer that fires failed after a timeout. /// </summary> /// <param name="serverPeerAddress"></param> /// <param name="timer">.NET-specific: CTS instead of timer.</param> /// <param name="delaySec">The delay in seconds.</param> public void Timeout(PeerAddress serverPeerAddress, ExecutorService timer, int delaySec) { _start = Convenient.CurrentTimeMillis(); var cts = timer.Schedule(DiscoverTimeoutTask, serverPeerAddress, TimeSpan.FromSeconds(delaySec).TotalMilliseconds); // ReSharper disable once MethodSupportsCancellation // cancel timeout if we are done Task.ContinueWith(tDelay => cts.Cancel()); }
public void Connect(PeerAddress peerAddress) { var connectAsServerMessage = new PeerAddressMessage(peerAddress, MessageType.ConnectAsClient); Peer.SendToSuperPeer(connectAsServerMessage); Peer.ReadFromSuperPeer(); var connection = new TcpClientPeerConnection(this, Peer.PeerAddress); _server = connection.GetConnection(); Peer.Close(); }
public Task<Message.Message> SendAsync(PeerAddress remotePeer, ISendDirectBuilder sendDirectBuilder, ChannelCreator channelCreator) { var requestHandler = SendInternal(remotePeer, sendDirectBuilder); if (!sendDirectBuilder.IsForceUdp) { return requestHandler.SendTcpAsync(channelCreator); } return requestHandler.SendUdpAsync(channelCreator); }
public void AllowConnection(PeerAddress peerAddress) { var connectAsServerMessage = new PeerAddressMessage(peerAddress, MessageType.ConnectAsServer); Peer.SendToSuperPeer(connectAsServerMessage); Peer.ReadFromSuperPeer(); ServerPeerConnection serverPeerConnection = new TcpServerPeerConnection(this); _client = serverPeerConnection.GetConnection(); Peer.Close(); Console.WriteLine("Client connected to server"); }
protected override async Task SetupAsync(Arguments args) { Network = BenchmarkUtil.CreateNodes(NetworkSize, Rnd, 7077, false, false); Sender = Network[0]; _remoteAddress = args.Param as PeerAddress; Cc = await Sender.ConnectionBean.Reservation.CreateAsync(IsForceUdp ? 1 : 0, IsForceUdp ? 0 : 1); SendDirectBuilder = new SendDirectBuilder(Sender, (PeerAddress)null) .SetIdleUdpSeconds(0) .SetIdleTcpSeconds(0) .SetBuffer(CreateSampleBuffer()) .SetIsForceUdp(IsForceUdp); }
private void Failed(PeerAddress serverPeerAddress, string failed) { lock (Lock) { if (!CompletedAndNotify()) { return; } // TODO reason and type needed? Logger.Debug(failed); _ourPeerAddress = serverPeerAddress; } NotifyListeners(); }
/// <summary> /// Sends a message that indicates this peer is about to quit. This is an RPC. /// </summary> /// <param name="remotePeer">The remote peer to send this request.</param> /// <param name="shutdownBuilder">Used for the sign and force TCP flag. Set if the message should be signed.</param> /// <param name="channelCreator">The channel creator that creates connections.</param> /// <returns>The future response message.</returns> public Task<Message.Message> QuitAsync(PeerAddress remotePeer, ShutdownBuilder shutdownBuilder, ChannelCreator channelCreator) { var message = CreateRequestMessage(remotePeer, Rpc.Commands.Quit.GetNr(), Message.Message.MessageType.RequestFf1); if (shutdownBuilder.IsSign) { message.SetPublicKeyAndSign(shutdownBuilder.KeyPair); } var tcsResponse = new TaskCompletionSource<Message.Message>(message); var requestHandler = new RequestHandler(tcsResponse, PeerBean, ConnectionBean, shutdownBuilder); Logger.Debug("Send QUIT message {0}.", message); if (!shutdownBuilder.IsForceTcp) { return requestHandler.FireAndForgetUdpAsync(channelCreator); } return requestHandler.SendTcpAsync(channelCreator); }
private void InitConnectionAsClient(PeerAddress peerAddress) { List<SuperPeerServer> onlineServers = new List<SuperPeerServer>(ConnectionsRepository.GetServers()); SuperPeerServer targetServer = null; foreach (SuperPeerServer server in onlineServers) { if (server.GetClientInfo().PeerAddress().Equals(peerAddress)) targetServer = server; } if (targetServer == null) return; if (!targetServer.AllowedConnection.Equals(_superPeerClient.GetClientInfo().PeerAddress())) return; ConnectionPair connectionPair = CreateConnectionPair(targetServer, _superPeerClient); ProcessConnectionBetweenClients(connectionPair); }
public PeerAddressMessage(byte[] encoding) : this() { try { MemoryStream memoryStream = new MemoryStream(encoding, 0, encoding.Length, false); BinaryReader binaryReader = new BinaryReader(new BufferedStream(memoryStream)); TypeOfMessage = (MessageType)MessagesEncodingUtil.ReadByte(binaryReader); IPEndPoint localEndPoint = ParseIpEndPoint(MessagesEncodingUtil.ReadString(binaryReader)); IPEndPoint publicEndPoint = ParseIpEndPoint(MessagesEncodingUtil.ReadString(binaryReader)); PeerAddress = new PeerAddress(localEndPoint, publicEndPoint); } catch (Exception) { throw new BinaryEncodingException("Encode"); } }
private bool InitClientAddress() { var requestMessage = _client.Read() as RequestMessage; if (requestMessage != null && requestMessage.RequestedMessageType == MessageType.ClientPeerAddress) { PeerAddress peerAddress = new PeerAddress {PublicEndPoint = _client.RemoteEndPoint}; _client.Send(new PeerAddressMessage(peerAddress, MessageType.ClientPeerAddress)); peerAddress.PrivateEndPoint = ((PeerAddressMessage) _client.Read()).PeerAddress.PrivateEndPoint; _clientInfo.PeerAddress(peerAddress); return true; } else { _client.Close(); return false; } }
/// <summary> /// Gets called if the discovery was a success and another peer could ping us with TCP and UDP. /// </summary> /// <param name="ourPeerAddress">The peer address of our server.</param> /// <param name="reporter">The peer address of the peer that reported our address.</param> public void Done(PeerAddress ourPeerAddress, PeerAddress reporter) { lock (Lock) { if (!CompletedAndNotify()) { return; } // TODO reason and type needed? if (_reporter != null) { /*if (!_reporter.Equals(reporter)) { // TODO reason and type needed? }*/ } _ourPeerAddress = ourPeerAddress; _reporter = reporter; } NotifyListeners(); }
public Task<Message.Message> SendAsync(PeerAddress remotePeer, BroadcastBuilder broadcastBuilder, ChannelCreator channelCreator, IConnectionConfiguration configuration) { var message = CreateRequestMessage(remotePeer, Rpc.Commands.Broadcast.GetNr(), Message.Message.MessageType.RequestFf1); message.SetIntValue(broadcastBuilder.HopCounter); message.SetKey(broadcastBuilder.MessageKey); if (broadcastBuilder.DataMap != null) { message.SetDataMap(new DataMap(broadcastBuilder.DataMap)); } var tcsResponse = new TaskCompletionSource<Message.Message>(message); var requestHandler = new RequestHandler(tcsResponse, PeerBean, ConnectionBean, configuration); if (!broadcastBuilder.IsUdp) { return requestHandler.SendTcpAsync(channelCreator); } else { return requestHandler.FireAndForgetUdpAsync(channelCreator); } }
/// <summary> /// .NET-specific: Used for DistributedRouting only. /// </summary> internal TaskCompletionSource<Message.Message> CloseNeighborsTcs(PeerAddress remotePeer, SearchValues searchValues, Message.Message.MessageType type, ChannelCreator channelCreator, IConnectionConfiguration configuration) { var message = CreateRequestMessage(remotePeer, Rpc.Commands.Neighbor.GetNr(), type); if (!message.IsRequest()) { throw new ArgumentException("The type must be a request."); } message.SetKey(searchValues.LocationKey); message.SetKey(searchValues.DomainKey ?? Number160.Zero); if (searchValues.From != null && searchValues.To != null) { ICollection<Number640> collection = new List<Number640>(); collection.Add(searchValues.From); collection.Add(searchValues.To); var keyCollection = new KeyCollection(collection); message.SetKeyCollection(keyCollection); } else { if (searchValues.ContentKey != null) { message.SetKey(searchValues.ContentKey); } if (searchValues.KeyBloomFilter != null) { message.SetBloomFilter(searchValues.KeyBloomFilter); } if (searchValues.ContentBloomFilter != null) { message.SetBloomFilter(searchValues.ContentBloomFilter); } } return Send(message, configuration, channelCreator); }
public bool Reject(PeerAddress peerAddress, ICollection<PeerAddress> all, Number160 target) { // TODO in Java: to be implemented return false; }
public static StellarMessage Decode(IByteReader stream) { StellarMessage decodedStellarMessage = new StellarMessage(); decodedStellarMessage.Discriminant = MessageType.Decode(stream); switch (decodedStellarMessage.Discriminant.InnerValue) { case MessageType.MessageTypeEnum.ERROR_MSG: decodedStellarMessage.Error = Error.Decode(stream); break; case MessageType.MessageTypeEnum.HELLO: decodedStellarMessage.Hello = Hello.Decode(stream); break; case MessageType.MessageTypeEnum.AUTH: decodedStellarMessage.Auth = Auth.Decode(stream); break; case MessageType.MessageTypeEnum.DONT_HAVE: decodedStellarMessage.DontHave = DontHave.Decode(stream); break; case MessageType.MessageTypeEnum.GET_PEERS: break; case MessageType.MessageTypeEnum.PEERS: int peerssize = XdrEncoding.DecodeInt32(stream); decodedStellarMessage.Peers = new PeerAddress[peerssize]; for (int i = 0; i < peerssize; i++) { decodedStellarMessage.Peers[i] = PeerAddress.Decode(stream); } break; case MessageType.MessageTypeEnum.GET_TX_SET: decodedStellarMessage.TxSetHash = Uint256.Decode(stream); break; case MessageType.MessageTypeEnum.TX_SET: decodedStellarMessage.TxSet = TransactionSet.Decode(stream); break; case MessageType.MessageTypeEnum.TRANSACTION: decodedStellarMessage.Transaction = TransactionEnvelope.Decode(stream); break; case MessageType.MessageTypeEnum.GET_SCP_QUORUMSET: decodedStellarMessage.QSetHash = Uint256.Decode(stream); break; case MessageType.MessageTypeEnum.SCP_QUORUMSET: decodedStellarMessage.QSet = SCPQuorumSet.Decode(stream); break; case MessageType.MessageTypeEnum.SCP_MESSAGE: decodedStellarMessage.Envelope = SCPEnvelope.Decode(stream); break; case MessageType.MessageTypeEnum.GET_SCP_STATE: decodedStellarMessage.GetSCPLedgerSeq = Uint32.Decode(stream); break; } return(decodedStellarMessage); }
public PeerAddressMessage(PeerAddress peerAddress, MessageType messageType = MessageType.PeerAddress) { PeerAddress = peerAddress; TypeOfMessage = messageType; }
private void InitConnectionAsServer(PeerAddress peerAddress) { _superPeerServer.AllowedConnection = peerAddress; }
public void Add(PeerAddress neighbor) { Neighbors.Add(neighbor); }
public Message SetRecipientRelay(PeerAddress recipientRelay) { RecipientRelay = recipientRelay; return this; }
public override void Read(ChannelHandlerContext ctx, object msg) { // client-side: // Here, the result for the awaitable task can be set. // If it is not a fire-and-forget message, the "result" of the TCS // must be set here. (If FF, then it is set in Sender.) // Java uses a SimpleChannelInboundHandler that only expects Message objects var responseMessage = msg as Message.Message; if (responseMessage == null) { return; } var recvMessageId = new MessageId(responseMessage); // error handling if (responseMessage.Type == Message.Message.MessageType.UnknownId) { string msg2 = "Message was not delivered successfully. Unknown ID (peer may be offline or unknown RPC handler): " + _message; ExceptionCaught(ctx, new PeerException(PeerException.AbortCauseEnum.PeerAbort, msg2)); return; } if (responseMessage.Type == Message.Message.MessageType.Exception) { string msg2 = "Message caused an exception on the other side. Handle as PeerAbort: " + _message; ExceptionCaught(ctx, new PeerException(PeerException.AbortCauseEnum.PeerAbort, msg2)); return; } if (responseMessage.IsRequest()) { ctx.FireRead(responseMessage); return; } if (!_sendMessageId.Equals(recvMessageId)) { string msg2 = String.Format( "Response message [{0}] sent to the node is not the same as we expect. We sent request message [{1}].", responseMessage, _message); ExceptionCaught(ctx, new PeerException(PeerException.AbortCauseEnum.PeerAbort, msg2)); return; } // We need to exclude RCON messages from the sanity check because we // use this RequestHandler for sending a Type.REQUEST_1, // RPC.Commands.RCON message on top of it. Therefore the response // type will never be the same Type as the one the user initially // used (e.g. DIRECT_DATA). if (responseMessage.Command != Rpc.Rpc.Commands.Rcon.GetNr() && _message.Recipient.IsRelayed != responseMessage.Sender.IsRelayed) { string msg2 = String.Format( "Response message [{0}] sent has a different relay flag than we sent with request message [{1}]. Recipient ({2}) / Sender ({3}).", responseMessage, _message, _message.Recipient.IsRelayed, responseMessage.Sender.IsRelayed); ExceptionCaught(ctx, new PeerException(PeerException.AbortCauseEnum.PeerAbort, msg2)); return; } // we got a good answer, let's mark the sender as alive if (responseMessage.IsOk() || responseMessage.IsNotOk()) { lock (PeerBean.PeerStatusListeners) { if (responseMessage.Sender.IsRelayed && responseMessage.PeerSocketAddresses.Count != 0) { // use the response message as we have up-to-date content for the relays PeerAddress remotePeer = responseMessage.Sender.ChangePeerSocketAddresses(responseMessage.PeerSocketAddresses); responseMessage.SetSender(remotePeer); } foreach (IPeerStatusListener listener in PeerBean.PeerStatusListeners) { listener.PeerFound(responseMessage.Sender, null, null); } } } // call this for streaming support if (!responseMessage.IsDone) { Logger.Debug("Good message is streaming. {0}", responseMessage); return; } if (!_message.IsKeepAlive()) { Logger.Debug("Good message {0}. Close channel {1}.", responseMessage, ctx.Channel); // .NET-specific: // set the result now, but trigger the notify when the channel is closed _tcsResponse.ResponseLater(responseMessage, ctx); // in Java, the channel creator adds a listener that sets the // future response result when the channel is closed ctx.Close(); // TODO needed? } else { Logger.Debug("Good message {0}. Leave channel {1} open.", responseMessage, ctx.Channel); _tcsResponse.SetResult(responseMessage); } }
/// <summary> /// Set the ID of the sender. The IP of the sender will NOT be transferred, as this information is in the IP packet. /// </summary> /// <param name="sender">The ID of the sender.</param> /// <returns>This class.</returns> public Message SetSender(PeerAddress sender) { Sender = sender; return this; }
public static void Encode(IByteWriter stream, StellarMessage encodedStellarMessage) { XdrEncoding.EncodeInt32((int)encodedStellarMessage.Discriminant.InnerValue, stream); switch (encodedStellarMessage.Discriminant.InnerValue) { case MessageType.MessageTypeEnum.ERROR_MSG: Error.Encode(stream, encodedStellarMessage.Error); break; case MessageType.MessageTypeEnum.HELLO: Hello.Encode(stream, encodedStellarMessage.Hello); break; case MessageType.MessageTypeEnum.AUTH: Auth.Encode(stream, encodedStellarMessage.Auth); break; case MessageType.MessageTypeEnum.DONT_HAVE: DontHave.Encode(stream, encodedStellarMessage.DontHave); break; case MessageType.MessageTypeEnum.GET_PEERS: break; case MessageType.MessageTypeEnum.PEERS: int peerssize = encodedStellarMessage.Peers.Length; XdrEncoding.EncodeInt32(peerssize, stream); for (int i = 0; i < peerssize; i++) { PeerAddress.Encode(stream, encodedStellarMessage.Peers[i]); } break; case MessageType.MessageTypeEnum.GET_TX_SET: Uint256.Encode(stream, encodedStellarMessage.TxSetHash); break; case MessageType.MessageTypeEnum.TX_SET: TransactionSet.Encode(stream, encodedStellarMessage.TxSet); break; case MessageType.MessageTypeEnum.TRANSACTION: TransactionEnvelope.Encode(stream, encodedStellarMessage.Transaction); break; case MessageType.MessageTypeEnum.GET_SCP_QUORUMSET: Uint256.Encode(stream, encodedStellarMessage.QSetHash); break; case MessageType.MessageTypeEnum.SCP_QUORUMSET: SCPQuorumSet.Encode(stream, encodedStellarMessage.QSet); break; case MessageType.MessageTypeEnum.SCP_MESSAGE: SCPEnvelope.Encode(stream, encodedStellarMessage.Envelope); break; case MessageType.MessageTypeEnum.GET_SCP_STATE: Uint32.Encode(stream, encodedStellarMessage.GetSCPLedgerSeq); break; } }
static void Main(string[] args) { #region Configs creation. BlockchainStorageManagerParameters managerParameters = new BlockchainStorageManagerParameters() { BlocksInUnit = 2 }; UnitRepositoryParameters firstRepositoryParameters = new UnitRepositoryParameters() { DirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "blockchain0") }; UnitRepositoryParameters secondRepositoryParameters = new UnitRepositoryParameters() { DirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "blockchain1") }; WalletManagerParameters walletManagerParameters = new WalletManagerParameters() { WalletDirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "wallets") }; NetworkParameters networkParametersFirst = new NetworkParameters() { AddressBookPath = Path.Combine(Directory.GetCurrentDirectory(), FirstBookPath), PeerHostName = Dns.GetHostName(), PeerPort = 8900, ClientTimeout = new TimeSpan(0, 0, 4), ServerTimeout = new TimeSpan(0, 0, 4) }; NetworkParameters networkParametersSecond = new NetworkParameters() { AddressBookPath = Path.Combine(Directory.GetCurrentDirectory(), SecondBookPath), PeerHostName = Dns.GetHostName(), PeerPort = 8910, ClientTimeout = new TimeSpan(0, 0, 4), ServerTimeout = new TimeSpan(0, 0, 4) }; BasicMiningFactoryParameters parameters = new BasicMiningFactoryParameters() { HashLeastUpFactor = 1.25, HashMostUpFactor = 1.75, HashLeastDownFactor = 0.25, HashMostDownFactor = 0.75, DifficultyLeastUpFactor = 1.25, DifficultyMostUpFactor = 1.75, DifficultyLeastDownFactor = 0.25, DifficultyMostDownFactor = 0.75, MinDifficulty = Difficulty }; JsonSerializer jsonSerializer = new JsonSerializer() { Formatting = Formatting.Indented }; using (Stream jsonFile = File.Open(MiningConfigPath, FileMode.Create, FileAccess.Write, FileShare.None)) using (StreamWriter writer = new StreamWriter(jsonFile)) using (JsonWriter jsonWriter = new JsonTextWriter(writer)) jsonSerializer.Serialize(jsonWriter, parameters); using (Stream jsonFile = File.Open(ManagerConfigPath, FileMode.Create, FileAccess.Write, FileShare.None)) using (StreamWriter writer = new StreamWriter(jsonFile)) using (JsonWriter jsonWriter = new JsonTextWriter(writer)) jsonSerializer.Serialize(jsonWriter, managerParameters); using (Stream jsonFile = File.Open(FirstRepositoryConfigPath, FileMode.Create, FileAccess.Write, FileShare.None)) using (StreamWriter writer = new StreamWriter(jsonFile)) using (JsonWriter jsonWriter = new JsonTextWriter(writer)) jsonSerializer.Serialize(jsonWriter, firstRepositoryParameters); using (Stream jsonFile = File.Open(SecondRepositoryConfigPath, FileMode.Create, FileAccess.Write, FileShare.None)) using (StreamWriter writer = new StreamWriter(jsonFile)) using (JsonWriter jsonWriter = new JsonTextWriter(writer)) jsonSerializer.Serialize(jsonWriter, secondRepositoryParameters); using (Stream jsonFile = File.Open(WalletManagerConfigPath, FileMode.Create, FileAccess.Write, FileShare.None)) using (StreamWriter writer = new StreamWriter(jsonFile)) using (JsonWriter jsonWriter = new JsonTextWriter(writer)) jsonSerializer.Serialize(jsonWriter, walletManagerParameters); using (Stream jsonFile = File.Open(FirstNetworkConfigPath, FileMode.Create, FileAccess.Write, FileShare.None)) using (StreamWriter writer = new StreamWriter(jsonFile)) using (JsonWriter jsonWriter = new JsonTextWriter(writer)) jsonSerializer.Serialize(jsonWriter, networkParametersFirst); using (Stream jsonFile = File.Open(SecondNetworkConfigPath, FileMode.Create, FileAccess.Write, FileShare.None)) using (StreamWriter writer = new StreamWriter(jsonFile)) using (JsonWriter jsonWriter = new JsonTextWriter(writer)) jsonSerializer.Serialize(jsonWriter, networkParametersSecond); JsonBasicMiningFactoryConfig miningConfig = new JsonBasicMiningFactoryConfig(MiningConfigPath); JsonBlockchainStorageManagerConfig managerConfig = new JsonBlockchainStorageManagerConfig(ManagerConfigPath); JsonUnitRepositoryConfig firstRepositoryConfig = new JsonUnitRepositoryConfig(FirstRepositoryConfigPath); JsonUnitRepositoryConfig secondRepositoryConfig = new JsonUnitRepositoryConfig(SecondRepositoryConfigPath); JsonWalletManagerConfig walletManagerConfig = new JsonWalletManagerConfig(WalletManagerConfigPath); JsonNetworkConfig firstNetworkConfig = new JsonNetworkConfig(FirstNetworkConfigPath); JsonNetworkConfig secondNetworkConfig = new JsonNetworkConfig(SecondNetworkConfigPath); #endregion #region Directory remove. removeDirectory(firstRepositoryConfig.DirectoryPath); removeDirectory(secondRepositoryConfig.DirectoryPath); removeDirectory(walletManagerConfig.WalletDirectoryPath); #endregion #region Directory creation. Directory.CreateDirectory(firstRepositoryParameters.DirectoryPath); Directory.CreateDirectory(secondRepositoryParameters.DirectoryPath); Directory.CreateDirectory(Path.Combine(firstRepositoryConfig.DirectoryPath, "addressers")); Directory.CreateDirectory(Path.Combine(firstRepositoryConfig.DirectoryPath, "units")); Directory.CreateDirectory(Path.Combine(secondRepositoryConfig.DirectoryPath, "addressers")); Directory.CreateDirectory(Path.Combine(secondRepositoryConfig.DirectoryPath, "units")); Directory.CreateDirectory(walletManagerConfig.WalletDirectoryPath); #endregion #region Initial units. // Addressers. string firstAddresser0Path = Path.Combine(firstRepositoryParameters.DirectoryPath, "addressers", "addresser0.addr"); string secondAddresser0Path = Path.Combine(secondRepositoryParameters.DirectoryPath, "addressers", "addresser0.addr"); #if (CREATE_EXTRA_FILE) string firstAddresser1Path = Path.Combine(firstRepositoryParameters.DirectoryPath, "addressers", "addresser1.addr"); string secondAddresser1Path = Path.Combine(secondRepositoryParameters.DirectoryPath, "addressers", "addresser1.addr"); #endif File.Create(firstAddresser0Path).Close(); File.Create(secondAddresser0Path).Close(); #if (CREATE_EXTRA_FILE) File.Create(firstAddresser1Path).Close(); File.Create(secondAddresser1Path).Close(); #endif // Units. string firstUnit0Path = Path.Combine(firstRepositoryParameters.DirectoryPath, "units", "unit0.unit"); string secondUnit0Path = Path.Combine(secondRepositoryParameters.DirectoryPath, "units", "unit0.unit"); #if (CREATE_EXTRA_FILE) string firstUnit1Path = Path.Combine(firstRepositoryParameters.DirectoryPath, "units", "unit1.unit"); string secondUnit1Path = Path.Combine(secondRepositoryParameters.DirectoryPath, "units", "unit1.unit"); #endif File.Create(firstUnit0Path).Close(); File.Create(secondUnit0Path).Close(); #if (CREATE_EXTRA_FILE) File.Create(firstUnit1Path).Close(); File.Create(secondUnit1Path).Close(); #endif BlockchainUnit firstUnit0 = new BlockchainUnit(firstUnit0Path, new AddressStorage(firstAddresser0Path)); BlockchainUnit secondUnit0 = new BlockchainUnit(secondUnit0Path, new AddressStorage(secondAddresser0Path)); #endregion IMiningFactory miningFactory = new BasicMiningFactory(miningConfig); IHashFactory hashFactory = miningFactory.GetMiningHashFactoryById(3); IHashFactory transactionHashFactory = new TransactionHashFactory(); ISignatureFactory signatureFactory = new ECDSAFactory(); IWalletManager walletManager = new WalletManager(walletManagerConfig, signatureFactory, transactionHashFactory); Wallet firstWallet = walletManager.AddNewWallet(); #region Initial transactions. LinkedList <Transaction> firstInitialList = new LinkedList <Transaction>(); LinkedList <Transaction> secondInitialList = new LinkedList <Transaction>(); Transaction firstInitialTransaction = new Transaction(firstWallet.PublicKey, firstWallet.PublicKey, 32, transactionHashFactory); Transaction secondInitialTransaction = new Transaction(firstWallet.PublicKey, firstWallet.PublicKey, 19, transactionHashFactory); Transaction thirdInitialTransaction = new Transaction(firstWallet.PublicKey, firstWallet.PublicKey, 32, transactionHashFactory); Transaction fourthInitialTransaction = new Transaction(firstWallet.PublicKey, firstWallet.PublicKey, 19, transactionHashFactory); firstInitialTransaction.SignTransaction(firstWallet.Signer); secondInitialTransaction.SignTransaction(firstWallet.Signer); thirdInitialTransaction.SignTransaction(firstWallet.Signer); fourthInitialTransaction.SignTransaction(firstWallet.Signer); firstInitialList.AddLast(firstInitialTransaction); firstInitialList.AddLast(secondInitialTransaction); secondInitialList.AddLast(thirdInitialTransaction); secondInitialList.AddLast(fourthInitialTransaction); #endregion #region Initial blocks. IHashFactory miningHashFactory = miningFactory.GetMiningHashFactoryById(3); IMiner miner = new BasicMiner(3, Difficulty, miningHashFactory); Block firstInitialBlock = new Block(firstWallet.PublicKey, new byte[hashFactory.GetDigest().HashLength], firstInitialList, hashFactory); miner.MineBlock(firstInitialBlock); firstInitialBlock.SignBlock(firstWallet.Signer); Block secondInitialBlock = new Block(firstWallet.PublicKey, firstInitialBlock.Hash, secondInitialList, hashFactory); miner.MineBlock(secondInitialBlock); secondInitialBlock.SignBlock(firstWallet.Signer); firstUnit0.AddBlock(firstInitialBlock); firstUnit0.AddBlock(secondInitialBlock); secondUnit0.AddBlock(firstInitialBlock); secondUnit0.AddBlock(secondInitialBlock); firstUnit0.Dispose(); secondUnit0.Dispose(); #endregion UnitRepository firstRepository = new UnitRepository(firstRepositoryConfig); UnitRepository secondRepository = new UnitRepository(secondRepositoryConfig); BlockchainStorageManager firstManager = new BlockchainStorageManager(managerConfig, firstRepository); BlockchainStorageManager secondManager = new BlockchainStorageManager(managerConfig, secondRepository); Blockchain firstBlockchain = new Blockchain(firstWallet, walletManager, transactionHashFactory, signatureFactory, miningFactory, firstManager); Wallet secondWallet = walletManager.AddNewWallet(); Blockchain secondBlockchain = new Blockchain(secondWallet, walletManager, transactionHashFactory, signatureFactory, miningFactory, secondManager); #region Address books creation. File.Create(FirstBookPath).Close(); File.Create(SecondBookPath).Close(); PeerAddress firstPeer = new PeerAddress(firstWallet.PublicKey); PeerAddress secondPeer = new PeerAddress(secondWallet.PublicKey); AddressBook firstPeerAddressBook = new AddressBook(FirstBookPath); AddressBook secondPeerAddressBook = new AddressBook(SecondBookPath); firstPeerAddressBook.Add(secondPeer, "ws://" + secondNetworkConfig.PeerHostName + $":{secondNetworkConfig.PeerPort}/simplecoin"); secondPeerAddressBook.Add(firstPeer, "ws://" + firstNetworkConfig.PeerHostName + $":{firstNetworkConfig.PeerPort}/simplecoin"); firstPeerAddressBook.SaveOnDrive(); secondPeerAddressBook.SaveOnDrive(); #endregion #region Network. IBroadcaster firstNetwork = new Network(firstBlockchain, firstPeerAddressBook, firstNetworkConfig, firstWallet.Signer); IBroadcaster secondNetwork = new Network(secondBlockchain, secondPeerAddressBook, secondNetworkConfig, secondWallet.Signer); firstBlockchain.NetworkBroadcaster = firstNetwork; secondBlockchain.NetworkBroadcaster = secondNetwork; firstNetwork.Start(); secondNetwork.Start(); #endregion firstWallet.Blockchain = firstBlockchain; secondWallet.Blockchain = secondBlockchain; firstWallet.SendTokens(16, secondWallet.PublicKey); firstWallet.SendTokens(8, secondWallet.PublicKey); secondBlockchain.ProcessPendingTransactions(); secondWallet.SendTokens(8, firstWallet.PublicKey); firstBlockchain.ProcessPendingTransactions(); Console.WriteLine("First blockchain:\n"); foreach (Block block in firstBlockchain) { Console.WriteLine(JsonConvert.SerializeObject(block, Formatting.Indented)); Console.WriteLine(); } Console.WriteLine("--------------------------------------------------------------------------------------"); Console.WriteLine("Second blockchain:\n"); foreach (Block block in secondBlockchain) { Console.WriteLine(JsonConvert.SerializeObject(block, Formatting.Indented)); Console.WriteLine(); } Console.WriteLine("}\n"); Console.WriteLine(firstBlockchain.IsValid ? "First blockchain is valid" : "First blockchain is invalid"); Console.WriteLine(firstBlockchain.IsValid ? "Second blockchain is valid" : "Second blockchain is invalid"); Console.WriteLine($"Cryptocurrency ownership for first wallet: {firstBlockchain.CountBalanceForWallet(firstWallet.PublicKey)}"); Console.WriteLine($"Cryptocurrency ownership for second wallet: {firstBlockchain.CountBalanceForWallet(secondWallet.PublicKey)}"); }
public Buffer Reply(PeerAddress sender, Buffer requestBuffer, bool complete) { // server returns just OK if same buffer is returned return(requestBuffer); }
public SendDirectBuilder(Peer peer, PeerAddress peerAddress) { _peer = peer; RecipientAddress = peerAddress; TcsRecipientConnection = null; }
/** Returns true if the given address has been seen via markBroadcastBy() */ public boolean wasBroadcastBy(PeerAddress address) { return(broadcastBy.contains(address)); }
public void TestBitcoinSerialize() { var pa = new PeerAddress(IPAddress.Loopback, 8333, 0); Assert.AreEqual("000000000000000000000000000000000000ffff7f000001208d", Utils.BytesToHexString(pa.BitcoinSerialize())); }
public static void Encode(IByteWriter stream, PeerAddress encodedPeerAddress) { PeerAddressIp.Encode(stream, encodedPeerAddress.Ip); Uint32.Encode(stream, encodedPeerAddress.Port); Uint32.Encode(stream, encodedPeerAddress.NumFailures); }
/// <summary> /// Sets a new address for this peer. /// </summary> /// <param name="serverPeerAddress">The new address of this peer.</param> /// <returns>This class.</returns> public PeerBean SetServerPeerAddress(PeerAddress serverPeerAddress) { ServerPeerAddress = serverPeerAddress; return(this); }
public static Message.Message CreateResponseMessage(Message.Message requestMessage, Message.Message.MessageType replyType, PeerAddress peerAddress) { // this will have the ports >40'000 that we need to know for sending the reply return new Message.Message() .SetSenderSocket(requestMessage.SenderSocket) .SetRecipientSocket(requestMessage.RecipientSocket) .SetRecipient(requestMessage.Sender) .SetSender(peerAddress) .SetCommand(requestMessage.Command) .SetType(replyType) .SetVersion(requestMessage.Version) .SetMessageId(requestMessage.MessageId) .SetIsUdp(requestMessage.IsUdp); }
public PeerConnection ChangeRemotePeer(PeerAddress remotePeer) { return(new PeerConnection(_oneConnection, remotePeer, ChannelCreator, _initiator, _map, _tcsClose, HeartBeatMillis, _channel)); }
public TcpClientPeerConnection(ClientPeer clientPeer, PeerAddress clientPeerAddress) : base(clientPeer, clientPeerAddress) { }
private bool DecodePayload(AlternativeCompositeByteBuf buffer) { Logger.Debug("About to pass message {0} to {1}. Buffer to read: {2}.", Message, Message.SenderSocket, buffer.ReadableBytes); if (!Message.HasContent()) { return(true); } int size; IPublicKey receivedPublicKey; while (_contentTypes.Count > 0) { Message.Content content = _contentTypes.Peek(); Logger.Debug("Go for content: {0}.", content); switch (content) { case Message.Content.Integer: if (buffer.ReadableBytes < Utils.Utils.IntegerByteSize) { return(false); } Message.SetIntValue(buffer.ReadInt()); LastContent = _contentTypes.Dequeue(); break; case Message.Content.Long: if (buffer.ReadableBytes < Utils.Utils.LongByteSize) { return(false); } Message.SetLongValue(buffer.ReadLong()); LastContent = _contentTypes.Dequeue(); break; case Message.Content.Key: if (buffer.ReadableBytes < Number160.ByteArraySize) { return(false); } var keyBytes = new sbyte[Number160.ByteArraySize]; buffer.ReadBytes(keyBytes); Message.SetKey(new Number160(keyBytes)); LastContent = _contentTypes.Dequeue(); break; case Message.Content.BloomFilter: if (buffer.ReadableBytes < Utils.Utils.ShortByteSize) { return(false); } size = buffer.GetUShort(buffer.ReaderIndex); if (buffer.ReadableBytes < size) { return(false); } Message.SetBloomFilter(new SimpleBloomFilter <Number160>(buffer)); LastContent = _contentTypes.Dequeue(); break; case Message.Content.SetNeighbors: if (_neighborSize == -1 && buffer.ReadableBytes < Utils.Utils.ByteByteSize) { return(false); } if (_neighborSize == -1) { _neighborSize = buffer.ReadByte(); } if (_neighborSet == null) { _neighborSet = new NeighborSet(-1, new List <PeerAddress>(_neighborSize)); } for (int i = _neighborSet.Size; i < _neighborSize; i++) { if (buffer.ReadableBytes < Utils.Utils.ShortByteSize) { return(false); } int header = buffer.GetUShort(buffer.ReaderIndex); size = PeerAddress.CalculateSize(header); if (buffer.ReadableBytes < size) { return(false); } var pa = new PeerAddress(buffer); _neighborSet.Add(pa); } Message.SetNeighborSet(_neighborSet); LastContent = _contentTypes.Dequeue(); _neighborSize = -1; // TODO why here? not in prepareFinish()? _neighborSet = null; break; case Message.Content.SetPeerSocket: if (_peerSocketAddressSize == -1 && buffer.ReadableBytes < Utils.Utils.ByteByteSize) { return(false); } if (_peerSocketAddressSize == -1) { _peerSocketAddressSize = buffer.ReadUByte(); } if (_peerSocketAddresses == null) { _peerSocketAddresses = new List <PeerSocketAddress>(_peerSocketAddressSize); } for (int i = _peerSocketAddresses.Count; i < _peerSocketAddressSize; i++) { if (buffer.ReadableBytes < Utils.Utils.ByteByteSize) { return(false); } int header = buffer.GetUByte(buffer.ReaderIndex); bool isIPv4 = header == 0; // TODO check if works size = PeerSocketAddress.Size(isIPv4); if (buffer.ReadableBytes < size + Utils.Utils.ByteByteSize) { return(false); } // skip the ipv4/ipv6 header buffer.SkipBytes(1); _peerSocketAddresses.Add(PeerSocketAddress.Create(buffer, isIPv4)); } Message.SetPeerSocketAddresses(_peerSocketAddresses); LastContent = _contentTypes.Dequeue(); _peerSocketAddressSize = -1; // TODO why here? not in prepareFinish()? _peerSocketAddresses = null; break; case Message.Content.SetKey640: if (_keyCollectionSize == -1 && buffer.ReadableBytes < Utils.Utils.IntegerByteSize) { return(false); } if (_keyCollectionSize == -1) { _keyCollectionSize = buffer.ReadInt(); } if (_keyCollection == null) { _keyCollection = new KeyCollection(new List <Number640>(_keyCollectionSize)); } for (int i = _keyCollection.Size; i < _keyCollectionSize; i++) { if (buffer.ReadableBytes < 4 * Number160.ByteArraySize) { return(false); } var me = new sbyte[Number160.ByteArraySize]; buffer.ReadBytes(me); var locationKey = new Number160(me); buffer.ReadBytes(me); var domainKey = new Number160(me); buffer.ReadBytes(me); var contentKey = new Number160(me); buffer.ReadBytes(me); var versionKey = new Number160(me); _keyCollection.Add(new Number640(locationKey, domainKey, contentKey, versionKey)); } Message.SetKeyCollection(_keyCollection); LastContent = _contentTypes.Dequeue(); _keyCollectionSize = -1; // TODO why here? not in prepareFinish()? _keyCollection = null; break; case Message.Content.MapKey640Data: if (_mapSize == -1 && buffer.ReadableBytes < Utils.Utils.IntegerByteSize) { return(false); } if (_mapSize == -1) { _mapSize = buffer.ReadInt(); } if (_dataMap == null) { _dataMap = new DataMap(new Dictionary <Number640, Data>(2 * _mapSize)); } if (_data != null) { if (!_data.DecodeBuffer(buffer)) { return(false); } if (!_data.DecodeDone(buffer, Message.PublicKey(0), _signatureFactory)) { return(false); } _data = null; // TODO why here? not in prepareFinish()? _key = null; } for (int i = _dataMap.Size; i < _mapSize; i++) { if (_key == null) { if (buffer.ReadableBytes < 4 * Number160.ByteArraySize) { return(false); } var me = new sbyte[Number160.ByteArraySize]; buffer.ReadBytes(me); var locationKey = new Number160(me); buffer.ReadBytes(me); var domainKey = new Number160(me); buffer.ReadBytes(me); var contentKey = new Number160(me); buffer.ReadBytes(me); var versionKey = new Number160(me); _key = new Number640(locationKey, domainKey, contentKey, versionKey); } _data = Data.DeocdeHeader(buffer, _signatureFactory); if (_data == null) { return(false); } _dataMap.BackingDataMap.Add(_key, _data); if (!_data.DecodeBuffer(buffer)) { return(false); } if (!_data.DecodeDone(buffer, Message.PublicKey(0), _signatureFactory)) { return(false); } // if we have signed the message, set the public key anyway, but only if we indicated so if (Message.IsSign && Message.PublicKey(0) != null && _data.HasPublicKey && (_data.PublicKey == null || _data.PublicKey == PeerBuilder.EmptyPublicKey)) // TODO check empty key condition { _data.SetPublicKey(Message.PublicKey(0)); } _data = null; // TODO why here? not in prepareFinish()? _key = null; } Message.SetDataMap(_dataMap); LastContent = _contentTypes.Dequeue(); _mapSize = -1; // TODO why here? not in prepareFinish()? _dataMap = null; break; case Message.Content.MapKey640Keys: if (_keyMap640KeysSize == -1 && buffer.ReadableBytes < Utils.Utils.IntegerByteSize) { return(false); } if (_keyMap640KeysSize == -1) { _keyMap640KeysSize = buffer.ReadInt(); } if (_keyMap640Keys == null) { _keyMap640Keys = new KeyMap640Keys(new SortedDictionary <Number640, ICollection <Number160> >()); // TODO check TreeMap equivalent } const int meta = 4 * Number160.ByteArraySize; for (int i = _keyMap640Keys.Size; i < _keyMap640KeysSize; i++) { if (buffer.ReadableBytes < meta + Utils.Utils.ByteByteSize) { return(false); } size = buffer.GetUByte(buffer.ReaderIndex + meta); if (buffer.ReadableBytes < meta + Utils.Utils.ByteByteSize + (size * Number160.ByteArraySize)) { return(false); } var me = new sbyte[Number160.ByteArraySize]; buffer.ReadBytes(me); var locationKey = new Number160(me); buffer.ReadBytes(me); var domainKey = new Number160(me); buffer.ReadBytes(me); var contentKey = new Number160(me); buffer.ReadBytes(me); var versionKey = new Number160(me); int numBasedOn = buffer.ReadByte(); var value = new HashSet <Number160>(); for (int j = 0; j < numBasedOn; j++) { buffer.ReadBytes(me); var basedOnKey = new Number160(me); value.Add(basedOnKey); } _keyMap640Keys.Put(new Number640(locationKey, domainKey, contentKey, versionKey), value); } Message.SetKeyMap640Keys(_keyMap640Keys); LastContent = _contentTypes.Dequeue(); _keyMap640KeysSize = -1; // TODO why here? not in prepareFinish()? _keyMap640Keys = null; break; case Message.Content.MapKey640Byte: if (_keyMapByteSize == -1 && buffer.ReadableBytes < Utils.Utils.IntegerByteSize) { return(false); } if (_keyMapByteSize == -1) { _keyMapByteSize = buffer.ReadInt(); } if (_keyMapByte == null) { _keyMapByte = new KeyMapByte(new Dictionary <Number640, sbyte>(2 * _keyMapByteSize)); } for (int i = _keyMapByte.Size; i < _keyMapByteSize; i++) { if (buffer.ReadableBytes < 4 * Number160.ByteArraySize + 1) { return(false); } var me = new sbyte[Number160.ByteArraySize]; buffer.ReadBytes(me); var locationKey = new Number160(me); buffer.ReadBytes(me); var domainKey = new Number160(me); buffer.ReadBytes(me); var contentKey = new Number160(me); buffer.ReadBytes(me); var versionKey = new Number160(me); sbyte value = buffer.ReadByte(); _keyMapByte.Put(new Number640(locationKey, domainKey, contentKey, versionKey), value); } Message.SetKeyMapByte(_keyMapByte); LastContent = _contentTypes.Dequeue(); _keyMapByteSize = -1; // TODO why here? not in prepareFinish()? _keyMapByte = null; break; case Message.Content.ByteBuffer: if (_bufferSize == -1 && buffer.ReadableBytes < Utils.Utils.IntegerByteSize) { return(false); } if (_bufferSize == -1) { _bufferSize = buffer.ReadInt(); } if (_buffer == null) { _buffer = new DataBuffer(); } int already = _buffer.AlreadyTransferred; int remaining = _bufferSize - already; // already finished if (remaining != 0) { int read = _buffer.TransferFrom(buffer, remaining); if (read != remaining) { Logger.Debug( "Still looking for data. Indicating that its not finished yet. Already Transferred = {0}, Size = {1}.", _buffer.AlreadyTransferred, _bufferSize); return(false); } } ByteBuf buf2 = AlternativeCompositeByteBuf.CompBuffer(_buffer.ToByteBufs()); Message.SetBuffer(new Buffer(buf2, _bufferSize)); LastContent = _contentTypes.Dequeue(); _bufferSize = -1; _buffer = null; break; case Message.Content.SetTrackerData: if (_trackerDataSize == -1 && buffer.ReadableBytes < Utils.Utils.ByteByteSize) { return(false); } if (_trackerDataSize == -1) { _trackerDataSize = buffer.ReadUByte(); } if (_trackerData == null) { _trackerData = new TrackerData(new Dictionary <PeerAddress, Data>(2 * _trackerDataSize)); } if (_currentTrackerData != null) { if (!_currentTrackerData.DecodeBuffer(buffer)) { return(false); } if (!_currentTrackerData.DecodeDone(buffer, Message.PublicKey(0), _signatureFactory)) { return(false); } _currentTrackerData = null; } for (int i = _trackerData.Size; i < _trackerDataSize; i++) { if (buffer.ReadableBytes < Utils.Utils.ShortByteSize) { return(false); } int header = buffer.GetUShort(buffer.ReaderIndex); size = PeerAddress.CalculateSize(header); if (buffer.ReadableBytes < Utils.Utils.ShortByteSize) { return(false); } var pa = new PeerAddress(buffer); _currentTrackerData = Data.DeocdeHeader(buffer, _signatureFactory); if (_currentTrackerData == null) { return(false); } _trackerData.PeerAddresses.Add(pa, _currentTrackerData); if (Message.IsSign) { _currentTrackerData.SetPublicKey(Message.PublicKey(0)); } if (!_currentTrackerData.DecodeBuffer(buffer)) { return(false); } if (!_currentTrackerData.DecodeDone(buffer, Message.PublicKey(0), _signatureFactory)) { return(false); } _currentTrackerData = null; // TODO why here? } Message.SetTrackerData(_trackerData); LastContent = _contentTypes.Dequeue(); _trackerDataSize = -1; _trackerData = null; break; case Message.Content.PublicKey: // fall-through case Message.Content.PublicKeySignature: receivedPublicKey = _signatureFactory.DecodePublicKey(buffer); if (content == Message.Content.PublicKeySignature) { if (receivedPublicKey == PeerBuilder.EmptyPublicKey) // TODO check if works { // TODO throw InvalidKeyException throw new SystemException("The public key cannot be empty."); } } if (receivedPublicKey == null) { return(false); } Message.SetPublicKey(receivedPublicKey); LastContent = _contentTypes.Dequeue(); break; default: break; } } if (Message.IsSign) { var signatureEncode = _signatureFactory.SignatureCodec; size = signatureEncode.SignatureSize; if (buffer.ReadableBytes < size) { return(false); } signatureEncode.Read(buffer); Message.SetReceivedSignature(signatureEncode); } return(true); }
/// <summary> /// Set the ID of the recipient. The IP is used to connect to the recipient, but the IP is NOT transferred. /// </summary> /// <param name="recipient">The ID of the recipient.</param> /// <returns>This class.</returns> public Message SetRecipient(PeerAddress recipient) { Recipient = recipient; return this; }
public ClientInfo PeerAddress(PeerAddress peerAddress) { _peerAddress = peerAddress; return this; }
public static void Encode(XdrDataOutputStream stream, PeerAddress encodedPeerAddress) { PeerAddressIp.Encode(stream, encodedPeerAddress.Ip); Uint32.Encode(stream, encodedPeerAddress.Port); Uint32.Encode(stream, encodedPeerAddress.NumFailures); }