Exemple #1
0
        /// <summary>
        /// Creates a master peer and starts UDP and TCP channels.
        /// </summary>
        /// <param name="p2PId">The ID of the network.</param>
        /// <param name="peerId">The ID of this peer.</param>
        /// <param name="keyPair">The key pair or null.</param>
        /// <param name="channelServerConfiguration">The server configuration to create the
        /// channel server that is used for listening for incoming connections.</param>
        /// <param name="channelClientConfiguration">The client-side configuration.</param>
        /// <param name="timer"></param>
        public PeerCreator(int p2PId, Number160 peerId, KeyPair keyPair,
                           ChannelServerConfiguration channelServerConfiguration,
                           ChannelClientConfiguration channelClientConfiguration,
                           ExecutorService timer)
        {
            // peer bean
            PeerBean = new PeerBean(keyPair);
            PeerAddress self = FindPeerAddress(peerId, channelClientConfiguration, channelServerConfiguration);

            PeerBean.SetServerPeerAddress(self);
            Logger.Info("Visible address to other peers: {0}.", self);

            // start server
            var dispatcher    = new Dispatcher(p2PId, PeerBean, channelServerConfiguration.HearBeatMillis);
            var channelServer = new ChannelServer(channelServerConfiguration, dispatcher, PeerBean.PeerStatusListeners);

            if (!channelServer.Startup())
            {
                ShutdownNetty();
                throw new IOException("Cannot bind to TCP or UDP port.");
            }

            // connection bean
            var sender      = new Sender(peerId, PeerBean.PeerStatusListeners, channelClientConfiguration, dispatcher);
            var reservation = new Reservation(channelClientConfiguration);

            ConnectionBean = new ConnectionBean(p2PId, dispatcher, sender, channelServer, reservation, channelClientConfiguration, timer);
            _master        = true;
        }
Exemple #2
0
        /// <summary>
        /// If we shutdown, we remove the handlers. This means that a server may respond that the handler is unknown.
        /// </summary>
        /// <param name="peerId">The ID of the peer to remove the handlers.</param>
        /// <param name="onBehalfOf">The IO Handler can be registered for the own use in behalf of another peer.
        /// (E.g., in case of a relay node.)</param>
        public void RemoveIOHandlers(Number160 peerId, Number160 onBehalfOf)
        {
            IDictionary <Number320, IDictionary <int, DispatchHandler> > copy = new Dictionary <Number320, IDictionary <int, DispatchHandler> >(_ioHandlers);

            copy.Remove(new Number320(peerId, onBehalfOf));
            _ioHandlers = new ReadOnlyDictionary <Number320, IDictionary <int, DispatchHandler> >(copy);
        }
Exemple #3
0
        /// <summary>
        /// Requests the server address from the user and stores it to the arguments.
        /// </summary>
        /// <param name="args"></param>
        private static void DetermineServerAddress(Arguments args)
        {
            // ask user for remote address
            Console.WriteLine("Please enter server address: [PeerID] [IP address] [TCP port] [UDP port]");
            var input = Console.ReadLine();

            if (input != null)
            {
                var parts = input.Split(' ');
                if (parts.Length != 4)
                {
                    throw new ArgumentException("PeerID, IP address, TCP and UDP ports required.");
                }
                var n160          = new Number160(parts[0]);
                var ip            = IPAddress.Parse(parts[1]);
                var tcpPort       = Int32.Parse(parts[2]);
                var udpPort       = Int32.Parse(parts[3]);
                var serverAddress = new PeerAddress(n160, ip, tcpPort, udpPort);
                args.Param = serverAddress;
            }
            else
            {
                throw new NullReferenceException("input");
            }
        }
Exemple #4
0
        /// <summary>
        /// Creates the peer address based on the network discovery that was done./>
        /// </summary>
        /// <param name="peerId">The ID of this peer.</param>
        /// <param name="channelClientConfiguration"></param>
        /// <param name="channelServerConfiguration"></param>
        /// <returns>The peer address of this peer.</returns>
        private static PeerAddress FindPeerAddress(Number160 peerId,
                                                   ChannelClientConfiguration channelClientConfiguration, ChannelServerConfiguration channelServerConfiguration)
        {
            string status = DiscoverNetworks.DiscoverInterfaces(channelClientConfiguration.BindingsOutgoing);

            Logger.Info("Status of external address search: " + status);

            IPAddress outsideAddress = channelClientConfiguration.BindingsOutgoing.FoundAddress;

            if (outsideAddress == null)
            {
                throw new IOException("Not listening to anything. Maybe the binding information is wrong.");
            }

            var peerSocketAddress = new PeerSocketAddress(outsideAddress,
                                                          channelServerConfiguration.Ports.TcpPort,
                                                          channelServerConfiguration.Ports.UdpPort);

            var self = new PeerAddress(peerId, peerSocketAddress,
                                       channelServerConfiguration.IsBehindFirewall,
                                       channelServerConfiguration.IsBehindFirewall,
                                       false, PeerAddress.EmptyPeerSocketAddresses);

            return(self);
        }
