2020-10-24 08:07:54 +00:00
|
|
|
from onionrtypes import OnionAddressString
|
|
|
|
from typing import Iterable
|
2020-10-25 04:12:42 +00:00
|
|
|
|
|
|
|
from collections import OrderedDict
|
|
|
|
|
2020-10-24 08:07:54 +00:00
|
|
|
from .extracted25519 import extract_ed25519_from_onion_address
|
|
|
|
|
|
|
|
|
|
|
|
def identify_neighbors(
|
|
|
|
address: OnionAddressString,
|
|
|
|
peers: Iterable[OnionAddressString],
|
|
|
|
closest_n: int) -> OnionAddressString:
|
2020-10-26 06:11:24 +00:00
|
|
|
"""Identify node addresses that are closest
|
|
|
|
in value to a given node address"""
|
|
|
|
peers_to_test = list(peers)
|
|
|
|
|
|
|
|
try:
|
|
|
|
peers_to_test.remove(address)
|
|
|
|
except ValueError:
|
|
|
|
pass
|
2020-10-24 08:07:54 +00:00
|
|
|
|
|
|
|
address = extract_ed25519_from_onion_address(address)
|
|
|
|
address_int = int.from_bytes(address, "big")
|
2020-10-26 06:11:24 +00:00
|
|
|
closeness_values = []
|
|
|
|
end_result = []
|
2020-10-24 08:07:54 +00:00
|
|
|
|
|
|
|
def _calc_closeness(y):
|
2020-10-26 06:11:24 +00:00
|
|
|
ret = abs(
|
|
|
|
address_int -
|
|
|
|
int.from_bytes(extract_ed25519_from_onion_address(y), "big"))
|
|
|
|
return ret
|
2020-10-25 04:12:42 +00:00
|
|
|
|
2020-10-26 06:11:24 +00:00
|
|
|
for peer in peers_to_test:
|
2020-10-25 04:12:42 +00:00
|
|
|
closeness_values.append((peer, _calc_closeness(peer)))
|
2020-10-26 06:11:24 +00:00
|
|
|
closeness_values.sort(key=lambda p: p[1])
|
2020-10-25 04:12:42 +00:00
|
|
|
for i, result in enumerate(closeness_values):
|
2020-10-26 06:11:24 +00:00
|
|
|
end_result.append(result[0])
|
2020-10-25 04:12:42 +00:00
|
|
|
if i > closest_n:
|
|
|
|
break
|
|
|
|
return end_result
|