Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions src/meshcore/commands/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,16 +379,39 @@ async def send_anon_req(self, dst: DestinationType, request_type: AnonReqType, d
# asking a freshly discovered neighbour for its regions.
contact = self._get_contact_by_prefix(dst_bytes.hex())

device_contact = None
if contact is not None and contact["out_path_len"] == -1:
# This copy says flood, but it can be out of date: another app, or
# the device itself since the contacts were last read, may have
# given the device a path. Read the device's own record first, so
# that a path it holds is used, not replaced by zero-hop and then
# reset to flood at the end.
res = await self.get_contact_by_key(dst_bytes)
if res.type == EventType.NEXT_CONTACT and res.payload.get("public_key") == dst_bytes.hex():
device_contact = res.payload
for field in ("out_path", "out_path_len", "out_path_hash_mode"):
contact[field] = device_contact[field]
elif res.type == EventType.ERROR and res.payload.get("error_code") == 2:
# ERR_CODE_NOT_FOUND: the device doesn't hold it, so send as
# to any unknown destination rather than add it to the device.
contact = None
else:
logger.error("Could not read the contact from the device, aborting anon request")
return Event(EventType.ERROR, {"reason": "contact_read_failed"})

zero_hop = False
if contact is None:
logger.debug("No contact found, requesting a zero-hop direct reply path")
out_path_len = 0
reply_path = encode_reply_path(0, "", 0)
else:
if contact["out_path_len"] == -1:
# The device holds it as flood too. Set zero-hop on the
# device's own record, so nothing else in it changes, and
# reset it to flood after sending.
logger.info("No path set trying zero hop")
zero_hop = True
path_res = await self.change_contact_path(contact, "")
path_res = await self.change_contact_path(device_contact, "")
if path_res is not None and path_res.type == EventType.ERROR:
# The device still has this contact as flood, so sendAnonReq
# will flood the request -- and the server gates REGIONS,
Expand All @@ -397,9 +420,8 @@ async def send_anon_req(self, dst: DestinationType, request_type: AnonReqType, d
# for a reply that cannot come.
logger.error("Could not set zero-hop path, aborting anon request")
return Event(EventType.ERROR, {"reason": "path_reset_failed"})
# update_contact() normally reflects the change back onto the dict, so
# out_path_len reads 0 here. Clamp anyway: if that call failed (e.g. the
# device query inside it errored) the dict is still -1, and the unsigned
# After a zero-hop change, this dict still reads -1 (the change was
# reflected onto the device's record). Clamp it: the unsigned
# to_bytes below would raise OverflowError -- which would skip the
# reset_path at the end of this method and leave the contact pinned to
# zero-hop on the device. Zero is the right value to send regardless,
Expand Down
132 changes: 132 additions & 0 deletions tests/unit/test_anon_req_device_path.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
"""send_anon_req doesn't lose a path the device holds (#119: B4).

When meshcore's copy of a contact says flood, it reads the device's own record before changing it: a path the device
holds is used and left alone; a flood record is set to zero-hop and reset to flood after sending.
"""
import asyncio
from unittest.mock import AsyncMock, MagicMock

import pytest

from meshcore.commands import CommandHandler
from meshcore.events import Event, EventType, Subscription

pytestmark = pytest.mark.asyncio

KEY = bytes(range(32))
ANON_REQ = b"\x39" + KEY + b"\x02" # CMD_SEND_ANON_REQ, the key, AnonReqType.OWNER's value


def record(out_path_len, out_path="", hash_mode=0, name="Repeater"):
"""A contact as the reader reads it."""
return {
"public_key": KEY.hex(),
"type": 2,
"flags": 0,
"out_path_len": out_path_len,
"out_path_hash_mode": -1 if out_path_len == -1 else hash_mode,
"out_path": out_path,
"adv_name": name,
"last_advert": 1000,
"adv_lat": 0.0,
"adv_lon": 0.0,
"lastmod": 1000,
}


@pytest.fixture
def handler():
"""A CommandHandler on a device that answers the request with MSG_SENT."""
dispatcher = MagicMock()

def subscribe(event_type, callback, attribute_filters=None):
if event_type == EventType.MSG_SENT:
payload = {"type": 0, "expected_ack": b"\x01\x02\x03\x04", "suggested_timeout": 4000}
asyncio.get_event_loop().call_soon(callback, Event(event_type, payload))
return MagicMock(spec=Subscription)

dispatcher.subscribe = MagicMock(side_effect=subscribe)
handler = CommandHandler()
handler.sent = []

async def sender(data):
handler.sent.append(bytes(data))

handler._sender_func = sender
handler.dispatcher = dispatcher
handler.change_contact_path = AsyncMock()
handler.reset_path = AsyncMock()
return handler


def holding(handler, copy, device_answer):
handler._get_contact_by_prefix = MagicMock(return_value=copy)
handler.get_contact_by_key = AsyncMock(return_value=device_answer)


@pytest.mark.parametrize(
"device, reply_path",
[
(record(0), b"\x00"),
(record(2, "aabb"), b"\x02" + bytes.fromhex("bbaa")),
],
ids=["zero_hop", "two_hops"],
)
async def test_path_the_device_holds_is_used_and_left_alone(handler, device, reply_path):
copy = record(-1)
holding(handler, copy, Event(EventType.NEXT_CONTACT, device))

result = await handler.send_anon_req(KEY, MagicMock(value=2))

assert result.type == EventType.MSG_SENT
handler.get_contact_by_key.assert_awaited_once_with(KEY)
assert handler.sent == [ANON_REQ + reply_path]
handler.change_contact_path.assert_not_awaited()
handler.reset_path.assert_not_awaited()
# meshcore's copy now has the device's path
assert (copy["out_path_len"], copy["out_path"]) == (device["out_path_len"], device["out_path"])


async def test_flood_on_the_device_is_set_to_zero_hop_on_its_own_record_and_reset(handler):
copy = record(-1, name="Old name")
device = record(-1, name="Repeater")
holding(handler, copy, Event(EventType.NEXT_CONTACT, device))

await handler.send_anon_req(KEY, MagicMock(value=2))

handler.change_contact_path.assert_awaited_once()
assert handler.change_contact_path.await_args.args[0]["adv_name"] == "Repeater"
assert handler.sent == [ANON_REQ + b"\x00"]
handler.reset_path.assert_awaited_once()


async def test_contact_the_device_does_not_hold_is_not_added(handler):
holding(handler, record(-1), Event(EventType.ERROR, {"error_code": 2}))

result = await handler.send_anon_req(KEY, MagicMock(value=2))

assert result.type == EventType.MSG_SENT
assert handler.sent == [ANON_REQ + b"\x00"]
handler.change_contact_path.assert_not_awaited()
handler.reset_path.assert_not_awaited()


async def test_record_that_cannot_be_read_aborts_before_any_change(handler):
holding(handler, record(-1), Event(EventType.ERROR, {"reason": "no_event_received"}))

result = await handler.send_anon_req(KEY, MagicMock(value=2))

assert result.is_error()
assert result.payload["reason"] == "contact_read_failed"
assert handler.sent == []
handler.change_contact_path.assert_not_awaited()
handler.reset_path.assert_not_awaited()


async def test_copy_with_a_path_is_not_read_again(handler):
holding(handler, record(1, "cc"), None)

await handler.send_anon_req(KEY, MagicMock(value=2))

handler.get_contact_by_key.assert_not_awaited()
assert handler.sent == [ANON_REQ + b"\x01" + bytes.fromhex("cc")]
7 changes: 7 additions & 0 deletions tests/unit/test_error_handling.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,10 @@ async def fake_change_path(c, path):
c["out_path"] = ""

command_handler._get_contact_by_prefix = MagicMock(return_value=contact)
# The device's own record says flood too.
command_handler.get_contact_by_key = AsyncMock(
return_value=Event(EventType.NEXT_CONTACT, dict(contact, out_path_hash_mode=-1))
)
command_handler.change_contact_path = AsyncMock(side_effect=fake_change_path)
command_handler.reset_path = AsyncMock()
setup_event_response(
Expand Down Expand Up @@ -380,6 +384,9 @@ async def test_send_anon_req_aborts_when_change_contact_path_fails(
"""
contact = {"public_key": VALID_PUBKEY_HEX, "out_path_len": -1, "out_path": ""}
command_handler._get_contact_by_prefix = MagicMock(return_value=contact)
command_handler.get_contact_by_key = AsyncMock(
return_value=Event(EventType.NEXT_CONTACT, dict(contact, out_path_hash_mode=-1))
)
command_handler.change_contact_path = AsyncMock(
return_value=Event(EventType.ERROR, {"reason": "device_query_failed"})
)
Expand Down