Exemple #5
0
        /// <summary>
        /// .NET constructor used to set default property values.
        /// </summary>
        private PeerBuilder(Number160 peerId, KeyPair keyPair)
        {
            PeerId = peerId;
            KeyPair = keyPair;

            P2PId = -1;
            TcpPort = -1;
            UdpPort = -1;
            TcpPortForwarding = -1;
            UdpPortForwarding = -1;
            InterfaceBindings = null;
            ExternalBindings = null;
            PeerMap = null;
            MasterPeer = null;
            ChannelServerConfiguration = null;
            ChannelClientConfiguration = null;
            BroadcastHandler = null;
            BloomfilterFactory = null;
            MaintenanceTask = null;

            IsEnabledHandshakeRpc = true;
            IsEnabledNeighborRpc = true;
            IsEnabledDirectDataRpc = true;
            IsEnabledBroadcastRpc = true;
            IsEnabledRoutingRpc = true;
            IsEnabledMaintenance = true;
            IsEnabledQuitRpc = true;
        }
Exemple #6
0
        public void RemoveResponsibility(Number160 locationKey, bool keepData)
        {
            var lockResp = LockResponsibility(locationKey);

            try
            {
                if (!keepData)
                {
                    var rangeLock = Lock(locationKey);
                    try
                    {
                        var removed = _backend.Remove(
                            new Number640(locationKey, Number160.Zero, Number160.Zero, Number160.Zero),
                            new Number640(locationKey, Number160.MaxValue, Number160.MaxValue, Number160.MaxValue),
                            false);
                        foreach (var num640 in removed.Keys)
                        {
                            _backend.RemoveTimeout(num640);
                        }
                    }
                    finally
                    {
                        rangeLock.Unlock();
                    }
                }
                _backend.RemoveResponsibility(locationKey);
            }
            finally
            {
                lockResp.Unlock();
            }
        }
Exemple #7
0
        /// <summary>
        /// This method is called on relaying peers. We select a random set and we send the message
        /// to those random peers.
        /// </summary>
        /// <param name="messageKey">The key of the message.</param>
        /// <param name="dataMap">The data map to send around.</param>
        /// <param name="hopCounter">The number of hops.</param>
        /// <param name="isUdp">Flag indicating whether the message can be sent with UDP.</param>
        private void OtherPeer(Number160 messageKey, IDictionary <Number640, Data> dataMap, int hopCounter, bool isUdp)
        {
            Logger.Debug("Other");
            var list = _peer.PeerBean.PeerMap.All;
            int max  = Math.Min(Nr, list.Count);

            var taskCc = _peer.ConnectionBean.Reservation.CreateAsync(isUdp ? max : 0, isUdp ? 0 : max);

            taskCc.ContinueWith(tcc =>
            {
                if (!tcc.IsFaulted)
                {
                    var taskResponses = new Task[max];
                    for (int i = 0; i < max; i++)
                    {
                        var randomAddress = list.RemoveAt2(_rnd.Next(list.Count));

                        var broadcastBuilder = new BroadcastBuilder(_peer, messageKey);
                        broadcastBuilder.SetDataMap(dataMap);
                        broadcastBuilder.SetHopCounter(hopCounter + 1);
                        broadcastBuilder.SetIsUdp(isUdp);

                        taskResponses[i] = _peer.BroadcastRpc.SendAsync(randomAddress, broadcastBuilder, tcc.Result,
                                                                        broadcastBuilder);
                        Logger.Debug("2nd broadcast to {0}.", randomAddress);
                    }
                    Utils.Utils.AddReleaseListener(tcc.Result, taskResponses);
                }
                else
                {
                    Utils.Utils.AddReleaseListener(tcc.Result);
                }
            });
        }
Exemple #8
0
        public static PeerAddress CreateAddress(int iid, int portTcp, int portUdp)
        {
            var id      = new Number160(iid);
            var address = IPAddress.Parse("127.0.0.1");

            return(new PeerAddress(id, address, portTcp, portUdp));
        }
