Skip to content

Instantly share code, notes, and snippets.

@stuhood
Created May 24, 2011 09:57
Show Gist options
  • Select an option

  • Save stuhood/988452 to your computer and use it in GitHub Desktop.

Select an option

Save stuhood/988452 to your computer and use it in GitHub Desktop.
XOR Metric Example
/**
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.examples;
import com.google.bitcoin.core.*;
import java.util.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
public class Distance {
public static final int K = 32;
/** @return An integer distance between the given addresses. */
private static final int distance(InetAddress addr1, InetAddress addr2) {
byte[] b1 = addr1.getAddress();
byte[] b2 = addr2.getAddress();
int distance;
distance = (b1[0] ^ b2[0]) & 0xFF;
distance = ((b1[1] ^ b2[1]) & 0xFF) | (distance << 8);
distance = ((b1[2] ^ b2[2]) & 0xFF) | (distance << 8);
return ((b1[3] ^ b2[3]) & 0xFF) | (distance << 8);
}
public static void main(String[] args) throws Exception {
final boolean prodNet = true;
IrcDiscovery d = new IrcDiscovery("#bitcoin" + (prodNet ? "" : "TEST")) {
@Override
protected void onIRCSend(String message) {
System.out.println("-> " + message);
}
};
InetSocketAddress[] peers = d.getPeers();
Random rand = new Random();
InetAddress localhost = InetAddress.getByName("68.27.46.62");
TreeMap<Integer,List<InetAddress>> distances = new TreeMap<Integer,List<InetAddress>>();
for (InetSocketAddress peer : peers)
{
int bin = Integer.numberOfLeadingZeros(distance(localhost, peer.getAddress()));
List<InetAddress> atDistance = distances.get(bin);
if (atDistance == null)
distances.put(bin, atDistance = new ArrayList<InetAddress>());
if (atDistance.size() < K)
// add to list
atDistance.add(peer.getAddress());
else
// randomly replace in list
atDistance.set(rand.nextInt(K), peer.getAddress());
}
System.out.println("Localhost: " + localhost);
System.out.println("Random addresses from each bucket:");
for (Map.Entry<Integer,List<InetAddress>> entry : distances.entrySet())
{
System.out.println(" Peers in bin " + entry.getKey());
for (InetAddress addr : entry.getValue())
System.out.println(String.format(" at 0x%08x: %s", distance(localhost, addr), addr));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment