/** * Does a binary search for the k-bucket whose key range contains a given * {@link Hash}. * The bucket may or may not contain a peer with that hash. * @param key * @return */ private KBucket getKBucket(Hash key) { return kBuckets.get(getBucketIndex(key)); }
/** * Moves peers from the k-buckets to the s-bucket until the s-bucket is full * or all k-buckets are empty. */ private void refillSiblings() { // Sort all k-peers by distance to the local destination List<KademliaPeer> kPeers = new ArrayList<KademliaPeer>(); for (KBucket kBucket: kBuckets) kPeers.addAll(kBucket.getPeers()); Collections.sort(kPeers, new PeerDistanceComparator(localDestinationHash)); while (!sBucket.isFull() && !kPeers.isEmpty()) { // move the closest k-peer to the s-bucket KademliaPeer peerToMove = kPeers.remove(0); int bucketIndex = getBucketIndex(peerToMove.getDestinationHash()); kBuckets.get(bucketIndex).remove(peerToMove); sBucket.addOrUpdate(peerToMove); } }
int bucketIndex = getBucketIndex(peer.calculateHash()); KBucket bucket = kBuckets.get(bucketIndex);