Exemple #9
0
        /// <summary>
        /// The first peer is the initiator. The peer that wants to start the broadcast
        /// will send it to all its neighbors. Since this peer has an interest in sending,
        /// it should also work more than the other peers.
        /// </summary>
        /// <param name="messageKey">The key of the message.</param>
        /// <param name="dataMap">The data map to send around.</param>
        /// <param name="hopCounter">The number of hops.</param>
        /// <param name="isUdp">Flag indicating whether the message can be sent with UDP.</param>
        private void FirstPeer(Number160 messageKey, IDictionary <Number640, Data> dataMap, int hopCounter, bool isUdp)
        {
            var list = _peer.PeerBean.PeerMap.All;

            foreach (var peerAddress in list)
            {
                var         taskCc  = _peer.ConnectionBean.Reservation.CreateAsync(isUdp ? 1 : 0, isUdp ? 0 : 1);
                PeerAddress address = peerAddress;
                taskCc.ContinueWith(tcc =>
                {
                    if (!tcc.IsFaulted)
                    {
                        var broadcastBuilder = new BroadcastBuilder(_peer, messageKey);
                        broadcastBuilder.SetDataMap(dataMap);
                        broadcastBuilder.SetHopCounter(hopCounter + 1);
                        broadcastBuilder.SetIsUdp(isUdp);

                        var taskResponse = _peer.BroadcastRpc.SendAsync(address, broadcastBuilder, tcc.Result,
                                                                        broadcastBuilder);
                        Logger.Debug("1st broadcast to {0}.", address);
                        Utils.Utils.AddReleaseListener(tcc.Result, taskResponse);
                    }
                    else
                    {
                        Utils.Utils.AddReleaseListener(tcc.Result);
                    }
                });
            }
        }
Exemple #10
0
        /// <summary>
        /// .NET constructor used to set default property values.
        /// </summary>
        private PeerBuilder(Number160 peerId, KeyPair keyPair)
        {
            PeerId  = peerId;
            KeyPair = keyPair;

            P2PId                      = -1;
            TcpPort                    = -1;
            UdpPort                    = -1;
            TcpPortForwarding          = -1;
            UdpPortForwarding          = -1;
            InterfaceBindings          = null;
            ExternalBindings           = null;
            PeerMap                    = null;
            MasterPeer                 = null;
            ChannelServerConfiguration = null;
            ChannelClientConfiguration = null;
            BroadcastHandler           = null;
            BloomfilterFactory         = null;
            MaintenanceTask            = null;

            IsEnabledHandshakeRpc  = true;
            IsEnabledNeighborRpc   = true;
            IsEnabledDirectDataRpc = true;
            IsEnabledBroadcastRpc  = true;
            IsEnabledRoutingRpc    = true;
            IsEnabledMaintenance   = true;
            IsEnabledQuitRpc       = true;
        }
Exemple #11
0
 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;
 }
Exemple #12
0
        private bool IsEmpty(Number160 locationKey)
        {
            var from = new Number640(locationKey, Number160.Zero, Number160.Zero, Number160.Zero);
            var to   = new Number640(locationKey, Number160.MaxValue, Number160.MaxValue, Number160.MaxValue);
            var tmp  = _backend.SubMap(from, to, 1, false);

            return(tmp.Count == 0);
        }
Exemple #13
0
 public KeyValuePair <PeerAddress, Data>?Get(Number160 key)
 {
     foreach (var peerAddress in _peerAddresses.Where(peerAddress => peerAddress.Key.PeerId.Equals(key)))
     {
         return(peerAddress);
     }
     return(null);
 }
Exemple #14
0
 public Sender(Number160 peerId, IList<IPeerStatusListener> peerStatusListeners,
     ChannelClientConfiguration channelClientConfiguration, Dispatcher dispatcher)
 {
     _peerStatusListeners = peerStatusListeners;
     ChannelClientConfiguration = channelClientConfiguration;
     _dispatcher = dispatcher;
     _random = new InteropRandom((ulong)peerId.GetHashCode());
 }
Exemple #15
0
 public KeyCollection(ICollection <Number640> keys)
 {
     Keys        = keys;
     KeysConvert = null;
     LocationKey = null;
     DomainKey   = null;
     VersionKey  = null;
 }
Exemple #16
0
 public Sender(Number160 peerId, IList <IPeerStatusListener> peerStatusListeners,
               ChannelClientConfiguration channelClientConfiguration, Dispatcher dispatcher)
 {
     _peerStatusListeners       = peerStatusListeners;
     ChannelClientConfiguration = channelClientConfiguration;
     _dispatcher = dispatcher;
     _random     = new InteropRandom((ulong)peerId.GetHashCode());
 }
