2018-07-18 02:45:51 +02:00
|
|
|
from binascii import hexlify
|
|
|
|
|
2018-05-29 16:59:46 +02:00
|
|
|
from lbrynet.dht import constants
|
2018-07-18 02:45:51 +02:00
|
|
|
import sys
|
|
|
|
if sys.version_info > (3,):
|
|
|
|
long = int
|
2018-05-29 16:59:46 +02:00
|
|
|
|
|
|
|
|
2018-07-22 00:34:59 +02:00
|
|
|
class Distance:
|
2017-10-23 19:09:46 +02:00
|
|
|
"""Calculate the XOR result between two string variables.
|
|
|
|
|
|
|
|
Frequently we re-use one of the points so as an optimization
|
|
|
|
we pre-calculate the long value of that point.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, key):
|
2018-05-29 16:59:46 +02:00
|
|
|
if len(key) != constants.key_bits / 8:
|
2018-05-29 22:50:23 +02:00
|
|
|
raise ValueError("invalid key length: %i" % len(key))
|
2017-10-23 19:09:46 +02:00
|
|
|
self.key = key
|
2018-07-18 02:45:51 +02:00
|
|
|
self.val_key_one = long(hexlify(key), 16)
|
2017-10-23 19:09:46 +02:00
|
|
|
|
|
|
|
def __call__(self, key_two):
|
2018-07-18 02:45:51 +02:00
|
|
|
val_key_two = long(hexlify(key_two), 16)
|
2017-10-23 19:09:46 +02:00
|
|
|
return self.val_key_one ^ val_key_two
|
|
|
|
|
|
|
|
def is_closer(self, a, b):
|
|
|
|
"""Returns true is `a` is closer to `key` than `b` is"""
|
|
|
|
return self(a) < self(b)
|
|
|
|
|
|
|
|
def to_contact(self, contact):
|
|
|
|
"""A convenience function for calculating the distance to a contact"""
|
|
|
|
return self(contact.id)
|