Skip to content

Commit af403d0

Browse files
committed
Allow persisting more session to flash
1 parent 0186856 commit af403d0

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
@@ -2216,6 +2216,14 @@ void MyMesh::checkSerialInterface() {
22162216
}
22172217
}
22182218

2219+
bool MyMesh::isSessionKeyInRAM(const uint8_t* pub_key_prefix) {
2220+
return isSessionKeyInRAMPool(pub_key_prefix);
2221+
}
2222+
2223+
bool MyMesh::isSessionKeyRemoved(const uint8_t* pub_key_prefix) {
2224+
return isSessionKeyRemovedFromPool(pub_key_prefix);
2225+
}
2226+
22192227
void MyMesh::loop() {
22202228
BaseChatMesh::loop();
22212229

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
@@ -971,7 +971,7 @@ bool BaseChatMesh::removeContact(ContactInfo& contact) {
971971
}
972972
if (idx >= num_contacts) return false; // not found
973973

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

976976
// remove from contacts array and parallel nonce tracking
977977
num_contacts--;
@@ -1086,6 +1086,41 @@ void BaseChatMesh::loop() {
10861086
}
10871087
}
10881088

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

10911126
static bool canUseSessionKey(const SessionKeyEntry* entry) {
@@ -1101,7 +1136,7 @@ static bool canUseSessionKey(const SessionKeyEntry* entry) {
11011136
}
11021137

11031138
const uint8_t* BaseChatMesh::getEncryptionKeyFor(const ContactInfo& contact) {
1104-
auto entry = session_keys.findByPrefix(contact.id.pub_key);
1139+
auto entry = findSessionKey(contact.id.pub_key);
11051140
if (canUseSessionKey(entry)) {
11061141
return entry->session_key;
11071142
}
@@ -1110,7 +1145,7 @@ const uint8_t* BaseChatMesh::getEncryptionKeyFor(const ContactInfo& contact) {
11101145

11111146
uint16_t BaseChatMesh::getEncryptionNonceFor(const ContactInfo& contact) {
11121147
uint16_t nonce = 0;
1113-
auto entry = session_keys.findByPrefix(contact.id.pub_key);
1148+
auto entry = findSessionKey(contact.id.pub_key);
11141149
if (canUseSessionKey(entry)) {
11151150
++entry->nonce;
11161151
if (entry->sends_since_last_recv < 255) entry->sends_since_last_recv++;
@@ -1124,7 +1159,7 @@ uint16_t BaseChatMesh::getEncryptionNonceFor(const ContactInfo& contact) {
11241159
int idx = &contact - contacts;
11251160
if (idx >= 0 && idx < num_contacts)
11261161
contacts[idx].flags &= ~CONTACT_FLAG_AEAD;
1127-
session_keys.remove(contact.id.pub_key);
1162+
removeSessionKey(contact.id.pub_key);
11281163
onSessionKeysUpdated();
11291164
// nonce = 0 (ECB)
11301165
} else if (entry->sends_since_last_recv >= SESSION_KEY_ECB_THRESHOLD) {
@@ -1153,7 +1188,7 @@ bool BaseChatMesh::shouldInitiateSessionKey(const ContactInfo& contact) {
11531188
// Need a known path to send the request
11541189
if (contact.out_path_len < 0) return false;
11551190

1156-
auto entry = session_keys.findByPrefix(contact.id.pub_key);
1191+
auto entry = findSessionKey(contact.id.pub_key);
11571192

11581193
// Don't trigger if negotiation already in progress
11591194
if (entry && entry->state == SESSION_STATE_INIT_SENT) return false;
@@ -1189,7 +1224,7 @@ bool BaseChatMesh::shouldInitiateSessionKey(const ContactInfo& contact) {
11891224
}
11901225

11911226
bool BaseChatMesh::initiateSessionKeyNegotiation(const ContactInfo& contact) {
1192-
auto entry = session_keys.allocate(contact.id.pub_key);
1227+
auto entry = allocateSessionKey(contact.id.pub_key);
11931228
if (!entry) return false;
11941229

11951230
// Don't start a new negotiation if one is already pending
@@ -1225,7 +1260,7 @@ bool BaseChatMesh::handleSessionKeyResponse(ContactInfo& contact, const uint8_t*
12251260
if (len < 5 + PUB_KEY_SIZE) return false;
12261261
if (data[4] != RESP_TYPE_SESSION_KEY_ACCEPT) return false;
12271262

1228-
auto entry = session_keys.findByPrefix(contact.id.pub_key);
1263+
auto entry = findSessionKey(contact.id.pub_key);
12291264
if (!entry || entry->state != SESSION_STATE_INIT_SENT) return false;
12301265

12311266
const uint8_t* ephemeral_pub_B = &data[5];
@@ -1287,7 +1322,7 @@ uint8_t BaseChatMesh::handleIncomingSessionKeyInit(ContactInfo& from, const uint
12871322
memset(ephemeral_secret, 0, PUB_KEY_SIZE);
12881323

12891324
// 4. Store in pool (dual-decode: new key active, old key still valid)
1290-
auto entry = session_keys.allocate(from.id.pub_key);
1325+
auto entry = allocateSessionKey(from.id.pub_key);
12911326
if (!entry) return 0;
12921327

12931328
if (entry->state == SESSION_STATE_ACTIVE || entry->state == SESSION_STATE_DUAL_DECODE) {
@@ -1350,7 +1385,7 @@ void BaseChatMesh::checkSessionKeyTimeouts() {
13501385
const uint8_t* BaseChatMesh::getPeerSessionKey(int peer_idx) {
13511386
int i = matching_peer_indexes[peer_idx];
13521387
if (i >= 0 && i < num_contacts) {
1353-
auto entry = session_keys.findByPrefix(contacts[i].id.pub_key);
1388+
auto entry = findSessionKey(contacts[i].id.pub_key);
13541389
// Also try decode during INIT_SENT renegotiation (nonce > 1 means prior key exists)
13551390
if (entry && (entry->state == SESSION_STATE_ACTIVE || entry->state == SESSION_STATE_DUAL_DECODE
13561391
|| (entry->state == SESSION_STATE_INIT_SENT && entry->nonce > 1)))
@@ -1362,7 +1397,7 @@ const uint8_t* BaseChatMesh::getPeerSessionKey(int peer_idx) {
13621397
const uint8_t* BaseChatMesh::getPeerPrevSessionKey(int peer_idx) {
13631398
int i = matching_peer_indexes[peer_idx];
13641399
if (i >= 0 && i < num_contacts) {
1365-
auto entry = session_keys.findByPrefix(contacts[i].id.pub_key);
1400+
auto entry = findSessionKey(contacts[i].id.pub_key);
13661401
if (entry && entry->state == SESSION_STATE_DUAL_DECODE)
13671402
return entry->prev_session_key;
13681403
}
@@ -1372,7 +1407,7 @@ const uint8_t* BaseChatMesh::getPeerPrevSessionKey(int peer_idx) {
13721407
void BaseChatMesh::onSessionKeyDecryptSuccess(int peer_idx) {
13731408
int i = matching_peer_indexes[peer_idx];
13741409
if (i >= 0 && i < num_contacts) {
1375-
auto entry = session_keys.findByPrefix(contacts[i].id.pub_key);
1410+
auto entry = findSessionKey(contacts[i].id.pub_key);
13761411
if (entry) {
13771412
bool changed = (entry->state == SESSION_STATE_DUAL_DECODE);
13781413
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)