feat(#772): fake radio messaging (send, ACK, incoming)

CMD_SEND_TXT_MSG answers RESP_CODE_SENT with the flood flag, the
expected ACK (composeMsgPacket's SHA-256, matched against the client's
own MessageRetryService prediction) and a timeout; the ACK arrives as
PUSH_CODE_SEND_CONFIRMED on the fake clock. CLI commands expect no ACK.
CMD_SEND_CHANNEL_TXT_MSG is OK/NOT_FOUND; Offband keeps the 8-slot
packet-hash ring and answers 0xC6 with it (unknown sub-codes are
MALFORMED, per firmware). receiveDirect/receiveChannel queue V3 (or
legacy, below protocol 3) frames and tickle PUSH_CODE_MSG_WAITING;
Offband drops DMs from blocked senders, stock delivers them.

Connector check: an incoming DM lands in the real connector's
conversation over the in-process adapter. 50 fake-radio tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
feat/757-fake-radio-behaviors
diffwireauto 2 months ago
parent 79c6cd9d32
commit aff4b58a65

@ -0,0 +1,263 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/storage/drift/blob_store.dart';
import 'package:meshcore_open/storage/drift/offband_database.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../support/fake_radio/fake_radio.dart';
import '../support/fake_radio/fake_radio_adapters.dart';
import '../support/fake_radio/fake_radio_codes.dart';
import '../support/fake_radio/fake_radio_profile.dart';
import '../support/fake_radio/fake_radio_seed.dart';
Uint8List _le32(int v) =>
Uint8List(4)..buffer.asByteData().setUint32(0, v, Endian.little);
int _u32(List<int> b, int at) => ByteData.sublistView(
Uint8List.fromList(b),
at,
at + 4,
).getUint32(0, Endian.little);
/// The client's own CMD_SEND_TXT_MSG layout (meshcore_protocol.dart).
Uint8List _dm(
FakeContact to,
String text, {
int type = fwTxtTypePlain,
int attempt = 0,
int ts = 1790000100,
}) => Uint8List.fromList([
fwCmdSendTxtMsg,
type,
attempt,
..._le32(ts),
...to.publicKey.sublist(0, 6),
...utf8.encode(text),
0,
]);
Uint8List _chan(int index, String text, {int ts = 1790000100}) =>
Uint8List.fromList([
fwCmdSendChannelTxtMsg,
fwTxtTypePlain,
index,
..._le32(ts),
...utf8.encode(text),
0,
]);
void main() {
final alpha = FakeContact.keyed(0x11, 'Alpha');
final flooded = FakeContact.keyed(0x22, 'Bravo');
final routed = FakeContact(
publicKey: Uint8List.fromList(List<int>.filled(32, 0x33)),
name: 'Routed',
outPathLength: 1,
outPath: Uint8List.fromList([0x9A]),
);
FakeRadio radio({FakeRadioProfile? profile}) => FakeRadio(
profile: profile,
seed: FakeRadioSeed(
contacts: [alpha, flooded, routed],
channels: [FakeChannel(index: 0, name: 'Public')],
),
);
group('direct send (#772)', () {
test('SENT carries flood flag, expected ACK and timeout', () {
final r = radio();
final sent = r.handle(_dm(flooded, 'hello')).single;
expect(sent[0], fwRespSent);
expect(sent[1], 1); // no known path: flood
expect(sent.length, 10);
expect(_u32(sent, 6), 3000);
expect(r.handle(_dm(routed, 'hi')).single[1], 0); // direct
expect(r.sentDirect.map((s) => s.text), ['hello', 'hi']);
});
test("the expected ACK is the client's own prediction", () {
final r = radio();
final sent = r.handle(_dm(alpha, 'hello', attempt: 2)).single;
expect(
_u32(sent, 2),
MessageRetryService.computeExpectedAckHash(
1790000100,
2,
'hello',
r.seed.publicKey,
),
);
});
test('the ACK arrives only when the fake clock reaches it', () {
final r = radio()..ackDelay = const Duration(seconds: 2);
final pushes = <Uint8List>[];
r.pushes.listen(pushes.add);
final ack = _u32(r.handle(_dm(alpha, 'hello')).single, 2);
r.clock.advance(const Duration(seconds: 1));
expect(pushes, isEmpty);
r.clock.advance(const Duration(seconds: 1));
expect(pushes.single[0], fwPushSendConfirmed);
expect(_u32(pushes.single, 1), ack);
expect(_u32(pushes.single, 5), 2000); // trip time
});
test('a CLI command expects no ACK, and none arrives', () {
final r = radio();
final pushes = <Uint8List>[];
r.pushes.listen(pushes.add);
final sent = r.handle(_dm(alpha, 'ver', type: fwTxtTypeCliData)).single;
expect(_u32(sent, 2), 0);
r.clock.advance(const Duration(minutes: 1));
expect(pushes, isEmpty);
});
test('unknown recipient is NOT_FOUND; other text types UNSUPPORTED', () {
final r = radio();
final stranger = FakeContact.keyed(0x77, 'Stranger');
expect(r.handle(_dm(stranger, 'x')).single, [fwRespErr, fwErrNotFound]);
expect(r.handle(_dm(alpha, 'x', type: fwTxtTypeSignedPlain)).single, [
fwRespErr,
fwErrUnsupportedCmd,
]);
expect(r.sentDirect, isEmpty);
});
});
group('channel send', () {
test('OK for a known channel, NOT_FOUND otherwise', () {
final r = radio();
expect(r.handle(_chan(0, 'hi all')).single, [fwRespOk]);
expect(r.handle(_chan(3, 'nobody')).single, [fwRespErr, fwErrNotFound]);
expect(r.sentChannel.single.text, 'hi all');
});
test('Offband answers 0xC6 with the recorded hash, echoing the key', () {
final r = radio();
r.handle(_chan(0, 'hi all', ts: 1790000200));
final reply = r
.handle(
Uint8List.fromList([
fwOffbandPktHash,
fwPktHashGet,
..._le32(1790000200),
0,
]),
)
.single;
expect(reply.sublist(0, 2), [fwOffbandPktHash, fwPktHashGet]);
expect(_u32(reply, 2), 1790000200);
expect(reply[6], 0);
expect(reply.sublist(7), r.sentPktHash(1790000200, 0));
expect(reply.length, 15);
});
test('the hash ring keeps the last 8 sends', () {
final r = radio();
for (var i = 0; i < 9; i++) {
r.handle(_chan(0, 'm$i', ts: 1790000000 + i));
}
expect(r.sentPktHash(1790000000, 0), isNull);
expect(r.sentPktHash(1790000008, 0), isNotNull);
});
});
group('incoming messages', () {
test('a DM queues a V3 frame and tickles the app', () {
final r = radio();
final pushes = <Uint8List>[];
r.pushes.listen(pushes.add);
r.receiveDirect(alpha, 'yo', timestamp: 1790000300, rssiDbm: -130);
expect(pushes.single, [fwPushMsgWaiting]);
final f = r.handle(Uint8List.fromList([fwCmdSyncNextMessage])).single;
expect(f[0], fwRespContactMsgRecvV3);
expect(f[2], 0); // received, not device-composed
expect(f[3], (-128) & 0xFF); // RSSI clamped to int8
expect(f.sublist(4, 10), alpha.publicKey.sublist(0, 6));
expect(f[10], 0xFF);
expect(f[11], fwTxtTypePlain);
expect(_u32(f, 12), 1790000300);
expect(utf8.decode(f.sublist(16)), 'yo');
});
test('an app below protocol v3 gets the legacy frame', () {
final r = radio();
r.handle(Uint8List.fromList([fwCmdDeviceQuery, 2]));
r.receiveDirect(alpha, 'old');
final f = r.handle(Uint8List.fromList([fwCmdSyncNextMessage])).single;
expect(f[0], fwRespContactMsgRecv);
expect(f.sublist(1, 7), alpha.publicKey.sublist(0, 6));
});
test('a channel message carries the slot and "Sender: text"', () {
final r = radio();
r.receiveChannel(0, 'Bravo: morning', timestamp: 1790000400);
final f = r.handle(Uint8List.fromList([fwCmdSyncNextMessage])).single;
expect(f[0], fwRespChannelMsgRecvV3);
expect(f[4], 0);
expect(_u32(f, 7), 1790000400);
expect(utf8.decode(f.sublist(11)), 'Bravo: morning');
});
test('Offband drops a DM from a blocked sender; stock delivers it', () {
final offband = radio()..blockedKeys.add(alpha.publicKey);
offband.receiveDirect(alpha, 'blocked');
expect(offband.offlineQueue, isEmpty);
final stock = radio(profile: FakeRadioProfile.stock())
..blockedKeys.add(alpha.publicKey);
stock.receiveDirect(alpha, 'delivered');
expect(stock.offlineQueue, hasLength(1));
});
});
group('through the real connector', () {
late OffbandDatabase db;
late MeshCoreConnector connector;
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
db = OffbandDatabase(NativeDatabase.memory());
BlobStore.overrideForTest(BlobStore(db));
connector = MeshCoreConnector();
});
tearDown(() async {
await connector.disconnect();
BlobStore.clearTestOverride();
await db.close();
});
test(
'an incoming DM lands in the conversation',
() async {
final r = radio();
final link = await FakeRadioInProcess.connect(connector, r);
addTearDown(link.close);
final sw = Stopwatch()..start();
while (!connector.contacts.any((c) => c.name == 'Alpha')) {
if (sw.elapsed > const Duration(seconds: 10)) fail('no contacts');
await Future<void>.delayed(const Duration(milliseconds: 10));
}
r.receiveDirect(alpha, 'hello from the mesh');
final contact = connector.contacts.firstWhere((c) => c.name == 'Alpha');
while (!connector
.getMessages(contact)
.any((m) => m.text == 'hello from the mesh' && !m.isOutgoing)) {
if (sw.elapsed > const Duration(seconds: 10)) fail('no message');
await Future<void>.delayed(const Duration(milliseconds: 10));
}
},
timeout: const Timeout(Duration(seconds: 30)),
);
});
}