Exemple #17
0
        /// <summary>
        /// Creates peers for testing. The first peer will be used as the master.
        /// This means that shutting down the master will shut down all other peers as well.
        /// </summary>
        /// <param name="nrOfPeers"></param>
        /// <param name="rnd"></param>
        /// <param name="port"></param>
        /// <param name="automaticTask"></param>
        /// <param name="maintenance"></param>
        /// <returns></returns>
        public static Peer[] CreateNodes(int nrOfPeers, Random rnd, int port, IAutomaticTask automaticTask, bool maintenance)
        {
            var bindings = new Bindings();
            var peers    = new Peer[nrOfPeers];

            if (automaticTask != null)
            {
                var peerId  = new Number160(rnd);
                var peerMap = new PeerMap(new PeerMapConfiguration(peerId));
                peers[0] = new PeerBuilder(peerId)
                           .SetPorts(port)
                           .SetEnableMaintenance(maintenance)
                           .SetExternalBindings(bindings)
                           .SetPeerMap(peerMap)
                           .Start()
                           .AddAutomaticTask(automaticTask);
            }
            else
            {
                var peerId  = new Number160(rnd);
                var peerMap = new PeerMap(new PeerMapConfiguration(peerId));
                peers[0] = new PeerBuilder(peerId)
                           .SetPorts(port)
                           .SetEnableMaintenance(maintenance)
                           .SetExternalBindings(bindings)
                           .SetPeerMap(peerMap)
                           .Start();
            }
            Console.WriteLine("Created master peer: {0}.", peers[0].PeerId);
            for (int i = 1; i < nrOfPeers; i++)
            {
                if (automaticTask != null)
                {
                    var peerId  = new Number160(rnd);
                    var peerMap = new PeerMap(new PeerMapConfiguration(peerId));
                    peers[i] = new PeerBuilder(peerId)
                               .SetMasterPeer(peers[0])
                               .SetEnableMaintenance(maintenance)
                               .SetExternalBindings(bindings)
                               .SetPeerMap(peerMap)
                               .Start()
                               .AddAutomaticTask(automaticTask);
                }
                else
                {
                    var peerId  = new Number160(rnd);
                    var peerMap = new PeerMap(new PeerMapConfiguration(peerId).SetPeerNoVerification());
                    peers[i] = new PeerBuilder(peerId)
                               .SetMasterPeer(peers[0])
                               .SetEnableMaintenance(maintenance)
                               .SetExternalBindings(bindings)
                               .SetPeerMap(peerMap)
                               .Start();
                }
                Console.WriteLine("Created slave peer {0}: {1}.", i, peers[i].PeerId);
            }
            return(peers);
        }
Exemple #18
0
 public DigestBuilder(PeerDht peerDht, Number160 locationKey)
     : base(peerDht, locationKey)
 {
     IsAscending      = true;
     IsBloomFilterAnd = true;
     IsFastGet        = true;
     ReturnNr         = -1;
     SetSelf(this);
 }
Exemple #19
0
 public KeyCollection(Number160 locationKey, Number160 domainKey, Number160 versionKey,
                      ICollection <Number160> keysConvert)
 {
     Keys        = null;
     KeysConvert = keysConvert;
     LocationKey = locationKey;
     DomainKey   = domainKey;
     VersionKey  = versionKey;
 }
Exemple #20
0
        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);
        }
Exemple #21
0
 public override PutBuilder SetVersionKey(Number160 versionKey)
 {
     // if we set data before we set the version key, we need to adapt the version key of the data object
     if (!Data.Equals(default(KeyValuePair <Number640, Data>))) // TODO check if correct
     {
         SetData(Data.Key.LocationKey, Data.Key.DomainKey, Data.Key.ContentKey, versionKey, Data.Value);
     }
     base.SetVersionKey(versionKey);
     return(this);
 }
Exemple #22
0
 /// <summary>
 /// Searches for one content key.
 /// </summary>
 /// <param name="locationKey">The location key.</param>
 /// <param name="domainKey">The domain key.</param>
 /// <param name="contentKey">For Get() and Remove(), one can provide a content key
 /// and the remote peer indicates if this key is on that peer.</param>
 public SearchValues(Number160 locationKey, Number160 domainKey, Number160 contentKey)
 {
     LocationKey        = locationKey;
     DomainKey          = domainKey;
     ContentKey         = contentKey;
     KeyBloomFilter     = null;
     ContentBloomFilter = null;
     From = null;
     To   = null;
 }
Exemple #23
0
 public SearchValues(Number160 locationKey, Number160 domainKey, Number640 from, Number640 to)
 {
     LocationKey        = locationKey;
     DomainKey          = domainKey;
     ContentKey         = null;
     KeyBloomFilter     = null;
     ContentBloomFilter = null;
     From = from;
     To   = to;
 }
Exemple #24
0
 /// <summary>
 /// Searches for multiple content keys. There may be false positives.
 /// </summary>
 /// <param name="locationKey">The location key.</param>
 /// <param name="domainKey">The domain key.</param>
 /// <param name="keyBloomFilter">For Get() and Remove() one can provide a bloom filter of
 /// content keys and the remote peer indicates if those keys are on that peer.</param>
 public SearchValues(Number160 locationKey, Number160 domainKey, SimpleBloomFilter <Number160> keyBloomFilter)
 {
     LocationKey        = locationKey;
     DomainKey          = domainKey;
     ContentKey         = null;
     KeyBloomFilter     = keyBloomFilter;
     ContentBloomFilter = null;
     From = null;
     To   = null;
 }
Exemple #25
0
        /// <summary>
        /// Creates a slave peer that will attach itself to a master peer.
        /// </summary>
        /// <param name="parent">The parent peer.</param>
        /// <param name="peerId">The ID of this peer.</param>
        /// <param name="keyPair">The key pair or null.</param>
        public PeerCreator(PeerCreator parent, Number160 peerId, KeyPair keyPair)
        {
            parent._childConnections.Add(this);
            ConnectionBean = parent.ConnectionBean;
            PeerBean       = new PeerBean(keyPair);
            PeerAddress self = parent.PeerBean.ServerPeerAddress.ChangePeerId(peerId);

            PeerBean.SetServerPeerAddress(self);
            _master = false;
        }
