/// <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; }
/// <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); }
/// <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"); } }
/// <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); }
/// <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; }
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(); } }
/// <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); } }); }
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)); }
/// <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); } }); } }
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; }
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); }
public KeyValuePair <PeerAddress, Data>?Get(Number160 key) { foreach (var peerAddress in _peerAddresses.Where(peerAddress => peerAddress.Key.PeerId.Equals(key))) { return(peerAddress); } return(null); }
public Sender(Number160 peerId, IList<IPeerStatusListener> peerStatusListeners, ChannelClientConfiguration channelClientConfiguration, Dispatcher dispatcher) { _peerStatusListeners = peerStatusListeners; ChannelClientConfiguration = channelClientConfiguration; _dispatcher = dispatcher; _random = new InteropRandom((ulong)peerId.GetHashCode()); }
public KeyCollection(ICollection <Number640> keys) { Keys = keys; KeysConvert = null; LocationKey = null; DomainKey = null; VersionKey = null; }
public Sender(Number160 peerId, IList <IPeerStatusListener> peerStatusListeners, ChannelClientConfiguration channelClientConfiguration, Dispatcher dispatcher) { _peerStatusListeners = peerStatusListeners; ChannelClientConfiguration = channelClientConfiguration; _dispatcher = dispatcher; _random = new InteropRandom((ulong)peerId.GetHashCode()); }
/// <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); }
public DigestBuilder(PeerDht peerDht, Number160 locationKey) : base(peerDht, locationKey) { IsAscending = true; IsBloomFilterAnd = true; IsFastGet = true; ReturnNr = -1; SetSelf(this); }
public KeyCollection(Number160 locationKey, Number160 domainKey, Number160 versionKey, ICollection <Number160> keysConvert) { Keys = null; KeysConvert = keysConvert; LocationKey = locationKey; DomainKey = domainKey; VersionKey = versionKey; }
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 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); }
/// <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; }
public SearchValues(Number160 locationKey, Number160 domainKey, Number640 from, Number640 to) { LocationKey = locationKey; DomainKey = domainKey; ContentKey = null; KeyBloomFilter = null; ContentBloomFilter = null; From = from; To = to; }
/// <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; }
/// <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; }
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); }
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); }
/// <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; }
/// <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)); }
/// <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); }
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); }
/// <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); }
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; }
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); }
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; }
/// <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; }
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; }
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; }
public Number160 FindPeerIdsForResponsibleContent(Number160 locationKey) { var lockResp = LockResponsibility(locationKey); try { return _backend.FindPeerIdsForResponsibleContent(locationKey); } finally { lockResp.Unlock(); } }
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(); } }
/// <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; }
/// <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) { }
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; }
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)); }
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); }
/// <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; }
/// <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); }
public BroadcastBuilder Broadcast(Number160 messageKey) { return new BroadcastBuilder(this, messageKey); }
private static bool IsMine(Number160 key, IPublicKey publicKey) { return key.Equals(Utils.MakeShaHash(publicKey.GetEncoded())); }
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; }
// 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; }
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(); } }