req_neighbours

This commit is contained in:
Florent 2025-11-09 16:51:54 +01:00
parent dea2f74eae
commit 307e517f5e
6 changed files with 155 additions and 6 deletions

View file

@ -23,7 +23,7 @@ class MessageReader:
# Track pending binary requests by tag for proper response parsing
self.pending_binary_requests: Dict[str, Dict[str, Any]] = {} # tag -> {request_type, expires_at}
def register_binary_request(self, prefix: str, tag: str, request_type: BinaryReqType, timeout_seconds: float):
def register_binary_request(self, prefix: str, tag: str, request_type: BinaryReqType, timeout_seconds: float, context={}):
"""Register a pending binary request for proper response parsing"""
# Clean up expired requests before adding new one
self.cleanup_expired_requests()
@ -32,7 +32,8 @@ class MessageReader:
self.pending_binary_requests[tag] = {
"request_type": request_type,
"pubkey_prefix": prefix,
"expires_at": expires_at
"expires_at": expires_at,
"context": context # optional info we want to keep from req to resp
}
logger.debug(f"Registered binary request: tag={tag}, type={request_type}, expires in {timeout_seconds}s")
@ -519,6 +520,7 @@ class MessageReader:
if tag in self.pending_binary_requests:
request_type = self.pending_binary_requests[tag]["request_type"]
pubkey_prefix = self.pending_binary_requests[tag]["pubkey_prefix"]
context = self.pending_binary_requests[tag]["context"]
del self.pending_binary_requests[tag]
logger.debug(f"Processing binary response for tag {tag}, type {request_type}, pubkey_prefix {pubkey_prefix}")
@ -558,6 +560,40 @@ class MessageReader:
)
except Exception as e:
logger.error(f"Error parsing binary ACL response: {e}")
elif request_type == BinaryReqType.NEIGHBOURS:
try:
pk_plen = context["pubkey_prefix_length"]
bbuf = io.BytesIO(response_data)
res = {
"pubkey_prefix": pubkey_prefix,
"tag": tag
}
res.update(context) # add context in result
res["neighbours_count"] = int.from_bytes(bbuf.read(2), "little", signed=True)
results_count = int.from_bytes(bbuf.read(2), "little", signed=True)
res["results_count"] = results_count
neighbours_list = []
for _ in range (results_count):
neighb = {}
neighb["pubkey"] = bbuf.read(pk_plen).hex()
neighb["secs_ago"] = int.from_bytes(bbuf.read(4), "little", signed=True)
neighb["snr"] = int.from_bytes(bbuf.read(1), "little", signed=True) / 4
neighbours_list.append(neighb)
res["neighbours"] = neighbours_list
await self.dispatcher.dispatch(
Event(EventType.NEIGHBOURS_RESPONSE, res, {"tag": tag, "pubkey_prefix": pubkey_prefix})
)
except Exception as e:
logger.error(f"Error parsing binary NEIGHBOURS response: {e}")
else:
logger.debug(f"No tracked request found for binary response tag {tag}")
@ -623,7 +659,7 @@ class MessageReader:
if len(pubkey) < 32:
pubkey = pubkey[0:8]
else:
pubkey = pubkey[0:32]
pubkey = pubkey[0:32]
ndr["pubkey"] = pubkey.hex()