Changeset 1022


Ignore:
Timestamp:
Dec 16, 2009, 5:55:00 PM (12 years ago)
Author:
Matthäus Wander
Message:

P2P:

  • implemented Equals and GetHashCode in PeerId
  • changed accessibility of PeerId variables to private -> lead to some refactoring
  • changed PeerId constructor to read ID from p@p OverlayAddress
  • added wrapper methods to retrieve OverlayAddress by byte[] id from p@p

Became some more complex than expected. It compiles and I hope it still works.

Location:
trunk/CrypPlugins
Files:
6 edited

Legend:

Unmodified
Added
Removed
  • trunk/CrypPlugins/PeerToPeerBase/IP2PControl.cs

    r971 r1022  
    8686
    8787        PeerId GetPeerID(out string sPeerName);
    88         //byte[] GetPeerID(out string sPeerName);
     88        PeerId GetPeerID(byte[] byteId);
    8989
    9090        void SendToPeer(string sData, PeerId destinationAddress);
     
    9696
    9797        PubSubMessageType GetMsgType(string byteData);
    98         string ConvertIdToString(byte[] byteId);
    9998
    10099        event P2PBase.P2PMessageReceived OnPeerReceivedMsg;
  • trunk/CrypPlugins/PeerToPeerBase/P2PPeer.cs

    r971 r1022  
    380380        }
    381381
     382        public PeerId GetPeerID(byte[] byteId)
     383        {
     384            return p2pPeer.p2pBase.GetPeerID(byteId);
     385        }
     386
    382387        public void SendToPeer(string sData, PeerId destinationAddress)
    383388        {
     
    416421        }
    417422
    418         public string ConvertIdToString(byte[] byteId)
    419         {
    420             string sRet = String.Empty;
    421             for (int i = 0; i < byteId.Length; i++)
    422             {
    423                 //sRet += UTF8Encoding.UTF8.GetString(byteId[i]) + ":";
    424                 sRet += Convert.ToString(byteId[i]) + ":";
    425             }
    426             return sRet;
    427         }
    428 
    429423        #endregion
    430424    }
  • trunk/CrypPlugins/PeerToPeerBase/PeerToPeerBase.cs

    r980 r1022  
    272272        {
    273273            sPeerName = this.linkmanager.UserName;
    274             PeerId pid = new PeerId(this.overlay.LocalAddress.ToString(), this.overlay.LocalAddress.ToByteArray());
    275             return pid;
     274            return new PeerId(this.overlay.LocalAddress);
     275        }
     276
     277        /// <summary>
     278        /// Construct PeerId object for a specific byte[] id
     279        /// </summary>
     280        /// <param name="byteId">overlay address as byte array</param>
     281        /// <returns>corresponding PeerId for given byte[] id</returns>
     282        public PeerId GetPeerID(byte[] byteId)
     283        {
     284            return new PeerId(overlay.GetAddress(byteId));
    276285        }
    277286
     
    299308        public void SendToPeer(string sData, PeerId destinationPeerId)
    300309        {
    301             SendToPeer(sData, destinationPeerId.byteId);
     310            SendToPeer(sData, destinationPeerId.ToByteArray());
    302311        }
    303312
    304313        public void SendToPeer(PubSubMessageType msgType, PeerId destinationAddress)
    305314        {
    306             SendToPeer(((int)msgType).ToString(), destinationAddress.byteId);
     315            SendToPeer(((int)msgType).ToString(), destinationAddress.ToByteArray());
    307316        }
    308317
     
    311320            if (OnP2PMessageReceived != null)
    312321            {
    313                 PeerId pid = new PeerId(e.Message.Source.ToString(), e.Message.Source.ToByteArray());
     322                PeerId pid = new PeerId(e.Message.Source);
    314323                OnP2PMessageReceived(pid, e.Message.Data.PopUTF8String());
    315324            }
     
    340349            if (OnP2PMessageReceived != null)
    341350            {
    342                 PeerId pid = new PeerId(e.Source.ToString(), e.Source.ToByteArray());
     351                PeerId pid = new PeerId(e.Source);
    343352                OnP2PMessageReceived(pid, e.Data.PopUTF8String());
    344353            }
     
    630639    public class PeerId
    631640    {
    632         public string stringId;
    633         public byte[] byteId;
    634 
    635         public PeerId(string sPid, byte[] byPid)
    636         {
    637             this.stringId = sPid;
    638             this.byteId = byPid;
    639         }
    640 
    641         public void Dispose()
    642         {
    643             this.byteId = null;
    644             this.stringId = String.Empty;
    645         }
    646 
    647        
     641        private readonly string stringId;
     642        private readonly byte[] byteId;
     643
     644        private const uint OFFSET_BASIS = 2166136261;
     645        private const uint PRIME = 16777619; // 2^24 + 2^8 + 0x93
     646        private readonly int hashCode;
     647
     648        public PeerId(OverlayAddress oAddress)
     649        {
     650            this.stringId = oAddress.ToString();
     651            this.byteId = oAddress.ToByteArray();
     652
     653            // FNV-1 hashing
     654            uint fnvHash = OFFSET_BASIS;
     655            foreach (byte b in byteId)
     656            {
     657                fnvHash = (fnvHash * PRIME) ^ b;
     658            }
     659            hashCode = (int)fnvHash;
     660        }
     661
     662        /// <summary>
     663        /// Returns true when the byteId content is identical
     664        /// </summary>
     665        /// <param name="right"></param>
     666        /// <returns></returns>
     667        public override bool Equals(object right)
     668        {
     669            /* standard checks for reference types */
     670
     671            if (right == null)
     672                return false;
     673
     674            if (object.ReferenceEquals(this, right))
     675                return true;
     676
     677            if (this.GetType() != right.GetType())
     678                return false;
     679
     680            // actual content comparison
     681            return this == (PeerId)right;
     682        }
     683
     684        public static bool operator ==(PeerId left, PeerId right)
     685        {
     686            if (left.hashCode != right.hashCode)
     687                return false;
     688
     689            if (left.byteId.Length != right.byteId.Length)
     690                return false;
     691
     692            for (int i = 0; i < left.byteId.Length; i++)
     693            {
     694                // uneven pattern content
     695                if (left.byteId[i] != right.byteId[i])
     696                    return false;
     697            }
     698
     699            return true;
     700        }
     701
     702        public static bool operator !=(PeerId left, PeerId right)
     703        {
     704            return !(left == right);
     705        }
     706
     707        public override int GetHashCode()
     708        {
     709            return hashCode;
     710        }
    648711
    649712        public override string ToString()
     
    655718        {
    656719            return this.byteId;
    657         }
    658 
    659         // not used at present...
    660         public bool Equals(PeerId otherPeerId)
    661         {
    662             if (this.stringId == otherPeerId.stringId)
    663                 return true;
    664             else
    665                 return false;
    666720        }
    667721    }
  • trunk/CrypPlugins/PeerToPeerPublisher/P2PPublisherBase.cs

    r980 r1022  
    7575            this.ownPeerId = myPeerId;
    7676
    77             // before storing the publishers ID in the DHT, proof whether there already exist an entry
     77            // before storing the publishers ID in the DHT, proof whether there already exists an entry
    7878            byte[] byRead = this.p2pControl.DHTload(sTopic);
    7979            // if byRead is not null, the DHT entry was already written
    8080            if (byRead != null)
    8181            {
     82                PeerId peerRead = this.p2pControl.GetPeerID(byRead);
     83
    8284                // if sRead equals sPeerId this Publisher with the same topic had written
    8385                // this entry - no problem! Otherwise abort Starting the publisher!
    84                 if (byRead != myPeerId.byteId)
     86                if (peerRead != myPeerId)
    8587                {
    8688                    GuiLogging("Can't store Publisher in the DHT because the Entry was already occupied.", NotificationLevel.Error);
     
    9092            /* END: CHECKING WHETHER THERE HAS ALREADY EXIST ANOTHER PUBLISHER */
    9193
    92             bool bolTopicStored = this.p2pControl.DHTstore(sTopic, myPeerId.byteId);
     94            bool bolTopicStored = this.p2pControl.DHTstore(sTopic, myPeerId.ToByteArray());
    9395            bool bolSettingsStored = this.p2pControl.DHTstore(sTopic + this.sDHTSettingsPostfix,
    9496                System.BitConverter.GetBytes(this.aliveMessageInterval));
     
    100102            }
    101103
    102             GuiLogging("Peer ID '" + myPeerId.stringId + "' is published to DHT -Entry-Key '" + this.topic + "'", NotificationLevel.Info);
     104            GuiLogging("Peer ID '" + myPeerId + "' is published to DHT -Entry-Key '" + this.topic + "'", NotificationLevel.Info);
    103105            this.Started = true;
    104106
     
    193195                        if (this.peerManagement.Add(sourceAddr))
    194196                        {
    195                             GuiLogging("REGISTERED: Peer with ID " + sourceAddr.stringId, NotificationLevel.Info);
     197                            GuiLogging("REGISTERED: Peer with ID " + sourceAddr, NotificationLevel.Info);
    196198                            this.p2pControl.SendToPeer(PubSubMessageType.RegisteringAccepted, sourceAddr);
    197199                        }
    198200                        else
    199201                        {
    200                             GuiLogging("ALREADY REGISTERED peer with ID " + sourceAddr.stringId, NotificationLevel.Info);
     202                            GuiLogging("ALREADY REGISTERED peer with ID " + sourceAddr, NotificationLevel.Info);
    201203                        }
    202204                        break;
    203205                    case PubSubMessageType.Unregister:
    204206                        if (this.peerManagement.Remove(sourceAddr))
    205                             GuiLogging("REMOVED peer " + sourceAddr.stringId + " because it had sent an unregister message", NotificationLevel.Info);
     207                            GuiLogging("REMOVED peer " + sourceAddr + " because it had sent an unregister message", NotificationLevel.Info);
    206208                        else
    207                             GuiLogging("ALREADY REMOVED or had not registered anytime. ID " + sourceAddr.stringId, NotificationLevel.Info);
     209                            GuiLogging("ALREADY REMOVED or had not registered anytime. ID " + sourceAddr, NotificationLevel.Info);
    208210                        break;
    209211                    case PubSubMessageType.Alive:
     
    211213                        if (this.peerManagement.Update(sourceAddr))
    212214                        {
    213                             GuiLogging("RECEIVED: " + msgType.ToString() + " Message from " + sourceAddr.stringId, NotificationLevel.Debug);
     215                            GuiLogging("RECEIVED: " + msgType.ToString() + " Message from " + sourceAddr, NotificationLevel.Debug);
    214216                        }
    215217                        else
    216218                        {
    217                             GuiLogging("UPDATE FAILED for " + sourceAddr.stringId + " because it hasn't registered first. " + msgType.ToString(), NotificationLevel.Info);
     219                            GuiLogging("UPDATE FAILED for " + sourceAddr + " because it hasn't registered first. " + msgType.ToString(), NotificationLevel.Info);
    218220                        }
    219221                        break;
    220222                    case PubSubMessageType.Ping:
    221223                        this.p2pControl.SendToPeer(PubSubMessageType.Pong, sourceAddr);
    222                         GuiLogging("REPLIED to a ping message from peer " + sourceAddr.stringId, NotificationLevel.Debug);
     224                        GuiLogging("REPLIED to a ping message from peer " + sourceAddr, NotificationLevel.Debug);
    223225                        break;
    224226                    case PubSubMessageType.Solution:
     
    238240            else
    239241            {
    240                 GuiLogging("RECEIVED message from non subscribed peer: " + sData.Trim() + ", ID: " + sourceAddr.stringId, NotificationLevel.Debug);
     242                GuiLogging("RECEIVED message from non subscribed peer: " + sData.Trim() + ", ID: " + sourceAddr, NotificationLevel.Debug);
    241243            }
    242244        }
     
    277279        private void peerManagement_OnSubscriberRemoved(PeerId peerId)
    278280        {
    279             GuiLogging("REMOVED peer " + peerId.stringId, NotificationLevel.Info);
     281            GuiLogging("REMOVED peer " + peerId, NotificationLevel.Info);
    280282        }
    281283
  • trunk/CrypPlugins/PeerToPeerPublisher/SubscribersManagement.cs

    r928 r1022  
    3636        /// contains all active subscribers
    3737        /// </summary>
    38         private Dictionary<string, PeerValue> checkList;
     38        private Dictionary<PeerId, PeerValue> checkList;
    3939
    4040
    4141        /*TESTING*/
    42         protected Dictionary<string, PeerId> activeSubsList;
     42        protected HashSet<PeerId> activeSubsList;
    4343
    4444
     
    4646        /// when a peer is in this list, it will be deleted on the next vitality check
    4747        /// </summary>
    48         private Dictionary<string,PeerId> secondChanceList;
     48        private HashSet<PeerId> secondChanceList;
    4949
    5050        private long expirationTime;
     
    6565        public SubscriberManagement(long expirationTime)
    6666        {
    67             this.activeSubsList = new Dictionary<string, PeerId>();
     67            this.activeSubsList = new HashSet<PeerId>();
    6868
    6969            this.dateTimeNow = new DateTime();
    70             this.checkList = new Dictionary<string, PeerValue>();
    71             this.secondChanceList = new Dictionary<string,PeerId>();
     70            this.checkList = new Dictionary<PeerId, PeerValue>();
     71            this.secondChanceList = new HashSet<PeerId>();
    7272            this.ExpirationTime = expirationTime;
    7373        }
     
    8080        public virtual bool Add(PeerId subscriberId)
    8181        {
    82             if (!this.checkList.ContainsKey(subscriberId.stringId))
     82            if (!this.checkList.ContainsKey(subscriberId))
    8383            {
    8484                this.dateTimeNow = DateTime.Now;
     
    8686                lock (this.checkList)
    8787                {
    88                     this.checkList.Add(subscriberId.stringId, new PeerValue(subscriberId, this.dateTimeNow));
    89                     this.activeSubsList.Add(subscriberId.stringId, subscriberId);
     88                    this.checkList.Add(subscriberId, new PeerValue(subscriberId, this.dateTimeNow));
     89                    this.activeSubsList.Add(subscriberId);
    9090                }
    9191                return true;
     
    104104        {
    105105            this.dateTimeNow = DateTime.Now;
    106             if (this.checkList.ContainsKey(subscriberId.stringId))
    107             {
    108                 this.checkList[subscriberId.stringId].dateTime = this.dateTimeNow;
     106            if (this.checkList.ContainsKey(subscriberId))
     107            {
     108                this.checkList[subscriberId].dateTime = this.dateTimeNow;
    109109                // remove subscriber from this list, because it's updated now and hence alive!
    110                 if (this.secondChanceList.ContainsKey(subscriberId.stringId))
    111                     this.secondChanceList.Remove(subscriberId.stringId);
     110                if (this.secondChanceList.Contains(subscriberId))
     111                    this.secondChanceList.Remove(subscriberId);
    112112                return true;
    113113            }
     
    130130            lock(this.checkList)
    131131            {
    132                 if(this.secondChanceList.ContainsKey(subId.stringId))
    133                     this.secondChanceList.Remove(subId.stringId);
    134                 if (this.checkList.ContainsKey(subId.stringId))
    135                 {
    136                     this.checkList.Remove(subId.stringId);
     132                if(this.secondChanceList.Contains(subId))
     133                    this.secondChanceList.Remove(subId);
     134                if (this.checkList.ContainsKey(subId))
     135                {
     136                    this.checkList.Remove(subId);
    137137                    result = true;
    138138                }
    139                 if (this.activeSubsList.ContainsKey(subId.stringId))
    140                 {
    141                     this.activeSubsList.Remove(subId.stringId);
     139                if (this.activeSubsList.Contains(subId))
     140                {
     141                    this.activeSubsList.Remove(subId);
    142142                    result = true;
    143143                }
     
    164164            lock (this.checkList)
    165165            {
    166                 foreach (KeyValuePair<string, PeerValue> entry in this.checkList)
     166                foreach (KeyValuePair<PeerId, PeerValue> entry in this.checkList)
    167167                {
    168168                    DateTime valueWithExpirationTime = entry.Value.dateTime.AddMilliseconds(ExpirationTime);
    169169
    170170                    // if time is expired AND the ID is already in the secondChanceList --> Add to remove list
    171                     if (this.dateTimeNow > valueWithExpirationTime && secondChanceList.ContainsKey(entry.Key))
     171                    if (this.dateTimeNow > valueWithExpirationTime && secondChanceList.Contains(entry.Key))
    172172                    {
    173173                        removeSubscribersFromDict.Add(entry.Value.peerId);
     
    175175                    else if (this.dateTimeNow > valueWithExpirationTime) //otherwise give a second chance
    176176                    {
    177                         this.secondChanceList.Add(entry.Key, entry.Value.peerId);
     177                        this.secondChanceList.Add(entry.Key);
    178178                    }
    179179                }
     
    186186            }
    187187
    188             return this.secondChanceList.Values.ToList<PeerId>();
     188            return this.secondChanceList.ToList<PeerId>();
    189189        }
    190190
     
    232232        public List<PeerId> GetAllSubscribers()
    233233        {
    234             return this.activeSubsList.Values.ToList<PeerId>();
     234            return this.activeSubsList.ToList<PeerId>();
    235235        }
    236236
  • trunk/CrypPlugins/PeerToPeerSubscriber/P2PSubscriberBase.cs

    r1012 r1022  
    9393        {
    9494            SendMessage(actualPublisher, PubSubMessageType.Solution);
    95             this.p2pControl.SendToPeer(sSolutionData, actualPublisher.byteId);
     95            this.p2pControl.SendToPeer(sSolutionData, actualPublisher.ToByteArray());
    9696        }
    9797        /* END: Only for experimental cases */
     
    134134        private void MessageReceived(PeerId sourceAddr, string sData)
    135135        {
    136             if (sourceAddr.stringId != actualPublisher.stringId)
    137             {
    138                 GuiLogging("RECEIVED message from third party peer (not the publisher!): " + sData.Trim() + ", ID: " + sourceAddr.stringId, NotificationLevel.Debug);
     136            if (sourceAddr != actualPublisher)
     137            {
     138                GuiLogging("RECEIVED message from third party peer (not the publisher!): " + sData.Trim() + ", ID: " + sourceAddr, NotificationLevel.Debug);
    139139                return;
    140140            }
     
    225225        protected virtual void HandleIncomingData(PeerId senderId, string sData)
    226226        {
    227             GuiLogging("RECEIVED: Message from '" + senderId.stringId
     227            GuiLogging("RECEIVED: Message from '" + senderId
    228228                    + "' with data: '" + sData + "'", NotificationLevel.Debug);
    229229
     
    311311            sendAliveMessageInterval = System.BitConverter.ToInt32(byteISettings, 0);
    312312
    313             string sPubId = this.p2pControl.ConvertIdToString(bytePubId);
    314             GuiLogging("RECEIVED: Publishers' peer name '" + sPubId + "', Alive-Msg-Interval: " + sendAliveMessageInterval / 1000 + " sec!", NotificationLevel.Debug);
    315 
    316             pid = new PeerId(sPubId, bytePubId);
     313            pid = this.p2pControl.GetPeerID(bytePubId);
    317314            if (actualPublisher == null) //first time initialization
    318315                actualPublisher = pid;
     316
     317            GuiLogging("RECEIVED: Publishers' peer name '" + pid + "', Alive-Msg-Interval: " + sendAliveMessageInterval / 1000 + " sec!", NotificationLevel.Debug);
    319318
    320319            // setting timer to check periodical the availability of the publishing peer
     
    340339                return;
    341340            }
    342             if (newPubId.stringId != actualPublisher.stringId)
     341            if (newPubId != actualPublisher)
    343342            {
    344343                //Handle case, when publisher changed or isn't active at present (don't reply on response)
    345                 GuiLogging("CHANGED: Publisher from '" + actualPublisher.stringId
    346                     + "' to '" + newPubId.stringId + "'!", NotificationLevel.Info);
     344                GuiLogging("CHANGED: Publisher from '" + actualPublisher
     345                    + "' to '" + newPubId + "'!", NotificationLevel.Info);
    347346                actualPublisher = newPubId;
    348347                // because the publisher has changed, send a new register msg
Note: See TracChangeset for help on using the changeset viewer.