Skip to content

Commit 6657715

Browse files
committed
Allow persisting more session to flash
1 parent 97f0af8 commit 6657715

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

416416
void DataStore::loadSessionKeys(DataStoreHost* host) {
417417
File file = openRead(_getContactsChannelsFS(), "/sess_keys");
418-
if (file) {
419-
uint8_t rec[71]; // 4-byte pub_key prefix + 1 flags + 2 nonce + 32 session_key + 32 prev_session_key
420-
while (file.read(rec, 71) == 71) {
421-
uint16_t nonce;
422-
memcpy(&nonce, &rec[5], 2);
423-
host->onSessionKeyLoaded(rec, rec[4], nonce, &rec[7], &rec[39]);
418+
if (!file) return;
419+
while (true) {
420+
uint8_t rec[SESSION_KEY_RECORD_MIN_SIZE];
421+
if (file.read(rec, SESSION_KEY_RECORD_MIN_SIZE) != SESSION_KEY_RECORD_MIN_SIZE) break;
422+
uint8_t flags = rec[4];
423+
uint16_t nonce;
424+
memcpy(&nonce, &rec[5], 2);
425+
uint8_t prev_key[SESSION_KEY_SIZE];
426+
if (flags & SESSION_FLAG_PREV_VALID) {
427+
if (file.read(prev_key, SESSION_KEY_SIZE) != SESSION_KEY_SIZE) break;
428+
} else {
429+
memset(prev_key, 0, SESSION_KEY_SIZE);
424430
}
425-
file.close();
431+
host->onSessionKeyLoaded(rec, flags, nonce, &rec[7], prev_key);
426432
}
433+
file.close();
427434
}
428435

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

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
@@ -2185,6 +2185,14 @@ void MyMesh::checkSerialInterface() {
21852185
}
21862186
}
21872187

2188+
bool MyMesh::isSessionKeyInRAM(const uint8_t* pub_key_prefix) {
2189+
return isSessionKeyInRAMPool(pub_key_prefix);
2190+
}
2191+
2192+
bool MyMesh::isSessionKeyRemoved(const uint8_t* pub_key_prefix) {
2193+
return isSessionKeyRemovedFromPool(pub_key_prefix);
2194+
}
2195+
21882196
void MyMesh::loop() {
21892197
BaseChatMesh::loop();
21902198

examples/companion_radio/MyMesh.h

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

172174
void clearPendingReqs() {
173175
pending_login = pending_status = pending_telemetry = pending_discovery = pending_req = 0;
@@ -210,9 +212,16 @@ class MyMesh : public BaseChatMesh, public DataStoreHost {
210212
void saveChannels() { _store->saveChannels(this); }
211213
void saveContacts() { _store->saveContacts(this); }
212214
void saveNonces() { if (_store->saveNonces(this)) clearNonceDirty(); }
213-
void saveSessionKeys() { if (_store->saveSessionKeys(this)) clearSessionKeysDirty(); }
215+
void saveSessionKeys() { if (_store->saveSessionKeys(this)) { clearSessionKeysDirty(); clearSessionKeysRemoved(); } }
214216
void onSessionKeysUpdated() override { saveSessionKeys(); }
215217

218+
// Flash-backed session key overrides
219+
bool loadSessionKeyRecordFromFlash(const uint8_t* pub_key_prefix,
220+
uint8_t* flags, uint16_t* nonce, uint8_t* session_key, uint8_t* prev_session_key) override {
221+
return _store->loadSessionKeyByPrefix(pub_key_prefix, flags, nonce, session_key, prev_session_key);
222+
}
223+
void mergeAndSaveSessionKeys() override { saveSessionKeys(); }
224+
216225
DataStore* _store;
217226
NodePrefs _prefs;
218227
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)