Exemple #26
0
 public SearchValues(Number160 locationKey, Number160 domainKey, Number640 from, Number640 to)
 {
     LocationKey = locationKey;
     DomainKey = domainKey;
     ContentKey = null;
     KeyBloomFilter = null;
     ContentBloomFilter = null;
     From = from;
     To = to;
 }
Exemple #27
0
 private bool ForceOverrideEntry(Number160 entryKey, IPublicKey publicKey)
 {
     // we are in public key mode
     if (ProtectionEntryMode == ProtectionMode.MasterPublicKey && publicKey?.GetEncoded() != null)
     {
         // if the hash of the public key is the same as the domain, we can overwrite
         return(IsMine(entryKey, publicKey));
     }
     return(false);
 }
Exemple #28
0
 /// <summary>
 /// Searches for one content key.
 /// </summary>
 /// <param name="locationKey">The location key.</param>
 /// <param name="domainKey">The domain key.</param>
 /// <param name="contentKey">For Get() and Remove(), one can provide a content key
 /// and the remote peer indicates if this key is on that peer.</param>
 public SearchValues(Number160 locationKey, Number160 domainKey, Number160 contentKey)
 {
     LocationKey = locationKey;
     DomainKey = domainKey;
     ContentKey = contentKey;
     KeyBloomFilter = null;
     ContentBloomFilter = null;
     From = null;
     To = null;
 }
Exemple #29
0
 private bool ForceOverrideDomain(Number160 domainKey, IPublicKey publicKey)
 {
     // we are in public key mode
     if (ProtectionDomainMode == ProtectionMode.MasterPublicKey && publicKey != null)
     {
         // if the hash of the public key is the same as the domain, we can overwrite
         return(IsMine(domainKey, publicKey));
     }
     return(false);
 }
Exemple #30
0
 /// <summary>
 /// Searches for multiple content keys. There may be false positives.
 /// </summary>
 /// <param name="locationKey">The location key.</param>
 /// <param name="domainKey">The domain key.</param>
 /// <param name="keyBloomFilter">For Get() and Remove() one can provide a bloom filter of
 /// content keys and the remote peer indicates if those keys are on that peer.</param>
 public SearchValues(Number160 locationKey, Number160 domainKey, SimpleBloomFilter<Number160> keyBloomFilter)
 {
     LocationKey = locationKey;
     DomainKey = domainKey;
     ContentKey = null;
     KeyBloomFilter = keyBloomFilter;
     ContentBloomFilter = null;
     From = null;
     To = null;
 }
Exemple #31
0
        /// <summary>
        /// Adds data on a remote peer. The main difference to PUT is that it will convert the data collection to a map.
        /// The key for the map will be the SHA-1 hash of the data.
        /// </summary>
        /// <param name="remotePeer">The remote peer on which to store the data.</param>
        /// <param name="addBuilder">The builder to use for this operation.</param>
        /// <param name="channelCreator">The channel creator that will be used.</param>
        /// <returns>The future response message.</returns>
        public Task <Message> AddAsync(PeerAddress remotePeer, AddBuilder addBuilder, ChannelCreator channelCreator)
        {
            Utils.NullCheck(remotePeer, addBuilder.LocationKey, addBuilder.DomainKey);

            Message.MessageType type;
            if (addBuilder.IsProtectDomain)
            {
                type = addBuilder.IsList ? Message.MessageType.Request4 : Message.MessageType.Request2;
            }
            else
            {
                type = addBuilder.IsList ? Message.MessageType.Request3 : Message.MessageType.Request1;
            }

            // convert the data
            var dataMap = new SortedDictionary <Number160, Data>();

            if (addBuilder.DataSet != null)
            {
                foreach (var data in addBuilder.DataSet)
                {
                    if (addBuilder.IsList)
                    {
                        Number160 hash;
                        do
                        {
                            hash = new Number160(addBuilder.Random);
                        } while (dataMap.ContainsKey(hash));
                        dataMap.Add(hash, data);
                    }
                    else
                    {
                        dataMap.Add(data.Hash, data);
                    }
                }
            }

            var message = CreateRequestMessage(remotePeer, Rpc.Commands.Add.GetNr(), type);

            if (addBuilder.IsSign)
            {
                message.SetPublicKeyAndSign(addBuilder.KeyPair);
            }

            message.SetDataMap(new DataMap(addBuilder.LocationKey, addBuilder.DomainKey, addBuilder.VersionKey, dataMap));

            var tcsResponse    = new TaskCompletionSource <Message>(message);
            var requestHandler = new RequestHandler(tcsResponse, PeerBean, ConnectionBean, addBuilder);

            if (!addBuilder.IsForceUdp)
            {
                return(requestHandler.SendTcpAsync(channelCreator));
            }
            return(requestHandler.SendUdpAsync(channelCreator));
        }
