feat(ota): add read-only running-image hash and find ops

OP_BLOCK_HASH reports the running image's size, its ESP segment table, its whole-image hash and up to four range hashes. OP_BLOCK_FIND takes up to twelve 64-bit rolling fingerprints and a search window, slides the hash once across the window and returns the aligned offsets where each block occurs. Both are answered in every state, never write flash and are feature-flagged in OP_INFO_REPORT. Lets the app build an update diff with no previous image on the device. Native OTA tests cover both ops.
This commit is contained in:
github-actions[bot] committed 2026-11-18 20:45:15 -06:00
1 parent be9ce5543d
commit ee5c21e75e
3 files changed
+421 -15

No files matched your search

+185 -9
View File
@@ -7,6 +7,7 @@
#include "OtaUpdate.h"
#include <Arduino.h>
#include <stdlib.h>
#include <SHA256.h>
#include <Utils.h>
@@ -104,12 +105,13 @@ public:
// SHA-256 over `size` bytes of one slot, read in 1 KB slices. Shared by the
// OP_END verification (staged) and hashRunningImage() (running).
static bool hashSlot(OtaSlotIo* io, bool staged, uint32_t size, uint8_t out[32]) {
static bool hashSlot(OtaSlotIo* io, bool staged, uint32_t start, uint32_t size, uint8_t out[32]) {
SHA256 sha;
uint8_t buf[1024];
uint32_t off = 0;
while (off < size) {
size_t n = size - off < sizeof(buf) ? size - off : sizeof(buf);
uint32_t off = start;
const uint32_t end = start + size;
while (off < end) {
size_t n = end - off < sizeof(buf) ? end - off : sizeof(buf);
if (staged ? !io->readStaged(off, buf, n) : !io->readSource(off, buf, n)) return false;
sha.update(buf, n);
off += n;
@@ -151,14 +153,17 @@ static uint32_t runningImageLength(OtaSlotIo* io) {
// included when it verifies against the computed hash, so this equals the hash
// the app computes over its own image file (the delta base match). Returns
// false when the slot does not hold a recognisable image.
static bool hashRunningImage(OtaSlotIo* io, uint8_t out[32]) {
static bool hashRunningImage(OtaSlotIo* io, uint8_t out[32], uint32_t* hashed_len = nullptr) {
const uint32_t len = runningImageLength(io);
if (len == 0) return false;
if (!hashSlot(io, /*staged=*/false, len, out)) return false;
if (!hashSlot(io, /*staged=*/false, 0, len, out)) return false;
uint8_t digest[32];
if (slotRead(io, false, len, digest, sizeof(digest)) && memcmp(digest, out, 32) == 0) {
return hashSlot(io, /*staged=*/false, len + sizeof(digest), out);
if (!hashSlot(io, /*staged=*/false, 0, len + sizeof(digest), out)) return false;
if (hashed_len != nullptr) *hashed_len = len + sizeof(digest);
return true;
}
if (hashed_len != nullptr) *hashed_len = len;
return true;
}
@@ -295,6 +300,7 @@ size_t OtaUpdate::buildInfoReport(uint8_t* out) {
slot = _io->slotSize();
features |= OTA_FEAT_DELTA; // OP_COPY is implemented everywhere with flash
features |= OTA_FEAT_APPLY; // dual app slot (ESP32)
features |= OTA_FEAT_BLOCK_HASH; // read-only running-image hash oracle
}
// OP_INFO_REPORT body: wire_ver(1) target(4) slot(4) max_literal(2) features(4)
@@ -320,6 +326,164 @@ size_t OtaUpdate::buildInfoReport(uint8_t* out) {
return sealFrame(out, 3 + sizeof(p));
}
uint32_t OtaUpdate::ensureRunningLength() {
if (_running_len_valid) return _running_len;
_running_len_valid = true;
// The digest of the hashed bytes is the length the app sees in its .bin.
// ensureRunningSha() computes both in one pass over flash.
ensureRunningSha();
return _running_len;
}
size_t OtaUpdate::buildBlockHashReport(const uint8_t* body, uint16_t body_len, uint8_t* out) {
if (body == nullptr || body_len < 1 || out == nullptr) return 0;
const uint8_t count = body[0];
const uint32_t running_len = ensureRunningLength();
uint8_t p[OTA_HASH_RANGE_BODY(OTA_HASH_MAX_RANGES)];
memset(p, 0, sizeof(p));
putLe32(p, running_len);
p[4] = count;
if (count == 0) {
// Metadata query: fixed segment table (six slots, unused ones zero) plus
// the whole-image hash. One round trip gives the app everything it needs
// to align segments and detect an identical image.
if (body_len != 1) return 0;
uint8_t seg_count = 0;
if (_io != nullptr && running_len > 0) {
uint8_t h[24];
if (slotRead(_io, false, 0, h, sizeof(h)) && h[0] == 0xE9 && h[1] >= 1 && h[1] <= 16) {
uint32_t off = sizeof(h);
for (uint8_t i = 0; i < h[1] && seg_count < OTA_HASH_MAX_SEGS; i++) {
uint8_t seg[8];
if (!slotRead(_io, false, off, seg, sizeof(seg))) break;
const uint32_t len = le32(seg + 4);
const uint32_t payload_off = off + 8;
if ((uint64_t)payload_off + len > running_len) break;
uint8_t* s = &p[6 + seg_count * 8];
putLe32(s, payload_off);
putLe32(s + 4, len);
seg_count++;
off = payload_off + len;
off = (off + 3) & ~3u;
if (off >= running_len) break;
}
}
}
p[5] = seg_count; // p[4] stays count == 0 (metadata marker)
ensureRunningSha();
memcpy(&p[6 + OTA_HASH_MAX_SEGS * 8], _running_sha, OTA_HASH_LEN);
out[0] = OTA_MAGIC0;
out[1] = OTA_MAGIC1;
out[2] = OTA_OP_BLOCK_HASH_REPORT;
memcpy(out + 3, p, OTA_HASH_META_BODY);
return sealFrame(out, 3 + OTA_HASH_META_BODY);
}
if (count > OTA_HASH_MAX_RANGES || body_len != (uint16_t)(1 + 8 * count)) return 0;
for (uint8_t i = 0; i < count; i++) {
const uint8_t* r = body + 1 + i * 8;
const uint32_t off = le32(r);
const uint32_t len = le32(r + 4);
uint8_t* dst = &p[5 + i * (4 + 1 + OTA_HASH_LEN)];
putLe32(dst, off);
uint8_t status = 0;
if (_io == nullptr || running_len == 0) {
status = 3; // no readable image
} else if ((off & (OTA_HASH_ALIGN - 1)) != 0 ||
(len != 0 && ((len & (OTA_HASH_ALIGN - 1)) != 0 ||
len > OTA_HASH_MAX_RANGE))) {
status = 3; // alignment / length rejected
} else {
uint32_t n = len;
if (len == 0 && off <= running_len) n = running_len - off;
if (off > running_len || n > running_len - off) {
status = 1; // out of bounds
} else if (!hashSlot(_io, false, off, n, dst + 5)) {
status = 2; // flash read failed
}
}
dst[4] = status;
}
out[0] = OTA_MAGIC0;
out[1] = OTA_MAGIC1;
out[2] = OTA_OP_BLOCK_HASH_REPORT;
memcpy(out + 3, p, OTA_HASH_RANGE_BODY(count));
return sealFrame(out, 3 + OTA_HASH_RANGE_BODY(count));
}
size_t OtaUpdate::buildFindReport(const uint8_t* body, uint16_t body_len, uint8_t* out) {
if (body == nullptr || body_len < 13 || _io == nullptr) return 0;
const uint32_t len = le32(body);
const uint32_t start = le32(body + 4);
const uint32_t end = le32(body + 8);
const uint8_t count = body[12];
const uint32_t running_len = ensureRunningLength();
if (count == 0 || count > OTA_FIND_MAX_BLOCKS) return 0;
if (body_len < (uint16_t)(13 + 8 * count)) return 0;
if (len == 0 || len % OTA_HASH_ALIGN != 0 || len > OTA_HASH_MAX_RANGE ||
start % OTA_HASH_ALIGN != 0 || end % OTA_HASH_ALIGN != 0 ||
start > end || end > running_len) return 0;
uint64_t want[OTA_FIND_MAX_BLOCKS];
uint8_t hit_count[OTA_FIND_MAX_BLOCKS];
uint32_t hits[OTA_FIND_MAX_BLOCKS][OTA_FIND_HITS_PER];
for (uint8_t i = 0; i < count; i++) {
const uint8_t* p = body + 13 + i * 8;
want[i] = (uint64_t)le32(p) | ((uint64_t)le32(p + 4) << 32);
hit_count[i] = 0;
memset(hits[i], 0, sizeof(hits[i]));
}
// Same polynomial as the app's delta matcher. Slide once across the window
// and compare every fingerprint at each offset; this keeps a 12-block query
// to one flash scan.
static const uint64_t kPrime = 0x00000100000001B3ull;
uint8_t* buf = (uint8_t*)malloc(len);
if (buf == nullptr) return 0;
if (!slotRead(_io, false, start, buf, len)) { free(buf); return 0; }
uint64_t h = 0;
for (uint32_t i = 0; i < len; i++) h = h * kPrime + buf[i];
uint64_t pow = 1;
for (uint32_t i = 1; i < len; i++) pow *= kPrime; // P^(len-1), mod 2^64
uint8_t remaining = count;
for (uint32_t off = start; off + len <= end && remaining > 0;
off += OTA_HASH_ALIGN) {
for (uint8_t i = 0; i < count; i++) {
if (h != want[i] || hit_count[i] >= OTA_FIND_HITS_PER) continue;
hits[i][hit_count[i]++] = off;
if (hit_count[i] == OTA_FIND_HITS_PER) remaining--;
}
if (remaining == 0 || off + OTA_HASH_ALIGN + len > end) break;
uint8_t in[OTA_HASH_ALIGN];
if (!slotRead(_io, false, off + len, in, sizeof(in))) break;
for (uint8_t k = 0; k < OTA_HASH_ALIGN; k++) {
h = (h - (uint64_t)buf[k] * pow) * kPrime + in[k];
}
memmove(buf, buf + OTA_HASH_ALIGN, len - OTA_HASH_ALIGN);
memcpy(buf + len - OTA_HASH_ALIGN, in, OTA_HASH_ALIGN);
}
free(buf);
uint8_t p[1 + OTA_FIND_MAX_BLOCKS * (1 + OTA_FIND_HITS_PER * 4)];
memset(p, 0, sizeof(p));
size_t used = 0;
p[used++] = count;
for (uint8_t i = 0; i < count; i++) {
p[used++] = hit_count[i];
for (uint8_t j = 0; j < hit_count[i]; j++) {
putLe32(p + used, hits[i][j]);
used += 4;
}
}
out[0] = OTA_MAGIC0;
out[1] = OTA_MAGIC1;
out[2] = OTA_OP_BLOCK_FIND_REPORT;
memcpy(out + 3, p, used);
return sealFrame(out, 3 + used);
}
size_t OtaUpdate::onFrame(const uint8_t* frame, size_t n, uint8_t* report_out, size_t report_cap) {
if (frame == nullptr || n < 5) return 0; // magic(2) + op(1) + crc(2); ops carry a seq
if (frame[0] != OTA_MAGIC0 || frame[1] != OTA_MAGIC1) return 0;
@@ -337,6 +501,18 @@ size_t OtaUpdate::onFrame(const uint8_t* frame, size_t n, uint8_t* report_out, s
if (_io == nullptr) return 0; // not an ESP32 (or slot lookup failed): inert
// Read-only diff oracle: answered in every state, like OP_INFO, and never
// touches the session or flash writes. Body is count + ranges (or just the
// count byte for the metadata query).
if (op == OTA_OP_BLOCK_HASH) {
if (report_out == nullptr || report_cap < OTA_HASH_REPORT_MAX) return 0;
return buildBlockHashReport(frame + 3, (uint16_t)(n - 5), report_out);
}
if (op == OTA_OP_BLOCK_FIND) {
if (report_out == nullptr || report_cap < OTA_FIND_REPORT_MAX) return 0;
return buildFindReport(frame + 3, (uint16_t)(n - 5), report_out);
}
if (op == OTA_OP_NOP || op == OTA_OP_REPORT || op == OTA_OP_INFO_REPORT) return 0;
if (op == OTA_OP_ASK) {
@@ -421,7 +597,7 @@ void OtaUpdate::applyOp(const uint8_t* body, uint16_t body_len, uint8_t op) {
if (_written != _size) { abortStaging(OTA_ERR_BOUNDS); return; }
{
uint8_t sha[32];
if (!hashSlot(_io, /*staged=*/true, _size, sha) || memcmp(sha, _expected_sha, 32) != 0) {
if (!hashSlot(_io, /*staged=*/true, 0, _size, sha) || memcmp(sha, _expected_sha, 32) != 0) {
abortStaging(OTA_ERR_SHA);
return;
}
@@ -605,7 +781,7 @@ void OtaUpdate::ensureRunningSha() {
if (_running_sha_valid) return;
_running_sha_valid = true;
memset(_running_sha, 0, sizeof(_running_sha));
if (_io != nullptr) hashRunningImage(_io, _running_sha); // zeros: unknown
if (_io != nullptr) hashRunningImage(_io, _running_sha, &_running_len); // zeros: unknown
}
void OtaUpdate::formatStatus(char* reply, size_t reply_size) {
+59 -5
View File
@@ -61,6 +61,20 @@
// OP_INFO 0x07 query node capabilities (any state)
// OP_INFO_REPORT 0x08 wire_ver:u8 target:u32 slot:u32 max_literal:u16 features:u32
// ver[32] sha256[32] (repeater → app, inside RESPONSE)
// OP_BLOCK_HASH 0x09 count:u8 (offset:u32 len:u32)[count]
// hash running-image ranges (any state)
// OP_BLOCK_HASH_REPORT 0x0A running_size:u32 ... (repeater → app, inside RESPONSE)
// count=0: seg_count:u8 (off:u32 len:u32)[segs] sha256[32]
// count>0: count:u8 (off:u32 status:u8 sha256[32])[count]
// OP_BLOCK_FIND 0x0B len:u32 start:u32 end:u32 count:u8 rolling64[count]:u64
// find up to 12 blocks in one
// window of the running image
// (4-byte aligned offsets).
// rolling64 is the same polynomial hash the app's delta matcher uses:
// h = 0; for each byte: h = h*0x100000001B3 + byte (mod 2^64)
// The node slides it once over the window, comparing all fingerprints.
// OP_BLOCK_FIND_REPORT 0x0C (hit_count:u8 offset:u32[hit_count])[count]
// (at most OTA_FIND_HITS_PER offsets per block)
//
// Stability contract (this is what lets the format live for years):
// - Unknown ops and unknown OP_INFO bodies are dropped silently.
@@ -78,7 +92,10 @@
// the app's own .bin and is what the app uses to pick a delta base by
// exact-image match. All zeros means "cannot tell".
// New features are only ever added as new bits or new report fields
// appended at the end.
// appended at the end. OP_BLOCK_HASH is answered in every state and never
// writes flash or changes the session; it is a read-only diff oracle. The
// app still SHA-256s the *new* image at OP_END, so a wrong diff can waste
// airtime but can never boot a wrong image.
// - New ops get new op codes; existing ops never change meaning, field
// order or size. The CRC algorithm, the magic bytes and the SEQ rules
// are frozen.
@@ -140,6 +157,10 @@
#define OTA_OP_REPORT 0x06
#define OTA_OP_INFO 0x07
#define OTA_OP_INFO_REPORT 0x08
#define OTA_OP_BLOCK_HASH 0x09
#define OTA_OP_BLOCK_HASH_REPORT 0x0A
#define OTA_OP_BLOCK_FIND 0x0B
#define OTA_OP_BLOCK_FIND_REPORT 0x0C
#define OTA_MAGIC0 0x4F // 'O'
#define OTA_MAGIC1 0x54 // 'T'
@@ -151,6 +172,7 @@
// feature bits reported in OP_INFO_REPORT.features (rest reserved, must be 0)
#define OTA_FEAT_DELTA 0x00000001 // OP_COPY is implemented
#define OTA_FEAT_APPLY 0x00000002 // apply/rollback is implemented (dual app slot)
#define OTA_FEAT_BLOCK_HASH 0x00000004 // OP_BLOCK_HASH is implemented
// OP_INFO_REPORT body size (before the OTA frame envelope: magic + op + crc)
#define OTA_INFO_BODY 79 // wire_ver(1) + target(4) + slot(4) + max_literal(2) + features(4) + ver[32] + running sha256[32]
@@ -162,8 +184,30 @@
static_assert(OTA_INFO_RUNNING_VER_OFF == 1 + 4 + 4 + 2 + 4, "OP_INFO_REPORT field order");
static_assert(OTA_INFO_RUNNING_SHA_OFF == OTA_INFO_RUNNING_VER_OFF + 32, "OP_INFO_REPORT field order");
static_assert(OTA_INFO_BODY == OTA_INFO_RUNNING_SHA_OFF + 32, "OP_INFO_REPORT field order");
// largest report frame the engine ever returns (OP_INFO_REPORT is the biggest)
#define OTA_REPORT_MAX OTA_INFO_REPORT_LEN
// OP_BLOCK_HASH: one request may carry up to OTA_HASH_MAX_RANGES ranges; the
// report echoes up to that many hashes. count=0 is the metadata query: it
// returns the running image's size, its ESP segment table and its whole-image
// hash so the app can align segments and detect "already up to date" in one
// round trip. Every range report also carries running_size.
#define OTA_HASH_LEN 32
#define OTA_HASH_MAX_RANGES 4
#define OTA_HASH_MAX_SEGS 6
#define OTA_HASH_MAX_RANGE 32768 // 32 x 1 KB flash reads per range
#define OTA_HASH_ALIGN 4
#define OTA_HASH_MAX_HITS 4
#define OTA_FIND_MAX_BLOCKS 12
#define OTA_FIND_HITS_PER 2
#define OTA_FIND_BODY (4 + 4 + 4 + 1 + OTA_FIND_MAX_BLOCKS * 8)
#define OTA_FIND_REPORT_MAX (3 + 1 + OTA_FIND_MAX_BLOCKS * (1 + OTA_FIND_HITS_PER * 4) + 2)
#define OTA_HASH_META_BODY (4 + 1 + 1 + OTA_HASH_MAX_SEGS * 8 + OTA_HASH_LEN)
#define OTA_HASH_RANGE_BODY(n) (4 + 1 + (n) * (4 + 1 + OTA_HASH_LEN))
#define OTA_HASH_META_LEN (3 + OTA_HASH_META_BODY + 2)
#define OTA_HASH_RANGE_LEN(n) (3 + OTA_HASH_RANGE_BODY(n) + 2)
#define OTA_HASH_REPORT_MAX (OTA_HASH_META_LEN > OTA_HASH_RANGE_LEN(OTA_HASH_MAX_RANGES) \
? OTA_HASH_META_LEN : OTA_HASH_RANGE_LEN(OTA_HASH_MAX_RANGES))
// largest report frame the engine ever returns
#define OTA_REPORT_MAX (OTA_INFO_REPORT_LEN > OTA_HASH_REPORT_MAX \
? OTA_INFO_REPORT_LEN : OTA_HASH_REPORT_MAX)
// OTA frames carrying an op: magic(2) + op(1) + seq(2) + body + crc16(2).
// ASK/REPORT/INFO*/NOP carry no seq.
@@ -288,6 +332,8 @@ private:
uint8_t _expected_sha[32] = {0};
uint8_t _running_sha[32] = {0};
bool _running_sha_valid = false;
uint32_t _running_len = 0; // image length (header + digest)
bool _running_len_valid = false;
bool _health_pending = false; // freshly-applied image booted
bool _health_sent = false; // health probe already dispatched
@@ -296,12 +342,20 @@ private:
uint16_t _health_nonce = 0; // sha-free marker nonce
bool stagingArmed() const { return _state == State::Staging || _state == State::Ready; }
// Compute _running_sha once per boot, on first use (the app's delta base
// match). Zeros when the platform cannot read the running image back.
// Compute _running_sha once per boot, on first use. Zeros when the platform
// cannot read the running image back.
void ensureRunningSha();
// runningImageLength(), cached for the read-only hash oracle.
uint32_t ensureRunningLength();
// Build the OP_INFO_REPORT frame (magic..CRC) into `out`. Works in every
// state — it is the negotiation handshake an app performs before arming.
size_t buildInfoReport(uint8_t* out);
// Build an OP_BLOCK_HASH_REPORT for a metadata query (count=0) or a range
// query. Read-only: never touches the session state or flash writes.
size_t buildBlockHashReport(const uint8_t* body, uint16_t body_len, uint8_t* out);
// Locate a 4-byte-aligned block of the running image by its SHA-256. This
// is what recovers matches after an edit shifts every following byte.
size_t buildFindReport(const uint8_t* body, uint16_t body_len, uint8_t* out);
public:
/// Boot-time verdict before the radio or mesh start: count this boot of a
/// freshly-applied image and roll back once the attempts run out. Covers the
+177 -1
View File
@@ -592,7 +592,8 @@ TEST_F(OtaTest, InfoReportAnswersWhenIdle) {
EXPECT_EQ(le32From(body + 1), testTargetId());
EXPECT_EQ(le32From(body + 5), 0x200000u); // FakeSlotIo slot size
EXPECT_EQ(body[9] | (body[10] << 8), (uint16_t)OTA_MAX_LITERAL);
EXPECT_EQ(le32From(body + 11), (uint32_t)(OTA_FEAT_DELTA | OTA_FEAT_APPLY));
EXPECT_EQ(le32From(body + 11),
(uint32_t)(OTA_FEAT_DELTA | OTA_FEAT_APPLY | OTA_FEAT_BLOCK_HASH));
// The fake slot holds no ESP image, so the running sha is reported as
// unknown (all zeros) rather than as a hash of erase fill.
for (size_t k = 0; k < 32; k++) EXPECT_EQ(body[OTA_INFO_RUNNING_SHA_OFF + k], 0u);
@@ -642,6 +643,181 @@ TEST_F(OtaTest, InfoReportHashesImageWithoutAppendedDigest) {
EXPECT_EQ(memcmp(report.data() + 3 + OTA_INFO_RUNNING_SHA_OFF, expect, 32), 0);
}
// ============================================================
// OP_BLOCK_HASH — the read-only diff oracle
// ============================================================
static std::vector<uint8_t> hashFrame(
const std::vector<std::pair<uint32_t, uint32_t>>& ranges) {
std::vector<uint8_t> body;
body.push_back((uint8_t)ranges.size());
for (const auto& r : ranges) {
for (int i = 0; i < 4; i++) body.push_back((uint8_t)(r.first >> (8 * i)));
for (int i = 0; i < 4; i++) body.push_back((uint8_t)(r.second >> (8 * i)));
}
return bodyFrame(OTA_OP_BLOCK_HASH, body);
}
static uint8_t hashStatus(const std::vector<uint8_t>& report, size_t i) {
return report[3 + 5 + i * (4 + 1 + OTA_HASH_LEN) + 4];
}
static const uint8_t* hashDigest(const std::vector<uint8_t>& report, size_t i) {
return report.data() + 3 + 5 + i * (4 + 1 + OTA_HASH_LEN) + 5;
}
TEST_F(OtaTest, BlockHashMetadataReportsSizeSegmentsAndWholeHash) {
auto image = syntheticImage(/*with_digest=*/true);
std::copy(image.begin(), image.end(), slot.source.begin());
auto report = feed(hashFrame({}));
ASSERT_EQ(report.size(), OTA_HASH_META_LEN);
EXPECT_EQ(report[2], OTA_OP_BLOCK_HASH_REPORT);
const uint8_t* body = report.data() + 3;
EXPECT_EQ(le32From(body), (uint32_t)image.size());
EXPECT_EQ(body[4], 0u); // metadata marker
ASSERT_EQ(body[5], 1u); // one program segment
EXPECT_EQ(le32From(body + 6), 32u); // payload starts after the header
EXPECT_EQ(le32From(body + 10), 400u); // its length
uint8_t expect[32];
mockSha256(image, expect);
EXPECT_EQ(memcmp(body + 6 + OTA_HASH_MAX_SEGS * 8, expect, 32), 0);
}
TEST_F(OtaTest, BlockHashHashesRequestedRanges) {
auto image = syntheticImage(/*with_digest=*/true);
std::copy(image.begin(), image.end(), slot.source.begin());
// Four hash calculations in one call — the whole point of the batch.
auto report = feed(hashFrame({{0, 16}, {32, 400}, {0, 0}, {448, 32}}));
ASSERT_EQ(report.size(), OTA_HASH_RANGE_LEN(4));
for (int i = 0; i < 4; i++) {
EXPECT_EQ(hashStatus(report, i), 0u) << "range " << i;
}
const size_t lengths[4] = {16, 400, image.size(), 32};
const size_t offsets[4] = {0, 32, 0, 448};
for (int i = 0; i < 4; i++) {
uint8_t expect[32];
mockSha256(std::vector<uint8_t>(image.begin() + offsets[i],
image.begin() + offsets[i] + lengths[i]), expect);
EXPECT_EQ(memcmp(hashDigest(report, i), expect, 32), 0) << "range " << i;
}
}
TEST_F(OtaTest, BlockHashRejectsAliasedAndOversizedRanges) {
auto image = syntheticImage(/*with_digest=*/true);
std::copy(image.begin(), image.end(), slot.source.begin());
auto report = feed(hashFrame({{1, 16}, // misaligned
{0, image.size() + 16}, // out of bounds
{32, OTA_HASH_MAX_RANGE + 4}, // too long
{image.size(), 0}})); // empty tail: hashed
ASSERT_EQ(report.size(), OTA_HASH_RANGE_LEN(4));
EXPECT_EQ(hashStatus(report, 0), 3u);
EXPECT_EQ(hashStatus(report, 1), 1u);
EXPECT_EQ(hashStatus(report, 2), 3u);
EXPECT_EQ(hashStatus(report, 3), 0u);
}
TEST_F(OtaTest, BlockHashIsReadOnlyInEverySessionState) {
auto image = syntheticImage(/*with_digest=*/true);
std::copy(image.begin(), image.end(), slot.source.begin());
auto metadata = hashFrame({});
ASSERT_EQ(feed(metadata).size(), OTA_HASH_META_LEN); // Idle
ASSERT_EQ(ota.state(), OtaUpdate::State::Idle);
arm(image);
ASSERT_EQ(feed(metadata).size(), OTA_HASH_META_LEN); // Staging
EXPECT_EQ(ota.state(), OtaUpdate::State::Staging);
EXPECT_EQ(slot.staged.size(), 0u); // no writes by the oracle
sendLiteral(1, image);
sendEnd(2);
ASSERT_EQ(ota.state(), OtaUpdate::State::Ready);
ASSERT_EQ(feed(metadata).size(), OTA_HASH_META_LEN); // Ready
EXPECT_EQ(ota.state(), OtaUpdate::State::Ready);
}
TEST_F(OtaTest, BlockHashWorksAfterAFailedStaging) {
auto image = syntheticImage(/*with_digest=*/true);
std::copy(image.begin(), image.end(), slot.source.begin());
arm(image);
sendCopy(1, 0xFFFFFF00u, 16); // out of bounds → Error
ASSERT_EQ(ota.state(), OtaUpdate::State::Error);
ASSERT_EQ(feed(hashFrame({{0, 16}})).size(), OTA_HASH_RANGE_LEN(1));
EXPECT_EQ(ota.state(), OtaUpdate::State::Error);
}
static uint64_t rollingTest(const std::vector<uint8_t>& d, size_t at, size_t len) {
uint64_t h = 0;
for (size_t i = 0; i < len; i++) h = h * 0x00000100000001B3ull + d[at + i];
return h;
}
static std::vector<uint8_t> findFrame(uint32_t len, uint32_t start, uint32_t end,
const std::vector<uint64_t>& wants) {
std::vector<uint8_t> body;
for (int i = 0; i < 4; i++) body.push_back((uint8_t)(len >> (8 * i)));
for (int i = 0; i < 4; i++) body.push_back((uint8_t)(start >> (8 * i)));
for (int i = 0; i < 4; i++) body.push_back((uint8_t)(end >> (8 * i)));
body.push_back((uint8_t)wants.size());
for (auto w : wants) {
for (int i = 0; i < 8; i++) body.push_back((uint8_t)(w >> (8 * i)));
}
return bodyFrame(OTA_OP_BLOCK_FIND, body);
}
static std::vector<int> findHits(const std::vector<uint8_t>& report, size_t i) {
size_t at = 4;
for (size_t k = 0; k < i; k++) {
uint8_t n = report[at++];
at += n * 4;
}
std::vector<int> out;
uint8_t n = report[at++];
for (uint8_t k = 0; k < n; k++) {
out.push_back((int)le32From(report.data() + at));
at += 4;
}
return out;
}
TEST_F(OtaTest, BlockFindLocatesShiftedBlocksInOneScan) {
auto image = syntheticImage(/*with_digest=*/true);
std::copy(image.begin(), image.end(), slot.source.begin());
const uint64_t want = rollingTest(image, 32, 16);
const uint64_t bogus = want ^ 0x12345678ull;
auto report = feed(findFrame(16, 0, (uint32_t)image.size(),
{bogus, want, want + 1}));
ASSERT_FALSE(report.empty());
ASSERT_EQ(report[2], OTA_OP_BLOCK_FIND_REPORT);
EXPECT_TRUE(findHits(report, 0).empty());
auto hits = findHits(report, 1);
ASSERT_FALSE(hits.empty());
EXPECT_TRUE(std::find(hits.begin(), hits.end(), 32) != hits.end());
EXPECT_TRUE(findHits(report, 2).empty());
}
TEST_F(OtaTest, BlockFindRejectsBadRangesWithoutDisturbingStaging) {
auto image = syntheticImage(/*with_digest=*/true);
std::copy(image.begin(), image.end(), slot.source.begin());
arm(image);
const uint64_t want = rollingTest(image, 32, 16);
// Misaligned start, end past the image, and zero length all produce no reply.
EXPECT_TRUE(feed(findFrame(16, 1, (uint32_t)image.size(), {want})).empty());
EXPECT_TRUE(feed(findFrame(16, 0, (uint32_t)image.size() + 4, {want})).empty());
EXPECT_TRUE(feed(findFrame(0, 0, (uint32_t)image.size(), {want})).empty());
EXPECT_EQ(ota.state(), OtaUpdate::State::Staging);
}
TEST_F(OtaTest, BlockHashWithoutAnImageReportsZeroSize) {
// FakeSlotIo starts as erase fill, which is not an ESP app image.
auto report = feed(hashFrame({}));
ASSERT_EQ(report.size(), OTA_HASH_META_LEN);
EXPECT_EQ(le32From(report.data() + 3), 0u);
EXPECT_EQ(report[3 + 5], 0u); // no segments
auto range = feed(hashFrame({{0, 16}}));
ASSERT_EQ(range.size(), OTA_HASH_RANGE_LEN(1));
EXPECT_EQ(hashStatus(range, 0), 3u);
}
TEST_F(OtaTest, StatusShaMatchesTheInfoReport) {
auto image = syntheticImage(/*with_digest=*/true);
std::copy(image.begin(), image.end(), slot.source.begin());