コード例 #1
0
        public void TestInteropSeed()
        {
            // use the same seed as in Java
            const int seed    = 1234567890;
            var       random  = new InteropRandom(seed);
            var       result1 = random.NextInt(1000);
            var       result2 = random.NextInt(500);
            var       result3 = random.NextInt(10);

            // requires same results as in Java
            // result1 is 677
            // result2 is 242
            // result3 is 1
            Assert.AreEqual(result1, 677);
            Assert.AreEqual(result2, 242);
            Assert.AreEqual(result3, 1);
        }
コード例 #2
0
        private static Number160 CreateRandomId(InteropRandom rnd)
        {
            var vals = new int[Number160.IntArraySize];

            for (int i = 0; i < vals.Length; i++)
            {
                vals[i] = rnd.NextInt(Int32.MaxValue);
            }
            return(new Number160(vals));
        }
コード例 #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="item"></param>
        /// <returns>Always returns false.</returns>
        public bool Add(T item)
        {
            var r = new InteropRandom((ulong)item.GetHashCode());

            for (int x = 0; x < _k; x++)
            {
                BitArray.Set(r.NextInt(_bitArraySize), true);
            }
            return(false);
        }
コード例 #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <returns>False indicates that o was definitely not added to this BloomFilter, true indicates that it probably was. The probability can be estimated using the expectedFalsePositiveProbability() method.</returns>
        public bool Contains(Object obj)
        {
            var r = new InteropRandom((ulong)obj.GetHashCode());

            for (int x = 0; x < _k; x++)
            {
                if (!BitArray.Get(r.NextInt(_bitArraySize)))
                {
                    return(false);
                }
            }
            return(true);
        }
コード例 #5
0
        /// <summary>
        /// Sends a message via UDP.
        /// </summary>
        /// <param name="handler">The handler to deal with the response message.</param>
        /// <param name="tcsResponse">The TCS for the response message. (FutureResponse equivalent.)</param>
        /// <param name="message">The message to send.</param>
        /// <param name="channelCreator">The channel creator for the UDP channel.</param>
        /// <param name="idleUdpSeconds">The idle time of a message until fail.</param>
        /// <param name="broadcast">True, if the message is to be sent via layer 2 broadcast.</param>
        /// <returns>The response message or null, if it is fire-and-forget or a failure occurred.</returns>
        public async Task SendUdpAsync(IInboundHandler handler, TaskCompletionSource <Message.Message> tcsResponse, Message.Message message, ChannelCreator channelCreator, int idleUdpSeconds, bool broadcast)
        {
            // no need to continue if already finished
            if (tcsResponse.Task.IsCompleted)
            {
                return;
            }
            RemovePeerIfFailed(tcsResponse, message);

            bool isFireAndForget = handler == null;

            // relay options
            if (message.Sender.IsRelayed)
            {
                message.SetPeerSocketAddresses(message.Sender.PeerSocketAddresses);

                IList <PeerSocketAddress> relayAddresses = new List <PeerSocketAddress>(message.Recipient.PeerSocketAddresses);
                Logger.Debug("Send neighbor request to random relay peer {0}.", relayAddresses);
                if (relayAddresses.Count > 0)
                {
                    var relayAddress = relayAddresses[_random.NextInt(relayAddresses.Count)];
                    message.SetRecipientRelay(message.Recipient
                                              .ChangePeerSocketAddress(relayAddress)
                                              .ChangeIsRelayed(true));
                }
                else
                {
                    const string msg = "Peer is relayed, but no relay is given.";
                    Logger.Error(msg);
                    tcsResponse.SetException(new TaskFailedException(msg));
                    return;
                }
            }

            // check for invalid UDP connection to unreachable peers
            if (message.Recipient.IsRelayed && message.Command != Rpc.Rpc.Commands.Neighbor.GetNr() &&
                message.Command != Rpc.Rpc.Commands.Ping.GetNr())
            {
                string msg =
                    String.Format(
                        "Tried to send a UDP message to unreachable peers. Only TCP messages can be sent to unreachable peers: {0}.",
                        message);
                Logger.Warn(msg);
                tcsResponse.SetException(new TaskFailedException(msg));
                return;
            }

            // pipeline handler setup
            TimeoutFactory timeoutFactory = CreateTimeoutHandler(tcsResponse, idleUdpSeconds, isFireAndForget);
            var            handlers       = new Dictionary <string, IChannelHandler>();

            if (!isFireAndForget)
            {
                handlers.Add("timeout0", timeoutFactory.CreateIdleStateHandlerTomP2P());
                handlers.Add("timeout1", timeoutFactory.CreateTimeHandler());
            }
            handlers.Add("decoder", new TomP2PSinglePacketUdp(ChannelClientConfiguration.SignatureFactory));
            handlers.Add("encoder", new TomP2POutbound(false, ChannelClientConfiguration.SignatureFactory));
            if (!isFireAndForget)
            {
                handlers.Add("handler", handler);
            }

            // create UDP channel
            MyUdpClient udpClient = null;

            try
            {
                udpClient = channelCreator.CreateUdp(broadcast, handlers);
            }
            catch (Exception ex)
            {
                string msg = "Channel creation failed. " + ex;
                Logger.Debug(msg);
                tcsResponse.SetException(ex);
                // may have been closed by the other side
                // or it may have been canceled from this side
            }

            // "afterConnect"
            // check if channel could be created (due to shutdown)
            if (udpClient == null)
            {
                const string msg = "Could not create a UDP socket. (Due to shutdown.)";
                Logger.Warn(msg);
                tcsResponse.SetException(new TaskFailedException(msg));
                return;
            }
            Logger.Debug("About to connect to {0} with channel {1}, ff = {2}.", message.Recipient, udpClient, isFireAndForget);

            // send request message
            // processes client-side outbound pipeline
            // (await for possible exception re-throw, does not block)
            await udpClient.SendMessageAsync(message);

            // if not fire-and-forget, receive response
            if (isFireAndForget)
            {
                Logger.Debug("Fire and forget message {0} sent. Close channel {1} now.", message, udpClient);
                tcsResponse.SetResult(null); // set FF result
            }
            else
            {
                // receive response message
                // processes client-side inbound pipeline
                await udpClient.ReceiveMessageAsync();
            }
            udpClient.Close();
        }