@ -127,6 +127,7 @@ void main() {
if (n.startsWith('fwCmd')) return 'cmd${n.substring(5)}';
if (n.startsWith('fwResp')) return 'respCode${n.substring(6)}';
if (n.startsWith('fwErr')) return 'errCode${n.substring(5)}';
if (n.startsWith('fwPush')) return 'pushCode${n.substring(6)}';
if (RegExp(r'^fwOffband[A-Z]').hasMatch(n)) {
return 'cmdOffband${n.substring(9)}';
}

@ -2,6 +2,8 @@ import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
import 'fake_clock.dart';
import 'fake_radio_codes.dart';
import 'fake_radio_profile.dart';
@ -81,6 +83,24 @@ class FakeRadio {
/// Every command frame received, in order, for assertions.
final List<Uint8List> received = [];
/// The protocol version the app declared in CMD_DEVICE_QUERY
/// (`app_target_ver`, MyMesh.cpp:2421). Picks the V3 or legacy message frames.
int appTargetVer = 3;
/// Direct messages the client asked the radio to send, in order.
final List<FakeSentDirect> sentDirect = [];
/// Channel messages the client asked the radio to send, in order.
final List<FakeSentChannel> sentChannel = [];
/// How long after a direct send the recipient's ACK arrives, on [clock].
Duration ackDelay = const Duration(seconds: 1);
/// `est_timeout` reported in RESP_CODE_SENT, in milliseconds.
int estTimeoutMs = 3000;
final List<_SentPktHash> _pktHashRing = [];
final StreamController<Uint8List> _pushes =
StreamController<Uint8List>.broadcast(sync: true);
@ -101,7 +121,12 @@ class FakeRadio {
}
switch (cmd[0]) {
case fwCmdDeviceQuery when len >= 2:
appTargetVer = cmd[1];
return [deviceInfoFrame()];
case fwCmdSendTxtMsg when len >= 14:
return [_sendDirect(cmd)];
case fwCmdSendChannelTxtMsg when len >= 7:
return [_sendChannel(cmd)];
case fwCmdAppStart when len >= 8:
return [selfInfoFrame()];
case fwCmdGetContacts:
@ -186,16 +211,8 @@ class FakeRadio {
];
case fwOffbandBlock when len >= 2:
return _block(cmd);
case fwOffbandPktHash when len >= 2 && cmd[1] == fwPktHashGet:
// MyMesh.cpp:2114-2133: exactly 7 bytes; the fake keeps no send ring,
// so every well-formed query is an unknown key.
return [
Uint8List.fromList([
fwOffbandPktHash,
fwPktHashErr,
len != 7 ? fwPktHashErrMalformed : fwPktHashErrUnknownKey,
]),
];
case fwOffbandPktHash when len >= 2:
return [_pktHashQuery(cmd)];
default:
return [errFrame(fwErrUnsupportedCmd)];
}
@ -245,6 +262,241 @@ class FakeRadio {
return [errFrame(fwErrIllegalArg)];
}
/// CMD_SEND_TXT_MSG (MyMesh.cpp:2587-2632). A plain message gets
/// RESP_CODE_SENT with the expected ACK, and the ACK arrives as
/// PUSH_CODE_SEND_CONFIRMED after [ackDelay]. A CLI command expects no ACK.
Uint8List _sendDirect(Uint8List cmd) {
final txtType = cmd[1];
final attempt = cmd[2];
final timestamp = _u32At(cmd, 3);
final prefix = cmd.sublist(7, 13);
final text = _cString(cmd, 13);
final to = contactByPrefix(prefix);
if (to == null) return errFrame(fwErrNotFound);
if (txtType != fwTxtTypePlain && txtType != fwTxtTypeCliData) {
return errFrame(fwErrUnsupportedCmd);
}
final ack = txtType == fwTxtTypePlain
? expectedAck(timestamp, attempt, text)
: 0;
final sent = FakeSentDirect(
to: to,
txtType: txtType,
attempt: attempt,
timestamp: timestamp,
text: text,
expectedAck: ack,
);
sentDirect.add(sent);
if (ack != 0) _scheduleAck(sent);
onDirectSent?.call(sent);
return Uint8List.fromList([
fwRespSent,
to.outPathLength < 0 ? 1 : 0, // MSG_SEND_SENT_FLOOD
..._u32(ack),
..._u32(estTimeoutMs),
]);
}
/// Called for every direct send, after it is recorded; B3's remote nodes
/// answer CLI commands from here.
void Function(FakeSentDirect sent)? onDirectSent;
/// Number of upcoming ACKs to lose, as if they never came back (B4).
int acksToDrop = 0;
void _scheduleAck(FakeSentDirect sent) {
if (acksToDrop > 0) {
acksToDrop--;
return;
}
clock.schedule(ackDelay, () {
push(
Uint8List.fromList([
fwPushSendConfirmed,
..._u32(sent.expectedAck),
..._u32(ackDelay.inMilliseconds), // trip_time (MyMesh.cpp:592)
]),
);
});
}
/// `composeMsgPacket` (src/helpers/BaseChatMesh.cpp:440-451): the first 4
/// bytes of SHA-256 over timestamp, attempt & 3, the text, then the sender's
/// public key, read little-endian.
int expectedAck(int timestamp, int attempt, String text) {
final digest = sha256.convert([
..._u32(timestamp),
attempt & 3,
...utf8.encode(text),
...seed.publicKey,
]).bytes;
return ByteData.sublistView(
Uint8List.fromList(digest),
0,
4,
).getUint32(0, Endian.little);
}
/// CMD_SEND_CHANNEL_TXT_MSG (MyMesh.cpp:2633-2675): OK for a known channel,
/// NOT_FOUND otherwise. Offband records the packet hash for 0xC6.
Uint8List _sendChannel(Uint8List cmd) {
final txtType = cmd[1];
final index = cmd[2];
final timestamp = _u32At(cmd, 3);
final text = _cString(cmd, 7);
if (txtType != fwTxtTypePlain) return errFrame(fwErrUnsupportedCmd);
if (!channels.containsKey(index) || index >= seed.maxChannels) {
return errFrame(fwErrNotFound);
}
sentChannel.add(
FakeSentChannel(index: index, timestamp: timestamp, text: text),
);
if (profile.offband) _recordPktHash(timestamp, index, text);
return okFrame();
}
/// `recordSentPktHash` (MyMesh.cpp:228-243): 8 slots, a repeated key
/// overwrites, otherwise the oldest goes. The fake's "hash" is the first 8
/// bytes of SHA-256 over the key and text: stable, not the on-air hash.
void _recordPktHash(int timestamp, int index, String text) {
final hash = Uint8List.fromList(
sha256
.convert([..._u32(timestamp), index, ...utf8.encode(text)])
.bytes
.sublist(0, 8),
);
final at = _pktHashRing.indexWhere(
(e) => e.timestamp == timestamp && e.index == index,
);
if (at >= 0) {
_pktHashRing[at] = _SentPktHash(timestamp, index, hash);
return;
}
if (_pktHashRing.length == 8) _pktHashRing.removeAt(0);
_pktHashRing.add(_SentPktHash(timestamp, index, hash));
}
/// The hash 0xC6 would return for a channel send, or null if not retained.
Uint8List? sentPktHash(int timestamp, int index) {
for (final e in _pktHashRing) {
if (e.timestamp == timestamp && e.index == index) return e.hash;
}
return null;
}
/// 0xC6 (MyMesh.cpp:2114-2152).
Uint8List _pktHashQuery(Uint8List cmd) {
Uint8List err(int reason) =>
Uint8List.fromList([fwOffbandPktHash, fwPktHashErr, reason]);
if (cmd[1] != fwPktHashGet || cmd.length != 7) {
return err(fwPktHashErrMalformed);
}
final timestamp = _u32At(cmd, 2);
final index = cmd[6];
final hash = sentPktHash(timestamp, index);
if (hash == null) return err(fwPktHashErrUnknownKey);
return Uint8List.fromList([
fwOffbandPktHash,
fwPktHashGet,
..._u32(timestamp),
index,
...hash,
]);
}
/// A direct message arriving over the mesh (`queueMessage`,
/// MyMesh.cpp:616-656): queued for CMD_SYNC_NEXT_MESSAGE, then the
/// PUSH_CODE_MSG_WAITING tickle. Offband drops it if the sender is blocked.
void receiveDirect(
FakeContact from,
String text, {
int txtType = fwTxtTypePlain,
int? timestamp,
int snrQuarterDb = 40,
int rssiDbm = -60,
int? floodPathLength,
}) {
if (profile.offband &&
blockedKeys.any((k) => _sameKey(k, from.publicKey))) {
return;
}
final head = appTargetVer >= 3
? [fwRespContactMsgRecvV3, snrQuarterDb & 0xFF, 0, _rssi(rssiDbm)]
: [fwRespContactMsgRecv];
_queue([
...head,
...from.publicKey.sublist(0, 6),
floodPathLength ?? 0xFF,
txtType,
..._u32(timestamp ?? clock.epochSeconds),
...utf8.encode(text),
]);
}
/// A channel message arriving over the mesh (`onChannelMessageRecv`,
/// MyMesh.cpp:921-952). MeshCore puts the sender in the text: "Name: msg".
void receiveChannel(
int index,
String text, {
int? timestamp,
int snrQuarterDb = 40,
int rssiDbm = -60,
int? floodPathLength,
}) {
final head = appTargetVer >= 3
? [fwRespChannelMsgRecvV3, snrQuarterDb & 0xFF, 0, _rssi(rssiDbm)]
: [fwRespChannelMsgRecv];
_queue([
...head,
index,
floodPathLength ?? 0xFF,
fwTxtTypePlain,
..._u32(timestamp ?? clock.epochSeconds),
...utf8.encode(text),
]);
}
/// `MAX_FRAME_SIZE` (src/helpers/BaseSerialInterface.h: 176) truncation,
/// offline queue, then the tickle.
void _queue(List<int> frame) {
final bytes = frame.length > 176 ? frame.sublist(0, 176) : frame;
offlineQueue.add(Uint8List.fromList(bytes));
push(Uint8List.fromList([fwPushMsgWaiting]));
}
/// `rssiToInt8` (MyMesh.cpp:610): clamped to int8, as a byte.
static int _rssi(int dbm) =>
(dbm < -128 ? -128 : (dbm > 127 ? 127 : dbm)) & 0xFF;
FakeContact? contactByPrefix(List<int> prefix) {
for (final c in contacts) {
var match = true;
for (var i = 0; i < prefix.length; i++) {
if (c.publicKey[i] != prefix[i]) {
match = false;
break;
}
}
if (match) return c;
}
return null;
}
static bool _sameKey(List<int> a, List<int> b) {
for (var i = 0; i < fwPubKeySize; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
/// Text from [offset] up to the first NUL (firmware NUL-terminates at len).
static String _cString(Uint8List b, int offset) {
var end = b.indexOf(0, offset);
if (end < 0) end = b.length;
return utf8.decode(b.sublist(offset, end), allowMalformed: true);
}
/// `writeOKFrame` (MyMesh.cpp:258).
static Uint8List okFrame() => Uint8List.fromList([fwRespOk]);
@ -388,3 +640,45 @@ class FakeRadio {
return out;
}
}
/// A direct send the client asked for (CMD_SEND_TXT_MSG).
class FakeSentDirect {
FakeSentDirect({
required this.to,
required this.txtType,
required this.attempt,
required this.timestamp,
required this.text,
required this.expectedAck,
});
final FakeContact to;
final int txtType;
final int attempt;
final int timestamp;
final String text;
/// 0 for a CLI command, which expects no ACK.
final int expectedAck;
}
/// A channel send the client asked for (CMD_SEND_CHANNEL_TXT_MSG).
class FakeSentChannel {
FakeSentChannel({
required this.index,
required this.timestamp,
required this.text,
});
final int index;
final int timestamp;
final String text;
}
class _SentPktHash {
_SentPktHash(this.timestamp, this.index, this.hash);
final int timestamp;
final int index;
final Uint8List hash;
}

@ -39,6 +39,10 @@ const int fwRespContact = 3;
const int fwRespEndOfContacts = 4;
const int fwRespSelfInfo = 5;
const int fwRespSent = 6;
const int fwRespContactMsgRecv = 7;
const int fwRespChannelMsgRecv = 8;
const int fwRespContactMsgRecvV3 = 16;
const int fwRespChannelMsgRecvV3 = 17;
const int fwRespCurrTime = 9;
const int fwRespNoMoreMessages = 10;
const int fwRespBattAndStorage = 12;
@ -47,6 +51,16 @@ const int fwRespChannelInfo = 18;
const int fwRespCustomVars = 21;
const int fwRespAutoAddConfig = 25;
const int fwPushSendConfirmed = 0x82;
const int fwPushMsgWaiting = 0x83;
const int fwPushLoginSuccess = 0x85;
const int fwPushLoginFail = 0x86;
/// `TXT_TYPE_*` (src/helpers/TxtDataHelpers.h:6-8).
const int fwTxtTypePlain = 0;
const int fwTxtTypeCliData = 1;
const int fwTxtTypeSignedPlain = 2;
const int fwErrUnsupportedCmd = 1;
const int fwErrNotFound = 2;
const int fwErrTableFull = 3;

Loading…
Cancel
Save

Powered by TurnKey Linux.