Exemple #32
0
        /// <summary>
        /// Returns the PeerConnection for the given Number160 peer ID.
        /// </summary>
        /// <param name="peerId">The ID of the peer.</param>
        /// <returns>The connection associated to the peer ID.</returns>
        public PeerConnection PeerConnection(Number160 peerId)
        {
            PeerConnection peerConnection = OpenPeerConnections[peerId];

            if (peerConnection != null)
            {
                return(peerConnection);
            }
            Logger.Error("There was no PeerConnection for peer ID = " + peerId);
            return(null);
        }
Exemple #33
0
 public KeyValuePair <PeerAddress, Data>?Remove(Number160 remotePeerId)
 {
     // TODO check if LINQ is calculated multiple times (2x)
     // TODO this might throw an exception (removing from current iteration) (2x)
     foreach (var peerAddress in _peerAddresses.Where(peerAddress => peerAddress.Key.PeerId.Equals(remotePeerId)))
     {
         _peerAddresses.Remove(peerAddress);
         return(peerAddress);
     }
     return(null);
 }
Exemple #34
0
        /// <summary>
        /// If a message is seen for the second time, then we don't want to send this message again.
        /// The cache has a size of 1024 entries and the objects have a default lifetime of 60s.
        /// </summary>
        /// <param name="messageKey">The key of the message.</param>
        /// <returns>True, if this message was sent withing the last 60 seconds.</returns>
        private bool TwiceSeen(Number160 messageKey)
        {
            var isInCache = _cache.PutIfAbsent(messageKey, new ReferenceStruct <bool>(true));

            if (isInCache != null)
            {
                // ttl refresh
                _cache.Put(messageKey, new ReferenceStruct <bool>(true));
                return(true);
            }
            return(false);
        }
Exemple #35
0
        public DataMap(Number160 loactionKey, Number160 domainKey, Number160 versionKey,
                       IDictionary <Number160, Data> dataMapConvert, bool isConvertMeta)
        {
            BackingDataMap = null;
            DataMapConvert = dataMapConvert;

            LocationKey = loactionKey;
            DomainKey   = domainKey;
            VersionKey  = versionKey;

            IsConvertMeta = isConvertMeta;
        }
Exemple #36
0
        public Number160 FindPeerIdsForResponsibleContent(Number160 locationKey)
        {
            var lockResp = LockResponsibility(locationKey);

            try
            {
                return(_backend.FindPeerIdsForResponsibleContent(locationKey));
            }
            finally
            {
                lockResp.Unlock();
            }
        }
        /// <summary>
        /// Constructor with reasonable defaults.
        /// </summary>
        /// <param name="self">The peer ID of this peer.</param>
        public PeerMapConfiguration(Number160 self)
        {
            Self = self;
            BagSizeVerified = 10;
            BagSizeOverflow = 10;
            OfflineTimeout = 60;
            ShutdownTimeout = 20;
            ExceptionTimeout = 120;
            OfflineCount = 3;
            Maintenance = new DefaultMaintenance(4, new[] { 2, 4, 8, 16, 32, 64 });
            IsPeerVerification = true;

            PeerFilters = new List<IPeerFilter>(2);
        }
Exemple #38
0
        public static Message CreateDummyMessage(Number160 idSender, String inetSender, int tcpPortSendor,
            int udpPortSender, Number160 idRecipient, String inetRecipient, int tcpPortRecipient,
            int udpPortRecipient, sbyte command, Message.MessageType type, bool firewallUdp, bool firewallTcp)
        {
            var message = new Message();

            PeerAddress n1 = CreateAddress(idSender, inetSender, tcpPortSendor, udpPortSender, firewallUdp, firewallTcp);
            message.SetSender(n1);
            //
            PeerAddress n2 = CreateAddress(idRecipient, inetRecipient, tcpPortRecipient, udpPortRecipient, firewallUdp, firewallTcp);
            message.SetRecipient(n2);
            message.SetType(type);
            message.SetCommand(command);
            return message;
        }
