Skip to content

Commit 65af393

Browse files
committed
Allow persisting more session to flash
1 parent 5dee5a3 commit 65af393

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
@@ -409,37 +409,105 @@ bool DataStore::saveNonces(DataStoreHost* host) {
409409

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

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

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
@@ -2048,6 +2048,14 @@ void MyMesh::checkSerialInterface() {
20482048
}
20492049
}
20502050

2051+
bool MyMesh::isSessionKeyInRAM(const uint8_t* pub_key_prefix) {
2052+
return isSessionKeyInRAMPool(pub_key_prefix);
2053+
}
2054+
2055+
bool MyMesh::isSessionKeyRemoved(const uint8_t* pub_key_prefix) {
2056+
return isSessionKeyRemovedFromPool(pub_key_prefix);
2057+
}
2058+
20512059
void MyMesh::loop() {
20522060
BaseChatMesh::loop();
20532061

examples/companion_radio/MyMesh.h

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,8 @@ class MyMesh : public BaseChatMesh, public DataStoreHost {
165165
uint8_t* session_key, uint8_t* prev_session_key) override {
166166
return getSessionKeyEntry(idx, pub_key_prefix, flags, nonce, session_key, prev_session_key);
167167
}
168+
bool isSessionKeyInRAM(const uint8_t* pub_key_prefix) override;
169+
bool isSessionKeyRemoved(const uint8_t* pub_key_prefix) override;
168170

169171
void clearPendingReqs() {
170172
pending_login = pending_status = pending_telemetry = pending_discovery = pending_req = 0;
@@ -196,9 +198,16 @@ class MyMesh : public BaseChatMesh, public DataStoreHost {
196198
void saveChannels() { _store->saveChannels(this); }
197199
void saveContacts() { _store->saveContacts(this); }
198200
void saveNonces() { if (_store->saveNonces(this)) clearNonceDirty(); }
199-
void saveSessionKeys() { if (_store->saveSessionKeys(this)) clearSessionKeysDirty(); }
201+
void saveSessionKeys() { if (_store->saveSessionKeys(this)) { clearSessionKeysDirty(); clearSessionKeysRemoved(); } }
200202
void onSessionKeysUpdated() override { saveSessionKeys(); }
201203

204+
// Flash-backed session key overrides
205+
bool loadSessionKeyRecordFromFlash(const uint8_t* pub_key_prefix,
206+
uint8_t* flags, uint16_t* nonce, uint8_t* session_key, uint8_t* prev_session_key) override {
207+
return _store->loadSessionKeyByPrefix(pub_key_prefix, flags, nonce, session_key, prev_session_key);
208+
}
209+
void mergeAndSaveSessionKeys() override { saveSessionKeys(); }
210+
202211
DataStore* _store;
203212
NodePrefs _prefs;
204213
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
@@ -909,7 +909,7 @@ bool BaseChatMesh::removeContact(ContactInfo& contact) {
909909
}
910910
if (idx >= num_contacts) return false; // not found
911911

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

914914
// remove from contacts array and parallel nonce tracking
915915
num_contacts--;
@@ -1024,6 +1024,41 @@ void BaseChatMesh::loop() {
10241024
}
10251025
}
10261026

1027+
// --- Session key flash-backed wrappers ---
1028+
1029+
SessionKeyEntry* BaseChatMesh::findSessionKey(const uint8_t* pub_key) {
1030+
auto entry = session_keys.findByPrefix(pub_key);
1031+
if (entry) return entry;
1032+
1033+
// Cache miss — try flash
1034+
uint8_t flags; uint16_t nonce;
1035+
uint8_t sk[SESSION_KEY_SIZE], psk[SESSION_KEY_SIZE];
1036+
if (!loadSessionKeyRecordFromFlash(pub_key, &flags, &nonce, sk, psk)) return nullptr;
1037+
1038+
// Save dirty evictee before overwriting
1039+
if (session_keys.isFull() && session_keys_dirty) {
1040+
mergeAndSaveSessionKeys();
1041+
}
1042+
session_keys.applyLoaded(pub_key, flags, nonce, sk, psk);
1043+
return session_keys.findByPrefix(pub_key);
1044+
}
1045+
1046+
SessionKeyEntry* BaseChatMesh::allocateSessionKey(const uint8_t* pub_key) {
1047+
// Check RAM and flash first
1048+
auto entry = findSessionKey(pub_key);
1049+
if (entry) return entry;
1050+
1051+
// Not found anywhere — save dirty evictee before allocating
1052+
if (session_keys.isFull() && session_keys_dirty) {
1053+
mergeAndSaveSessionKeys();
1054+
}
1055+
return session_keys.allocate(pub_key);
1056+
}
1057+
1058+
void BaseChatMesh::removeSessionKey(const uint8_t* pub_key) {
1059+
session_keys.remove(pub_key);
1060+
}
1061+
10271062
// --- Session key support (Phase 2 — initiator) ---
10281063

10291064
static bool canUseSessionKey(const SessionKeyEntry* entry) {
@@ -1039,7 +1074,7 @@ static bool canUseSessionKey(const SessionKeyEntry* entry) {
10391074
}
10401075

10411076
const uint8_t* BaseChatMesh::getEncryptionKeyFor(const ContactInfo& contact) {
1042-
auto entry = session_keys.findByPrefix(contact.id.pub_key);
1077+
auto entry = findSessionKey(contact.id.pub_key);
10431078
if (canUseSessionKey(entry)) {
10441079
return entry->session_key;
10451080
}
@@ -1048,7 +1083,7 @@ const uint8_t* BaseChatMesh::getEncryptionKeyFor(const ContactInfo& contact) {
10481083

10491084
uint16_t BaseChatMesh::getEncryptionNonceFor(const ContactInfo& contact) {
10501085
uint16_t nonce = 0;
1051-
auto entry = session_keys.findByPrefix(contact.id.pub_key);
1086+
auto entry = findSessionKey(contact.id.pub_key);
10521087
if (canUseSessionKey(entry)) {
10531088
++entry->nonce;
10541089
if (entry->sends_since_last_recv < 255) entry->sends_since_last_recv++;
@@ -1062,7 +1097,7 @@ uint16_t BaseChatMesh::getEncryptionNonceFor(const ContactInfo& contact) {
10621097
int idx = &contact - contacts;
10631098
if (idx >= 0 && idx < num_contacts)
10641099
contacts[idx].flags &= ~CONTACT_FLAG_AEAD;
1065-
session_keys.remove(contact.id.pub_key);
1100+
removeSessionKey(contact.id.pub_key);
10661101
onSessionKeysUpdated();
10671102
// nonce = 0 (ECB)
10681103
} else if (entry->sends_since_last_recv >= SESSION_KEY_ECB_THRESHOLD) {
@@ -1091,7 +1126,7 @@ bool BaseChatMesh::shouldInitiateSessionKey(const ContactInfo& contact) {
10911126
// Need a known path to send the request
10921127
if (contact.out_path_len < 0) return false;
10931128

1094-
auto entry = session_keys.findByPrefix(contact.id.pub_key);
1129+
auto entry = findSessionKey(contact.id.pub_key);
10951130

10961131
// Don't trigger if negotiation already in progress
10971132
if (entry && entry->state == SESSION_STATE_INIT_SENT) return false;
@@ -1127,7 +1162,7 @@ bool BaseChatMesh::shouldInitiateSessionKey(const ContactInfo& contact) {
11271162
}
11281163

11291164
bool BaseChatMesh::initiateSessionKeyNegotiation(const ContactInfo& contact) {
1130-
auto entry = session_keys.allocate(contact.id.pub_key);
1165+
auto entry = allocateSessionKey(contact.id.pub_key);
11311166
if (!entry) return false;
11321167

11331168
// Don't start a new negotiation if one is already pending
@@ -1163,7 +1198,7 @@ bool BaseChatMesh::handleSessionKeyResponse(ContactInfo& contact, const uint8_t*
11631198
if (len < 5 + PUB_KEY_SIZE) return false;
11641199
if (data[4] != RESP_TYPE_SESSION_KEY_ACCEPT) return false;
11651200

1166-
auto entry = session_keys.findByPrefix(contact.id.pub_key);
1201+
auto entry = findSessionKey(contact.id.pub_key);
11671202
if (!entry || entry->state != SESSION_STATE_INIT_SENT) return false;
11681203

11691204
const uint8_t* ephemeral_pub_B = &data[5];
@@ -1225,7 +1260,7 @@ uint8_t BaseChatMesh::handleIncomingSessionKeyInit(ContactInfo& from, const uint
12251260
memset(ephemeral_secret, 0, PUB_KEY_SIZE);
12261261

12271262
// 4. Store in pool (dual-decode: new key active, old key still valid)
1228-
auto entry = session_keys.allocate(from.id.pub_key);
1263+
auto entry = allocateSessionKey(from.id.pub_key);
12291264
if (!entry) return 0;
12301265

12311266
if (entry->state == SESSION_STATE_ACTIVE || entry->state == SESSION_STATE_DUAL_DECODE) {
@@ -1288,7 +1323,7 @@ void BaseChatMesh::checkSessionKeyTimeouts() {
12881323
const uint8_t* BaseChatMesh::getPeerSessionKey(int peer_idx) {
12891324
int i = matching_peer_indexes[peer_idx];
12901325
if (i >= 0 && i < num_contacts) {
1291-
auto entry = session_keys.findByPrefix(contacts[i].id.pub_key);
1326+
auto entry = findSessionKey(contacts[i].id.pub_key);
12921327
// Also try decode during INIT_SENT renegotiation (nonce > 1 means prior key exists)
12931328
if (entry && (entry->state == SESSION_STATE_ACTIVE || entry->state == SESSION_STATE_DUAL_DECODE
12941329
|| (entry->state == SESSION_STATE_INIT_SENT && entry->nonce > 1)))
@@ -1300,7 +1335,7 @@ const uint8_t* BaseChatMesh::getPeerSessionKey(int peer_idx) {
13001335
const uint8_t* BaseChatMesh::getPeerPrevSessionKey(int peer_idx) {
13011336
int i = matching_peer_indexes[peer_idx];
13021337
if (i >= 0 && i < num_contacts) {
1303-
auto entry = session_keys.findByPrefix(contacts[i].id.pub_key);
1338+
auto entry = findSessionKey(contacts[i].id.pub_key);
13041339
if (entry && entry->state == SESSION_STATE_DUAL_DECODE)
13051340
return entry->prev_session_key;
13061341
}
@@ -1310,7 +1345,7 @@ const uint8_t* BaseChatMesh::getPeerPrevSessionKey(int peer_idx) {
13101345
void BaseChatMesh::onSessionKeyDecryptSuccess(int peer_idx) {
13111346
int i = matching_peer_indexes[peer_idx];
13121347
if (i >= 0 && i < num_contacts) {
1313-
auto entry = session_keys.findByPrefix(contacts[i].id.pub_key);
1348+
auto entry = findSessionKey(contacts[i].id.pub_key);
13141349
if (entry) {
13151350
bool changed = (entry->state == SESSION_STATE_DUAL_DECODE);
13161351
if (changed) {

src/helpers/BaseChatMesh.h

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

150150
// Session key support (Phase 2 — initiator)
151151
virtual void onSessionKeysUpdated() { session_keys_dirty = true; } // called when session key pool changes; override to persist
152+
virtual bool loadSessionKeyRecordFromFlash(const uint8_t* pub_key_prefix,
153+
uint8_t* flags, uint16_t* nonce, uint8_t* session_key, uint8_t* prev_session_key) { return false; }
154+
virtual void mergeAndSaveSessionKeys() {} // merge RAM + flash, write back
155+
156+
// Wrappers that add flash fallback on cache miss
157+
SessionKeyEntry* findSessionKey(const uint8_t* pub_key);
158+
SessionKeyEntry* allocateSessionKey(const uint8_t* pub_key);
159+
void removeSessionKey(const uint8_t* pub_key);
160+
152161
const uint8_t* getEncryptionKeyFor(const ContactInfo& contact);
153162
uint16_t getEncryptionNonceFor(const ContactInfo& contact);
154163
bool shouldInitiateSessionKey(const ContactInfo& contact);
@@ -165,6 +174,9 @@ class BaseChatMesh : public mesh::Mesh {
165174
int getSessionKeyCount() const { return session_keys.getCount(); }
166175
bool isSessionKeysDirty() const { return session_keys_dirty; }
167176
void clearSessionKeysDirty() { session_keys_dirty = false; }
177+
bool isSessionKeyInRAMPool(const uint8_t* pub_key_prefix) { return session_keys.hasPrefix(pub_key_prefix); }
178+
bool isSessionKeyRemovedFromPool(const uint8_t* pub_key_prefix) { return session_keys.isRemoved(pub_key_prefix); }
179+
void clearSessionKeysRemoved() { session_keys.clearRemoved(); }
168180

169181
// Mesh overrides
170182
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)