@amritk/nish-aarch64-linux 0.38.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/bin/nish +0 -0
  2. package/docs/AI.md +348 -37
  3. package/package.json +1 -1
  4. package/runtime/core/host.d.ts +11 -0
  5. package/runtime/core/host.mjs +35 -0
  6. package/runtime/nish.d.ts +301 -18
  7. package/runtime/nish.h +74 -10
  8. package/runtime/nish.mjs +69 -6
  9. package/runtime/node.mjs +117 -0
  10. package/runtime/runtime-aes.c +12 -4
  11. package/runtime/runtime-async.c +43 -10
  12. package/runtime/runtime-checksum.c +207 -15
  13. package/runtime/runtime-net.c +32 -3
  14. package/runtime/runtime-os.c +174 -27
  15. package/runtime/runtime-region.c +94 -10
  16. package/runtime/runtime-sandbox.c +377 -17
  17. package/runtime/runtime-sha256.c +11 -4
  18. package/runtime/runtime-wasm.c +15 -0
  19. package/runtime/runtime.c +5 -0
  20. package/scripts/build.sh +27 -8
  21. package/std/README.md +5 -4
  22. package/std/compress/checksum.ts +13 -0
  23. package/std/compress/deflate.ts +0 -2
  24. package/std/crypto/p256.ts +247 -74
  25. package/std/crypto/p384.ts +3 -1
  26. package/std/crypto/pki.ts +35 -9
  27. package/std/crypto/x25519.ts +153 -64
  28. package/std/crypto/x509.ts +113 -10
  29. package/std/json-tokenizer.ts +20 -0
  30. package/std/json-typed.ts +217 -8
  31. package/std/net/handler.ts +130 -16
  32. package/std/net/http1-codec.ts +499 -150
  33. package/std/net/http1-server.ts +495 -22
  34. package/std/net/http2-cleartext.ts +526 -0
  35. package/std/net/http2-tls.ts +48 -0
  36. package/std/net/http2.ts +84 -0
  37. package/std/net/postgres-async.ts +1304 -86
  38. package/std/net/postgres-carrier.ts +343 -10
  39. package/std/net/postgres.ts +122 -7
  40. package/std/net/prefork.ts +195 -11
  41. package/std/net/quic-datagram.ts +30 -0
  42. package/std/net/quic-listener.ts +38 -12
  43. package/std/net/quic-packet.ts +19 -6
  44. package/std/net/quic-recovery.ts +134 -19
  45. package/std/net/quic-stream.ts +174 -36
  46. package/std/net/quic.ts +418 -18
  47. package/std/net/router.ts +39 -17
  48. package/std/net/serve.ts +162 -58
  49. package/std/net/tls/codec.ts +110 -32
  50. package/std/net/tls/record-server.ts +37 -7
  51. package/std/net/tls-tcp.ts +56 -1
  52. package/std/net/tls.ts +196 -50
  53. package/std/net/websocket.ts +55 -18
  54. package/std/net/webtransport.ts +179 -1
  55. package/std/regex.ts +69 -47
  56. package/std/region.ts +62 -11
  57. package/std/secret.ts +26 -59
  58. package/std/text.ts +233 -0
@@ -182,6 +182,21 @@ void nish_exit(int32_t code) { (void)code; __builtin_trap(); }
182
182
  * link; the loader throws a RangeError before the call reaches it. */
183
183
  void nish_panic(const void *s) { (void)s; __builtin_trap(); }
184
184
  #endif
185
+ /* ---- Streaming reads (WP44 §9 Q7): the checker refuses `fileOpen`,
186
+ * `fileReadAt`, `fileSize` and `fileClose` on a freestanding wasm32 target
187
+ * (NL2718), but `--profile wasm` links IR compiled for the host, which no
188
+ * check sees. There is no file system to read, so each answers -38 (`ENOSYS`)
189
+ * and the link never fails on their names. The path is `const void *`, as
190
+ * `nish_panic`'s string is: this file has no `nish_str`, and the ABI is the
191
+ * same pointer. tests/run.js's wasm profile section links all four. */
192
+ int32_t nish_file_open(const void *path) { (void)path; return -38; }
193
+ int32_t nish_file_read_at(int32_t fd, nish_array *buf, int64_t off, int64_t len, int64_t pos) {
194
+ (void)fd; (void)buf; (void)off; (void)len; (void)pos;
195
+ return -38;
196
+ }
197
+ int64_t nish_file_size(int32_t fd) { (void)fd; return -38; }
198
+ int32_t nish_file_close(int32_t fd) { (void)fd; return -38; }
199
+
185
200
  /* Output has nowhere to go either. */
186
201
  void nish_write(const void *s, int32_t fd, _Bool newline) { (void)s; (void)fd; (void)newline; }
187
202
 
package/runtime/runtime.c CHANGED
@@ -368,6 +368,11 @@ uint64_t nish_arena_mark(void) {
368
368
  }
369
369
  uint64_t nish_arena_used(void) { return nish_arena.off; }
370
370
 