Exemple #39
0
 /// <summary>
 /// Registers a handler with this dispatcher. Future received messages adhering to the given parameters will be
 /// forwarded to that handler. Note that the dispatcher only handles REQUEST messages. This method is thread-safe,
 /// and uses copy on write as it is expected to run this only during initialization.
 /// </summary>
 /// <param name="peerId">Specifies the receiver the dispatcher filters for. This allows to use one dispatcher for 
 /// several interfaces or even nodes.</param>
 /// <param name="onBehalfOf">The IO Handler can be registered for the own use in behalf of another peer.
 /// (E.g., in case of a relay node.)</param>
 /// <param name="ioHandler">The handler which should process the given type of messages.</param>
 /// <param name="names">The command of the Message the given handler processes. All messages having that command will
 /// be forwarded to the given handler.
 /// Note: If you register multiple handlers with the same command, only the last registered handler will receive 
 /// these messages!</param>
 public void RegisterIOHandler(Number160 peerId, Number160 onBehalfOf, DispatchHandler ioHandler,
     params int[] names)
 {
     IDictionary<Number320, IDictionary<int, DispatchHandler>> copy = new Dictionary<Number320, IDictionary<int, DispatchHandler>>(_ioHandlers);
     IDictionary<int, DispatchHandler> types;
     
     // .NET specific
     copy.TryGetValue(new Number320(peerId, onBehalfOf), out types);
     if (types == null)
     {
         types = new Dictionary<int, DispatchHandler>();
         copy.Add(new Number320(peerId, onBehalfOf), types);
     }
     foreach (int name in names)
     {
         types.Put(name, ioHandler);
     }
     _ioHandlers = new ReadOnlyDictionary<Number320, IDictionary<int, DispatchHandler>>(copy);
 }
 public bool Reject(PeerAddress peerAddress, ICollection<PeerAddress> all, Number160 target)
 {
     // TODO in Java: to be implemented
     return false;
 }
Exemple #41
0
        private bool CanProtectEntry(Number160 contentKey, IPublicKey publicKey)
        {
		    if (ProtectionEntryEnable == ProtectionEnable.All)
            {
			    return true;
		    } 
            if (ProtectionEntryEnable == ProtectionEnable.None)
            {
			    // only if we have the master key
			    return ForceOverrideEntry(contentKey, publicKey);
		    }
		    return false;
	    }
Exemple #42
0
        private bool ForceOverrideDomain(Number160 domainKey, IPublicKey publicKey)
        {
		    // we are in public key mode
		    if (ProtectionDomainMode == ProtectionMode.MasterPublicKey && publicKey != null)
            {
			    // if the hash of the public key is the same as the domain, we can overwrite
			    return IsMine(domainKey, publicKey);
		    }
		    return false;
	    }
Exemple #43
0
        public Number160 FindPeerIdsForResponsibleContent(Number160 locationKey)
        {
		    var lockResp = LockResponsibility(locationKey);
		    try
            {
			    return _backend.FindPeerIdsForResponsibleContent(locationKey);
		    }
            finally
            {
			    lockResp.Unlock();
            }
	    }
Exemple #44
0
        public bool UpdateResponsibilities(Number160 locationKey, Number160 peerId)
        {
		    var lockResp1 = LockResponsibility(peerId);
		    var lockResp2 = LockResponsibility(locationKey);
            try
            {
                return _backend.UpdateResponsibilities(locationKey, peerId);
            }
            finally 
            {
        	    lockResp1.Unlock();
        	    lockResp2.Unlock();
            }
	    }
Exemple #45
0
 /// <summary>
 /// Creates a peer. Please use <see cref="PeerBuilder"/> to create a <see cref="Peer"/> instance.
 /// </summary>
 /// <param name="p2PId">The P2P ID.</param>
 /// <param name="peerId">The ID of the peer.</param>
 /// <param name="peerCreator">The peer creator that holds the peer bean and the connection bean.</param>
 internal Peer(int p2PId, Number160 peerId, PeerCreator peerCreator)
 {
     P2PId = p2PId;
     PeerId = peerId;
     PeerCreator = peerCreator;
 }
Exemple #46
0
        public void RemoveResponsibility(Number160 locationKey, bool keepData)
        {
		    var lockResp = LockResponsibility(locationKey);
		    try
            {
			    if (!keepData)
                {
				    var rangeLock = Lock(locationKey);
				    try
                    {
					    var removed = _backend.Remove(
						    new Number640(locationKey, Number160.Zero, Number160.Zero, Number160.Zero),
						    new Number640(locationKey, Number160.MaxValue, Number160.MaxValue, Number160.MaxValue),
						    false);
					    foreach (var num640 in removed.Keys)
                        {
						    _backend.RemoveTimeout(num640);
					    }
				    }
                    finally
                    {
					    rangeLock.Unlock();
		            }
			    }
        	    _backend.RemoveResponsibility(locationKey);
            }
            finally
            {
        	    lockResp.Unlock();
            }
	    }
Exemple #47
0
 /// <summary>
 /// Creates a peer builder with the provided peer ID and an empty key pair.
 /// </summary>
 /// <param name="peerId">The peer ID.</param>
 public PeerBuilder(Number160 peerId)
     : this(peerId, null)
 { }
Exemple #48
0
        private bool CanProtectDomain(Number160 domainKey, IPublicKey publicKey)
        {
		    if (IsDomainRemoved(domainKey))
            {
			    return false;
		    }
		    if (ProtectionDomainEnable == ProtectionEnable.All)
            {
			    return true;
		    } 
            if (ProtectionDomainEnable == ProtectionEnable.None) 
            {
			    // only if we have the master key
			    return ForceOverrideDomain(domainKey, publicKey);
		    }
		    return false;
	    }
