/** * Returns <code>true</code> if <code>dest1</code> is closer to <code>key</code> than <code>dest2</code>. * @param key * @param destination * @param peers */ private boolean isCloser(Destination dest1, Destination dest2, Hash key) { return new PeerDistanceComparator(key).compare(dest1, dest2) < 0; }
SBucket(Hash localDestinationHash) { super(KademliaConstants.S); distanceComparator = new PeerDistanceComparator(localDestinationHash); int numSections = (KademliaConstants.S - 1) / KademliaConstants.K + 1; if (numSections < 1) numSections = 1; sections = new BucketSection[numSections]; for (int i=0; i<numSections; i++) sections[i] = new BucketSection(BigInteger.ZERO, BigInteger.ZERO, 0); }
/** * Returns the <code>count</code> peers that are closest to a given key, * and which are not locked. * Less than <code>count</code> peers may be returned if there aren't * enough peers in the k-buckets and the s-bucket. * @param key * @param count * @return Up to <code>count</code> peers, sorted by distance to <code>key</code>. */ public List<Destination> getClosestPeers(Hash key, int count) { // TODO don't put all peers in one huge list, only use two k-buckets and the s-bucket at a time List<Destination> peers = getAllUnlockedPeers(); Collections.sort(peers, new PeerDistanceComparator(key)); if (peers.size() < count) return peers; else return peers.subList(0, count); }
PeerDistanceComparator comparator = new PeerDistanceComparator(localDestination.calculateHash()); for (KademliaPeer sibling: bucketManager.getSBucket()) for (KademliaPeer peer: getKPeers()) assertTrue(comparator.compare(sibling, peer) <= 0);
/** * 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); } }