371
+ /* ---- cErrno (WP27 S5, docs/wp27-ffi.md §10): compiled code zeroes errno through this
372
+ * pointer before a foreign call and copies it into the per-thread slot after. */
373
+ NISH_TLS int32_t nish_errno_slot;
374
+ int *nish_errno_ptr(void) { return &errno; }
375
+
371
376
  void nish_arena_release(uint64_t mark) {
372
377
  nish_chunk *c = nish_arena.chunks;
373
378
  if (!mark) { nish_reset_arena(); return; }
package/scripts/build.sh CHANGED
@@ -16,7 +16,8 @@
16
16
  # <dir>/runtime-aes.c, AES-GCM on the CPU's AES instructions,
17
17
  # <dir>/runtime-sha256.c, SHA-256 on the CPU's SHA instructions,
18
18
  # <dir>/runtime-chacha20.c, ChaCha20's keystream on AVX2 or NEON vectors,
19
- # <dir>/runtime-checksum.c, CRC-32 on its carry-less multiply or CRC instructions,
19
+ # <dir>/runtime-checksum.c, CRC-32 on its carry-less multiply or CRC instructions
20
+ # and Adler-32 on SSSE3 or NEON,
20
21
  # <dir>/runtime-term.c, stdin and the terminal of `nish:term`,
21
22
  # <dir>/runtime-bytes.c, the byte-class runs of `nish/bytes`,
22
23
  # <dir>/runtime-sandbox.c, the confinement `--sandbox` applies,
@@ -445,10 +446,11 @@ if [ "$debug" = 1 ]; then common+=(-g); strip_flag=(); fi
445
446
  # own command line instead of using `common`; it is empty on every ordinary
446
447
  # build, hence the bash 3.2 expansion spelling explained below.
447
448
  #
448
- # -pthread is for runtime-parallel.c, the translation unit that divides a range
449
+ # -pthread is here for runtime-parallel.c, the translation unit that divides a range
449
450
  # of work across threads: it is compiled in either configuration and only spawns
450
- # under this macro, so this is the build where the flag has to be on the command
451
- # line. On a current glibc the library half is already inside libc and the link
451
+ # under this macro, so this is the build where it needs the flag on the command
452
+ # line. (Every Linux build has the flag already, for runtime-sandbox.c; see
453
+ # where `common` gets its hardening flags below.) On a current glibc the library half is already inside libc and the link
452
454
  # would succeed without it; passing it is what makes that an implementation
453
455
  # detail rather than something the build depends on.
454
456
  #
@@ -491,6 +493,22 @@ case "$(uname -s)" in
491
493
  Darwin) ;;
492
494
  *)
493
495
  common+=(-fstack-clash-protection)
496
+ # runtime-sandbox.c runs each spawn under an exec allowlist on threads of
497
+ # its own, and a glibc before 2.34 keeps pthread_create outside libc. The
498
+ # flag is on every build rather than the sandboxed ones because this
499
+ # script cannot tell them apart: an input may be an object file, where
500
+ # the call of `nish_sandbox` is not there to be read. A build without
501
+ # `--sandbox` is the binary it was: on glibc 2.34 and later the flag adds
502
+ # nothing to the link (measured on 2.39: `arena_placement` and
503
+ # `caps_process_spawn` at debug, speed and size are byte for byte the
504
+ # same with and without it). Before 2.34 it names libpthread to the
505
+ # linker, and a build without `--sandbox` can then carry a DT_NEEDED on
506
+ # libpthread.so.0 that it did not have: the debug profile always (its link
507
+ # line has no --as-needed), speed and size wherever the linker still sees
508
+ # the runtime's reference to pthread_create. That is one more library of
509
+ # the same glibc loaded at start, and not measured: no machine the tests
510
+ # run on has such a glibc.
511
+ common+=(-pthread)
494
512
  # shellcheck disable=SC2054 # -Wl,<flag> is one argument: the comma is the linker's
495
513
  common+=(-Wl,-z,relro,-z,now -Wl,-z,noexecstack) ;;
496
514
  esac
@@ -780,15 +798,16 @@ case "$profile" in
780
798
  # IR compiled for the host rather than with `--target wasm32` calls std/crypto/aes.ts's
781
799
  # AES kernels behind `nish_aes_hw`, std/crypto/sha256.ts's block function behind
782
800
  # `nish_sha256_hw`, std/crypto/chacha20poly1305.ts's keystream loop behind
783
- # `nish_chacha20_hw` and std/compress/checksum.ts's CRC-32 kernel behind
784
- # `nish_crc32_hw` (src/kernels.ts). runtime-aes.c's, runtime-sha256.c's,
801
+ # `nish_chacha20_hw` and std/compress/checksum.ts's CRC-32 and Adler-32
802
+ # kernels behind `nish_crc32_hw` and `nish_adler32_hw` (src/kernels.ts). runtime-aes.c's, runtime-sha256.c's,
785
803
  # runtime-chacha20.c's and runtime-checksum.c's wasm32 builds answer 0 there,
786
804
  # so the Nish code runs, and
787
805
  # each is added only for such IR: every other module links the bytes it always did.
788
- # Each pair is a unit and the kernel its probe names.
806
+ # Each pair is a unit and the kernel its probe names; checksum has two, and
807
+ # its second pair sees the unit the first added, so it is added once.
789
808
  # A caller that names the unit itself is left alone, as `halves` leaves it:
790
809
  # one object named twice is a duplicate-symbol error.
791
- for pair in aes:aes sha256:sha256 chacha20:chacha20 checksum:crc32; do
810
+ for pair in aes:aes sha256:sha256 chacha20:chacha20 checksum:crc32 checksum:adler32; do
792
811
  unit=${pair%%:*}