Exemple #49
0
 private RangeLock<Number640>.Range Lock(Number160 number160)
 {
     return RangeLock.Lock(
         new Number640(number160, Number160.Zero, Number160.Zero, Number160.Zero), 
         new Number640(number160, Number160.MaxValue, Number160.MaxValue, Number160.MaxValue));
 }
Exemple #50
0
 private RangeLock<Number640>.Range LockResponsibility(Number160 number160)
 {
     return _responsibilityLock.Lock(
         new Number640(number160, Number160.Zero, Number160.Zero, Number160.Zero), 
         new Number640(number160, Number160.MaxValue, Number160.MaxValue, Number160.MaxValue));
 }
 public BroadcastBuilder(Peer peer, Number160 messageKey)
 {
     _peer = peer;
     MessageKey = messageKey;
 }
 /// <summary>
 /// Registers all names on the dispatcher on behalf of the provided peer.
 /// </summary>
 /// <param name="onBehalfOf">The IO handler can be registered for the own 
 /// use of in behalf of another peer. (e.g., iin case of a relay node)</param>
 /// <param name="names"></param>
 public void Register(Number160 onBehalfOf, params int[] names)
 {
     ConnectionBean.Dispatcher.RegisterIOHandler(PeerBean.ServerPeerAddress.PeerId, onBehalfOf, this, names);
 }
Exemple #53
0
        /// <summary>
        /// Looks for a registered handler according to the given parameters.
        /// </summary>
        /// <param name="recipientId">The ID of the recipient of the message.</param>
        /// <param name="onBehalfOf">The ID of the onBehalfOf peer.</param>
        /// <param name="command">The command of the message to be filtered for.</param>
        /// <returns>The handler for the provided parameters or null, if none has been found.</returns>
        public DispatchHandler SearchHandler(Number160 recipientId, Number160 onBehalfOf, int command)
        {
            IDictionary<int, DispatchHandler> commands;
            _ioHandlers.TryGetValue(new Number320(recipientId, onBehalfOf), out commands);

            if (commands != null && commands.ContainsKey(command))
            {
                return commands[command];
            }
            else
            {
                // not registered
                Logger.Debug("Handler not found for command {0}. Looking for the server with ID {1}.", command, recipientId);
                return null;
            }
        }
 public bool Reject(PeerAddress peerAddress, ICollection<PeerAddress> all, Number160 target)
 {
     // by default, don't reject anything
     return false;
 }
Exemple #55
0
 /// <summary>
 /// If we shutdown, we remove the handlers. This means that a server may respond that the handler is unknown.
 /// </summary>
 /// <param name="peerId">The ID of the peer to remove the handlers.</param>
 /// <param name="onBehalfOf">The IO Handler can be registered for the own use in behalf of another peer.
 /// (E.g., in case of a relay node.)</param>
 public void RemoveIOHandlers(Number160 peerId, Number160 onBehalfOf)
 {
     IDictionary<Number320, IDictionary<int, DispatchHandler>> copy = new Dictionary<Number320, IDictionary<int, DispatchHandler>>(_ioHandlers);
     copy.Remove(new Number320(peerId, onBehalfOf));
     _ioHandlers = new ReadOnlyDictionary<Number320, IDictionary<int, DispatchHandler>>(copy);
 }
Exemple #56
0
 public BroadcastBuilder Broadcast(Number160 messageKey)
 {
     return new BroadcastBuilder(this, messageKey);
 }
Exemple #57
0
        private static bool IsMine(Number160 key, IPublicKey publicKey)
        {
		    return key.Equals(Utils.MakeShaHash(publicKey.GetEncoded()));
	    }
Exemple #58
0
        private bool ForceOverrideEntry(Number160 entryKey, IPublicKey publicKey)
        {
		    // we are in public key mode
		    if (ProtectionEntryMode == ProtectionMode.MasterPublicKey && publicKey?.GetEncoded() != null)
            {
			    // if the hash of the public key is the same as the domain, we can overwrite
			    return IsMine(entryKey, publicKey);
		    }
		    return false;
	    }
Exemple #59
0
        // Header data ends here.
        // Static payload starts now.

        public Message SetKey(Number160 key)
        {
            if (!_presetContentTypes)
            {
                SetContentType(Content.Key);
            }
            if (_keyList == null)
            {
                _keyList = new List<Number160>(1);
            }
            _keyList.Add(key);
            return this;
        }
Exemple #60
0
        public ICollection<Number160> FindContentForResponsiblePeerId(Number160 peerId)
        {
		    var lockResp = LockResponsibility(peerId);
		    try 
            {
			    var contentIds = _backend.FindContentForResponsiblePeerId(peerId);
			    if (contentIds == null)
			    {
			        return Convenient.EmptyList<Number160>();
			    } else {
				    return new List<Number160>(contentIds);
			    }
		    } 
            finally
            {
			    lockResp.Unlock();
            }
	    }