Skip to content

Commit b689893

Browse files
hanno-beckermkannwischer
authored andcommitted
CBMC: Add loop termination clauses for ML-KEM Braid helpers
Signed-off-by: Hanno Becker <beckphan@amazon.co.uk>
1 parent b75b12f commit b689893

1 file changed

Lines changed: 12 additions & 6 deletions

File tree

mlkem/src/kem.c

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -385,7 +385,8 @@ static void mlk_serialize_epp(uint8_t out[MLKEM_EPP_BYTES], const mlk_poly *p)
385385
for (j = 0; j < MLKEM_N / 2; j++)
386386
__loop__(
387387
assigns(j, memory_slice(out, MLKEM_EPP_BYTES))
388-
invariant(j <= MLKEM_N / 2))
388+
invariant(j <= MLKEM_N / 2)
389+
decreases(MLKEM_N / 2 - j))
389390
{
390391
uint8_t lo = (uint8_t)(MLKEM_ETA2 - p->coeffs[2 * j]);
391392
uint8_t hi = (uint8_t)(MLKEM_ETA2 - p->coeffs[2 * j + 1]);
@@ -400,7 +401,8 @@ static void mlk_deserialize_epp(mlk_poly *p, const uint8_t in[MLKEM_EPP_BYTES])
400401
__loop__(
401402
assigns(j, memory_slice(p, sizeof(mlk_poly)))
402403
invariant(j <= MLKEM_N / 2)
403-
invariant(array_abs_bound(p->coeffs, 0, 2 * j, 16)))
404+
invariant(array_abs_bound(p->coeffs, 0, 2 * j, 16))
405+
decreases(MLKEM_N / 2 - j))
404406
{
405407
p->coeffs[2 * j] = (int16_t)((int16_t)MLKEM_ETA2 - (int16_t)(in[j] & 0xF));
406408
p->coeffs[2 * j + 1] =
@@ -418,12 +420,14 @@ static void mlk_serialize_polyvec_16le(uint8_t out[MLKEM_POLYVEC16_BYTES],
418420
for (i = 0; i < MLKEM_K; i++)
419421
__loop__(
420422
assigns(i, j, memory_slice(out, MLKEM_POLYVEC16_BYTES))
421-
invariant(i <= MLKEM_K))
423+
invariant(i <= MLKEM_K)
424+
decreases(MLKEM_K - i))
422425
{
423426
for (j = 0; j < MLKEM_N; j++)
424427
__loop__(
425428
assigns(j, memory_slice(out, MLKEM_POLYVEC16_BYTES))
426-
invariant(j <= MLKEM_N))
429+
invariant(j <= MLKEM_N)
430+
decreases(MLKEM_K - j))
427431
{
428432
uint16_t c = (uint16_t)v->vec[i].coeffs[j];
429433
out[i * MLKEM_POLY16_BYTES + 2 * j] = (uint8_t)(c & 0xFF);
@@ -439,12 +443,14 @@ static void mlk_deserialize_polyvec_16le(
439443
for (i = 0; i < MLKEM_K; i++)
440444
__loop__(
441445
assigns(i, j, memory_slice(v, sizeof(mlk_polyvec)))
442-
invariant(i <= MLKEM_K))
446+
invariant(i <= MLKEM_K)
447+
decreases(MLKEM_K - i))
443448
{
444449
for (j = 0; j < MLKEM_N; j++)
445450
__loop__(
446451
assigns(j, memory_slice(v, sizeof(mlk_polyvec)))
447-
invariant(j <= MLKEM_N))
452+
invariant(j <= MLKEM_N)
453+
decreases(MLKEM_K - j))
448454
{
449455
v->vec[i].coeffs[j] = mlk_cast_uint16_to_int16(
450456
(uint16_t)((unsigned)in[i * MLKEM_POLY16_BYTES + 2 * j] |

0 commit comments

Comments
 (0)