793
812
  kernel=${pair#*:}
794
813
  named=0
package/std/README.md CHANGED
@@ -10,7 +10,7 @@ whatever program imports it, and subject to the same rules as `examples/` or
10
10
  | Module | What it is |
11
11
  | --- | --- |
12
12
  | [`testing.ts`](https://github.com/amritk/nish/blob/main/std/testing.ts) | a test runner: a `Suite` a program drives with straight-line assertions, printing the `PASS` / `FAIL` / `SKIP` lines the repository's own harness prints, and answering the exit code |
13
- | [`text.ts`](https://github.com/amritk/nish/blob/main/std/text.ts) | the string operations a program would otherwise write inline: `splitLines`, `splitWhitespace`, `trim` and its halves, `contains`, `replaceAll`, `firstDifference` over two arrays of lines, `codePointLength`, the number of Unicode code points (what JSON Schema's `minLength` counts, where `.length` counts UTF-8 bytes natively and UTF-16 units under Node; it answers the same on both by asking which it is reading), and `indexOfAny(text, bytes, from)`, the first index at or after `from` whose byte is one of 1 to 16 ASCII `bytes`. Its walker is the meaning and what runs under Node; natively the compiler replaces the one call to it with the runtime kernel `nish_str_index_of_any`, which reads 16 or 32 bytes at a time and is variable-time ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#byte-search-indexofany-in-nishtext)). `tests/link/std_text_index_of_any*` are its programs |
13
+ | [`text.ts`](https://github.com/amritk/nish/blob/main/std/text.ts) | the string operations a program would otherwise write inline: `split` and `splitLimit` (JavaScript's `split(sep, limit)`), `toFixed` (JavaScript's `x.toFixed(digits)`, rounded on the exact binary value), `splitLines`, `splitWhitespace`, `trim` and its halves, `contains`, `replaceAll`, `firstDifference` over two arrays of lines, `codePointLength`, the number of Unicode code points (what JSON Schema's `minLength` counts, where `.length` counts UTF-8 bytes natively and UTF-16 units under Node; it answers the same on both by asking which it is reading), and `indexOfAny(text, bytes, from)`, the first index at or after `from` whose byte is one of 1 to 16 ASCII `bytes`. Its walker is the meaning and what runs under Node; natively the compiler replaces the one call to it with the runtime kernel `nish_str_index_of_any`, which reads 16 or 32 bytes at a time and is variable-time ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#byte-search-indexofany-in-nishtext)). `tests/link/std_text_index_of_any*` are its programs |
14
14
  | [`math.ts`](https://github.com/amritk/nish/blob/main/std/math.ts) | `Math.tan`, `Math.atan2` and `Math.hypot` on `f64`, ported from fdlibm (`LICENSE-fdlibm`) so that every target, wasm included, answers alike without libm. A program never imports it: a call to one of the three loads it, and the compiler copies the functions the call reaches into the calling module as `internal` ones. JavaScript's answer for every NaN, signed zero and infinity, and within one ulp elsewhere (0.83, 0.84 and 0.93 ulp measured against mpmath). `tests/cases/math_std_edges` pins the special values |
15
15
  | [`sort.ts`](https://github.com/amritk/nish/blob/main/std/sort.ts) | `xs.sort(cmp)` on any array: `sortWith`, a stable merge sort over runs of 32 sorted by insertion — one scratch array released before it returns, a pair of runs already in order copied without merging, no bounds check left in it — so its order is element for element Node's `Array.prototype.sort`. Like `math.ts` it is one the compiler knows about: a program never imports it, a `.sort(cmp)` call loads it, the checker rewrites the call to `sortWith`, and each comparator's instantiation — the comparator called directly, no function pointer — is copied into the module that sorts. Under Node the call stays the platform's own. `tests/cases/arr_sort_cmp*` are its programs, a 10,000-element sort with ties among them |
16
16
  | [`regex.ts`](https://github.com/amritk/nish/blob/main/std/regex.ts) | Regular expressions in JavaScript's syntax with the `u` flag's strictness, matched by a Pike VM in time linear in the input whatever the pattern; finding every match is one search per match, so `findAll` and its kin can be quadratic when a long branch is preferred to a short one that wins ([`docs/security/regex.md`](../docs/security/regex.md)). `regexCompile(pattern, flags)` answers a `Regex` or the error text; `test`, `exec` into a reused `RegexMatch`, `find`, `findAll`, `count`, `replace` and `replaceAll` with `$&`, `$1` and `$<name>`, and `split`. Flags `i`, `m`, `s` and `u`; `i` folds by Unicode's simple case folding, ASCII letters only to ASCII. `\p{…}` and `\P{…}` take Unicode 16.0's General_Category, Script, Script_Extensions and binary properties by JavaScript's names, from tables `scripts/gen-regex-unicode.mjs` generates into the module and checks against Node's `RegExp`; backreferences and lookaround are refused at compile time. Offsets are UTF-8 bytes. A search allocates nothing beyond its answer: the thread lists and capture tables are the `Regex`'s, so one `Regex` serves one thread at a time. A leading literal is found with `indexOf`, a small leading set with `indexOfAny`. `tests/link/std_regex` and `tests/link/std_regex_unicode` check it against JavaScript's own answers |
@@ -328,8 +328,9 @@ accept into the slot, and after its handshake a connection allocates nothing
328
328
  that outlives a record. The handshake keeps its state in the slot, which
329
329
  `accept` restarts, and a KeyUpdate installs its keys in place, so neither
330
330
  leaves anything in the arena (TLS-3); a connection still takes at most
331
- `TLS_RECORD_MAX_KEY_UPDATES` (64) KeyUpdates from its client. The carrier has
332
- no clock, so closing quiet slots is the program's (TLS-4). On this path the
331
+ `TLS_RECORD_MAX_KEY_UPDATES` (64) KeyUpdates from its client. The program's
332
+ loop calls `expire(monotonicNanos())`, which closes slots idle past
333
+ `idleTimeout`, a minute by default (TLS-4). On this path the
333
334
  record layer wipes `TlsServer`'s traffic and handshake secrets and the
334
335
  ephemeral key once it has what it needs from them, which narrows TLS-1.
335
336
  `tests/link/net_tls_record_*` are its programs, and the `net_tls_tcp` block of
@@ -541,7 +542,7 @@ have, and all three have since landed as builtins:
541
542
  | Was missing | Now |
542
543
  | --- | --- |
543
544
  | a directory listing | `readdirSync(path): string[] \| null`, sorted by bytes, because there is no `sort` for a caller to reach for |
544
- | a child's **output** — `spawnSync` answers a status and nothing else | `spawnSyncTo(argv, stdoutPath, stderrPath)`, each stream to a file, an empty path inheriting; `spawnPiped(argv, stdin, stdout, stderr)`, stdin from a `u8[]` and both outputs into `u8[]`s, for a secret the child reads on stdin |
545
+ | a child's **output** — `spawnSync` answers a status and nothing else | `spawnSyncTo(argv, stdoutPath, stderrPath)`, each stream to a file, an empty path inheriting; `spawnPiped(argv, stdin, stdout, stderr)`, stdin from a `u8[]` and both outputs into `u8[]`s, for a secret the child reads on stdin; `spawnPipedWithin(argv, stdin, stdout, stderr, timeoutMs)`, the same run that answers -3 at a deadline |
545
546
  | a clock | `monotonicNanos(): i64` |
546
547
 
547
548
  So the driver exists, in the language, and it is
@@ -291,6 +291,19 @@ export const crc32 = (buf: u8[], off: i32, len: i32): u32 => new Crc32().update(
291
291
  */
292
292
  export const adler32Update = (adler: u32, buf: u8[], off: i32, len: i32): u32 => {
293
293
  checksumWindow("adler32Update", buf, off, len)
294
+ return adler32Walk(adler, buf, off, len)
295
+ }
296
+
297
+ /**
298
+ * `adler32Update`'s loop: the Adler-32 of the bytes `adler` was the Adler-32
299
+ * of, followed by `buf[off .. off + len)`, a window its one caller has
300
+ * checked. Natively the compiler puts the call behind a branch on
301
+ * `nish_adler32_hw` and hands the same window to the runtime's
302
+ * `nish_adler32_update`, which runs it on SSSE3 or NEON vectors
303
+ * (`src/kernels.ts`); a machine without SSSE3, a process run with
304
+ * `NISH_ADLER32=soft`, a wasm32 build and Node run this.
305
+ */
306
+ const adler32Walk = (adler: u32, buf: u8[], off: i32, len: i32): u32 => {
294
307
  let s1: u32 = adler & 0xffff
295
308
  let s2: u32 = adler >>> 16
296
309
  let p: i32 = off
@@ -613,7 +613,6 @@ const deflateLengths = (freq: i32[], n: i32, limit: i32, lens: i32[], w: Deflate
613
613
  let usedHere: i32 = 0
614
614
  let depth: i32 = 0
615
615
  root = used - 2
616
- let next: i32 = used - 1
617
616
  while (avail > 0) {
618
617
  while (root >= 0 && uncheckedGet(keys, root) === depth) {
619
618
  usedHere += 1
@@ -623,7 +622,6 @@ const deflateLengths = (freq: i32[], n: i32, limit: i32, lens: i32[], w: Deflate
623
622
  if (depth < 33) {
624
623
  per[depth] += 1
625
624
  }
626
- next -= 1
627
625
  avail -= 1
628
626
  }
629
627
  avail = 2 * usedHere
@@ -46,14 +46,17 @@
46
46
  * no arithmetic; it kept the input's pointer from being spilled in a way the
47
47
  * aarch64 disassembly check once misread (#334). The scalar functions use the
48
48
  * field's four helpers, which fiat generates identically for both. The nonce's
49
- * inverse, `p256ScalarInverse`, is libsecp256k1's 32-bit safegcd (`modinv32`),
50
- * function for function; the section that holds it says what changes.
51
- * Everything else in this file — the curve, the encodings, the other inversions
52
- * and ECDSA — is written for this module from the documents it names.
49
+ * inverse, `p256ScalarInverse`, and the field's, `p256FieldInvert`, are
50
+ * libsecp256k1's 32-bit safegcd (`modinv32`), function for function; the
51
+ * section that holds it says what changes. Everything else in this file — the
52
+ * curve, the encodings, verification's inversion and ECDSA — is written for
53
+ * this module from the documents it names.
53
54
  *
54
55
  * **The curve** is `y^2 = x^3 - 3x + b` over GF(p),
55
56
  * p = 2^256 - 2^224 + 2^192 + 2^96 - 1, with the base point G and its order n from SEC 2 §2.4.2 (FIPS
56
- * 186-4 §D.1.2.3). Points are projective (X : Y : Z), Z = 0 the identity, and
57
+ * 186-4 §D.1.2.3).
58
+ *
59
+ * Points are projective (X : Y : Z), Z = 0 the identity, and
57
60
  * are added and doubled with the complete formulas of J. Renes, C. Costello and
58
61
  * L. Batina, "Complete addition formulas for prime order elliptic curves"
59
62
  * (EUROCRYPT 2016), Algorithms 4 and 6 for a = -3. Complete means no input is
@@ -74,16 +77,18 @@
74
77
  * none, and the sum is then discarded by the same conditional move rather than
75
78
  * skipped, so neither a branch nor an address depends on the scalar.
76
79
  * `p256ScalarMult`, a fixed 4-bit window over sixteen multiples of a point, is
77
- * what verification multiplies G and the received key by, and the reference the
78
- * comb is held to bit for bit (`tests/link/crypto_p256_agree`).
80
+ * what ECDH multiplies the peer's key by, and the reference the comb is held
81
+ * to bit for bit (`tests/link/crypto_p256_agree`).
79
82
  *
80
83
  * The signer inverts the nonce by Bernstein and Yang's safegcd,
81
84
  * `p256ScalarInverse`: twenty batches of thirty divsteps, each a fixed run of
82
85
  * masks and adds, whatever the scalar, so its loops count constants and no
83
86
  * branch or address follows the nonce; Fermat's `p256ScalarInvert` is the
84
87
  * reference it is held to bit for bit (`tests/link/crypto_p256_inverse`) and
85
- * what verification still uses. The other inversions raise to the public
86
- * exponents p - 2 and n - 2, so their branches follow a constant.
88
+ * what verification still uses, raising to the public exponent n - 2, so its
89
+ * branches follow a constant. Every field inversion — of a Z that follows the
90
+ * key or the nonce in the public key, ECDH and signing — is the same safegcd
91
+ * modulo p, `p256FieldInvert`, on the same divstep and update functions.
87
92
  *
88
93
  * The branches that remain are on public facts: a length, a limb or bit
89
94
  * position, whether a received key or signature is in range, and — once in
@@ -110,7 +115,12 @@
110
115
  * limb loops among them), the encodings and the nonce derivation are constant
111
116
  * time by construction rather than by that proof.
112
117
  *
113
- * Verification multiplies only public values, by `p256ScalarMult` alone.
118
+ * **Verification is variable time, on public values only.** `p256Verify`
119
+ * computes u1 G + u2 Q in one interleaved pass, `p256DoubleMultPublic`: both
120
+ * scalars recoded as width-5 wNAF, eight odd multiples of each point, the
121
+ * doublings shared, and both the digits and the table reads follow the
122
+ * scalars. Every input to it is the signature, the digest or the public key.
123
+ * Nothing secret may be passed to it.
114
124
  *
115
125
  * **The private key is a `Secret`** (`nish:secret`, docs/LANGUAGE.md
116
126
  * "Secrets"). `p256PublicKey` and `p256Sign` read it only inside `expose` /
@@ -3750,25 +3760,6 @@ const p256Bit = (e: u32[], i: i32): boolean => {
3750
3760
  return ((e[limb] >> toU32(i & 31)) & 1) === 1
3751
3761
  }
3752
3762
 
3753
- /**
3754
- * `out = 1 / a` in the field, as `a^(p - 2)` (Fermat); zero for a zero `a`.
3755
- * Square-and-multiply from the top bit: the branch is on the exponent's bits,
3756
- * which are a constant.
3757
- */
3758
- const p256FieldInvert = (out: u32[], a: u32[]): void => {
3759
- const e: u32[] = p256Prime()
3760
- e[0] = 0xfffffffd
3761
- const acc: u32[] = p256Limbs()
3762
- p256FiatSetOne(acc)
3763
- for (let i: i32 = 255; i >= 0; i--) {
3764
- p256FiatSquare(acc, acc)
3765
- if (p256Bit(e, i)) {
3766
- p256FiatMul(acc, acc, a)
3767
- }
3768
- }
3769
- p256Copy(out, acc)
3770
- }
3771
-
3772
3763
  /**
3773
3764
  * `out = 1 / a` mod n, as `a^(n - 2)` with the scalar Montgomery multiply;
3774
3765
  * the exponent is public, so the square-and-multiply branches only on a
@@ -3789,14 +3780,14 @@ const p256ScalarInvert = (out: u32[], a: u32[]): void => {
3789
3780
  p256Copy(out, acc)
3790
3781
  }
3791
3782
 
3792
- // ---- The nonce's inverse by safegcd -------------------------------------------
3783
+ // ---- The nonce's and the field's inverses by safegcd -------------------------
3793
3784
  //
3794
3785
  // Bernstein and Yang's constant-time inversion ("Fast constant-time gcd
3795
3786
  // computation and modular inversion", 2019), as libsecp256k1's modinv32 writes
3796
3787
  // it for 32-bit targets (MIT, std/crypto/LICENSE-libsecp256k1): the functions
3797
3788
  // below are its secp256k1_modinv32_divsteps_30, _update_de_30, _update_fg_30,
3798
3789
  // _normalize_30 and secp256k1_modinv32, with its scalar_8x32 conversions to and
3799
- // from signed-30, ported to Nish for the one modulus n. A value is nine limbs
3790
+ // from signed-30, ported to Nish for the two moduli n and p. A value is nine limbs
3800
3791
  // of 30 bits each, limb 8 carrying the sign, held as the u32 bit patterns of
3801
3792
  // the C's int32_t: `u32` arithmetic wraps where the C's never overflows, so the
3802
3793
  // low bits agree, and the arithmetic shifts go through `i32` and `i64`.
@@ -3925,12 +3916,13 @@ const p256Divsteps30 = (zeta: u32, f0: u32, g0: u32, t: u32[]): u32 => {
3925
3916
  }
3926
3917
 
3927
3918
  /**
3928
- * `[d, e] = (t [d, e] + n [md, me]) / 2^30`, with `md` and `me` chosen so
3929
- * that the division is exact: d and e stay in (-2n, n) and keep tracking f
3930
- * and g modulo n (`secp256k1_modinv32_update_de_30`). The products are 32 by
3931
- * 32 bits into 64.
3919
+ * `[d, e] = (t [d, e] + n [md, me]) / 2^30` for the modulus `n` (n or p),
3920
+ * with `md` and `me` chosen so that the division is exact: d and e stay in
3921
+ * (-2n, n) and keep tracking f and g modulo n
3922
+ * (`secp256k1_modinv32_update_de_30`). `inverse30` is n^-1 mod 2^30, which
3923
+ * makes the sum's bottom 30 bits zero. The products are 32 by 32 bits into 64.
3932
3924
  */
3933
- const p256UpdateDe30 = (d: u32[], e: u32[], t: u32[], n: u32[]): void => {
3925
+ const p256UpdateDe30 = (d: u32[], e: u32[], t: u32[], n: u32[], inverse30: u32): void => {
3934
3926
  if (toI32(d.length) < 9 || toI32(e.length) < 9 || toI32(t.length) < 4 || toI32(n.length) < 9) {
3935
3927
  return
3936
3928
  }
@@ -3938,8 +3930,6 @@ const p256UpdateDe30 = (d: u32[], e: u32[], t: u32[], n: u32[]): void => {
3938
3930
  const v: u64 = p256Wide(t[1])
3939
3931
  const q: u64 = p256Wide(t[2])
3940
3932
  const r: u64 = p256Wide(t[3])
3941
- // n^-1 mod 2^30, which makes the sum's bottom 30 bits zero below.
3942
- const inverse30: u32 = 0x11ff43b1
3943
3933
  // [md, me] start as [u, q] if d is negative plus [v, r] if e is.
3944
3934
  const sd: u32 = p256SignMask(d[8])
3945
3935
  const se: u32 = p256SignMask(e[8])
@@ -3998,8 +3988,8 @@ const p256UpdateFg30 = (f: u32[], g: u32[], t: u32[]): void => {
3998
3988
  g[8] = toU32(cg)
3999
3989
  }
4000
3990
 
4001
- /** Add n to the signed-30 `a` when `mask` is all ones, then carry so every limb but the last is in [0, 2^30). */
4002
- const p256AddOrder30 = (a: u32[], n: u32[], mask: u32, negate: u32): void => {
3991
+ /** Add the modulus `n` to the signed-30 `a` when `mask` is all ones, then carry so every limb but the last is in [0, 2^30). */
3992
+ const p256AddModulus30 = (a: u32[], n: u32[], mask: u32, negate: u32): void => {
4003
3993
  if (toI32(a.length) < 9 || toI32(n.length) < 9) {
4004
3994
  return
4005
3995
  }
@@ -4013,48 +4003,52 @@ const p256AddOrder30 = (a: u32[], n: u32[], mask: u32, negate: u32): void => {
4013
4003
  }
4014
4004
 
4015
4005
  /**
4016
- * `d` in (-2n, n) to [0, n), negated first when `sign`'s top bit is set: f
4017
- * ended as -1 rather than 1 (`secp256k1_modinv32_normalize_30`).
4006
+ * `d` in (-2n, n) to [0, n) for the modulus `n`, negated first when `sign`'s
4007
+ * top bit is set: f ended as -1 rather than 1
4008
+ * (`secp256k1_modinv32_normalize_30`).
4018
4009
  */
4019
4010
  const p256Normalize30 = (d: u32[], sign: u32, n: u32[]): void => {
4020
4011
  if (toI32(d.length) < 9) {
4021
4012
  return
4022
4013
  }
4023
4014
  const zero: u32 = 0
4024
- p256AddOrder30(d, n, p256SignMask(d[8]), p256SignMask(sign))
4025
- p256AddOrder30(d, n, p256SignMask(d[8]), zero)
4015
+ p256AddModulus30(d, n, p256SignMask(d[8]), p256SignMask(sign))
4016
+ p256AddModulus30(d, n, p256SignMask(d[8]), zero)
4026
4017
  }
4027
4018
 
4028
4019
  /**
4029
- * `out = 1 / a` mod n for `a` in the Montgomery domain, zero for a zero `a`:
4030
- * the signing paths' inversion of the nonce. Twenty batches of thirty divsteps
4020
+ * `out = 1 / a` mod `m` for the plain limbs `a`, below m, and the odd
4021
+ * modulus `m` in signed-30 limbs (n or p), with `inverse30` = m^-1 mod 2^30;
4022
+ * zero for an `a` that is zero mod `m`. Twenty batches of thirty divsteps
4031
4023
  * each: 600, past the 590 that bound any 256-bit input, so the count never
4032
4024
  * depends on `a`, and every step and update runs the same instructions on any
4033
- * value. The divsteps invert `a R` as a plain number; one Montgomery multiply
4034
- * by R^3 takes `(a R)^-1` to `a^-1 R`. f, g, d, e and the matrix are wiped
4035
- * before it returns (ECC-2).
4025
+ * value. f, g, d, e and the matrix are wiped before it returns (ECC-2).
4036
4026
  */
4037
- const p256ScalarInverse = (out: u32[], a: u32[]): void => {
4038
- const n: u32[] = p256Order30()
4027
+ const p256Safegcd = (out: u32[], a: u32[], m: u32[], inverse30: u32): void => {
4039
4028
  const d: u32[] = new Array<u32>(9)
4040
4029
  const e: u32[] = new Array<u32>(9)
4041
- const f: u32[] = p256Order30()
4030
+ const f: u32[] = new Array<u32>(9)
4042
4031
  const g: u32[] = new Array<u32>(9)
4043
4032
  const t: u32[] = new Array<u32>(4)
4033
+ if (toI32(m.length) < 9) {
4034
+ return
4035
+ }
4036
+ for (let i: i32 = 0; i < 9; i++) {
4037
+ f[i] = m[i]
4038
+ }
4044
4039
  e[0] = 1
4045
4040
  p256ToSigned30(g, a)
4046
4041
  // zeta = -(delta + 1/2), delta starting at 1/2.
4047
4042
  let zeta: u32 = 0xffffffff
4048
4043
  for (let i: i32 = 0; i < 20; i++) {
4049
4044
  zeta = p256Divsteps30(zeta, f[0], g[0], t)
4050
- p256UpdateDe30(d, e, t, n)
4045
+ p256UpdateDe30(d, e, t, m, inverse30)
4051
4046
  p256UpdateFg30(f, g, t)
4052
4047
  }
4053
4048
  // g is now 0 and f is 1 or -1, with d the inverse up to that sign; for a
4054
- // zero `a`, f is n and d stays 0.
4055
- p256Normalize30(d, f[8], n)
4049
+ // zero `a`, f is m and d stays 0.
4050
+ p256Normalize30(d, f[8], m)
4056
4051
  p256FromSigned30(out, d)
4057
- p256FiatScalarMul(out, out, p256ScalarR3())
4058
4052
  wipe(d)
4059
4053
  wipe(e)
4060
4054
  wipe(f)
@@ -4062,6 +4056,51 @@ const p256ScalarInverse = (out: u32[], a: u32[]): void => {
4062
4056
  wipe(t)
4063
4057
  }
4064
4058
 
4059
+ /**
4060
+ * `out = 1 / a` mod n for `a` in the Montgomery domain, zero for a zero `a`:
4061
+ * the signing paths' inversion of the nonce, by `p256Safegcd`. The divsteps
4062
+ * invert `a R` as a plain number; one Montgomery multiply by R^3 takes
4063
+ * `(a R)^-1` to `a^-1 R`.
4064
+ */
4065
+ const p256ScalarInverse = (out: u32[], a: u32[]): void => {
4066
+ p256Safegcd(out, a, p256Order30(), 0x11ff43b1)
4067
+ p256FiatScalarMul(out, out, p256ScalarR3())
4068
+ }
4069
+
4070
+ /** p in nine signed-30 limbs, limb 0 the least significant. */
4071
+ const p256Prime30 = (): u32[] => {
4072
+ const out: u32[] = new Array<u32>(9)
4073
+ out[0] = 0x3fffffff
4074
+ out[1] = 0x3fffffff
4075
+ out[2] = 0x3fffffff
4076
+ out[3] = 0x0000003f
4077
+ out[4] = 0
4078
+ out[5] = 0
4079
+ out[6] = 0x00001000
4080
+ out[7] = 0x3fffc000
4081
+ out[8] = 0x0000ffff
4082
+ return out
4083
+ }
4084
+
4085
+ /** R^3 mod p, which does for `p256FieldInvert` what `p256ScalarR3` does for the scalars. */
4086
+ const p256FieldR3 = (): u32[] => {
4087
+ const out: u32[] = p256Limbs()
4088
+ p256SetLimbs(out, 0xa, 0xfffffffd, 0xfffffff7, 0xffffffed, 0xfffffffc, 0x5, 0x1, 0x18)
4089
+ return out
4090
+ }
4091
+
4092
+ /**
4093
+ * `out = 1 / a` in the field for `a` in the Montgomery domain, zero for a
4094
+ * zero `a`, by `p256Safegcd` modulo p (p^-1 mod 2^30 is 2^30 - 1, as p is
4095
+ * -1 mod 2^96) and a Montgomery multiply by R^3. Constant time: what it
4096
+ * inverts is a Z that follows a secret scalar in signing, ECDH and the public
4097
+ * key. `out` may be `a`.
4098
+ */
4099
+ const p256FieldInvert = (out: u32[], a: u32[]): void => {
4100
+ p256Safegcd(out, a, p256Prime30(), 0x3fffffff)
4101
+ p256FiatMul(out, out, p256FieldR3())
4102
+ }
4103
+
4065
4104
  /**
4066
4105
  * A point in projective coordinates (X : Y : Z), each coordinate a field
4067
4106
  * element in the Montgomery domain. It stands for the affine (X/Z, Y/Z), and
@@ -5319,9 +5358,9 @@ export const p256Ecdh = (priv: Secret<u8[]>, peerPoint: u8[]): Secret<u8[]> | nu
5319
5358
 
5320
5359
  /**
5321
5360
  * `p256Ecdh` on the plain key, for `exposeWith` to run. The scratch, the
5322
- * product and every limb of `X / Z` follow the key, so all are wiped; the
5323
- * inversion is written out here, rather than through `p256AffineX`, so that its
5324
- * accumulator and Z's inverse are this function's to wipe.
5361
+ * product and every limb of `X / Z` follow the key, so all are wiped; Z is
5362
+ * inverted here, rather than through `p256AffineX`, so that its inverse is this
5363
+ * function's to wipe (`p256FieldInvert` wipes its own intermediates).
5325
5364
  */
5326
5365
  const p256EcdhExposed = (priv: u8[], peerPoint: u8[]): u8[] | null => {
5327
5366
  if (!p256ScalarInRange(priv)) {
@@ -5336,17 +5375,9 @@ const p256EcdhExposed = (priv: u8[], peerPoint: u8[]): u8[] | null => {
5336
5375
  p256ScalarMult(point, priv, peer, scratch)
5337
5376
  p256WipeScratch(scratch)
5338
5377
  const infinity: boolean = p256FiatNonzero(point.z) === 0
5339
- // 1 / Z as Z^(p - 2), as p256FieldInvert computes it, over limbs wiped below.
5340
- const e: u32[] = p256Prime()
5341
- e[0] = 0xfffffffd
5378
+ // 1 / Z, over limbs wiped below.
5342
5379
  const acc: u32[] = p256Limbs()
5343
- p256FiatSetOne(acc)
5344
- for (let i: i32 = 255; i >= 0; i--) {
5345
- p256FiatSquare(acc, acc)
5346
- if (p256Bit(e, i)) {
5347
- p256FiatMul(acc, acc, point.z)
5348
- }
5349
- }
5380
+ p256FieldInvert(acc, point.z)
5350
5381
  const x: u32[] = p256Limbs()
5351
5382
  p256FiatMul(x, point.x, acc)
5352
5383
  p256FiatMul(x, x, p256PlainOne())
@@ -5387,6 +5418,148 @@ const p256SignExposed = (priv: u8[], digest: u8[]): u8[] | null => {
5387
5418
  return p256SignScalar(priv, z)
5388
5419
  }
5389
5420
 
5421
+ /** The width of `p256Verify`'s window: its digits are odd, in [-15, 15]. */
5422
+ const P256_WNAF_WIDTH: i32 = 5
5423
+
5424
+ /** The bits of a scalar `p256Wnaf` reads; its form has one more digit, for the last carry. */
5425
+ const P256_WNAF_BITS: i32 = 256
5426
+
5427
+ /** The number of odd multiples `p256OddMultiples` builds: 1, 3, ..., 15 times a point. */
5428
+ const P256_WNAF_TABLE: i32 = 8
5429
+
5430
+ /**
5431
+ * The width-5 non-adjacent form of the 32 big-endian bytes `k`: `out[i]`, for
5432
+ * `i` from 0 to 256, is zero or an odd digit in [-15, 15], `k` is the sum of
5433
+ * `out[i] * 2^i`, and of any five digits in a row at most one is nonzero. Read
5434
+ * from the bottom bit up, a window opening at each bit that differs from the
5435
+ * carry (libsecp256k1's `secp256k1_ecmult_wnaf`). Variable time: `k` is
5436
+ * public wherever this is used.
5437
+ */
5438
+ const p256Wnaf = (out: i32[], k: u8[]): void => {
5439
+ if (toI32(out.length) <= P256_WNAF_BITS || toI32(k.length) < 32) {
5440
+ return
5441
+ }
5442
+ let carry: i32 = 0
5443
+ let bit: i32 = 0
5444
+ while (bit < P256_WNAF_BITS) {
5445
+ if (p256ByteBit(k, bit) === carry) {
5446
+ bit++
5447
+ continue
5448
+ }
5449
+ const left: i32 = P256_WNAF_BITS - bit
5450
+ const now: i32 = left < P256_WNAF_WIDTH ? left : P256_WNAF_WIDTH
5451
+ let word: i32 = carry
5452
+ for (let j: i32 = 0; j < now; j++) {
5453
+ word = word + (p256ByteBit(k, bit + j) << j)
5454
+ }
5455
+ carry = (word >> (P256_WNAF_WIDTH - 1)) & 1
5456
+ if (bit >= 0 && bit < toI32(out.length)) {
5457
+ out[bit] = word - (carry << P256_WNAF_WIDTH)
5458
+ }
5459
+ bit = bit + now
5460
+ }
5461
+ out[P256_WNAF_BITS] = carry
5462
+ }
5463
+
5464
+ /** Bit `i` of the 32 big-endian bytes `k`, 0 the least significant. */
5465
+ const p256ByteBit = (k: u8[], i: i32): i32 => {
5466
+ const at: i32 = (P256_WNAF_BITS >> 3) - 1 - (i >> 3)
5467
+ if (at < 0 || at >= toI32(k.length)) {
5468
+ return 0
5469
+ }
5470
+ return toI32((toU32(k[at]) >> toU32(i & 7)) & 1)
5471
+ }
5472
+
5473
+ /** `table[j] = (2 j + 1) p` for each `j` in `table`, eight of them: one doubling and seven additions. */
5474
+ const p256OddMultiples = (
5475
+ table: P256ProjectivePoint[],
5476
+ p: P256ProjectivePoint,
5477
+ s: P256PointScratch
5478
+ ): void => {
5479
+ if (toI32(table.length) < P256_WNAF_TABLE) {
5480
+ return
5481
+ }
5482
+ const twice = new P256ProjectivePoint()
5483
+ p256PointDouble(twice, p, s)
5484
+ p256PointCopy(table[0], p)
5485
+ for (let j: i32 = 1; j < toI32(table.length); j++) {
5486
+ p256PointAdd(table[j], table[j - 1], twice, s)
5487
+ }
5488
+ }
5489
+
5490
+ /**
5491
+ * `acc += digit * p`, `digit` odd in [-15, 15], read from `p256OddMultiples`'
5492
+ * `table`; a negative digit adds the entry's negation (X : -Y : Z), built in
5493
+ * `neg`. Variable time: which entry is read, and its sign, follow the digit.
5494
+ */
5495
+ const p256WnafAdd = (
5496
+ acc: P256ProjectivePoint,
5497
+ table: P256ProjectivePoint[],
5498
+ digit: i32,
5499
+ neg: P256ProjectivePoint,
5500
+ s: P256PointScratch
5501
+ ): void => {
5502
+ const at: i32 = (digit < 0 ? -digit : digit) >> 1
5503
+ if (at < 0 || at >= toI32(table.length)) {
5504
+ return
5505
+ }
5506
+ if (digit > 0) {
5507
+ p256PointAdd(acc, acc, table[at], s)
5508
+ return
5509
+ }
5510
+ p256Copy(neg.x, table[at].x)
5511
+ p256SetZero(neg.y)
5512
+ p256FiatSub(neg.y, neg.y, table[at].y)
5513
+ p256Copy(neg.z, table[at].z)
5514
+ p256PointAdd(acc, acc, neg, s)
5515
+ }
5516
+
5517
+ /**
5518
+ * `out = a * G + b * q` for 32 big-endian bytes `a` and `b`, by Shamir's trick
5519
+ * over width-5 NAFs: one shared chain of doublings from the top digit down,
5520
+ * and an addition from the odd multiples of G or of `q` wherever a digit is
5521
+ * nonzero. The doublings before the first nonzero digit are skipped. **Not
5522
+ * constant time**: the additions, their table reads and their signs follow
5523
+ * the scalars' digits, so this is only for public scalars and points, as in
5524
+ * `p256Verify`.
5525
+ */
5526
+ const p256DoubleMultPublic = (
5527
+ out: P256ProjectivePoint,
5528
+ a: u8[],
5529
+ b: u8[],
5530
+ q: P256ProjectivePoint,
5531
+ s: P256PointScratch
5532
+ ): void => {
5533
+ const wa: i32[] = new Array<i32>(P256_WNAF_BITS + 1)
5534
+ const wb: i32[] = new Array<i32>(P256_WNAF_BITS + 1)
5535
+ p256Wnaf(wa, a)
5536
+ p256Wnaf(wb, b)
5537
+ const tableG: P256ProjectivePoint[] = []
5538
+ const tableQ: P256ProjectivePoint[] = []
5539
+ for (let j: i32 = 0; j < P256_WNAF_TABLE; j++) {
5540
+ tableG.push(new P256ProjectivePoint())
5541
+ tableQ.push(new P256ProjectivePoint())
5542
+ }
5543
+ p256OddMultiples(tableG, p256Generator(), s)
5544
+ p256OddMultiples(tableQ, q, s)
5545
+ const neg = new P256ProjectivePoint()
5546
+ p256SetIdentity(out)
5547
+ let started: boolean = false
5548
+ for (let i: i32 = P256_WNAF_BITS; i >= 0; i--) {
5549
+ if (started) {
5550
+ p256PointDouble(out, out, s)
5551
+ }
5552
+ if (i < toI32(wa.length) && wa[i] !== 0) {
5553
+ p256WnafAdd(out, tableG, wa[i], neg, s)
5554
+ started = true
5555
+ }
5556
+ if (i < toI32(wb.length) && wb[i] !== 0) {
5557
+ p256WnafAdd(out, tableQ, wb[i], neg, s)
5558
+ started = true
5559
+ }
5560
+ }
5561
+ }
5562
+
5390
5563
  /**
5391
5564
  * Whether `sig` (`r || s`) is a valid ECDSA signature of `digest` under the
5392
5565
  * public key `pub` (FIPS 186-4 §6.4.2): `r` and `s` in [1, n), and the
@@ -5394,7 +5567,10 @@ const p256SignExposed = (priv: u8[], digest: u8[]): u8[] | null => {
5394
5567
  * `u1 = z w` and `u2 = r w`. A key or signature of the wrong length, a key
5395
5568
  * that is not a point on the curve, and a sum that is the identity all answer
5396
5569
  * `false`. Every value here is public, so the answer may be reached by
5397
- * branches; the multiplications are the constant-time ones all the same.
5570
+ * branches, and `u1 * G + u2 * Q` is one variable-time Shamir pass over
5571
+ * width-5 NAFs (`p256DoubleMultPublic`), not two constant-time
5572
+ * multiplications: its time follows `u1` and `u2`, which the signature and
5573
+ * digest already disclose.
5398
5574
  *
5399
5575
  * ECDSA is malleable, and so is this: when `(r, s)` verifies, `(r, n - s)`
5400
5576
  * verifies too, as FIPS 186-4 and SEC 1 have it. Nothing here asks for the
@@ -5446,10 +5622,7 @@ export const p256Verify = (pub: u8[], digest: u8[], sig: u8[]): boolean => {
5446
5622
 
5447
5623
  const scratch = new P256PointScratch()
5448
5624
  const sum = new P256ProjectivePoint()
5449
- const other = new P256ProjectivePoint()
5450
- p256ScalarMult(sum, u1Bytes, p256Generator(), scratch)
5451
- p256ScalarMult(other, u2Bytes, q, scratch)
5452
- p256PointAdd(sum, sum, other, scratch)
5625
+ p256DoubleMultPublic(sum, u1Bytes, u2Bytes, q, scratch)
5453
5626
  if (p256FiatNonzero(sum.z) === 0) {
5454
5627
  return false
5455
5628
  }
@@ -48,7 +48,9 @@
48
48
  *
49
49
  * **The curve** is `y^2 = x^3 - 3x + b` over GF(p),
50
50
  * p = 2^384 - 2^128 - 2^96 + 2^32 - 1, with the base point G and its order n from SEC 2 §2.5.1 (FIPS
51
- * 186-4 §D.1.2.4). Points are projective (X : Y : Z), Z = 0 the identity, and
51
+ * 186-4 §D.1.2.4).
52
+ *
53
+ * Points are projective (X : Y : Z), Z = 0 the identity, and
52
54
  * are added and doubled with the complete formulas of J. Renes, C. Costello and
53
55
  * L. Batina, "Complete addition formulas for prime order elliptic curves"
54
56
  * (EUROCRYPT 2016), Algorithms 4 and 6 for a = -3, as `nish/crypto/p256` uses