fe25519: take the carry out by multiplying, not by a left shift of a negative value

fe25519_carry's c << 51, with c negative after fe25519_sub, is
undefined in C99; the nightly's sanitized mesh boot stopped on it
(2026-11-20, run 333), reaching it through CI's signed capsules.
c * 2^51 is the same value. test_fe25519 (16 checks: values that
send a limb negative, and RFC 8032 tests 1 and 2 signed and verified)
runs in make -C v4 test and under ASan+UBSan in sanitize; it failed
first under UBSan at fe25519.c:31:26. Gates pass, POST 990/990.
The acceptance protocol runs before it reaches a PR (ruled: the next
PR, not #198).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017RzZgrf7V7Zk2iczBXDRbm
This commit is contained in:
Claude
2026-11-20 14:01:15 +00:00
parent 40e9773885
commit 1990a40f09
7 changed files with 1871 additions and 6 deletions
+8 -3
View File
@@ -22,17 +22,22 @@ void fe25519_copy(fe25519 *r, const fe25519 *a) { *r = *a; }
* extra scaling needed, unlike a limb count/width that doesn't divide
* 255 evenly). Two passes: the wraparound carry can itself need to
* ripple through limb 0 again on rare inputs. Works for negative limbs
* too (arithmetic shift preserves sign) -- needed after fe25519_sub. */
* too (arithmetic shift preserves sign) -- needed after fe25519_sub.
* The carry is taken out by multiplying, not by shifting it back left:
* after fe25519_sub it can be negative, and a left shift of a negative
* value is undefined in C99 (2026-11-20: the nightly's sanitized mesh
* boot stopped here, logs/20261120-fe25519/; the value is the same). */
#define RADIX ((int64_t)1 << WBITS)
static void fe25519_carry(fe25519 *r)
{
for (int pass = 0; pass < 2; pass++) {
for (int i = 0; i < 4; i++) {
int64_t c = r->v[i] >> WBITS;
r->v[i] -= c << WBITS;
r->v[i] -= c * RADIX;
r->v[i+1] += c;
}
int64_t c = r->v[4] >> WBITS;
r->v[4] -= c << WBITS;
r->v[4] -= c * RADIX;
r->v[0] += c * 19;
}
}