Skip to content

Commit e7dcfba

Browse files
committed
Allow persisting more session to flash
1 parent be32746 commit e7dcfba

10 files changed

Lines changed: 394 additions & 92 deletions

File tree

examples/companion_radio/DataStore.cpp

Lines changed: 91 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -411,37 +411,105 @@ bool DataStore::saveNonces(DataStoreHost* host) {
411411

412412
void DataStore::loadSessionKeys(DataStoreHost* host) {
413413
File file = openRead(_getContactsChannelsFS(), "/sess_keys");
414-
if (file) {
415-
uint8_t rec[71]; // 4-byte pub_key prefix + 1 flags + 2 nonce + 32 session_key + 32 prev_session_key
416-
while (file.read(rec, 71) == 71) {
417-
uint16_t nonce;
418-
memcpy(&nonce, &rec[5], 2);
419-
host->onSessionKeyLoaded(rec, rec[4], nonce, &rec[7], &rec[39]);
414+
if (!file) return;
415+
while (true) {
416+
uint8_t rec[SESSION_KEY_RECORD_MIN_SIZE];
417+
if (file.read(rec, SESSION_KEY_RECORD_MIN_SIZE) != SESSION_KEY_RECORD_MIN_SIZE) break;
418+
uint8_t flags = rec[4];
419+
uint16_t nonce;
420+
memcpy(&nonce, &rec[5], 2);
421+
uint8_t prev_key[SESSION_KEY_SIZE];
422+
if (flags & SESSION_FLAG_PREV_VALID) {
423+
if (file.read(prev_key, SESSION_KEY_SIZE) != SESSION_KEY_SIZE) break;
424+
} else {
425+
memset(prev_key, 0, SESSION_KEY_SIZE);
420426
}
421-
file.close();
427+
host->onSessionKeyLoaded(rec, flags, nonce, &rec[7], prev_key);
422428
}
429+
file.close();
423430
}
424431

425432
bool DataStore::saveSessionKeys(DataStoreHost* host) {
426-
File file = openWrite(_getContactsChannelsFS(), "/sess_keys");
427-
if (file) {
428-
uint8_t pub_key_prefix[4];
429-
uint8_t flags;
430-
uint16_t nonce;
431-
uint8_t session_key[32];
432-
uint8_t prev_session_key[32];
433-
for (int idx = 0; idx < MAX_SESSION_KEYS; idx++) {
434-
if (host->getSessionKeyForSave(idx, pub_key_prefix, &flags, &nonce, session_key, prev_session_key)) {
435-
file.write(pub_key_prefix, 4);
436-
file.write(&flags, 1);
437-
file.write((uint8_t*)&nonce, 2);
438-
file.write(session_key, 32);
439-
file.write(prev_session_key, 32);
433+
FILESYSTEM* fs = _getContactsChannelsFS();
434+
435+
// 1. Read old flash file into buffer (variable-length records)
436+
uint8_t old_buf[MAX_SESSION_KEYS_FLASH * SESSION_KEY_RECORD_SIZE];
437+
int old_len = 0;
438+
File rf = openRead(fs, "/sess_keys");
439+
if (rf) {
440+
while (true) {
441+
if (old_len + SESSION_KEY_RECORD_MIN_SIZE > (int)sizeof(old_buf)) break;
442+
if (rf.read(&old_buf[old_len], SESSION_KEY_RECORD_MIN_SIZE) != SESSION_KEY_RECORD_MIN_SIZE) break;
443+
uint8_t flags = old_buf[old_len + 4];
444+
int rec_len = SESSION_KEY_RECORD_MIN_SIZE;
445+
if (flags & SESSION_FLAG_PREV_VALID) {
446+
if (old_len + SESSION_KEY_RECORD_SIZE > (int)sizeof(old_buf)) break;
447+
if (rf.read(&old_buf[old_len + SESSION_KEY_RECORD_MIN_SIZE], SESSION_KEY_SIZE) != SESSION_KEY_SIZE) break;
448+
rec_len = SESSION_KEY_RECORD_SIZE;
440449
}
450+
old_len += rec_len;
451+
}
452+
rf.close();
453+
}
454+
455+
// 2. Write merged file
456+
File wf = openWrite(fs, "/sess_keys");
457+
if (!wf) return false;
458+
459+
// Write kept old records (variable-length)
460+
int pos = 0;
461+
while (pos + SESSION_KEY_RECORD_MIN_SIZE <= old_len) {
462+
uint8_t* rec = &old_buf[pos];
463+
uint8_t flags = rec[4];
464+
int rec_len = (flags & SESSION_FLAG_PREV_VALID) ? SESSION_KEY_RECORD_SIZE : SESSION_KEY_RECORD_MIN_SIZE;
465+
if (pos + rec_len > old_len) break;
466+
if (!host->isSessionKeyInRAM(rec) && !host->isSessionKeyRemoved(rec)) {
467+
wf.write(rec, rec_len);
468+
}
469+
pos += rec_len;
470+
}
471+
// Write current RAM entries (variable-length)
472+
for (int idx = 0; idx < MAX_SESSION_KEYS_RAM; idx++) {
473+
uint8_t pk[4]; uint8_t fl; uint16_t n; uint8_t sk[32]; uint8_t psk[32];
474+
if (!host->getSessionKeyForSave(idx, pk, &fl, &n, sk, psk)) continue;
475+
wf.write(pk, 4); wf.write(&fl, 1); wf.write((uint8_t*)&n, 2);
476+
wf.write(sk, 32);
477+
if (fl & SESSION_FLAG_PREV_VALID) {
478+
wf.write(psk, 32);
479+
}
480+
}
481+
wf.close();
482+
return true;
483+
}
484+
485+
bool DataStore::loadSessionKeyByPrefix(const uint8_t* prefix,
486+
uint8_t* flags, uint16_t* nonce, uint8_t* session_key, uint8_t* prev_session_key) {
487+
File f = openRead(_getContactsChannelsFS(), "/sess_keys");
488+
if (!f) return false;
489+
while (true) {
490+
uint8_t rec[SESSION_KEY_RECORD_MIN_SIZE];
491+
if (f.read(rec, SESSION_KEY_RECORD_MIN_SIZE) != SESSION_KEY_RECORD_MIN_SIZE) break;
492+
uint8_t rec_flags = rec[4];
493+
bool has_prev = (rec_flags & SESSION_FLAG_PREV_VALID);
494+
if (memcmp(rec, prefix, 4) == 0) {
495+
*flags = rec_flags;
496+
memcpy(nonce, &rec[5], 2);
497+
memcpy(session_key, &rec[7], SESSION_KEY_SIZE);
498+
if (has_prev) {
499+
if (f.read(prev_session_key, SESSION_KEY_SIZE) != SESSION_KEY_SIZE) break;
500+
} else {
501+
memset(prev_session_key, 0, SESSION_KEY_SIZE);
502+
}
503+
f.close();
504+
return true;
505+
}
506+
// Skip prev_key if present
507+
if (has_prev) {
508+
uint8_t skip[SESSION_KEY_SIZE];
509+
if (f.read(skip, SESSION_KEY_SIZE) != SESSION_KEY_SIZE) break;
441510
}
442-
file.close();
443-
return true;
444511
}
512+
f.close();
445513
return false;
446514
}
447515

examples/companion_radio/DataStore.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ class DataStoreHost {
1717
const uint8_t* session_key, const uint8_t* prev_session_key) { return false; }
1818
virtual bool getSessionKeyForSave(int idx, uint8_t* pub_key_prefix, uint8_t* flags, uint16_t* nonce,
1919
uint8_t* session_key, uint8_t* prev_session_key) { return false; }
20+
virtual bool isSessionKeyInRAM(const uint8_t* pub_key_prefix) { return false; }
21+
virtual bool isSessionKeyRemoved(const uint8_t* pub_key_prefix) { return false; }
2022
};
2123

2224
class DataStore {
@@ -49,6 +51,8 @@ class DataStore {
4951
bool saveNonces(DataStoreHost* host);
5052
void loadSessionKeys(DataStoreHost* host);
5153
bool saveSessionKeys(DataStoreHost* host);
54+
bool loadSessionKeyByPrefix(const uint8_t* prefix,
55+
uint8_t* flags, uint16_t* nonce, uint8_t* session_key, uint8_t* prev_session_key);
5256
void migrateToSecondaryFS();
5357
uint8_t getBlobByKey(const uint8_t key[], int key_len, uint8_t dest_buf[]);
5458
bool putBlobByKey(const uint8_t key[], int key_len, const uint8_t src_buf[], uint8_t len);

examples/companion_radio/MyMesh.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2138,6 +2138,14 @@ void MyMesh::checkSerialInterface() {
21382138
}
21392139
}
21402140

2141+
bool MyMesh::isSessionKeyInRAM(const uint8_t* pub_key_prefix) {
2142+
return isSessionKeyInRAMPool(pub_key_prefix);
2143+
}
2144+
2145+
bool MyMesh::isSessionKeyRemoved(const uint8_t* pub_key_prefix) {
2146+
return isSessionKeyRemovedFromPool(pub_key_prefix);
2147+
}
2148+
21412149
void MyMesh::loop() {
21422150
BaseChatMesh::loop();
21432151

examples/companion_radio/MyMesh.h

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,8 @@ class MyMesh : public BaseChatMesh, public DataStoreHost {
167167
uint8_t* session_key, uint8_t* prev_session_key) override {
168168
return getSessionKeyEntry(idx, pub_key_prefix, flags, nonce, session_key, prev_session_key);
169169
}
170+
bool isSessionKeyInRAM(const uint8_t* pub_key_prefix) override;
171+
bool isSessionKeyRemoved(const uint8_t* pub_key_prefix) override;
170172

171173
void clearPendingReqs() {
172174
pending_login = pending_status = pending_telemetry = pending_discovery = pending_req = 0;
@@ -198,9 +200,16 @@ class MyMesh : public BaseChatMesh, public DataStoreHost {
198200
void saveChannels() { _store->saveChannels(this); }
199201
void saveContacts() { _store->saveContacts(this); }
200202
void saveNonces() { if (_store->saveNonces(this)) clearNonceDirty(); }
201-
void saveSessionKeys() { if (_store->saveSessionKeys(this)) clearSessionKeysDirty(); }
203+
void saveSessionKeys() { if (_store->saveSessionKeys(this)) { clearSessionKeysDirty(); clearSessionKeysRemoved(); } }
202204
void onSessionKeysUpdated() override { saveSessionKeys(); }
203205

206+
// Flash-backed session key overrides
207+
bool loadSessionKeyRecordFromFlash(const uint8_t* pub_key_prefix,
208+
uint8_t* flags, uint16_t* nonce, uint8_t* session_key, uint8_t* prev_session_key) override {
209+
return _store->loadSessionKeyByPrefix(pub_key_prefix, flags, nonce, session_key, prev_session_key);
210+
}
211+
void mergeAndSaveSessionKeys() override { saveSessionKeys(); }
212+
204213
DataStore* _store;
205214
NodePrefs _prefs;
206215
uint32_t pending_login;

src/MeshCore.h

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,11 @@
3636
#define NONCE_INITIAL_MAX 50000 // max random nonce seed for new contacts
3737
#define SESSION_KEY_TIMEOUT_MS 180000 // 3 minutes per attempt
3838
#define SESSION_KEY_MAX_RETRIES 3 // attempts per negotiation round
39-
#define MAX_SESSION_KEYS 8 // max concurrent session key entries
39+
#define MAX_SESSION_KEYS_RAM 8 // max concurrent session key entries in RAM (LRU cache)
40+
#define MAX_SESSION_KEYS_FLASH 48 // max entries in flash file
41+
#define SESSION_KEY_RECORD_SIZE 71 // max bytes per record (with prev_key)
42+
#define SESSION_KEY_RECORD_MIN_SIZE 39 // min bytes per record: [pub_prefix:4][flags:1][nonce:2][key:32]
43+
#define SESSION_FLAG_PREV_VALID 0x01 // prev_session_key is valid for dual-decode
4044
#define SESSION_KEY_STALE_THRESHOLD 50 // sends without recv before fallback to static ECDH
4145
#define SESSION_KEY_ECB_THRESHOLD 100 // sends without recv before fallback to ECB
4246
#define SESSION_KEY_ABANDON_THRESHOLD 255 // sends without recv before clearing AEAD + session key

src/helpers/BaseChatMesh.cpp

Lines changed: 46 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -967,7 +967,7 @@ bool BaseChatMesh::removeContact(ContactInfo& contact) {
967967
}
968968
if (idx >= num_contacts) return false; // not found
969969

970-
session_keys.remove(contact.id.pub_key); // also remove session key if any
970+
removeSessionKey(contact.id.pub_key); // also remove session key if any
971971

972972
// remove from contacts array and parallel nonce tracking
973973
num_contacts--;
@@ -1082,6 +1082,41 @@ void BaseChatMesh::loop() {
10821082
}
10831083
}
10841084

1085+
// --- Session key flash-backed wrappers ---
1086+
1087+
SessionKeyEntry* BaseChatMesh::findSessionKey(const uint8_t* pub_key) {
1088+
auto entry = session_keys.findByPrefix(pub_key);
1089+
if (entry) return entry;
1090+
1091+
// Cache miss — try flash
1092+
uint8_t flags; uint16_t nonce;
1093+
uint8_t sk[SESSION_KEY_SIZE], psk[SESSION_KEY_SIZE];
1094+
if (!loadSessionKeyRecordFromFlash(pub_key, &flags, &nonce, sk, psk)) return nullptr;
1095+
1096+
// Save dirty evictee before overwriting
1097+
if (session_keys.isFull() && session_keys_dirty) {
1098+
mergeAndSaveSessionKeys();
1099+
}
1100+
session_keys.applyLoaded(pub_key, flags, nonce, sk, psk);
1101+
return session_keys.findByPrefix(pub_key);
1102+
}
1103+
1104+
SessionKeyEntry* BaseChatMesh::allocateSessionKey(const uint8_t* pub_key) {
1105+
// Check RAM and flash first
1106+
auto entry = findSessionKey(pub_key);
1107+
if (entry) return entry;
1108+
1109+
// Not found anywhere — save dirty evictee before allocating
1110+
if (session_keys.isFull() && session_keys_dirty) {
1111+
mergeAndSaveSessionKeys();
1112+
}
1113+
return session_keys.allocate(pub_key);
1114+
}
1115+
1116+
void BaseChatMesh::removeSessionKey(const uint8_t* pub_key) {
1117+
session_keys.remove(pub_key);
1118+
}
1119+
10851120
// --- Session key support (Phase 2 — initiator) ---
10861121

10871122
static bool canUseSessionKey(const SessionKeyEntry* entry) {
@@ -1097,7 +1132,7 @@ static bool canUseSessionKey(const SessionKeyEntry* entry) {
10971132
}
10981133

10991134
const uint8_t* BaseChatMesh::getEncryptionKeyFor(const ContactInfo& contact) {
1100-
auto entry = session_keys.findByPrefix(contact.id.pub_key);
1135+
auto entry = findSessionKey(contact.id.pub_key);
11011136
if (canUseSessionKey(entry)) {
11021137
return entry->session_key;
11031138
}
@@ -1106,7 +1141,7 @@ const uint8_t* BaseChatMesh::getEncryptionKeyFor(const ContactInfo& contact) {
11061141

11071142
uint16_t BaseChatMesh::getEncryptionNonceFor(const ContactInfo& contact) {
11081143
uint16_t nonce = 0;
1109-
auto entry = session_keys.findByPrefix(contact.id.pub_key);
1144+
auto entry = findSessionKey(contact.id.pub_key);
11101145
if (canUseSessionKey(entry)) {
11111146
++entry->nonce;
11121147
if (entry->sends_since_last_recv < 255) entry->sends_since_last_recv++;
@@ -1120,7 +1155,7 @@ uint16_t BaseChatMesh::getEncryptionNonceFor(const ContactInfo& contact) {
11201155
int idx = &contact - contacts;
11211156
if (idx >= 0 && idx < num_contacts)
11221157
contacts[idx].flags &= ~CONTACT_FLAG_AEAD;
1123-
session_keys.remove(contact.id.pub_key);
1158+
removeSessionKey(contact.id.pub_key);
11241159
onSessionKeysUpdated();
11251160
// nonce = 0 (ECB)
11261161
} else if (entry->sends_since_last_recv >= SESSION_KEY_ECB_THRESHOLD) {
@@ -1149,7 +1184,7 @@ bool BaseChatMesh::shouldInitiateSessionKey(const ContactInfo& contact) {
11491184
// Need a known path to send the request
11501185
if (contact.out_path_len < 0) return false;
11511186

1152-
auto entry = session_keys.findByPrefix(contact.id.pub_key);
1187+
auto entry = findSessionKey(contact.id.pub_key);
11531188

11541189
// Don't trigger if negotiation already in progress
11551190
if (entry && entry->state == SESSION_STATE_INIT_SENT) return false;
@@ -1185,7 +1220,7 @@ bool BaseChatMesh::shouldInitiateSessionKey(const ContactInfo& contact) {
11851220
}
11861221

11871222
bool BaseChatMesh::initiateSessionKeyNegotiation(const ContactInfo& contact) {
1188-
auto entry = session_keys.allocate(contact.id.pub_key);
1223+
auto entry = allocateSessionKey(contact.id.pub_key);
11891224
if (!entry) return false;
11901225

11911226
// Don't start a new negotiation if one is already pending
@@ -1221,7 +1256,7 @@ bool BaseChatMesh::handleSessionKeyResponse(ContactInfo& contact, const uint8_t*
12211256
if (len < 5 + PUB_KEY_SIZE) return false;
12221257
if (data[4] != RESP_TYPE_SESSION_KEY_ACCEPT) return false;
12231258

1224-
auto entry = session_keys.findByPrefix(contact.id.pub_key);
1259+
auto entry = findSessionKey(contact.id.pub_key);
12251260
if (!entry || entry->state != SESSION_STATE_INIT_SENT) return false;
12261261

12271262
const uint8_t* ephemeral_pub_B = &data[5];
@@ -1283,7 +1318,7 @@ uint8_t BaseChatMesh::handleIncomingSessionKeyInit(ContactInfo& from, const uint
12831318
memset(ephemeral_secret, 0, PUB_KEY_SIZE);
12841319

12851320
// 4. Store in pool (dual-decode: new key active, old key still valid)
1286-
auto entry = session_keys.allocate(from.id.pub_key);
1321+
auto entry = allocateSessionKey(from.id.pub_key);
12871322
if (!entry) return 0;
12881323

12891324
if (entry->state == SESSION_STATE_ACTIVE || entry->state == SESSION_STATE_DUAL_DECODE) {
@@ -1346,7 +1381,7 @@ void BaseChatMesh::checkSessionKeyTimeouts() {
13461381
const uint8_t* BaseChatMesh::getPeerSessionKey(int peer_idx) {
13471382
int i = matching_peer_indexes[peer_idx];
13481383
if (i >= 0 && i < num_contacts) {
1349-
auto entry = session_keys.findByPrefix(contacts[i].id.pub_key);
1384+
auto entry = findSessionKey(contacts[i].id.pub_key);
13501385
// Also try decode during INIT_SENT renegotiation (nonce > 1 means prior key exists)
13511386
if (entry && (entry->state == SESSION_STATE_ACTIVE || entry->state == SESSION_STATE_DUAL_DECODE
13521387
|| (entry->state == SESSION_STATE_INIT_SENT && entry->nonce > 1)))
@@ -1358,7 +1393,7 @@ const uint8_t* BaseChatMesh::getPeerSessionKey(int peer_idx) {
13581393
const uint8_t* BaseChatMesh::getPeerPrevSessionKey(int peer_idx) {
13591394
int i = matching_peer_indexes[peer_idx];
13601395
if (i >= 0 && i < num_contacts) {
1361-
auto entry = session_keys.findByPrefix(contacts[i].id.pub_key);
1396+
auto entry = findSessionKey(contacts[i].id.pub_key);
13621397
if (entry && entry->state == SESSION_STATE_DUAL_DECODE)
13631398
return entry->prev_session_key;
13641399
}
@@ -1368,7 +1403,7 @@ const uint8_t* BaseChatMesh::getPeerPrevSessionKey(int peer_idx) {
13681403
void BaseChatMesh::onSessionKeyDecryptSuccess(int peer_idx) {
13691404
int i = matching_peer_indexes[peer_idx];
13701405
if (i >= 0 && i < num_contacts) {
1371-
auto entry = session_keys.findByPrefix(contacts[i].id.pub_key);
1406+
auto entry = findSessionKey(contacts[i].id.pub_key);
13721407
if (entry) {
13731408
bool changed = (entry->state == SESSION_STATE_DUAL_DECODE);
13741409
if (changed) {

src/helpers/BaseChatMesh.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,15 @@ class BaseChatMesh : public mesh::Mesh {
151151

152152
// Session key support (Phase 2 — initiator)
153153
virtual void onSessionKeysUpdated() { session_keys_dirty = true; } // called when session key pool changes; override to persist
154+
virtual bool loadSessionKeyRecordFromFlash(const uint8_t* pub_key_prefix,
155+
uint8_t* flags, uint16_t* nonce, uint8_t* session_key, uint8_t* prev_session_key) { return false; }
156+
virtual void mergeAndSaveSessionKeys() {} // merge RAM + flash, write back
157+
158+
// Wrappers that add flash fallback on cache miss
159+
SessionKeyEntry* findSessionKey(const uint8_t* pub_key);
160+
SessionKeyEntry* allocateSessionKey(const uint8_t* pub_key);
161+
void removeSessionKey(const uint8_t* pub_key);
162+
154163
const uint8_t* getEncryptionKeyFor(const ContactInfo& contact);
155164
uint16_t getEncryptionNonceFor(const ContactInfo& contact);
156165
bool shouldInitiateSessionKey(const ContactInfo& contact);
@@ -167,6 +176,9 @@ class BaseChatMesh : public mesh::Mesh {
167176
int getSessionKeyCount() const { return session_keys.getCount(); }
168177
bool isSessionKeysDirty() const { return session_keys_dirty; }
169178
void clearSessionKeysDirty() { session_keys_dirty = false; }
179+
bool isSessionKeyInRAMPool(const uint8_t* pub_key_prefix) { return session_keys.hasPrefix(pub_key_prefix); }
180+
bool isSessionKeyRemovedFromPool(const uint8_t* pub_key_prefix) { return session_keys.isRemoved(pub_key_prefix); }
181+
void clearSessionKeysRemoved() { session_keys.clearRemoved(); }
170182

171183
// Mesh overrides
172184
void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len) override;

0 commit comments

Comments
 (0)