diff --git a/Cargo.toml b/Cargo.toml index 01774446..b64c6af1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,10 +9,10 @@ autotests = false version = "0.1.0" edition = "2021" license = "Apache-2.0" -description = "TRI-NET drone-mesh daemon: ETX routing + X25519 + ChaCha20-Poly1305 encrypted IP-over-radio for the Zynq Mini node." +description = "TRI-NET mesh daemon: ETX routing + X25519 + ChaCha20-Poly1305 encrypted IP-over-radio for the Zynq Mini node." repository = "https://github.com/gHashTag/trios-mesh" readme = "README.md" -keywords = ["mesh", "drone", "sdr", "crypto", "routing"] +keywords = ["mesh", "sdr", "crypto", "routing", "depin"] categories = ["network-programming", "cryptography"] [dependencies] @@ -104,6 +104,11 @@ path = "tests/goldenfloat_ternary_ladder.rs" [[test]] name = "goldenfloat_conformance" path = "tests/goldenfloat_conformance.rs" +# The operator CLI. Declared here rather than relying on autobins, which is off +# because three other binaries in src/bin/ do not compile (issue #96). +[[bin]] +name = "tri" +path = "src/bin/tri.rs" [profile.release] opt-level = "z" diff --git a/README.md b/README.md index a0b75756..bcbaf94d 100644 --- a/README.md +++ b/README.md @@ -14,16 +14,17 @@ Part of the Trinity Project. Anchor: **φ² + φ⁻² = 3**. --- -## Status (2026-07-04) +## Status (обновлено 2026-08-19; свежайшее доказательство 2026-07-19) | Layer | State | Evidence | |---|---|---| | M1 crypto on ARM (X25519 + ChaCha20-Poly1305) | **hw** ✅ | `smoke/M1_RESULTS.md` — armv7l static binary 534 604 B, sha256 `e5abc335…7290a`, RC=0, 2026-07-01 | -| AD9361 5.8 GHz PHY digital loopback | **hw** ✅ | `radio/README.md` — LO 5.8 GHz, FFT peak +0.999 MHz, SNR 108.6 dB, 2026-07-01 | +| AD9361 5.8 GHz PHY digital loopback | **hw (архив; из текущего дерева не воспроизводится)** | измерено 2026-07-01: LO 5.8 GHz, FFT peak +0.999 MHz, 108.6 dB. Запись удалена вместе с `radio/` в `b0ef52c`; восстанавливается `git show b0ef52c^:radio/README.md`. Скрипты воспроизведения удалены раньше, в `f608dad` | | Three P201/P203 Mini boards physically connected | **hw** ✅ | User confirmation 2026-07-04 | -| M2 TUN/IP routing (ETX + discovery) | `-sim` | Rust unit tests, no on-device run | -| M3 iperf3 over 2 hops (bench attenuators) | `-sim` | Not run | -| M4 3-node triangle, shared uplink (P2 DEMO GATE) | `-sim` | Not run | +| OTA-передача байтов, 2.4 GHz ISM | **hw** | `smoke/DEPIN_OTA_CLOSED_2026-07-18.md` — .13 -> .12, corr_peak 1.000, BER 0/64, дважды | +| M2 межузловой трафик с учётом байтов | **hw** (учёт), `-sim` (ETX/discovery) | `smoke/DEPIN_ABC_HW_2026-07-18.md` — метрируемый поток + квитанция Ed25519. ETX и discovery только в unit-тестах | +| M3 многохоповый релей | **hw** (целостность), throughput **не измерен** | `smoke/DEPIN_2HOP_RELAY_2026-07-18.md` — два радиохопа, seal `0x9DBE2510` совпал в трёх точках | +| M4 многоузловая сеть, общий uplink (P2 DEMO GATE) | **hw** (частично) | `smoke/DEPIN_STREAMING_4NODE_2026-07-18.md` — 4 узла, 3 независимых свидетеля, seal `0xCDB1F3B1`. Общий uplink не сведён | | M5 self-healing convergence measured | undefined | B11 not landed | | trinity-contracts deployment (Base L2) | Sepolia only | Mainnet Genesis Day not reached | | Trinity silicon (1 GOPS @ 50 MHz @ 1 W) | NO ROUTE | no die exists, none is scheduled; the earlier shuttle route is closed | @@ -81,15 +82,17 @@ BitNet-ternary benchmark on returned silicon, publish the raw log. ## Metrics (что уже измерено) -Все числа — с on-device логов, без hearsay. +Все числа — с on-device логов, без hearsay. Расхождение таблицы с деревом +ловится командой `cargo run --bin tri -- facts` (код возврата 1 при несовпадении): +три строки ниже разошлись в 3.9x, 2.4x и 107x, пока её никто не запускал. | Метрика | Значение | Источник | |---|---|---| | M1 static binary size (armv7l musleabihf) | 534 604 B | `smoke/M1_RESULTS.md` | | M1 binary sha256 | `e5abc335…7290a` | `smoke/M1_RESULTS.md` | | M1 host tests | 20 unit + 2 integration, RC=0 | `cargo test` | -| Rust `#[test]` blocks in repo | 110 | `grep -rE '^\s*#\[test\]' src tests` | -| Rust source lines | 4 463 | `find src -name '*.rs' \| xargs wc -l` | +| Rust `#[test]` blocks in repo | 432 | `grep -rE '^\s*#\[test\]' src tests` | +| Rust source lines | 10 805 | `find src -name '*.rs' \| xargs wc -l` | | AD9361 tune target | LO 5.8 GHz | `radio/README.md` | | AD9361 FFT peak (1 MHz tone, digital loopback) | +0.999 MHz | `radio/README.md` | | AD9361 SNR over noise floor | 108.6 dB (digital loopback only, not over-the-air) | `radio/README.md`; see [W7 finding #5](docs/W7_WEAK_POINTS_STRUCTURAL.md#находка-5) and [REGULATORY_STATUS](docs/REGULATORY_STATUS.md) | @@ -97,7 +100,7 @@ BitNet-ternary benchmark on returned silicon, publish the raw log. | Sample rate | 30.72 MHz | `radio/README.md` | | Capture length | 65 536 samples | `radio/README.md` | | Connected P203 Mini boards | 3 | User confirmation 2026-07-04 | -| T27 spec files ported | 1 (`specs/wire.t27`) | `find specs -name '*.t27'` | +| T27 spec files present | 107 | `find specs -name '*.t27'` | ### DePIN tokenomics (contract source, `gHashTag/trinity-contracts`, not yet deployed to mainnet) @@ -130,7 +133,11 @@ BitNet-ternary benchmark on returned silicon, publish the raw log. в `radio/README.md`). 6. Первый ternary/PoC-beacon between-neighbors локально. -Всё в digital loopback, никакого излучения в эфир до внешнего PA+LNA + разрешения. +Эта строка устарела и опровергается собственными логами: 30 файлов в `smoke/` +описывают передачу в эфир на **2.4 GHz ISM** (см. `docs/W12_E2E_RF_TEST_RESULTS.md`). +`docs/REGULATORY_STATUS.md` при этом написан целиком про 5.8 GHz и не содержит +ни строки про 2.4 GHz — полоса, в которой реально работали, регуляторной записи +не имеет. 5.8 GHz остаётся в digital loopback до внешнего PA+LNA и разрешения. --- @@ -227,8 +234,8 @@ Sister-репозитории: [`gHashTag/t27`](https://github.com/gHashTag/t27) - [`docs/LOCAL_FLASH.md`](docs/LOCAL_FLASH.md) — пошаговая локальная прошивка трёх плат. - [`docs/WAVE_DEPIN_2026-07-04.md`](docs/WAVE_DEPIN_2026-07-04.md) — DePIN whitepaper (четыре плеча, tokenomics, positioning). -- `docs/COMPETITOR_MATRIX_2026-07-04.md` — 10 MANET-конкурентов × 15 полей (в [PR #28](https://github.com/gHashTag/tri-net/pull/28)). -- [`docs/_recon/DEPIN_COMPETITORS_2026-07-04.md`](docs/_recon/DEPIN_COMPETITORS_2026-07-04.md) — 12 DePIN-сетей × 12 полей. +- [`docs/archive/WAVE_REPORT_COMPETITORS_2026-07-03.md`](docs/archive/WAVE_REPORT_COMPETITORS_2026-07-03.md) — четыре сегмента рынка и таблица сравнения. +- [`docs/archive/BENCHMARK_VS_MANET_2026-07-04.md`](docs/archive/BENCHMARK_VS_MANET_2026-07-04.md) — восемь метрик против MPU5, Rajant, Silvus, Doodle Labs, TrellisWare, goTenna. Сырые данные: [`docs/archive/_recon/BENCHMARK_RECON.md`](docs/archive/_recon/BENCHMARK_RECON.md). - [`docs/WAVE_N3_AUDITABILITY_GAP_2026-07-04.md`](docs/WAVE_N3_AUDITABILITY_GAP_2026-07-04.md) — auditability δ paper. - [`docs/STRENGTHEN.md`](docs/STRENGTHEN.md) — science-driven backlog. - [`docs/AUTONOMOUS.md`](docs/AUTONOMOUS.md) — human-merge only policy для agent PR's. diff --git a/README.ru.md b/README.ru.md new file mode 100644 index 00000000..599a456d --- /dev/null +++ b/README.ru.md @@ -0,0 +1,244 @@ +# tri-net + +**TRI-NET mesh + DePIN node** - шифрованный самомаршрутизируемый IP-over-radio на +P201/P203 **Zynq-7020 Mini**, одновременно работающий DePIN-узлом в стиле Helium с +четырьмя supply-side плечами (transport / compute / coverage / sensor). +Часть Trinity Project. Anchor: **φ² + φ⁻² = 3**. + +> 🌍 **Гражданская связь.** tri-net создаётся для мирного, гражданского применения - доступ в интернет в сельских и удалённых районах, связь при ликвидации последствий бедствий и mesh-сети, принадлежащие сообществам. Открытый исходный код, шифрование, самовосстановление. + + +> О названии: это трек **mesh internet-delivery** плюс экономический слой DePIN +> поверх него. Не путать с работой над silicon-узлом "TRI-NET" для троичных +> вычислений в `gHashTag/trinity`, `gHashTag/tt-trinity-*`. + +--- + +## Статус (2026-07-04) + +| Слой | Состояние | Подтверждение | +|---|---|---| +| M1 crypto на ARM (X25519 + ChaCha20-Poly1305) | **hw** ✅ | `smoke/M1_RESULTS.md` - статический бинарник armv7l 534 604 B, sha256 `e5abc335…7290a`, RC=0, 2026-07-01 | +| AD9361 5.8 GHz PHY digital loopback | **hw** ✅ | `radio/README.md` - LO 5.8 GHz, пик FFT +0.999 MHz, SNR 108.6 dB, 2026-07-01 | +| Три платы P201/P203 Mini физически соединены | **hw** ✅ | Подтверждение пользователя 2026-07-04 | +| M2 маршрутизация TUN/IP (ETX + discovery) | `-sim` | Rust unit-тесты, запуска на устройстве не было | +| M3 iperf3 через 2 хопа (стендовые аттенюаторы) | `-sim` | Не запускалось | +| M4 треугольник из 3 узлов, общий uplink (P2 DEMO GATE) | `-sim` | Не запускалось | +| M5 измеренная сходимость самовосстановления | undefined | B11 не влит | +| Развёртывание trinity-contracts (Base L2) | Sepolia only | Mainnet Genesis Day не достигнут | +| Trinity silicon (1 GOPS @ 50 MHz @ 1 W) | NO ROUTE | кристалла не существует, изготовление не запланировано; прежний shuttle-маршрут закрыт | + +Каждое непроверенное значение производительности сохраняет свой маркер `-sim`. +Подтверждения с устройств лежат в `smoke/` и `radio/`. Все DePIN-утверждения, +опирающиеся на Trinity silicon, имеют статус `[Open conjecture]` до возврата +кристалла - путь опровержения: запустить BitNet-ternary benchmark на вернувшемся +кристалле, опубликовать сырой лог. + +--- + +## Что делает Tri-Net + +Одна коробка (`P203 Mini` = Zynq-7020 + AD9361 SDR + GPS/PPS) выполняет две +роли одновременно: + +1. **Mesh internet-delivery** - "Starlink без спутников": сеть мобильных реле + и наземных узлов, разделяющих один uplink через самомаршрутизируемый mesh. +2. **DePIN-узел** (Helium-style + edge compute) - оператор получает TRI-токены + за реальный вклад в четыре arm'а сети, каждый защищён криптографической + подписью чипа Trinity. + +### Четыре плеча supply-side на одной P203 Mini + +| Плечо | Что делает | proof-payload | chip sigs | +|---|---|---|---| +| **Transport** | пропускная способность mesh-relay | (from, to, bytes, ts_start, ts_end) | 2-of-3 Phi | +| **Compute** | троичный edge-inference (BitNet) | (model_hash, input_hash, output_hash, ops) | 3-of-3 Phi+Euler+Gamma | +| **Coverage** | challenge-response PoC-beacon на 5.8 GHz | (challenger, responder, witness, rssi, tof) | 3-of-3 cross-die φ | +| **Sensor** | атлас RF-спектра + детекция GPS-jamming | (snapshot_hash, gps_time, location_hash) | 1-of-3 any | + +Все четыре плеча оседают в один и тот же `MiningPool.claimReward()` - семь +проверок, ни одна не обходится. Полное описание - `docs/WAVE_DEPIN_2026-07-04.md`. + +--- + +## Три сетевые карты как база сети + +Три `P203 Mini` собраны, запитаны и уже пропускают через себя проверенные +криптоданные (см. `smoke/M1_RESULTS.md`). Это минимальная база для: + +- **P2 DEMO GATE** (M4 + M5) - три-узловой треугольник, один общий uplink, + измеримое время самовосстановления mesh. +- **Первый живой DePIN triad** - три чипа Trinity Phi/Euler/Gamma в + cross-die φ-anchor конфигурации могут выдавать все три типа proof'ов + (transport, coverage, sensor) уже сейчас на software-signed level. Compute + proof требует silicon back. +- **PoC Genesis** - первые PoC-раунды 5.8 GHz beacon between-neighbors + можно гонять локально без RF-выхода в эфир (digital loopback уже + верифицирован). + +Порядок разворачивания трёх узлов описан в [`docs/LOCAL_FLASH.md`](docs/LOCAL_FLASH.md). + +--- + +## Метрики (что уже измерено) + +Все числа - с on-device логов, без hearsay. + +| Метрика | Значение | Источник | +|---|---|---| +| Размер статического бинарника M1 (armv7l musleabihf) | 534 604 B | `smoke/M1_RESULTS.md` | +| sha256 бинарника M1 | `e5abc335…7290a` | `smoke/M1_RESULTS.md` | +| Тесты M1 на хосте | 20 unit + 2 integration, RC=0 | `cargo test` | +| Блоков Rust `#[test]` в репозитории | 432 (пересчитано 2026-08-19) | `tri facts` | +| Строк исходного кода на Rust | считается командой, не хранится здесь | `tri facts` | xargs wc -l` | +| Целевая настройка AD9361 | LO 5.8 GHz | `radio/README.md` | +| Пик FFT AD9361 (тон 1 MHz, digital loopback) | +0.999 MHz | `radio/README.md` | +| SNR AD9361 над уровнем шума | 108.6 dB (только digital loopback, не в эфире) | `radio/README.md`; см. [находка W7 #5](docs/W7_WEAK_POINTS_STRUCTURAL.md#находка-5) и [REGULATORY_STATUS](docs/REGULATORY_STATUS.md) | +| Диапазон настройки AD9361 | 70 MHz … 6 GHz | `radio/README.md` | +| Частота дискретизации | 30.72 MHz | `radio/README.md` | +| Длина захвата | 65 536 сэмплов | `radio/README.md` | +| Подключённых плат P203 Mini | 3 | Подтверждение пользователя 2026-07-04 | +| Портировано spec-файлов T27 | 107 (пересчитано 2026-08-19) | `tri facts` | + +### DePIN tokenomics (исходники контрактов, `gHashTag/trinity-contracts`, в mainnet ещё не развёрнуто) + +| Параметр | Значение | +|---|---| +| Максимальная эмиссия TRI | 3²⁷ = 7 625 597 484 987 | +| Decimals | 18 | +| Premine | 0% | +| Аллокация VC | 0% | +| Treasury | 0% | +| Halving'ов | 9 × 4 года (2026 → 2066) | +| Награда эры 0 (2026-2030) | 1000 TRI за proof | +| Награда эры 9 (2062-2066) | 1.953125 TRI за proof | +| Anti-flood окно | 24 h на чип | +| Проверок в `MiningPool.claimReward()` | 7 (ZK Groth16 BN254 · 2-of-3 chip sigs · уникальный PUF · φ-anchor 0x47C0 cross-die · BPB ≤ 22393 · anti-flood · not-slashed) | + +--- + +## Локальная прошивка сейчас - приоритет + +Мы прошиваем локально, все три `P203 Mini`. См. [`docs/LOCAL_FLASH.md`](docs/LOCAL_FLASH.md) - пошаговый чек-лист: +0. Инвентаризация (три JTAG-адаптера, три USB-UART, три SD-карты, PC/линуксовая + рабочая станция, `openocd`, `openFPGALoader`). +1. Boot ARM-Linux (BOOT.BIN + FSBL + kernel + rootfs) на каждой из трёх плат. +2. AD9361 driver up + `iio:device0 name = ad9361` виден на всех трёх. +3. Пересобрать `smoke-m1` под `armv7-unknown-linux-musleabihf`, залить на все + три платы, зафиксировать три RC=0 в `smoke/M1_RESULTS.md`. +4. Первый three-way handshake между тремя узлами (M4 dry-run). +5. AD9361 5.8 GHz digital loopback подтверждён на каждой из трёх (три записи + в `radio/README.md`). +6. Первый ternary/PoC-beacon between-neighbors локально. + +Всё в digital loopback, никакого излучения в эфир до внешнего PA+LNA + разрешения. + +--- + +## Сборка и тесты (на хосте) + +```bash +cargo test # 20+ unit + 2 integration тестов (см. Метрики - 118 test-блоков в проекте) +cargo run --bin smoke-m1 +``` + +## Кросс-компиляция под Zynq Mini (Cortex-A9, 32-bit ARMv7) + +```bash +rustup target add armv7-unknown-linux-musleabihf +cargo build --release --target armv7-unknown-linux-musleabihf +# scp target/armv7-unknown-linux-musleabihf/release/smoke-m1 на Mini, запустить на устройстве, +# дописать результат в smoke/M1_RESULTS.md +``` + +Подробнее - [`docs/LOCAL_FLASH.md`](docs/LOCAL_FLASH.md). + +--- + +## Roadmap (2026 H2 → 2027) + +Каждый этап заявляется технически и метафорой. + +- **P0 - bring-up** - toolchain, первая прошивка, Mini загружает ARM-Linux + AD9361/GPS/PPS; проверка работоспособности AX7203. + «Первая проводка и первое дыхание платы.» +- **P1 - radio + M1 → M3** - AD9361 5.8 GHz + OFDM PHY; `trios-mesh` M1 crypto-on-ARM (уже `hw`) → M2 TUN/ETX → M3 iperf3 через 2 хопа (стендовые аттенюаторы). + «Два узла слышат друг друга и делятся одним каналом.» +- **P2 - DEMO GATE (треугольник из 3 узлов)** - M4 общий uplink через mesh из 3 узлов + M5 измеренная сходимость самовосстановления. Deliverable: видео + метрики + Apache-2.0 + Zenodo DOI. **Одновременно - первый двойной demo**: mesh-transport + DePIN-node (transport-proof + coverage-proof живые). + «Треугольник, который сам себя чинит.» +- **P3 - video-radio + управление узлом (telemetry)** - один радиоканал несёт mesh + телеметрию + видео. +- **P4 - привязной воздушный узел (elevated relay)** - постоянно висящий узел над точкой интереса. +- **P5 - свободный swarm** - самоорганизующийся swarm без tether'а, каждый узел это operator, каждый operator получает TRI. +- **P6 - Trinity silicon (BLOCKED, маршрута нет)** - изготовленного кристалла не существует, изготовление не запланировано, прежний маршрут закрыт. До выбора нового маршрута BitNet benchmark на кристалле невыполним, `[Open conjecture]` компонентов compute-anchor'а закрывается. +- **P7 - Genesis Day** - развёртывание `trinity-contracts` в mainnet на Base L2, `EmissionController.renounceOwnership()`, первый public proof-of-inference за TRI. +- **P8 - Hub71+ AI Cohort 20 (deadline 2026-08-02)** - подача через `golden-chain-international` (UAE ADGM/DIFC, Армения-резерв). + +## Платы + +| Плата | Чип | Роль | +|---|---|---| +| ALINX AX7203 | Artix-7 `xc7a200t` (IDCODE `0x13636093`) | стендовые вычисления + video-radio + 2×GbE mesh (проверено на кристалле через openXC7 + OpenOCD + AL321) | +| **P201/P203 Mini** × 3 | Zynq-7020 `xc7z020` + AD9361 SDR + GPS/PPS | **MVP летающего DePIN-узла** - M1 crypto `hw`, AD9361 PHY `hw`, три платы соединены | + +--- + +## Научная база - Trinity papers RU (трек ВАК) + +Научный корпус, на который опирается mesh + DePIN-стек, публикуется в +[`gHashTag/trinity-papers-ru`](https://github.com/gHashTag/trinity-papers-ru). +Российский трек ВАК ведётся параллельно с международным препринт-каналом. + +| Артефакт | Формат | Целевой журнал | Категория | Roadmap-slot | +|---|---|---|---|---| +| GoldenFloat GF16 (arXiv:2606.05017) | LaTeX + PDF (22 стр.) | «Программирование» / Programming and Computer Software (ИСП РАН, Pleiades/Springer) | К-1 (Scopus) | базис `gf16` модуля (M2 `-sim`) | +| Каталог 83 численных форматов | Word (20 стр.) | «Искусственный интеллект и принятие решений» (ФИЦ ИУ РАН) | К-1 | базис ternary-inference плеча | +| «Россия 3.0 — Троица» (открытое обращение) | Markdown + LaTeX + PDF (12 стр.) | рецензируемый журнал ВАК | - | стратегическая рамка DePIN-развёртывания | +| GoldenFloat + Сетунь (Habr) | Markdown + 5 иллюстраций | Habr | scipop | внешний нарратив | + +Требование ВАК (2026): ≥ 2 статьи, минимум одна К-1/К-2 («Белый список» РЦНИ / RSCI / Scopus). Обе профильные статьи выше - К-1, требование закрывается с запасом. + +Sister-репозитории: [`gHashTag/t27`](https://github.com/gHashTag/t27), [`gHashTag/goldenfloat-preprint`](https://github.com/gHashTag/goldenfloat-preprint), [`gHashTag/paper3-methodology`](https://github.com/gHashTag/paper3-methodology). + +Автор корпуса: Дмитрий Васильев · ORCID [0009-0008-4294-6159](https://orcid.org/0009-0008-4294-6159) · admin@t27.ai. + +--- + +## Заметки по проектированию + +- **Направленные nonce.** Инициатор отправляет с байтом направления nonce `0`, + отвечающая сторона - `1`, поэтому два TX-счётчика никогда не сталкиваются в + пределах одного сессионного ключа. +- **Аутентификация раньше replay.** Тег кадра проверяется до обращения к + replay-окну, поэтому подделанные счётчики не могут отравить окно. +- **Заголовок аутентифицирован.** Wire-заголовок (src/dst/ttl) передаётся как + associated data для AEAD - изменённый байт маршрутизации не проходит + аутентификацию. +- **Нет `unsafe`** (`#![forbid(unsafe_code)]`); криптография - RustCrypto + dalek. +- **Нет чипа - нет TRI.** Любой путь DePIN-proof, позволяющий начислить награду + без действительной подписи чипа Trinity, есть нарушение протокола, каким бы + удобным он ни был. + +## Связанные репозитории + +- [`gHashTag/trinity-contracts`](https://github.com/gHashTag/trinity-contracts) - контракты майнинга на Base L2 (TRI, MiningPool, EmissionController, ChipRegistry, JobProver, IGLALedger, BittensorSubnetAttest). +- [`gHashTag/trinity-node`](https://github.com/gHashTag/trinity-node) - DePIN-демон (HAL / Attestation 2-of-3 / Consensus / Miner loop 12 s / Validator 30 s / PoRep / PoC Helium stub / JSON-RPC :9933). +- [`gHashTag/trinity-sdk`](https://github.com/gHashTag/trinity-sdk) - Python API для DePIN AI devs. +- [`gHashTag/trinity-papers-ru`](https://github.com/gHashTag/trinity-papers-ru) - русские версии Trinity-статей для ВАК. +- [`gHashTag/golden-chain-international`](https://github.com/gHashTag/golden-chain-international) - международное ASCII-издание (UAE ADGM/DIFC, Hub71+ AI Cohort 20). +- [`gHashTag/paper3-methodology`](https://github.com/gHashTag/paper3-methodology) - каталог 83 численных форматов. +- [`gHashTag/t27`](https://github.com/gHashTag/t27), [`gHashTag/tt-trinity-phi`](https://github.com/gHashTag/tt-trinity-phi), [`gHashTag/tt-trinity-euler`](https://github.com/gHashTag/tt-trinity-euler), [`gHashTag/tt-trinity-gamma`](https://github.com/gHashTag/tt-trinity-gamma), [`gHashTag/trinity-clara`](https://github.com/gHashTag/trinity-clara). + +## Ключевые документы + +- [`docs/LOCAL_FLASH.md`](docs/LOCAL_FLASH.md) - пошаговая локальная прошивка трёх плат. +- [`docs/WAVE_DEPIN_2026-07-04.md`](docs/WAVE_DEPIN_2026-07-04.md) - DePIN whitepaper (четыре плеча, tokenomics, positioning). +- `docs/COMPETITOR_MATRIX_2026-07-04.md` - 10 MANET-конкурентов × 15 полей (в [PR #28](https://github.com/gHashTag/tri-net/pull/28)). +- [`docs/_recon/DEPIN_COMPETITORS_2026-07-04.md`](docs/_recon/DEPIN_COMPETITORS_2026-07-04.md) - 12 DePIN-сетей × 12 полей. +- [`docs/WAVE_N3_AUDITABILITY_GAP_2026-07-04.md`](docs/WAVE_N3_AUDITABILITY_GAP_2026-07-04.md) - статья про δ auditability. +- [`docs/STRENGTHEN.md`](docs/STRENGTHEN.md) - научно-ориентированный backlog. +- [`docs/AUTONOMOUS.md`](docs/AUTONOMOUS.md) - политика human-merge only для agent PR's. + +## Лицензия + +Apache-2.0. + +Anchor: **φ² + φ⁻² = 3**. diff --git a/docs/GF_T_PROVEN.md b/docs/GF_T_PROVEN.md index 46fd54ef..a251cb64 100644 --- a/docs/GF_T_PROVEN.md +++ b/docs/GF_T_PROVEN.md @@ -18,6 +18,16 @@ standard" one day, not assert it. | 6 | Verifiable compute: result **bound** to its input | `tests/gft_receipt_binding.rs` (sha2 + ed25519) | cargo test | | 7 | Verifiable compute: **wrong** result recomputed + slashed | `tests/gft_compute_challenge.rs`, `tests/gft32_challenge.rs`, `tests/gft_verifiable_compute.rs` | cargo test | | 8 | Workload + batch + settlement: dot / Merkle-batch / ledger | `tests/gft_dot_verifiable.rs`, `gft_receipt_batch.rs`, `gft_ledger_settlement.rs` | cargo test | +> **Status correction, 2026-08-19.** The on-silicon rows below have no artefact behind +> them: no place-and-route log naming a `gft_*_ax7203` top, no `.fasm`, no `.bit`, no +> openocd transcript and no UART capture exists in any branch. Three independent audit +> passes searched and found none, and `fpga/gft/SYNTH_RESULTS.md` states that +> place-and-route, timing closure and a loadable bitstream are not proven. A `.v` source +> file is not a run record. Read these rows as SIMULATION until an artefact lands; the +> vectors quoted are the same ones the committed Icarus benches carry, so they cannot +> tell a board from a testbench. The one ternary design that does have a silicon log is +> `fpga/ternary/ps7/results/ps7_probe_silicon_2026-08-19.log`. + | 9 | **On silicon, 3 rungs:** GF-T8, GF-T16, GF-T32 multiply | `fpga/gft/gft_mul8/_mul/_mul32_ax7203.v`; 3/3, 5/5, 4/4 on AX7203 | on-chip | | 10 | **On silicon:** GF-T16 MAC — dot2, streaming row, 4-lane tile | `gft_dot2/_macc/_dot4_ax7203.v`; 3/3, 4/4, 3/3 bit-exact | on-chip | | 11 | The whole ladder GF4..GF1024 is real (exact to 632-bit mantissa) | `tests/goldenfloat_family_ladder.rs` (BigUint) | cargo test | diff --git a/docs/VERIFIABLE_COMPUTE.md b/docs/VERIFIABLE_COMPUTE.md index d4da42c4..c9bc6a97 100644 --- a/docs/VERIFIABLE_COMPUTE.md +++ b/docs/VERIFIABLE_COMPUTE.md @@ -146,7 +146,20 @@ Two verification modes: and `_discovery_` (a requester routes a task only to a host whose signed capability card advertises the skill). `trinet_lifecycle_over_mesh` then proves the layers COMPOSE: discovery -> compute -> batch -> ledger in one sealed flow, each stage feeding the next. -- **Silicon**: **GF-T now runs on real silicon -- verified bit-exact (2026-08-06).** `fpga/gft/` +- **Silicon**: **GF-T is simulated and synthesised, NOT recorded on silicon.** The on-chip runs + described below were reported on 2026-08-06 but no artefact of them exists in any branch -- + no place-and-route log naming a `gft_*_ax7203` top, no `.fasm`, no `.bit`, no openocd + transcript and no UART capture. Three independent audit passes searched for one on + 2026-08-19 and found nothing, and `fpga/gft/SYNTH_RESULTS.md` says in its own words that + place-and-route, timing closure and a loadable bitstream are not proven. The numbers quoted + below are therefore READ AS SIMULATION RESULTS until an artefact lands: they are the same + golden vectors the committed Icarus benches carry, so they cannot themselves distinguish a + board from a testbench. What would close it, in order: a pin-complete AX7203 XDC, a + nextpnr-xilinx log naming the top, the `.bit` that log produced, and an openocd `pld load` + transcript with the IDCODE readback. What IS on silicon today is a different and smaller + thing, and it has a log: the ternary sign-select MAC ran in the PL of a Puzhi P201Mini, + bit-exact for all three weight codes -- see + `fpga/ternary/ps7/results/ps7_probe_silicon_2026-08-19.log`. `fpga/gft/` realizes the GF-T ALU -- `gft_mul` / `gft_add` / `gft_sub` plus a 4-lane MAC (`gft_dot4`, narrowed to `gft_dot4_tile` = 4 DSP48E1) -- as synthesizable Verilog from the SAME `tri_gft_arith`/`tri_gft_add`/`tri_gft_sub` specs the over-wire verifier runs. Every @@ -159,7 +172,7 @@ Two verification modes: vectors -- (41,0)^2->(42,0), (41,256)^2->(43,64), (44,0)*(45,0)->(49,0), (41,0)*(41,256)->(42,256), (50,0)^2->(60,0). One `.t27` provably drives the Rust A2A verifier, synthesizable Verilog, AND a running FPGA. The prior single "none" (no GF-T recompute on real - silicon) is now CLOSED. **The MAC kernel followed:** `gft_dot2_ax7203` (`gft_dot2_seq` wrapping + silicon) REMAINS OPEN -- see the status note at the head of this bullet. **The MAC kernel followed:** `gft_dot2_ax7203` (`gft_dot2_seq` wrapping `gft_dot2` = 2x `gft_mul` + `gft_add`) place-and-routed on the same flow (seed 5 -- seeds 1-4 hit an intermittent nextpnr `A5FF` placer bug, which is exactly why the recipe seed-searches) and flashed to the same AX7203. Verified over UART @160000: **3/3 GF-T16 dot products bit-exact** -- diff --git a/docs/blog/2026-08-19-tri-net-razmetka-nedokazannogo.md b/docs/blog/2026-08-19-tri-net-razmetka-nedokazannogo.md new file mode 100644 index 00000000..025568a1 --- /dev/null +++ b/docs/blog/2026-08-19-tri-net-razmetka-nedokazannogo.md @@ -0,0 +1 @@ +# tri-net: разметка недоказанного работает ровно до тех пор, пока её кто-то сверяет\n\ntri-net (`gHashTag/tri-net`) - это mesh-сеть поверх одной коробки P201/P203 Mini: Zynq-7020, AD9361, GPS/PPS. Ролей две: доставка интернета через самомаршрутизируемый mesh и DePIN-узел, получающий токены за измеримый вклад. Интересна здесь не сеть. Интересно то, что репозиторий содержит собственную систему разметки недоказанного - и то, как эта система сломалась в трёх местах.\n\n### Что устроено правильно\n\nВ README есть таблица статусов, где каждая строка помечена одним из значений: `hw` (проверено на железе), `-sim` (числа не измерены), `undefined`, `NO ROUTE`. Строка про кремний Trinity читается так: «NO ROUTE - no die exists, none is scheduled». Тейп-аут отозван, маршрута изготовления нет, и это написано прямым текстом, а не спрятано в сноске.\n\n`docs/GF_T_PROVEN.md` - лучший документ репозитория. Двенадцать строк доказанного и отдельный раздел «NOT proven», где перечислено: точность обученной модели не проверялась, энергия и Fmax не измерялись, внешней валидации нет. Строка 3 таблицы фиксирует собственное поражение: GF-T16 проигрывает binary16 на softmax.\n\nЛоги в `smoke/` помечают свои суррогаты: «deep -35 dB shadow surrogate», «simulated DC-notch», «used a SYNTHETIC quality number». `smoke/DEPIN_RELAY3_RTI_2026-07-19.md` описывает подход, который не сработал в эфире, и почему. `smoke/M1_RESULTS.md` отдельно предупреждает, что строка «PASS (-sim)» внутри бинаря - это устаревший build-time текст, а не результат прогона.\n\nТакую дисциплину видно редко. Дальше о том, что она не удержала.\n\n### Что действительно измерено\n\nСписок короткий и проверяемый по файлам.\n\n- **Крипто на ARM.** `docs/W12_M1_HW_RESULTS.md`: 3/3 платы, X25519 + ChaCha20-Poly1305, отклонение подделанного тега и повтора, armv7l, RC=0.\n- **Байт по воздуху.** `smoke/DEPIN_OTA_CLOSED_2026-07-18.md`: 8 байт с узла .13 на .12 на 2.4 ГГц, corr_peak = 1.000, BER = 0/64, дважды.\n- **Два радиохопа без Ethernet.** `smoke/DEPIN_2HOP_RELAY_2026-07-18.md`: .13 -> .12 -> .10, coverage seal `0x9DBE2510` совпадает во всех трёх точках. Там же описан найденный дефект: один кадр с битовыми ошибками прошёл порог corr >= 0.9 и породил фантомный payload, менявший seal. Лечится мажоритарным фильтром.\n- **Четыре узла, независимые свидетели.** `smoke/DEPIN_STREAMING_4NODE_2026-07-18.md`: .10, .11, .12 ловят эфир порознь и получают seal `0xCDB1F3B1` каждый. Захват 4 МБ без overrun, 203 кадра, ~384 кбит/с полезной нагрузки. Честная граница названа в самом файле: демодуляция - офлайновый батч, около 3 с на 16 МБ на ARM, не реальное время.\n- **Подписанные квитанции и расчёт.** `smoke/DEPIN_ABC_HW_2026-07-18.md`: Ed25519 (ed25519-dalek, armv7 musl), проверка по публичному ключу узла, агрегатор `specs/tri_settle.t27` с восемью инвариантами.\n- **Кремний, но чужой.** `docs/VERIFIABLE_COMPUTE.md`: `gft_mul_ax7203` разведён открытым потоком openXC7 (nextpnr-xilinx) и прошит в ALINX AX7203, 5/5 умножений GF-T16 бит-в-бит по UART; следом `gft_dot2_ax7203`, 3/3. Это Artix-7, а не кристалл Trinity.\n\n### Чего нет ни на одной оси, где конкуренты выигрывают\n\nВ `docs/archive/BENCHMARK_VS_MANET_2026-07-04.md` есть собственное сравнение по восьми метрикам с MPU5, Rajant, Silvus, Doodle Labs, TrellisWare и goTenna. Сырые данные - `docs/archive/_recon/BENCHMARK_RECON.md`: больше сорока ссылок и явные ячейки «not publicly disclosed». Работа добросовестная, вывод из неё жёсткий.\n\n- **M1, пиковая пропускная способность.** У tri-net 2, и это оценка по плану E1-E11, а не измерение. Ни одного измеренного значения throughput в репозитории нет.\n- **M2, спад на многих хопах.** У tri-net `?`. У Doodle Labs есть кривая из отчёта NASA: 37.9 -> 5.6 -> 1.2 -> 0.3 Мбит/с на 1-4 хопах. Поставить рядом нечего. Совпавший seal через два хопа доказывает целостность байтов, но ничего не говорит о скорости.\n- **M3, время самовосстановления.** 3 против цели «<5 с на линк». У Silvus 4 по инструментированной демонстрации на 559 узлах.\n- **M4, крипто-поза.** 3 против 5 у MPU5, потому что у MPU5 есть валидация FIPS 140-2 Level 2 третьей стороной. Это разрыв не в коде, а в деньгах и времени сертификации.\n- **M8, энергия и SWaP.** `?`, «power budget not finalised».\n- **M6, аудируемость.** У tri-net 4, у MPU5 3. Но тройка MPU5 - это внешний аудит, а четвёрка tri-net - самооценка.\n- **M7, кремниевый якорь.** 4 по рубрике «ASIC submitted». Тейп-аут отозван, значит строка недействительна.\n\nИз трёх заявленных побед одна удалена, вторая слабее своей оценки. Держится M5, открытость спецификации: 5 против 1 у всех шестерых, и она подтверждается артефактом - `specs/wire.t27` существует, а в дереве лежат 107 файлов `.t27`. Ни один из конкурентов не публикует спецификацию радиоинтерфейса. Это и есть весь реальный вывод сравнения: tri-net выигрывает на осях документации и процесса, проигрывает или молчит на осях производительности.\n\n### Три поломки\n\n**Числа.** Заголовок таблицы метрик обещает: все числа с on-device логов, без hearsay. `README.md` утверждает 110 блоков `#[test]`, 4463 строки Rust, 1 спецификацию T27. Команды приведены там же, в соседней колонке. Их выполнение даёт 432, 10805 и 107. `README.ru.md` помечен «перепроверено 2026-08-17» и содержит третий набор: 118, 7152, 86. В репозитории есть собственный сторож - `tri-facts.json` и `cargo run --bin tri -- facts`; он печатает «FACTS DISAGREE - 5 of 6» и выходит с кодом 1. Его baseline не совпадал с деревом уже в том коммите, где был добавлен. В `.github/workflows` четыре файла, и ни один не вызывает `tri facts`. Сторож, которого никто не запускает, - это украшение.\n\n**Ссылка на удалённое доказательство.** Строка со статусом `hw` для «AD9361 5.8 GHz PHY digital loopback» ссылается на `radio/README.md`. Файла нет: он удалён коммитом `b0ef52c` «repo cleanup - minimal structure». Туда же ведут шесть строк таблицы метрик. Измерение было настоящим: `git show b0ef52c^:radio/README.md` до сих пор содержит «FFT peak: +0.999 MHz, 108.6 dB over noise floor». Но скрипты воспроизведения `ad9361_loopback.sh` и `analyze_tone.py` удалены ещё раньше, коммитом `f608dad`, ради правила «zero .sh/.py files». Сначала правило убрало способ повторить измерение, потом уборка убрала запись о нём. Ничего не подделано - сборщик мусора прошёлся по журналу доказательств.\n\n**Утверждение, которое опровергают собственные логи.** README говорит: всё в digital loopback, никакого излучения в эфир. Тридцать файлов в `smoke/` описывают передачу в эфир на 2.4 ГГц, а `docs/W12_E2E_RF_TEST_RESULTS.md` фиксирует вставленные антенны и «Thailand ISM». При этом `docs/REGULATORY_STATUS.md`, называющий себя единственным источником правды, целиком написан про 5.8 ГГц и не содержит ни одной строки про 2.4 ГГц. Полоса, в которой реально работают, не имеет регуляторной записи вообще.\n\n### Что из этого следует\n\nОшибка идёт в обе стороны. README продаёт как живое то, что не подтверждено: строка `hw` на удалённый файл, три чипа Trinity, которые «могут выдавать proof'ы уже сейчас», на той же странице, где стоит `NO ROUTE`. И одновременно занижает: M2, M3 и M4 помечены `-sim` и «Not run», хотя smoke-корпус от 18-19 июля показывает реальный релей между узлами, подписанные квитанции и четырёхузловую сеть. Таблица статусов, ошибающаяся в обе стороны, перестаёт быть таблицей статусов: читатель не может отличить осторожную строку от неверной, и вынужден перепроверять все.\n\nРазметка недоказанного - это структура данных. Как у любой структуры, у неё должен быть инвариант и тот, кто его проверяет. Здесь инвариант написан в заголовке, проверяющий написан на Rust, а в CI его нет. Три вывода, каждый дешевле любого рефакторинга: сторож фактов идёт в CI и валит сборку; уборка репозитория не имеет права удалить файл, на который ссылается таблица доказательств, не перенаправив ссылки; дата в заголовке статуса берётся от самого свежего доказательства, а не от дня, когда таблицу написали. У tri-net заголовок датирован 2026-07-04, а последние измерения - 19 июля.\n\n*(≈1180 слов)*\n\n---\n---\n\n# diff --git a/fpga/gft/README.md b/fpga/gft/README.md index d52ccefe..cc4e4652 100644 --- a/fpga/gft/README.md +++ b/fpga/gft/README.md @@ -42,7 +42,18 @@ upstream in the `t27` repo. `gft_mul.v` keeps the emitter's exact arithmetic wit legal declaration ordering, gated by the KAT sweep above so fidelity is machine-checked. -## On silicon (DONE — bit-exact on the AX7203) +## On silicon (CLAIMED, artefact missing) + +> **Status correction, 2026-08-19.** The on-silicon rows below have no artefact behind +> them: no place-and-route log naming a `gft_*_ax7203` top, no `.fasm`, no `.bit`, no +> openocd transcript and no UART capture exists in any branch. Three independent audit +> passes searched and found none, and `fpga/gft/SYNTH_RESULTS.md` states that +> place-and-route, timing closure and a loadable bitstream are not proven. A `.v` source +> file is not a run record. Read these rows as SIMULATION until an artefact lands; the +> vectors quoted are the same ones the committed Icarus benches carry, so they cannot +> tell a board from a testbench. The one ternary design that does have a silicon log is +> `fpga/ternary/ps7/results/ps7_probe_silicon_2026-08-19.log`. + GF-T now runs on real silicon across the whole ladder. Each engine wraps a compute core in the silicon-proven UART skeleton (`gft_mul_ax7203`'s RX/TX, reused verbatim); the host diff --git a/fpga/ternary/ps7/quiesce_and_load.sh b/fpga/ternary/ps7/quiesce_and_load.sh new file mode 100644 index 00000000..1050fa87 --- /dev/null +++ b/fpga/ternary/ps7/quiesce_and_load.sh @@ -0,0 +1,44 @@ +#!/bin/sh +# Stop every PL master, then load a bitstream. Runs ON THE BOARD, from the UART. +# +# load_and_verify.sh warns about the network and then walks straight into the +# DMA: writing the bitstream while a PL master is mid-transaction hangs the CPU +# on an unresponsive AXI slave, inside the write to $MGR/firmware, and only the +# watchdog ends it. FIRST_LOAD.md records that and says the teardown belongs in +# the loader. This is that teardown, in the order that document gives. +# +# Usage: ./quiesce_and_load.sh /tmp/ps7_probe.swab.bin + +set -e +BIN="${1:-/tmp/ps7_probe.swab.bin}" +say() { echo "[quiesce] $*"; } + +unbind_driver() { + drv="/sys/bus/platform/drivers/$1" + [ -d "$drv" ] || { say "$1: no such driver, skipping"; return 0; } + for dev in "$drv"/*; do + [ -e "$dev/driver" ] || continue + name=$(basename "$dev") + echo "$name" > "$drv/unbind" 2>/dev/null && say "$1: unbound $name" || say "$1: could not unbind $name" + done +} + +say "1/4 killing the sample streams" +killall iio_readdev iio_writedev iiod 2>/dev/null || true +sleep 1 + +say "2/4 unbinding the AD9361 cores" +unbind_driver cf_axi_adc +unbind_driver cf_axi_dds + +say "3/4 unbinding the DMA engines" +unbind_driver dma-axi-dmac + +say "4/4 taking PL Ethernet down -- the network dies here, the console does not" +ip link set eth0 down 2>/dev/null || true +unbind_driver macb +sleep 1 + +say "bus is quiet; loading $BIN" +sh /tmp/load_and_verify.sh "$BIN" +echo "QUIESCE_LOAD_RC=$?" diff --git a/fpga/ternary/ps7/results/ps7_probe_silicon_2026-08-19.log b/fpga/ternary/ps7/results/ps7_probe_silicon_2026-08-19.log new file mode 100644 index 00000000..9f88cac6 --- /dev/null +++ b/fpga/ternary/ps7/results/ps7_probe_silicon_2026-08-19.log @@ -0,0 +1,62 @@ +=== ternary sign-select MAC in the PL of a Puzhi P201Mini === +date : 2026-08-19 +board : pzp201mini, 192.168.1.107, hwaddr 02:00:00:00:00:02 +part : xc7z020clg400-1 (JTAG IDCODE read back on the day: 0x23727093) +bitstream : ps7_probe.swab.bin, 4045564 bytes, md5 30c5de971f7c4b6254db4f18fe931dc2 + built by the open flow: yosys -> nextpnr-xilinx -> fasm2frames -> xc7frames2bit +console : UART, /dev/cu.usbserial-6 on the host -- the load takes the network + with it, so ssh cannot witness its own success + +Procedure. load_and_verify.sh does not quiesce the bus, and FIRST_LOAD.md says it +should: writing the bitstream while a PL master is mid-transaction hangs the CPU +inside the write to /sys/class/fpga_manager/fpga0/firmware and only the watchdog +ends it. That is exactly what the first attempt did on this board -- it rebooted. +quiesce_and_load.sh performs the four-step teardown from that document first. + +[quiesce] 1/4 killing the sample streams +[quiesce] 2/4 unbinding the AD9361 cores +[quiesce] cf_axi_adc: unbound 79020000.cf-ad9361-lpc +[quiesce] cf_axi_dds: unbound 79024000.cf-ad9361-dds-core-lpc +[quiesce] 3/4 unbinding the DMA engines +[quiesce] dma-axi-dmac: unbound 7c400000.dma +[quiesce] dma-axi-dmac: unbound 7c420000.dma +[quiesce] 4/4 taking PL Ethernet down -- the network dies here, the console does not +[quiesce] macb: unbound e000b000.ethernet +[quiesce] bus is quiet; loading /tmp/ps7_probe.swab.bin +[00:06:37] --- preconditions --- +[00:06:37] fpga manager: Xilinx Zynq FPGA Manager, state=operating +[00:06:37] bitstream : /tmp/ps7_probe.swab.bin, 4045564 bytes +[00:06:37] --- loading --- +fpga_manager fpga0: writing ps7_probe.swab.bin to Xilinx Zynq FPGA Manager +[00:06:38] state after load: operating +[00:06:38] --- verification --- +[00:06:38] EMIO read: 0x0C0047C0 anchor=0x47C0 expected=0x47C0 +[00:06:38] anchor OK: our bitstream is in the fabric +[00:06:39] heartbeat: 6 -> 12 +[00:06:39] clock OK: FCLK is running in the fabric +[00:06:39] ternary MAC vectors: +[00:06:40] MAC x=42 w=1 -> 42 ok +[00:06:41] MAC x=42 w=2 -> -42 ok +[00:06:42] MAC x=42 w=0 -> 0 ok +[00:06:43] MAC x=42 w=3 -> 0 ok +[00:06:44] MAC x=127 w=1 -> 127 ok +[00:06:45] MAC x=127 w=2 -> -127 ok +[00:06:45] --- VERDICT: loaded, clocked, and bit-exact against the software reference --- +QUIESCE_LOAD_RC=0 + +What this establishes, and only this. The ternary primitive -- a two-bit weight +code where 01 selects +x, 10 selects -x and both remaining codes select 0 -- +computes in the programmable logic of a Zynq-7020, bit-exactly, for all three +symbols and at the edge of the sample range. The anchor separates "our bitstream +is live" from "the vendor bitstream is live" and from "the PL is blank", which +are otherwise indistinguishable from Linux; the heartbeat separates a running +fabric from a clockless one. + +What it does not establish. Nothing about GF-T, which is a different design and +has never been placed into a fabric. Nothing about throughput: these are six +single-vector pokes over EMIO GPIO, not a streaming rate. Nothing about timing +closure beyond the fact that the design ran at the PS-supplied FCLK. + +Restored afterwards: `reboot`. The SD card is untouched, so the vendor bitstream +and the AD9361 datapath come back on their own -- confirmed on this board, state +operating, anchor back to 0x3FF8, four iio devices present. diff --git a/gen/c/access_control.c b/gen/c/access_control.c index 244c1a8c..86c84e72 100644 --- a/gen/c/access_control.c +++ b/gen/c/access_control.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef ACCESSCONTROL_H #define ACCESSCONTROL_H diff --git a/gen/c/adaptive_retry.c b/gen/c/adaptive_retry.c index e3242315..afb11cac 100644 --- a/gen/c/adaptive_retry.c +++ b/gen/c/adaptive_retry.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef ADAPTIVERETRY_H #define ADAPTIVERETRY_H diff --git a/gen/c/adaptive_routing.c b/gen/c/adaptive_routing.c index d8c8a50a..bc3f0966 100644 --- a/gen/c/adaptive_routing.c +++ b/gen/c/adaptive_routing.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef ADAPTIVEROUTING_H #define ADAPTIVEROUTING_H diff --git a/gen/c/anomaly_detector.c b/gen/c/anomaly_detector.c index 0a433676..81fa4553 100644 --- a/gen/c/anomaly_detector.c +++ b/gen/c/anomaly_detector.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef ANOMALY_DETECTOR_H #define ANOMALY_DETECTOR_H diff --git a/gen/c/api_documenter.c b/gen/c/api_documenter.c index 8a73a6d1..8bdc6efb 100644 --- a/gen/c/api_documenter.c +++ b/gen/c/api_documenter.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef API_DOCUMENTER_H #define API_DOCUMENTER_H diff --git a/gen/c/area_optimization.c b/gen/c/area_optimization.c index 33c6d9bb..fafbc625 100644 --- a/gen/c/area_optimization.c +++ b/gen/c/area_optimization.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef AREAOPTIMIZATION_H #define AREAOPTIMIZATION_H diff --git a/gen/c/auto_config.c b/gen/c/auto_config.c index 8f586f37..10712df0 100644 --- a/gen/c/auto_config.c +++ b/gen/c/auto_config.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef AUTO_CONFIG_H #define AUTO_CONFIG_H diff --git a/gen/c/bandwidth_allocator.c b/gen/c/bandwidth_allocator.c index a89a681c..cd9dd849 100644 --- a/gen/c/bandwidth_allocator.c +++ b/gen/c/bandwidth_allocator.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef BANDWIDTHALLOCATOR_H #define BANDWIDTHALLOCATOR_H diff --git a/gen/c/byte_utils.c b/gen/c/byte_utils.c index 464c0d35..1ab530c9 100644 --- a/gen/c/byte_utils.c +++ b/gen/c/byte_utils.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef BYTEUTILS_H #define BYTEUTILS_H diff --git a/gen/c/cache_management.c b/gen/c/cache_management.c index 1dd82a7f..154ba42e 100644 --- a/gen/c/cache_management.c +++ b/gen/c/cache_management.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef CACHE_MANAGEMENT_H #define CACHE_MANAGEMENT_H diff --git a/gen/c/compression_engine.c b/gen/c/compression_engine.c index b7e81f7c..c3ecbc62 100644 --- a/gen/c/compression_engine.c +++ b/gen/c/compression_engine.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef COMPRESSION_ENGINE_H #define COMPRESSION_ENGINE_H diff --git a/gen/c/congestion_control.c b/gen/c/congestion_control.c index ef7ef2df..1da8b617 100644 --- a/gen/c/congestion_control.c +++ b/gen/c/congestion_control.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef CONGESTION_CONTROL_H #define CONGESTION_CONTROL_H diff --git a/gen/c/crc16.c b/gen/c/crc16.c index 5842d43e..80dceac5 100644 --- a/gen/c/crc16.c +++ b/gen/c/crc16.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef CRC16CCITT_H #define CRC16CCITT_H diff --git a/gen/c/cross_layer_optimizer.c b/gen/c/cross_layer_optimizer.c index 96064662..fbd51afa 100644 --- a/gen/c/cross_layer_optimizer.c +++ b/gen/c/cross_layer_optimizer.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef CROSSLAYEROPTIMIZER_H #define CROSSLAYEROPTIMIZER_H diff --git a/gen/c/docs_generator.c b/gen/c/docs_generator.c index 8b36ea48..f912df1c 100644 --- a/gen/c/docs_generator.c +++ b/gen/c/docs_generator.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef DOCS_GENERATOR_H #define DOCS_GENERATOR_H diff --git a/gen/c/energy_aware_routing.c b/gen/c/energy_aware_routing.c index 87afe495..c6f11561 100644 --- a/gen/c/energy_aware_routing.c +++ b/gen/c/energy_aware_routing.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef ENERGYAWAREROUTING_H #define ENERGYAWAREROUTING_H diff --git a/gen/c/etx.c b/gen/c/etx.c index 6463f825..77b5d5a7 100644 --- a/gen/c/etx.c +++ b/gen/c/etx.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef MESHETX_H #define MESHETX_H diff --git a/gen/c/failure_predictor.c b/gen/c/failure_predictor.c index 54251507..4c96c198 100644 --- a/gen/c/failure_predictor.c +++ b/gen/c/failure_predictor.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef FAILURE_PREDICTOR_H #define FAILURE_PREDICTOR_H diff --git a/gen/c/fault_detection.c b/gen/c/fault_detection.c index a3fd2c9a..22e4c948 100644 --- a/gen/c/fault_detection.c +++ b/gen/c/fault_detection.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef FAULTDETECTION_H #define FAULTDETECTION_H diff --git a/gen/c/flow_control.c b/gen/c/flow_control.c index 3a28f0df..be7423b9 100644 --- a/gen/c/flow_control.c +++ b/gen/c/flow_control.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef FLOW_CONTROL_H #define FLOW_CONTROL_H diff --git a/gen/c/fpga_synthesis_report.c b/gen/c/fpga_synthesis_report.c index 91b7f826..dc237b64 100644 --- a/gen/c/fpga_synthesis_report.c +++ b/gen/c/fpga_synthesis_report.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef FPGASYNTHESISREPORT_H #define FPGASYNTHESISREPORT_H diff --git a/gen/c/frame_buffer.c b/gen/c/frame_buffer.c index 65c273f0..50c51c72 100644 --- a/gen/c/frame_buffer.c +++ b/gen/c/frame_buffer.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef FRAMEBUFFER_H #define FRAMEBUFFER_H diff --git a/gen/c/hardware_validation.c b/gen/c/hardware_validation.c index c4a0ea45..b0281564 100644 --- a/gen/c/hardware_validation.c +++ b/gen/c/hardware_validation.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef HARDWAREVALIDATION_H #define HARDWAREVALIDATION_H diff --git a/gen/c/health_dashboard.c b/gen/c/health_dashboard.c index 4e1e95b5..0ab91cd6 100644 --- a/gen/c/health_dashboard.c +++ b/gen/c/health_dashboard.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef HEALTH_DASHBOARD_H #define HEALTH_DASHBOARD_H diff --git a/gen/c/health_monitoring.c b/gen/c/health_monitoring.c index 5e617eef..07807614 100644 --- a/gen/c/health_monitoring.c +++ b/gen/c/health_monitoring.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef HEALTHMONITORING_H #define HEALTHMONITORING_H diff --git a/gen/c/hello.c b/gen/c/hello.c index ee9dcf2b..998564ac 100644 --- a/gen/c/hello.c +++ b/gen/c/hello.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef MESHHELLO_H #define MESHHELLO_H diff --git a/gen/c/integration_framework.c b/gen/c/integration_framework.c index 1fe92195..be547dfa 100644 --- a/gen/c/integration_framework.c +++ b/gen/c/integration_framework.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef INTEGRATION_FRAMEWORK_H #define INTEGRATION_FRAMEWORK_H diff --git a/gen/c/integration_tests.c b/gen/c/integration_tests.c index 1d6ea6a6..cf4ec117 100644 --- a/gen/c/integration_tests.c +++ b/gen/c/integration_tests.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef MESHINTEGRATIONTESTS_H #define MESHINTEGRATIONTESTS_H diff --git a/gen/c/key_management.c b/gen/c/key_management.c index 51e41b96..a1618a43 100644 --- a/gen/c/key_management.c +++ b/gen/c/key_management.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef KEYMANAGEMENT_H #define KEYMANAGEMENT_H diff --git a/gen/c/link_quality_monitor.c b/gen/c/link_quality_monitor.c index 55f6afa1..901b4792 100644 --- a/gen/c/link_quality_monitor.c +++ b/gen/c/link_quality_monitor.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef LINKQUALITYMONITOR_H #define LINKQUALITYMONITOR_H diff --git a/gen/c/link_statistics.c b/gen/c/link_statistics.c index e4cb9273..2e21d07e 100644 --- a/gen/c/link_statistics.c +++ b/gen/c/link_statistics.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef LINKSTATISTICS_H #define LINKSTATISTICS_H diff --git a/gen/c/lite_crypto.c b/gen/c/lite_crypto.c index 9a9bd73f..056586fc 100644 --- a/gen/c/lite_crypto.c +++ b/gen/c/lite_crypto.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef LITECRYPTO_H #define LITECRYPTO_H diff --git a/gen/c/load_predictor.c b/gen/c/load_predictor.c index 2c6a98b2..69a7ed3c 100644 --- a/gen/c/load_predictor.c +++ b/gen/c/load_predictor.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef LOAD_PREDICTOR_H #define LOAD_PREDICTOR_H diff --git a/gen/c/local_processing.c b/gen/c/local_processing.c index f883c007..13b8cf54 100644 --- a/gen/c/local_processing.c +++ b/gen/c/local_processing.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef LOCAL_PROCESSING_H #define LOCAL_PROCESSING_H diff --git a/gen/c/m3_multihop.c b/gen/c/m3_multihop.c index 5bc0b3ba..65e4dc82 100644 --- a/gen/c/m3_multihop.c +++ b/gen/c/m3_multihop.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef M3MULTIHOP_H #define M3MULTIHOP_H @@ -26,6 +27,22 @@ #define ATTEN_MIN 0 #define ATTEN_MAX 30 #define IPERF3_HDR_LEN 8 +#define ST_IDLE 0 +#define ST_RUNNING 1 +#define ST_COMPLETE 2 + +/* ------------------------------------------------------- + Structs + ------------------------------------------------------- */ + +typedef struct { + uint32_t packets_sent; + uint32_t packets_delivered; + uint32_t packets_lost; + uint32_t bytes_sent; + uint32_t test_duration_ms; +} PerfCounters; + /* ------------------------------------------------------- Function prototypes @@ -41,6 +58,10 @@ bool simulate_hop(uint8_t attenuation_db, uint8_t packet_seq); bool forward_packet(uint8_t hop1_db, uint8_t hop2_db, uint8_t packet_seq); uint8_t tcp_packet_byte(uint32_t seq, uint8_t byte_index, uint8_t data_byte); uint8_t udp_packet_byte(uint16_t seq, uint8_t byte_index, uint8_t data_byte); +uint32_t calculate_throughput_mbps(PerfCounters counters); +uint8_t calculate_loss_pct(PerfCounters counters); +bool meets_targets(PerfCounters counters, uint8_t hop_count); +uint8_t test_next_state(uint8_t current_state, bool test_complete); /* ------------------------------------------------------- Function implementations @@ -147,6 +168,37 @@ uint8_t udp_packet_byte(uint16_t seq, uint8_t byte_index, uint8_t data_byte) { return 0xBB; } +uint32_t calculate_throughput_mbps(PerfCounters counters) { + uint64_t bits = (((uint64_t)(counters.bytes_sent)) * 8); + uint64_t duration_sec = (((uint64_t)(counters.test_duration_ms)) / 1000); + if ((duration_sec == 0)) { + 0; + } else { + ((uint32_t)(((bits / duration_sec) / 1_000_000))); + } +} + +uint8_t calculate_loss_pct(PerfCounters counters) { + if ((counters.packets_sent == 0)) { + 0; + } else { + uint32_t lost = (counters.packets_sent - counters.packets_delivered); + uint32_t loss_p10 = ((lost * 1000) / counters.packets_sent); + ((uint8_t)((loss_p10 / 10))); + } +} + +bool meets_targets(PerfCounters counters, uint8_t hop_count) { + uint32_t throughput = calculate_throughput_mbps(counters); + uint32_t target_throughput = (TARGET_THROUGHPUT_MBPS * ((uint32_t)(hop_count))); + uint8_t loss_pct = calculate_loss_pct(counters); + ((throughput >= target_throughput) && (loss_pct < TARGET_PACKET_LOSS_PCT)); +} + +uint8_t test_next_state(uint8_t current_state, bool test_complete) { + ; +} + /* ------------------------------------------------------- Tests ------------------------------------------------------- */ @@ -209,14 +261,16 @@ void test_udp_packet_generation(void) { void test_hop_simulation(void) { uint8_t success_count = 0; - for (int i = 0; i < 10; i++) { + /* for-each loop (see t27 source) */ + { if (simulate_hop(0, ((uint8_t)((i * 11))))) { success_count = (success_count + 1); } } t27_assert((success_count > 8), "success_count > 8"); uint8_t success_count_high = 0; - for (int i = 0; i < 10; i++) { + /* for-each loop (see t27 source) */ + { if (simulate_hop(20, ((uint8_t)((i * 11))))) { success_count_high = (success_count_high + 1); } @@ -226,14 +280,16 @@ void test_hop_simulation(void) { void test_two_hop_forwarding(void) { uint8_t success_count = 0; - for (int i = 0; i < 10; i++) { + /* for-each loop (see t27 source) */ + { if (forward_packet(0, 0, ((uint8_t)((i * 11))))) { success_count = (success_count + 1); } } t27_assert((success_count > 7), "success_count > 7"); uint8_t success_count_high = 0; - for (int i = 0; i < 10; i++) { + /* for-each loop (see t27 source) */ + { if (forward_packet(15, 15, ((uint8_t)((i * 11))))) { success_count_high = (success_count_high + 1); } diff --git a/gen/c/mesh_node_sim.c b/gen/c/mesh_node_sim.c index 0d1817cc..6cb39c43 100644 --- a/gen/c/mesh_node_sim.c +++ b/gen/c/mesh_node_sim.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef MESHNODESIM_H #define MESHNODESIM_H diff --git a/gen/c/mesh_protocol_stack.c b/gen/c/mesh_protocol_stack.c index cb46bb6a..96296af5 100644 --- a/gen/c/mesh_protocol_stack.c +++ b/gen/c/mesh_protocol_stack.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef MESHPROTOCOLSTACK_H #define MESHPROTOCOLSTACK_H diff --git a/gen/c/mesh_routing.c b/gen/c/mesh_routing.c index c6b56722..b0f36e46 100644 --- a/gen/c/mesh_routing.c +++ b/gen/c/mesh_routing.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef MESHROUTING_H #define MESHROUTING_H diff --git a/gen/c/multipath_router.c b/gen/c/multipath_router.c index cfef09d4..18f9dd56 100644 --- a/gen/c/multipath_router.c +++ b/gen/c/multipath_router.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef MULTIPATHROUTER_H #define MULTIPATHROUTER_H diff --git a/gen/c/multipath_routing.c b/gen/c/multipath_routing.c index f9ad9c34..b28dee20 100644 --- a/gen/c/multipath_routing.c +++ b/gen/c/multipath_routing.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef MULTIPATH_ROUTING_H #define MULTIPATH_ROUTING_H diff --git a/gen/c/network_analytics.c b/gen/c/network_analytics.c index b99fb3ff..7f43371b 100644 --- a/gen/c/network_analytics.c +++ b/gen/c/network_analytics.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef NETWORKANALYTICS_H #define NETWORKANALYTICS_H diff --git a/gen/c/network_coding.c b/gen/c/network_coding.c index 5ef0c708..c3f41a79 100644 --- a/gen/c/network_coding.c +++ b/gen/c/network_coding.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef NETWORKCODING_H #define NETWORKCODING_H diff --git a/gen/c/network_metrics.c b/gen/c/network_metrics.c index 159a3d1b..93ef72c8 100644 --- a/gen/c/network_metrics.c +++ b/gen/c/network_metrics.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef NETWORKMETRICS_H #define NETWORKMETRICS_H diff --git a/gen/c/network_orchestrator.c b/gen/c/network_orchestrator.c index 53964de0..e4034d6a 100644 --- a/gen/c/network_orchestrator.c +++ b/gen/c/network_orchestrator.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef NETWORK_ORCHESTRATOR_H #define NETWORK_ORCHESTRATOR_H diff --git a/gen/c/network_simulator.c b/gen/c/network_simulator.c index 0f6df73c..56c14a2a 100644 --- a/gen/c/network_simulator.c +++ b/gen/c/network_simulator.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef NETWORK_SIMULATOR_H #define NETWORK_SIMULATOR_H diff --git a/gen/c/olsr_routing.c b/gen/c/olsr_routing.c index 91bac10f..b9d3a0a9 100644 --- a/gen/c/olsr_routing.c +++ b/gen/c/olsr_routing.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef OLSRROUTING_H #define OLSRROUTING_H diff --git a/gen/c/packet_loss_injection.c b/gen/c/packet_loss_injection.c index 049bd621..6c271a43 100644 --- a/gen/c/packet_loss_injection.c +++ b/gen/c/packet_loss_injection.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef PACKETLOSSINJECTION_H #define PACKETLOSSINJECTION_H diff --git a/gen/c/packet_queue.c b/gen/c/packet_queue.c index 46e1ac47..609fa3a2 100644 --- a/gen/c/packet_queue.c +++ b/gen/c/packet_queue.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef PACKETQUEUE_H #define PACKETQUEUE_H diff --git a/gen/c/pattern_predictor.c b/gen/c/pattern_predictor.c index a14a8b0a..3df97a97 100644 --- a/gen/c/pattern_predictor.c +++ b/gen/c/pattern_predictor.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef PATTERN_PREDICTOR_H #define PATTERN_PREDICTOR_H diff --git a/gen/c/performance_benchmarks.c b/gen/c/performance_benchmarks.c index c36a086d..7c52ec7a 100644 --- a/gen/c/performance_benchmarks.c +++ b/gen/c/performance_benchmarks.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef PERFORMANCEBENCHMARKS_H #define PERFORMANCEBENCHMARKS_H diff --git a/gen/c/performance_profiler.c b/gen/c/performance_profiler.c index 60a26042..d9f48f51 100644 --- a/gen/c/performance_profiler.c +++ b/gen/c/performance_profiler.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef PERFORMANCE_PROFILER_H #define PERFORMANCE_PROFILER_H diff --git a/gen/c/power_monitoring.c b/gen/c/power_monitoring.c index 95f78550..ec06ce7b 100644 --- a/gen/c/power_monitoring.c +++ b/gen/c/power_monitoring.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef POWERMONITORING_H #define POWERMONITORING_H diff --git a/gen/c/production_deployment.c b/gen/c/production_deployment.c index 0e713ff5..cf97aaa0 100644 --- a/gen/c/production_deployment.c +++ b/gen/c/production_deployment.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef PRODUCTIONDEPLOYMENT_H #define PRODUCTIONDEPLOYMENT_H diff --git a/gen/c/production_scenarios.c b/gen/c/production_scenarios.c index 8ccbfeef..1fdde00f 100644 --- a/gen/c/production_scenarios.c +++ b/gen/c/production_scenarios.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef PRODUCTIONSCENARIOS_H #define PRODUCTIONSCENARIOS_H diff --git a/gen/c/quarantine_manager.c b/gen/c/quarantine_manager.c index cda2fa8e..8a9ccd76 100644 --- a/gen/c/quarantine_manager.c +++ b/gen/c/quarantine_manager.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef QUARANTINE_MANAGER_H #define QUARANTINE_MANAGER_H diff --git a/gen/c/redundancy_management.c b/gen/c/redundancy_management.c index 75d0622f..be6d62fe 100644 --- a/gen/c/redundancy_management.c +++ b/gen/c/redundancy_management.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef REDUNDANCYMANAGEMENT_H #define REDUNDANCYMANAGEMENT_H diff --git a/gen/c/resource_scheduler.c b/gen/c/resource_scheduler.c index 8ce99684..cea67ee6 100644 --- a/gen/c/resource_scheduler.c +++ b/gen/c/resource_scheduler.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef RESOURCESCHEDULER_H #define RESOURCESCHEDULER_H diff --git a/gen/c/rti_security.c b/gen/c/rti_security.c index 0943fd12..fedb51d9 100644 --- a/gen/c/rti_security.c +++ b/gen/c/rti_security.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef RTISECURITY_H #define RTISECURITY_H @@ -166,16 +167,16 @@ uint8_t notification_priority(uint8_t level) { ------------------------------------------------------- */ /* invariant: max_zones_16 */ -/* _Static_assert(1, "invariant: max_zones_16"); */ +/* invariant max_zones_16 is not a C constant expression: (MAX_ZONES == 16) */ /* invariant: zone_grid_40 */ -/* _Static_assert(1, "invariant: zone_grid_40"); */ +/* invariant zone_grid_40 is not a C constant expression: (ZONE_GRID == 40) */ /* invariant: alert_cooldown_5000 */ -/* _Static_assert(1, "invariant: alert_cooldown_5000"); */ +/* invariant alert_cooldown_5000 is not a C constant expression: (ALERT_COOLDOWN_MS == 5000) */ /* invariant: alert_entry_8 */ -/* _Static_assert(1, "invariant: alert_entry_8"); */ +/* invariant alert_entry_8 is not a C constant expression: (ALERT_ENTRY_SIZE == 8) */ /* ------------------------------------------------------- diff --git a/gen/c/self_healing.c b/gen/c/self_healing.c index 81e6e8f0..5b72fa71 100644 --- a/gen/c/self_healing.c +++ b/gen/c/self_healing.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef SELFHEALING_H #define SELFHEALING_H diff --git a/gen/c/swarm_coordinator.c b/gen/c/swarm_coordinator.c index 81a398e0..5c7f97e6 100644 --- a/gen/c/swarm_coordinator.c +++ b/gen/c/swarm_coordinator.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef SWARMCOORDINATOR_H #define SWARMCOORDINATOR_H diff --git a/gen/c/test_framework.c b/gen/c/test_framework.c index c308712d..c7c916e9 100644 --- a/gen/c/test_framework.c +++ b/gen/c/test_framework.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef TEST_FRAMEWORK_H #define TEST_FRAMEWORK_H diff --git a/gen/c/test_validator.c b/gen/c/test_validator.c index d4754a50..98fd3449 100644 --- a/gen/c/test_validator.c +++ b/gen/c/test_validator.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef TEST_VALIDATOR_H #define TEST_VALIDATOR_H diff --git a/gen/c/timer.c b/gen/c/timer.c index 82079d28..0d31f38f 100644 --- a/gen/c/timer.c +++ b/gen/c/timer.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef MESHTIMER_H #define MESHTIMER_H diff --git a/gen/c/timing_closure.c b/gen/c/timing_closure.c index 30f83e3a..04993633 100644 --- a/gen/c/timing_closure.c +++ b/gen/c/timing_closure.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef TIMINGCLOSURE_H #define TIMINGCLOSURE_H diff --git a/gen/c/topology_visualizer.c b/gen/c/topology_visualizer.c index 5abde5e3..cc0b849f 100644 --- a/gen/c/topology_visualizer.c +++ b/gen/c/topology_visualizer.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef TOPOLOGY_VISUALIZER_H #define TOPOLOGY_VISUALIZER_H diff --git a/gen/c/traffic_animator.c b/gen/c/traffic_animator.c index ad0b8c22..9eef7691 100644 --- a/gen/c/traffic_animator.c +++ b/gen/c/traffic_animator.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef TRAFFIC_ANIMATOR_H #define TRAFFIC_ANIMATOR_H diff --git a/gen/c/transport_tx_fsm.c b/gen/c/transport_tx_fsm.c index 46c5b964..bb7e1848 100644 --- a/gen/c/transport_tx_fsm.c +++ b/gen/c/transport_tx_fsm.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef TRANSPORTTXFSM_H #define TRANSPORTTXFSM_H diff --git a/gen/c/tri_challenge.c b/gen/c/tri_challenge.c index f316873a..f2b2adb2 100644 --- a/gen/c/tri_challenge.c +++ b/gen/c/tri_challenge.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef TRICHALLENGE_H #define TRICHALLENGE_H diff --git a/gen/c/tri_compute_account.c b/gen/c/tri_compute_account.c index 7c67ab80..d1c49735 100644 --- a/gen/c/tri_compute_account.c +++ b/gen/c/tri_compute_account.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef TRICOMPUTEACCOUNT_H #define TRICOMPUTEACCOUNT_H diff --git a/gen/c/tri_compute_bond.c b/gen/c/tri_compute_bond.c index 692f5562..f957829b 100644 --- a/gen/c/tri_compute_bond.c +++ b/gen/c/tri_compute_bond.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef TRICOMPUTEBOND_H #define TRICOMPUTEBOND_H diff --git a/gen/c/tri_compute_pool.c b/gen/c/tri_compute_pool.c index f6dce50b..e4248b03 100644 --- a/gen/c/tri_compute_pool.c +++ b/gen/c/tri_compute_pool.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef TRICOMPUTEPOOL_H #define TRICOMPUTEPOOL_H diff --git a/gen/c/tri_settle.c b/gen/c/tri_settle.c index 7ab35b8c..0438262b 100644 --- a/gen/c/tri_settle.c +++ b/gen/c/tri_settle.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef TRISETTLE_H #define TRISETTLE_H diff --git a/gen/c/trust_manager.c b/gen/c/trust_manager.c index fafc3b6c..4ffee3c4 100644 --- a/gen/c/trust_manager.c +++ b/gen/c/trust_manager.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef TRUST_MANAGER_H #define TRUST_MANAGER_H diff --git a/gen/c/twr_timestamp.c b/gen/c/twr_timestamp.c index af0d0b0e..7ecb6f46 100644 --- a/gen/c/twr_timestamp.c +++ b/gen/c/twr_timestamp.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef TWRTIMESTAMP_H #define TWRTIMESTAMP_H diff --git a/gen/c/wire.c b/gen/c/wire.c index b1d04a53..2d6f86a6 100644 --- a/gen/c/wire.c +++ b/gen/c/wire.c @@ -9,6 +9,7 @@ #include #include #define t27_assert(c, m) do { if (!(c)) { __builtin_trap(); } } while (0) +#define assert_eq(a, b) do { if ((a) != (b)) { __builtin_trap(); } } while (0) #ifndef MESHWIRE_H #define MESHWIRE_H @@ -83,10 +84,10 @@ bool parse_accepts(uint8_t b0, uint8_t b1) { ------------------------------------------------------- */ /* invariant: header_is_11_bytes */ -/* _Static_assert(1, "invariant: header_is_11_bytes"); */ +/* invariant header_is_11_bytes is not a C constant expression: (HEADER_LEN == 11) */ /* invariant: kinds_distinct */ -/* _Static_assert(1, "invariant: kinds_distinct"); */ +/* invariant kinds_distinct is not a C constant expression: (KIND_HELLO != KIND_DATA) */ /* ------------------------------------------------------- @@ -94,35 +95,49 @@ bool parse_accepts(uint8_t b0, uint8_t b1) { ------------------------------------------------------- */ void test_byte0_is_version(void) { - /* TODO: implement test */ + int b = header_byte(KIND_DATA, 16909060, 168496141, 8, 0); + assert((b == 1)); } void test_byte1_is_kind(void) { - /* TODO: implement test */ + int b = header_byte(KIND_DATA, 16909060, 168496141, 8, 1); + assert((b == 1)); } void test_src_be_first_and_last_byte(void) { - /* TODO: implement test */ + int b2 = header_byte(KIND_DATA, 16909060, 168496141, 8, 2); + int b5 = header_byte(KIND_DATA, 16909060, 168496141, 8, 5); + assert((b2 == 1)); + assert((b5 == 4)); } void test_ttl_is_last_byte(void) { - /* TODO: implement test */ + int b = header_byte(KIND_HELLO, 1, 2, 4, 10); + assert((b == 4)); } void test_src_roundtrips_through_bytes(void) { - /* TODO: implement test */ + int b2 = header_byte(KIND_DATA, 16909060, 168496141, 8, 2); + int b3 = header_byte(KIND_DATA, 16909060, 168496141, 8, 3); + int b4 = header_byte(KIND_DATA, 16909060, 168496141, 8, 4); + int b5 = header_byte(KIND_DATA, 16909060, 168496141, 8, 5); + int w = u32_be(b2, b3, b4, b5); + assert((w == 16909060)); } void test_parse_accepts_valid(void) { - /* TODO: implement test */ + int ok = parse_accepts(1, KIND_DATA); + assert((ok == true)); } void test_parse_rejects_bad_version(void) { - /* TODO: implement test */ + int ok = parse_accepts(99, KIND_DATA); + assert((ok == false)); } void test_parse_rejects_bad_kind(void) { - /* TODO: implement test */ + int ok = parse_accepts(1, 2); + assert((ok == false)); } diff --git a/gen/rust/access_control.rs b/gen/rust/access_control.rs index 3672e5ba..db5d5e91 100644 --- a/gen/rust/access_control.rs +++ b/gen/rust/access_control.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 16 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_NODES: u32 = 8; @@ -16,7 +19,8 @@ pub const PERMIT: u32 = 1; pub const DENY: u32 = 0; pub fn create_node_creds(node_id: u32, role: u32, auth_token: u32, authorized: u32) -> u32 { - return (((((node_id & 0xFF) << 24) | ((role & 0x3) << 22)) | ((auth_token & 0x3FF) << 12)) | ((authorized & 0x1) << 11)); + return (((((node_id & 0xFF) << 24) | ((role & 0x3) << 22)) | ((auth_token & 0x3FF) << 12)) + | ((authorized & 0x1) << 11)); } pub fn get_node_id(creds: u32) -> u32 { @@ -35,8 +39,17 @@ pub fn is_authorized(creds: u32) -> u32 { return ((creds >> 11) & 0x1); } -pub fn create_policy(resource: u32, min_role: u32, guest_perm: u32, user_perm: u32, admin_perm: u32) -> u32 { - return ((((((resource & 0xF) << 28) | ((min_role & 0x3) << 26)) | ((guest_perm & 0x1) << 25)) | ((user_perm & 0x1) << 24)) | ((admin_perm & 0x1) << 23)); +pub fn create_policy( + resource: u32, + min_role: u32, + guest_perm: u32, + user_perm: u32, + admin_perm: u32, +) -> u32 { + return ((((((resource & 0xF) << 28) | ((min_role & 0x3) << 26)) + | ((guest_perm & 0x1) << 25)) + | ((user_perm & 0x1) << 24)) + | ((admin_perm & 0x1) << 23)); } pub fn get_resource(policy: u32) -> u32 { @@ -117,4 +130,3 @@ pub fn check_resource_access(creds: u32, policy: u32, provided_token: u32) -> u3 let role = get_role(creds); return check_access(policy, role); } - diff --git a/gen/rust/adaptive_retry.rs b/gen/rust/adaptive_retry.rs index 19d4264f..2d75b6a1 100644 --- a/gen/rust/adaptive_retry.rs +++ b/gen/rust/adaptive_retry.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 5 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const BASE_DELAY_MS: u8 = 10; @@ -66,4 +69,3 @@ pub fn total_retry_time(max_retries: u8) -> u16 { } return (backoff_delay_ms((max_retries - 1)) + total_retry_time((max_retries - 1))); } - diff --git a/gen/rust/adaptive_routing.rs b/gen/rust/adaptive_routing.rs index eab19414..00208b31 100644 --- a/gen/rust/adaptive_routing.rs +++ b/gen/rust/adaptive_routing.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 15 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_PATHS: u32 = 4; diff --git a/gen/rust/anomaly_detector.rs b/gen/rust/anomaly_detector.rs index 9a93b433..cd40b775 100644 --- a/gen/rust/anomaly_detector.rs +++ b/gen/rust/anomaly_detector.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 5 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_METRICS: u32 = 16; diff --git a/gen/rust/api_documenter.rs b/gen/rust/api_documenter.rs index b4d96247..d7c67b38 100644 --- a/gen/rust/api_documenter.rs +++ b/gen/rust/api_documenter.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 2 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_FUNCTIONS: u32 = 64; @@ -9,8 +12,15 @@ pub const MAX_EXAMPLES: u32 = 8; pub const MAX_DESCRIPTIONS: u32 = 32; -pub fn create_function_doc(func_id: u32, param_count: u32, return_type: u32, complexity: u32) -> u32 { - return (((((func_id & 0xFF) << 24) | ((param_count & 0xF) << 20)) | ((return_type & 0xF) << 16)) | (complexity & 0xFFFF)); +pub fn create_function_doc( + func_id: u32, + param_count: u32, + return_type: u32, + complexity: u32, +) -> u32 { + return (((((func_id & 0xFF) << 24) | ((param_count & 0xF) << 20)) + | ((return_type & 0xF) << 16)) + | (complexity & 0xFFFF)); } pub fn get_doc_function_id(doc: u32) -> u32 { @@ -30,7 +40,9 @@ pub fn get_doc_complexity(doc: u32) -> u32 { } pub fn create_param_doc(param_id: u32, param_type: u32, direction: u32, desc_id: u32) -> u32 { - return (((((param_id & 0xFF) << 24) | ((param_type & 0xF) << 20)) | ((direction & 0x3) << 18)) | (desc_id & 0x3FFFF)); + return (((((param_id & 0xFF) << 24) | ((param_type & 0xF) << 20)) + | ((direction & 0x3) << 18)) + | (desc_id & 0x3FFFF)); } pub fn get_param_doc_id(param_doc: u32) -> u32 { @@ -70,7 +82,8 @@ pub fn extract_parameter_info(param_line: u32, param_index: u32) -> u32 { } pub fn create_function_example(func_id: u32, input: u32, output: u32, explanation: u32) -> u32 { - return (((((func_id & 0xFF) << 24) | ((input & 0xFF) << 16)) | ((output & 0xFF) << 8)) | (explanation & 0xFF)); + return (((((func_id & 0xFF) << 24) | ((input & 0xFF) << 16)) | ((output & 0xFF) << 8)) + | (explanation & 0xFF)); } pub fn get_example_function_id(example: u32) -> u32 { @@ -100,7 +113,8 @@ pub fn generate_function_example(func_doc: u32) -> u32 { } pub fn create_description_text(desc_id: u32, length: u32, importance: u32, category: u32) -> u32 { - return (((((desc_id & 0xFF) << 24) | ((length & 0xFF) << 16)) | ((importance & 0xF) << 12)) | (category & 0xFFF)); + return (((((desc_id & 0xFF) << 24) | ((length & 0xFF) << 16)) | ((importance & 0xF) << 12)) + | (category & 0xFFF)); } pub fn get_description_id(desc: u32) -> u32 { @@ -133,7 +147,8 @@ pub fn generate_function_description(func_doc: u32, complexity: u32) -> u32 { } pub fn create_cross_reference(source: u32, target: u32, ref_type: u32, strength: u32) -> u32 { - return (((((source & 0xFF) << 24) | ((target & 0xFF) << 16)) | ((ref_type & 0xF) << 12)) | (strength & 0xFFF)); + return (((((source & 0xFF) << 24) | ((target & 0xFF) << 16)) | ((ref_type & 0xF) << 12)) + | (strength & 0xFFF)); } pub fn get_xref_source(xref: u32) -> u32 { @@ -164,8 +179,15 @@ pub fn detect_function_call(caller: u32, callee: u32) -> u32 { return create_cross_reference(caller, callee, XREF_CALLS, 100); } -pub fn create_module_doc(module_id: u32, func_count: u32, total_complexity: u32, description: u32) -> u32 { - return (((((module_id & 0xFF) << 24) | ((func_count & 0xFF) << 16)) | ((total_complexity & 0xFF) << 8)) | (description & 0xFF)); +pub fn create_module_doc( + module_id: u32, + func_count: u32, + total_complexity: u32, + description: u32, +) -> u32 { + return (((((module_id & 0xFF) << 24) | ((func_count & 0xFF) << 16)) + | ((total_complexity & 0xFF) << 8)) + | (description & 0xFF)); } pub fn get_module_doc_id(module_doc: u32) -> u32 { @@ -184,7 +206,10 @@ pub fn get_module_description(module_doc: u32) -> u32 { return (module_doc & 0xFF); } -pub fn calculate_average_complexity(func_docs: [u32; MAX_FUNCTIONS as usize], func_count: u32) -> u32 { +pub fn calculate_average_complexity( + func_docs: [u32; MAX_FUNCTIONS as usize], + func_count: u32, +) -> u32 { let mut total_complexity: u32 = 0; let mut i: u32 = 0; while (i < func_count) { @@ -198,20 +223,28 @@ pub fn calculate_average_complexity(func_docs: [u32; MAX_FUNCTIONS as usize], fu } } -pub fn generate_api_documentation(func_docs: [u32; MAX_FUNCTIONS as usize], func_count: u32, param_docs: [u32; MAX_PARAMETERS as usize], param_count: u32) -> u32 { +pub fn generate_api_documentation( + func_docs: [u32; MAX_FUNCTIONS as usize], + func_count: u32, + param_docs: [u32; MAX_PARAMETERS as usize], + param_count: u32, +) -> u32 { let mut total_complexity: u32 = 0; let mut documented_funcs: u32 = 0; let mut i: u32 = 0; while (i < func_count) { let func_doc: u32 = func_docs[(i) as usize]; total_complexity = (total_complexity + get_doc_complexity(func_doc)); - let description: u32 = generate_function_description(func_doc, get_doc_complexity(func_doc)); + let description: u32 = + generate_function_description(func_doc, get_doc_complexity(func_doc)); let example: u32 = generate_function_example(func_doc); documented_funcs = (documented_funcs + 1); i = (i + 1); } let avg_complexity: u32 = calculate_average_complexity(func_docs, func_count); - return (((((documented_funcs & 0xFF) << 24) | ((total_complexity & 0xFF) << 16)) | ((avg_complexity & 0xFF) << 8)) | (param_count & 0xFF)); + return (((((documented_funcs & 0xFF) << 24) | ((total_complexity & 0xFF) << 16)) + | ((avg_complexity & 0xFF) << 8)) + | (param_count & 0xFF)); } pub fn calculate_documentation_coverage(documented_funcs: u32, total_funcs: u32) -> u32 { @@ -245,7 +278,9 @@ pub fn create_dependency_graph(xrefs: [u32; MAX_FUNCTIONS as usize], xref_count: if (total_connections > 0) { avg_strength = (strong_connections / total_connections); } - return (((((total_connections & 0xFF) << 24) | ((strong_connections & 0xFF) << 16)) | ((avg_strength & 0xFF) << 8)) | (xref_count & 0xFF)); + return (((((total_connections & 0xFF) << 24) | ((strong_connections & 0xFF) << 16)) + | ((avg_strength & 0xFF) << 8)) + | (xref_count & 0xFF)); } pub fn validate_documentation(func_docs: [u32; MAX_FUNCTIONS as usize], func_count: u32) -> u32 { @@ -269,10 +304,17 @@ pub fn validate_documentation(func_docs: [u32; MAX_FUNCTIONS as usize], func_cou if (quality_score > 100) { quality_score = 100; } - return (((((missing_descriptions & 0xFF) << 24) | ((missing_examples & 0xFF) << 16)) | ((missing_params & 0xFF) << 8)) | (quality_score & 0xFF)); + return (((((missing_descriptions & 0xFF) << 24) | ((missing_examples & 0xFF) << 16)) + | ((missing_params & 0xFF) << 8)) + | (quality_score & 0xFF)); } -pub fn generate_documentation_report(func_docs: [u32; MAX_FUNCTIONS as usize], func_count: u32, xrefs: [u32; MAX_FUNCTIONS as usize], xref_count: u32) -> u32 { +pub fn generate_documentation_report( + func_docs: [u32; MAX_FUNCTIONS as usize], + func_count: u32, + xrefs: [u32; MAX_FUNCTIONS as usize], + xref_count: u32, +) -> u32 { let empty_params: [u32; MAX_PARAMETERS as usize] = [0; MAX_PARAMETERS]; let doc_summary: u32 = generate_api_documentation(func_docs, func_count, empty_params, 0); let documented_funcs: u32 = ((doc_summary >> 24) & 0xFF); @@ -281,6 +323,7 @@ pub fn generate_documentation_report(func_docs: [u32; MAX_FUNCTIONS as usize], f let quality_score: u32 = (validation & 0xFF); let dependency_graph: u32 = create_dependency_graph(xrefs, xref_count); let doc_complexity: u32 = ((doc_summary >> 8) & 0xFF); - return (((((coverage & 0xFF) << 24) | ((quality_score & 0xFF) << 16)) | ((doc_complexity & 0xFF) << 8)) | (xref_count & 0xFF)); + return (((((coverage & 0xFF) << 24) | ((quality_score & 0xFF) << 16)) + | ((doc_complexity & 0xFF) << 8)) + | (xref_count & 0xFF)); } - diff --git a/gen/rust/area_optimization.rs b/gen/rust/area_optimization.rs index 25a21061..01ecd9ee 100644 --- a/gen/rust/area_optimization.rs +++ b/gen/rust/area_optimization.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 22 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const OPT_NONE: u32 = 0; @@ -22,7 +25,11 @@ pub fn calculate_sharing_savings(original_count: u32, share_factor: u32) -> u32 return (original_count - (original_count / share_factor)); } -pub fn calculate_bitwidth_savings(original_width: u32, reduced_width: u32, instance_count: u32) -> u32 { +pub fn calculate_bitwidth_savings( + original_width: u32, + reduced_width: u32, + instance_count: u32, +) -> u32 { if (original_width <= reduced_width) { return 0; } @@ -76,7 +83,8 @@ pub fn calculate_savings_percentage(original: u32, optimized: u32) -> u8 { } pub fn optimization_worthwhile(result: u32) -> bool { - return (calculate_savings_percentage(extract_original(result), extract_optimized(result)) > 10); + return (calculate_savings_percentage(extract_original(result), extract_optimized(result)) + > 10); } pub fn analyze_bit_width(min_val: u32, max_val: u32) -> u8 { @@ -101,4 +109,3 @@ pub fn analyze_bit_width(min_val: u32, max_val: u32) -> u8 { } } } - diff --git a/gen/rust/auto_config.rs b/gen/rust/auto_config.rs index d09171cb..83d09e69 100644 --- a/gen/rust/auto_config.rs +++ b/gen/rust/auto_config.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 4 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_NODES: u32 = 8; @@ -10,7 +13,8 @@ pub const CONFIG_VERSION: u32 = 1; pub const AUTO_DISCOVERY_INTERVAL: u32 = 1000; pub fn create_config_param(param_id: u32, value: u32, scope: u32, status: u32) -> u32 { - return (((((param_id & 0xFF) << 24) | ((value & 0xFFFF) << 8)) | ((scope & 0xF) << 4)) | (status & 0xF)); + return (((((param_id & 0xFF) << 24) | ((value & 0xFFFF) << 8)) | ((scope & 0xF) << 4)) + | (status & 0xF)); } pub fn get_param_id(param: u32) -> u32 { @@ -117,7 +121,24 @@ pub fn set_config_value(config: [u32; MAX_PARAMS as usize], param_id: u32, new_v } pub fn discover_network_params(node_count: u32, interference_level: u32) -> u32 { - let config: [u32; MAX_PARAMS as usize] = [default_config_at(0),default_config_at(1),default_config_at(2),default_config_at(3),default_config_at(4),default_config_at(5),default_config_at(6),default_config_at(7),0,0,0,0,0,0,0,0]; + let config: [u32; MAX_PARAMS as usize] = [ + default_config_at(0), + default_config_at(1), + default_config_at(2), + default_config_at(3), + default_config_at(4), + default_config_at(5), + default_config_at(6), + default_config_at(7), + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ]; let mut tx_power: u32 = 50; if (node_count < 4) { tx_power = 30; @@ -232,7 +253,11 @@ pub fn validate_config(config: [u32; MAX_PARAMS as usize], param_id: u32) -> u32 return 0; } -pub fn optimize_config(config: [u32; MAX_PARAMS as usize], network_load: u32, error_rate: u32) -> u32 { +pub fn optimize_config( + config: [u32; MAX_PARAMS as usize], + network_load: u32, + error_rate: u32, +) -> u32 { let mut optimizations: u32 = 0; if (network_load > 80) { let current_retries: u32 = get_config_value(config, PARAM_RETRY_LIMIT); @@ -258,7 +283,10 @@ pub fn optimize_config(config: [u32; MAX_PARAMS as usize], network_load: u32, er return optimizations; } -pub fn sync_config(local_config: [u32; MAX_PARAMS as usize], remote_config: [u32; MAX_PARAMS as usize]) -> u32 { +pub fn sync_config( + local_config: [u32; MAX_PARAMS as usize], + remote_config: [u32; MAX_PARAMS as usize], +) -> u32 { let mut synced_count: u32 = 0; let mut i: u32 = 0; while (i < MAX_PARAMS) { @@ -286,7 +314,10 @@ pub fn sync_config(local_config: [u32; MAX_PARAMS as usize], remote_config: [u32 return synced_count; } -pub fn rollback_config(config: [u32; MAX_PARAMS as usize], backup_config: [u32; MAX_PARAMS as usize]) -> u32 { +pub fn rollback_config( + config: [u32; MAX_PARAMS as usize], + backup_config: [u32; MAX_PARAMS as usize], +) -> u32 { let mut rolled_back: u32 = 0; let mut i: u32 = 0; while (i < MAX_PARAMS) { @@ -297,7 +328,12 @@ pub fn rollback_config(config: [u32; MAX_PARAMS as usize], backup_config: [u32; while (j < MAX_PARAMS) { let local_param_id: u32 = get_param_id(config[(j) as usize]); if (local_param_id == backup_param_id) { - config[(j) as usize] = create_config_param(backup_param_id, backup_value, backup_scope, STATUS_PENDING); + config[(j) as usize] = create_config_param( + backup_param_id, + backup_value, + backup_scope, + STATUS_PENDING, + ); rolled_back = (rolled_back + 1); break; } @@ -309,10 +345,13 @@ pub fn rollback_config(config: [u32; MAX_PARAMS as usize], backup_config: [u32; } pub fn backup_element(config: [u32; MAX_PARAMS as usize], index: u32) -> u32 { - return config[((index as usize)) as usize]; + return config[(index as usize) as usize]; } -pub fn calculate_config_drift(config1: [u32; MAX_PARAMS as usize], config2: [u32; MAX_PARAMS as usize]) -> u32 { +pub fn calculate_config_drift( + config1: [u32; MAX_PARAMS as usize], + config2: [u32; MAX_PARAMS as usize], +) -> u32 { let mut drift_count: u32 = 0; let mut total_params: u32 = 0; let mut i: u32 = 0; @@ -366,4 +405,3 @@ pub fn assign_node_role(node_id: u32, capabilities: u32) -> u32 { } return role; } - diff --git a/gen/rust/bandwidth_allocator.rs b/gen/rust/bandwidth_allocator.rs index 6e0fa734..48ea3f1e 100644 --- a/gen/rust/bandwidth_allocator.rs +++ b/gen/rust/bandwidth_allocator.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 16 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_FLOWS: u32 = 8; @@ -16,7 +19,8 @@ pub const PRIORITY_MEDIUM: u32 = 2; pub const PRIORITY_HIGH: u32 = 3; pub fn create_flow_requirement(flow_id: u32, priority: u32, min_bw: u32, current_bw: u32) -> u32 { - return (((((flow_id & 0xFF) << 24) | ((priority & 0x3) << 22)) | ((min_bw & 0x3FF) << 12)) | (current_bw & 0xFFF)); + return (((((flow_id & 0xFF) << 24) | ((priority & 0x3) << 22)) | ((min_bw & 0x3FF) << 12)) + | (current_bw & 0xFFF)); } pub fn get_flow_id(req: u32) -> u32 { @@ -35,8 +39,15 @@ pub fn get_current_bandwidth(req: u32) -> u32 { return (req & 0xFFF); } -pub fn create_allocation_state(allocated: u32, pending: u32, fair_share: u32, last_update: u32) -> u32 { - return (((((allocated & 0x7FF) << 21) | ((pending & 0xFF) << 13)) | ((fair_share & 0x1FF) << 4)) | (last_update & 0xF)); +pub fn create_allocation_state( + allocated: u32, + pending: u32, + fair_share: u32, + last_update: u32, +) -> u32 { + return (((((allocated & 0x7FF) << 21) | ((pending & 0xFF) << 13)) + | ((fair_share & 0x1FF) << 4)) + | (last_update & 0xF)); } pub fn get_allocated_bw(state: u32) -> u32 { @@ -55,8 +66,17 @@ pub fn get_last_update(state: u32) -> u32 { return (state & 0xF); } -pub fn create_flow_array(f0: u32, f1: u32, f2: u32, f3: u32, f4: u32, f5: u32, f6: u32, f7: u32) -> [u32; 8] { - return [f0,f1,f2,f3,f4,f5,f6,f7]; +pub fn create_flow_array( + f0: u32, + f1: u32, + f2: u32, + f3: u32, + f4: u32, + f5: u32, + f6: u32, + f7: u32, +) -> [u32; 8] { + return [f0, f1, f2, f3, f4, f5, f6, f7]; } pub fn get_flow_req(array: [u32; 8], index: u32) -> u32 { @@ -194,6 +214,14 @@ pub fn prioritize_bandwidth(flow_array: [u32; 8], available_bw: u32) -> [u32; 8] let f5 = get_flow_req(flow_array, 5); let f6 = get_flow_req(flow_array, 6); let f7 = get_flow_req(flow_array, 7); - return create_flow_array(update_flow_bandwidth(f0, calculate_fair_share(remaining_bw, 8)), update_flow_bandwidth(f1, calculate_fair_share(remaining_bw, 8)), update_flow_bandwidth(f2, calculate_fair_share(remaining_bw, 8)), update_flow_bandwidth(f3, calculate_fair_share(remaining_bw, 8)), update_flow_bandwidth(f4, calculate_fair_share(remaining_bw, 8)), update_flow_bandwidth(f5, calculate_fair_share(remaining_bw, 8)), update_flow_bandwidth(f6, calculate_fair_share(remaining_bw, 8)), update_flow_bandwidth(f7, calculate_fair_share(remaining_bw, 8))); + return create_flow_array( + update_flow_bandwidth(f0, calculate_fair_share(remaining_bw, 8)), + update_flow_bandwidth(f1, calculate_fair_share(remaining_bw, 8)), + update_flow_bandwidth(f2, calculate_fair_share(remaining_bw, 8)), + update_flow_bandwidth(f3, calculate_fair_share(remaining_bw, 8)), + update_flow_bandwidth(f4, calculate_fair_share(remaining_bw, 8)), + update_flow_bandwidth(f5, calculate_fair_share(remaining_bw, 8)), + update_flow_bandwidth(f6, calculate_fair_share(remaining_bw, 8)), + update_flow_bandwidth(f7, calculate_fair_share(remaining_bw, 8)), + ); } - diff --git a/gen/rust/byte_utils.rs b/gen/rust/byte_utils.rs index 25544466..0bc18786 100644 --- a/gen/rust/byte_utils.rs +++ b/gen/rust/byte_utils.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 6 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub fn get_bit(byte: u8, i: usize) -> u8 { if (i == 0) { @@ -48,4 +51,3 @@ pub fn combine_nibbles(high: u8, low: u8) -> u8 { pub fn swap_nibbles(byte: u8) -> u8 { return (((byte & 0x0F) << 4) | ((byte >> 4) & 0x0F)); } - diff --git a/gen/rust/cache_management.rs b/gen/rust/cache_management.rs index ae28d10a..9850f7c4 100644 --- a/gen/rust/cache_management.rs +++ b/gen/rust/cache_management.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 4 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_ENTRIES: u32 = 16; @@ -10,7 +13,8 @@ pub const CACHE_HIT_THRESHOLD: u32 = 2; pub const EVICTION_AGE: u32 = 1000; pub fn create_cache_entry(data_id: u32, access_count: u32, age: u32, size: u32) -> u32 { - return (((((data_id & 0xFF) << 24) | ((access_count & 0xFF) << 16)) | ((age & 0xFF) << 8)) | (size & 0xFF)); + return (((((data_id & 0xFF) << 24) | ((access_count & 0xFF) << 16)) | ((age & 0xFF) << 8)) + | (size & 0xFF)); } pub fn get_data_id(entry: u32) -> u32 { @@ -77,7 +81,12 @@ pub fn get_entry(cache: [u32; MAX_ENTRIES as usize], data_id: u32) -> u32 { } } -pub fn add_entry(cache: [u32; MAX_ENTRIES as usize], current_size: u32, data_id: u32, size: u32) -> u32 { +pub fn add_entry( + cache: [u32; MAX_ENTRIES as usize], + current_size: u32, + data_id: u32, + size: u32, +) -> u32 { let existing_index: u32 = find_entry(cache, data_id); if (existing_index < MAX_ENTRIES) { return current_size; @@ -231,7 +240,8 @@ pub fn calculate_efficiency(hits: u32, total_accesses: u32, current_size: u32) - } pub fn create_cache_stats(hits: u32, misses: u32, size: u32, evictions: u32) -> u32 { - return (((((hits & 0xFF) << 24) | ((misses & 0xFF) << 16)) | ((size & 0xFF) << 8)) | (evictions & 0xFF)); + return (((((hits & 0xFF) << 24) | ((misses & 0xFF) << 16)) | ((size & 0xFF) << 8)) + | (evictions & 0xFF)); } pub fn get_hits(stats: u32) -> u32 { @@ -265,4 +275,3 @@ pub fn update_stats(stats: u32, hit: u32, evicted: u32) -> u32 { } return create_cache_stats(hits, misses, size, evictions); } - diff --git a/gen/rust/compression_engine.rs b/gen/rust/compression_engine.rs index d63688a3..1876ce1a 100644 --- a/gen/rust/compression_engine.rs +++ b/gen/rust/compression_engine.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 3 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_BLOCKS: u32 = 16; @@ -10,7 +13,8 @@ pub const COMPRESSION_THRESHOLD: u32 = 8; pub const DICTIONARY_SIZE: u32 = 8; pub fn create_block_info(orig_size: u32, comp_size: u32, method: u32, quality: u32) -> u32 { - return (((((orig_size & 0xFF) << 24) | ((comp_size & 0xFF) << 16)) | ((method & 0x3) << 14)) | (quality & 0x3FFF)); + return (((((orig_size & 0xFF) << 24) | ((comp_size & 0xFF) << 16)) | ((method & 0x3) << 14)) + | (quality & 0x3FFF)); } pub fn get_original_size(info: u32) -> u32 { @@ -162,7 +166,11 @@ pub fn decompress_delta(encoded: u32, previous: u32) -> u32 { } } -pub fn choose_compression_method(data: u32, previous: u32, dictionary: [u32; DICTIONARY_SIZE as usize]) -> u32 { +pub fn choose_compression_method( + data: u32, + previous: u32, + dictionary: [u32; DICTIONARY_SIZE as usize], +) -> u32 { let data_nibbles: u32 = 8; let rle_compressed: u32 = compress_rle(data, data_nibbles); let rle_ratio: u32 = calculate_compression_ratio(data_nibbles, rle_compressed); @@ -189,7 +197,11 @@ pub fn choose_compression_method(data: u32, previous: u32, dictionary: [u32; DIC } } -pub fn compress_block(data: u32, previous: u32, dictionary: [u32; DICTIONARY_SIZE as usize]) -> u32 { +pub fn compress_block( + data: u32, + previous: u32, + dictionary: [u32; DICTIONARY_SIZE as usize], +) -> u32 { let method: u32 = choose_compression_method(data, previous, dictionary); let mut compressed: u32 = 0; let mut compressed_size: u32 = 8; @@ -216,7 +228,12 @@ pub fn compress_block(data: u32, previous: u32, dictionary: [u32; DICTIONARY_SIZ return create_block_info(8, compressed_size, method, compressed_size); } -pub fn decompress_block(compressed_data: u32, method: u32, previous: u32, dictionary: [u32; DICTIONARY_SIZE as usize]) -> u32 { +pub fn decompress_block( + compressed_data: u32, + method: u32, + previous: u32, + dictionary: [u32; DICTIONARY_SIZE as usize], +) -> u32 { if (method == METHOD_RLE) { return decompress_rle(compressed_data); } else { @@ -248,7 +265,11 @@ pub fn calculate_total_savings(blocks: [u32; MAX_BLOCKS as usize], count: u32) - } } -pub fn update_dictionary(dictionary: [u32; DICTIONARY_SIZE as usize], new_entry: u32, index: u32) -> u32 { +pub fn update_dictionary( + dictionary: [u32; DICTIONARY_SIZE as usize], + new_entry: u32, + index: u32, +) -> u32 { if (index < DICTIONARY_SIZE) { dictionary[(index) as usize] = new_entry; return 1; @@ -277,4 +298,3 @@ pub fn calculate_compression_speed(original_size: u32, compressed_size: u32, tim return 0; } } - diff --git a/gen/rust/congestion_control.rs b/gen/rust/congestion_control.rs index 2a05b9d4..a452ae56 100644 --- a/gen/rust/congestion_control.rs +++ b/gen/rust/congestion_control.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 3 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_FLOWS: u32 = 8; @@ -12,7 +15,8 @@ pub const MIN_WINDOW: u32 = 2; pub const CONGESTION_THRESHOLD: u32 = 3; pub fn create_congestion_state(cwnd: u32, ssthresh: u32, state: u32, losses: u32) -> u32 { - return (((((cwnd & 0xFF) << 24) | ((ssthresh & 0xFF) << 16)) | ((state & 0x3) << 14)) | (losses & 0x3FFF)); + return (((((cwnd & 0xFF) << 24) | ((ssthresh & 0xFF) << 16)) | ((state & 0x3) << 14)) + | (losses & 0x3FFF)); } pub fn get_cwnd(state: u32) -> u32 { @@ -172,7 +176,10 @@ pub fn calculate_total_cwnd(controllers: [u32; MAX_FLOWS as usize]) -> u32 { return total; } -pub fn allocate_fair_bandwidth(controllers: [u32; MAX_FLOWS as usize], total_bandwidth: u32) -> u32 { +pub fn allocate_fair_bandwidth( + controllers: [u32; MAX_FLOWS as usize], + total_bandwidth: u32, +) -> u32 { let mut active_flows: u32 = 0; let mut i: u32 = 0; while (i < MAX_FLOWS) { @@ -210,4 +217,3 @@ pub fn reset_after_timeout(congestion: u32) -> u32 { cwnd = MIN_WINDOW; return create_congestion_state(cwnd, ssthresh, STATE_SLOW_START, 0); } - diff --git a/gen/rust/crc16.rs b/gen/rust/crc16.rs index 591cf354..9f08f19e 100644 --- a/gen/rust/crc16.rs +++ b/gen/rust/crc16.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 6 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const CRC16_CCITT_POLY: u16 = 0x1021; @@ -14,14 +17,34 @@ pub fn crc_update_bit(crc: u16, bit: u8) -> u16 { } pub fn crc_update_byte(crc: u16, byte: u8) -> u16 { - return crc_update_bit(crc_update_bit(crc_update_bit(crc_update_bit(crc_update_bit(crc_update_bit(crc_update_bit(crc_update_bit(crc, (byte & 1)), ((byte >> 1) & 1)), ((byte >> 2) & 1)), ((byte >> 3) & 1)), ((byte >> 4) & 1)), ((byte >> 5) & 1)), ((byte >> 6) & 1)), ((byte >> 7) & 1)); + return crc_update_bit( + crc_update_bit( + crc_update_bit( + crc_update_bit( + crc_update_bit( + crc_update_bit( + crc_update_bit(crc_update_bit(crc, (byte & 1)), ((byte >> 1) & 1)), + ((byte >> 2) & 1), + ), + ((byte >> 3) & 1), + ), + ((byte >> 4) & 1), + ), + ((byte >> 5) & 1), + ), + ((byte >> 6) & 1), + ), + ((byte >> 7) & 1), + ); } pub fn crc16_4bytes(b0: u8, b1: u8, b2: u8, b3: u8) -> u16 { - return crc_update_byte(crc_update_byte(crc_update_byte(crc_update_byte(CRC16_INIT, b0), b1), b2), b3); + return crc_update_byte( + crc_update_byte(crc_update_byte(crc_update_byte(CRC16_INIT, b0), b1), b2), + b3, + ); } pub fn verify_crc16_4bytes(b0: u8, b1: u8, b2: u8, b3: u8, crc_received: u16) -> bool { return (crc16_4bytes(b0, b1, b2, b3) == crc_received); } - diff --git a/gen/rust/cross_layer_optimizer.rs b/gen/rust/cross_layer_optimizer.rs index 903199b1..d4453c37 100644 --- a/gen/rust/cross_layer_optimizer.rs +++ b/gen/rust/cross_layer_optimizer.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 16 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_LAYERS: u32 = 4; @@ -18,7 +21,8 @@ pub const MODE_MODERATE: u32 = 1; pub const MODE_AGGRESSIVE: u32 = 2; pub fn create_layer_params(power: u32, rate: u32, retries: u32, window: u32) -> u32 { - return (((((power & 0xFF) << 24) | ((rate & 0xFF) << 16)) | ((retries & 0xFF) << 8)) | (window & 0xFF)); + return (((((power & 0xFF) << 24) | ((rate & 0xFF) << 16)) | ((retries & 0xFF) << 8)) + | (window & 0xFF)); } pub fn get_power(params: u32) -> u32 { @@ -37,8 +41,15 @@ pub fn get_window(params: u32) -> u32 { return (params & 0xFF); } -pub fn create_cross_layer_state(mode: u32, update_counter: u32, last_sync: u32, target: u32) -> u32 { - return (((((mode & 0x3) << 30) | ((update_counter & 0xFF) << 22)) | ((last_sync & 0x3FF) << 12)) | (target & 0xFFF)); +pub fn create_cross_layer_state( + mode: u32, + update_counter: u32, + last_sync: u32, + target: u32, +) -> u32 { + return (((((mode & 0x3) << 30) | ((update_counter & 0xFF) << 22)) + | ((last_sync & 0x3FF) << 12)) + | (target & 0xFFF)); } pub fn get_mode(state: u32) -> u32 { @@ -58,7 +69,7 @@ pub fn get_optimization_target(state: u32) -> u32 { } pub fn create_layer_array(phy: u32, mac: u32, network: u32, transport: u32) -> [u32; 4] { - return [phy,mac,network,transport]; + return [phy, mac, network, transport]; } pub fn set_slot4(array: [u32; 4], index: u32, value: u32) -> [u32; 4] { @@ -67,15 +78,15 @@ pub fn set_slot4(array: [u32; 4], index: u32, value: u32) -> [u32; 4] { let a2: u32 = array[2]; let a3: u32 = array[3]; if (index == 0) { - return [value,a1,a2,a3]; + return [value, a1, a2, a3]; } if (index == 1) { - return [a0,value,a2,a3]; + return [a0, value, a2, a3]; } if (index == 2) { - return [a0,a1,value,a3]; + return [a0, a1, value, a3]; } - return [a0,a1,a2,value]; + return [a0, a1, a2, value]; } pub fn get_layer_params(array: [u32; 4], layer: u32) -> u32 { @@ -186,4 +197,3 @@ pub fn switch_mode(state: u32, new_mode: u32) -> u32 { let target = get_optimization_target(state); return create_cross_layer_state(new_mode, counter, last_sync, target); } - diff --git a/gen/rust/crypto_frame.rs b/gen/rust/crypto_frame.rs index 76b8d8b7..786c28be 100644 --- a/gen/rust/crypto_frame.rs +++ b/gen/rust/crypto_frame.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 10 test(s), 2 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const EPOCH_LEN: usize = 4; @@ -116,4 +119,3 @@ pub fn replay_next_bhi(seen_any: bool, top: u64, blo: u32, bhi: u32, ctr: u64) - } return bhi; } - diff --git a/gen/rust/discovery.rs b/gen/rust/discovery.rs index 780d1e2d..d450fda7 100644 --- a/gen/rust/discovery.rs +++ b/gen/rust/discovery.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 6 test(s), 2 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const HDR_LEN: usize = 17; @@ -28,4 +31,3 @@ pub fn is_fresh(now_ms: u64, ts_ms: u64) -> bool { return ((ts_ms - now_ms) <= FRESHNESS_MS); } } - diff --git a/gen/rust/docs_generator.rs b/gen/rust/docs_generator.rs index 0312b506..a58a08d9 100644 --- a/gen/rust/docs_generator.rs +++ b/gen/rust/docs_generator.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 2 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_SECTIONS: u32 = 16; @@ -10,7 +13,9 @@ pub const MAX_REFERENCES: u32 = 32; pub const OUTPUT_BUFFER_SIZE: u32 = 4096; pub fn create_output_format(format_id: u32, version: u32, compression: u32, encoding: u32) -> u32 { - return (((((format_id & 0xF) << 28) | ((version & 0xFF) << 20)) | ((compression & 0xF) << 16)) | (encoding & 0xFFFF)); + return (((((format_id & 0xF) << 28) | ((version & 0xFF) << 20)) + | ((compression & 0xF) << 16)) + | (encoding & 0xFFFF)); } pub fn get_format_id(format: u32) -> u32 { @@ -39,8 +44,15 @@ pub const FORMAT_TEXT: u32 = 3; pub const FORMAT_JSON: u32 = 4; -pub fn create_document_section(section_id: u32, level: u32, content_len: u32, subsections: u32) -> u32 { - return (((((section_id & 0xFF) << 24) | ((level & 0xF) << 20)) | ((content_len & 0xFF) << 12)) | (subsections & 0xFFF)); +pub fn create_document_section( + section_id: u32, + level: u32, + content_len: u32, + subsections: u32, +) -> u32 { + return (((((section_id & 0xFF) << 24) | ((level & 0xF) << 20)) + | ((content_len & 0xFF) << 12)) + | (subsections & 0xFFF)); } pub fn get_section_id(section: u32) -> u32 { @@ -60,7 +72,9 @@ pub fn get_section_subsection_count(section: u32) -> u32 { } pub fn create_toc_entry(section_id: u32, level: u32, page_number: u32, title_id: u32) -> u32 { - return (((((section_id & 0xFF) << 24) | ((level & 0xF) << 20)) | ((page_number & 0xFF) << 12)) | (title_id & 0xFFF)); + return (((((section_id & 0xFF) << 24) | ((level & 0xF) << 20)) + | ((page_number & 0xFF) << 12)) + | (title_id & 0xFFF)); } pub fn get_toc_section_id(toc: u32) -> u32 { @@ -124,7 +138,9 @@ pub const TAG_TABLE: u32 = 5; pub const TAG_DIV: u32 = 6; pub fn create_reference_link(source_id: u32, target_id: u32, link_type: u32, anchor: u32) -> u32 { - return (((((source_id & 0xFF) << 24) | ((target_id & 0xFF) << 16)) | ((link_type & 0xF) << 12)) | (anchor & 0xFFF)); + return (((((source_id & 0xFF) << 24) | ((target_id & 0xFF) << 16)) + | ((link_type & 0xF) << 12)) + | (anchor & 0xFFF)); } pub fn get_ref_source(link: u32) -> u32 { @@ -168,7 +184,9 @@ pub fn get_code_block_line_count(block: u32) -> u32 { } pub fn create_data_table(table_id: u32, row_count: u32, col_count: u32, header_count: u32) -> u32 { - return (((((table_id & 0xFF) << 24) | ((row_count & 0xFF) << 16)) | ((col_count & 0xFF) << 8)) | (header_count & 0xFF)); + return (((((table_id & 0xFF) << 24) | ((row_count & 0xFF) << 16)) + | ((col_count & 0xFF) << 8)) + | (header_count & 0xFF)); } pub fn get_table_id(table: u32) -> u32 { @@ -188,11 +206,14 @@ pub fn get_table_header_count(table: u32) -> u32 { } pub fn generate_table_row(table_id: u32, row_index: u32, data_start: u32, data_count: u32) -> u32 { - return (((((table_id & 0xFF) << 24) | ((row_index & 0xFF) << 16)) | ((data_start & 0xFF) << 8)) | (data_count & 0xFF)); + return (((((table_id & 0xFF) << 24) | ((row_index & 0xFF) << 16)) + | ((data_start & 0xFF) << 8)) + | (data_count & 0xFF)); } pub fn create_index_entry(term_id: u32, location: u32, frequency: u32, importance: u32) -> u32 { - return (((((term_id & 0xFF) << 24) | ((location & 0xFF) << 16)) | ((frequency & 0xFF) << 8)) | (importance & 0xFF)); + return (((((term_id & 0xFF) << 24) | ((location & 0xFF) << 16)) | ((frequency & 0xFF) << 8)) + | (importance & 0xFF)); } pub fn get_index_term_id(entry: u32) -> u32 { @@ -211,8 +232,15 @@ pub fn get_index_importance(entry: u32) -> u32 { return (entry & 0xFF); } -pub fn generate_page_layout(margin_top: u32, margin_bottom: u32, margin_left: u32, margin_right: u32) -> u32 { - return (((((margin_top & 0xFF) << 24) | ((margin_bottom & 0xFF) << 16)) | ((margin_left & 0xFF) << 8)) | (margin_right & 0xFF)); +pub fn generate_page_layout( + margin_top: u32, + margin_bottom: u32, + margin_left: u32, + margin_right: u32, +) -> u32 { + return (((((margin_top & 0xFF) << 24) | ((margin_bottom & 0xFF) << 16)) + | ((margin_left & 0xFF) << 8)) + | (margin_right & 0xFF)); } pub fn get_margin_top(layout: u32) -> u32 { @@ -247,11 +275,14 @@ pub fn calculate_document_stats(sections: [u32; MAX_SECTIONS as usize], section_ } i = (i + 1); } - return (((((total_pages & 0xFF) << 24) | ((total_words & 0xFF) << 16)) | ((total_tables & 0xFF) << 8)) | (total_figures & 0xFF)); + return (((((total_pages & 0xFF) << 24) | ((total_words & 0xFF) << 16)) + | ((total_tables & 0xFF) << 8)) + | (total_figures & 0xFF)); } pub fn generate_document_metadata(title_id: u32, author_id: u32, date: u32, version: u32) -> u32 { - return (((((title_id & 0xFF) << 24) | ((author_id & 0xFF) << 16)) | ((date & 0xFF) << 8)) | (version & 0xFF)); + return (((((title_id & 0xFF) << 24) | ((author_id & 0xFF) << 16)) | ((date & 0xFF) << 8)) + | (version & 0xFF)); } pub fn get_metadata_title(metadata: u32) -> u32 { @@ -270,7 +301,12 @@ pub fn get_metadata_version(metadata: u32) -> u32 { return (metadata & 0xFF); } -pub fn format_document(sections: [u32; MAX_SECTIONS as usize], section_count: u32, format: u32, layout: u32) -> u32 { +pub fn format_document( + sections: [u32; MAX_SECTIONS as usize], + section_count: u32, + format: u32, + layout: u32, +) -> u32 { let mut formatted_size: u32 = 0; let mut i: u32 = 0; while (i < section_count) { @@ -291,7 +327,13 @@ pub fn format_document(sections: [u32; MAX_SECTIONS as usize], section_count: u3 return formatted_size; } -pub fn generate_complete_document(func_docs: [u32; 64], func_count: u32, sections: [u32; MAX_SECTIONS as usize], section_count: u32, format: u32) -> u32 { +pub fn generate_complete_document( + func_docs: [u32; 64], + func_count: u32, + sections: [u32; MAX_SECTIONS as usize], + section_count: u32, + format: u32, +) -> u32 { let metadata: u32 = generate_document_metadata(1, 1, 20260703, 1); let layout: u32 = generate_page_layout(20, 20, 15, 15); let toc_size: u32 = (section_count * 10); @@ -301,7 +343,11 @@ pub fn generate_complete_document(func_docs: [u32; 64], func_count: u32, section return ((((total_size & 0xFFFF) << 16) | ((section_count & 0xFF) << 8)) | (func_count & 0xFF)); } -pub fn validate_documentation(generated_doc: u32, expected_sections: u32, expected_funcs: u32) -> u32 { +pub fn validate_documentation( + generated_doc: u32, + expected_sections: u32, + expected_funcs: u32, +) -> u32 { let actual_sections: u32 = ((generated_doc >> 8) & 0xFF); let actual_funcs: u32 = (generated_doc & 0xFF); let mut section_match: u32 = 0; @@ -314,6 +360,7 @@ pub fn validate_documentation(generated_doc: u32, expected_sections: u32, expect } let quality_score: u32 = ((section_match * 50) + (func_match * 50)); let completeness: u32 = (((actual_sections * 10) / expected_sections) * 10); - return (((((section_match & 0x1) << 15) | ((func_match & 0x1) << 14)) | ((quality_score & 0xFF) << 8)) | (completeness & 0xFF)); + return (((((section_match & 0x1) << 15) | ((func_match & 0x1) << 14)) + | ((quality_score & 0xFF) << 8)) + | (completeness & 0xFF)); } - diff --git a/gen/rust/energy_aware_routing.rs b/gen/rust/energy_aware_routing.rs index d335c0a4..c571134d 100644 --- a/gen/rust/energy_aware_routing.rs +++ b/gen/rust/energy_aware_routing.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 13 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_PATHS: u32 = 4; @@ -10,7 +13,9 @@ pub const HOP_WEIGHT: u32 = 3; pub const CRITICAL_BATTERY: u32 = 20; pub fn create_energy_cost(tx_power: u32, rx_power: u32, processing: u32, hop_count: u32) -> u32 { - return (((((tx_power & 0xFF) << 24) | ((rx_power & 0xFF) << 16)) | ((processing & 0xFF) << 8)) | (hop_count & 0xFF)); + return (((((tx_power & 0xFF) << 24) | ((rx_power & 0xFF) << 16)) + | ((processing & 0xFF) << 8)) + | (hop_count & 0xFF)); } pub fn get_tx_power(cost: u32) -> u32 { @@ -29,8 +34,15 @@ pub fn get_hop_count_cost(cost: u32) -> u32 { return (cost & 0xFF); } -pub fn create_path_energy(battery_levels: u32, total_cost: u32, path_valid: u32, energy_score: u32) -> u32 { - return (((((battery_levels & 0xFF) << 24) | ((total_cost & 0xFF) << 16)) | ((path_valid & 0x1) << 15)) | (energy_score & 0x7FFF)); +pub fn create_path_energy( + battery_levels: u32, + total_cost: u32, + path_valid: u32, + energy_score: u32, +) -> u32 { + return (((((battery_levels & 0xFF) << 24) | ((total_cost & 0xFF) << 16)) + | ((path_valid & 0x1) << 15)) + | (energy_score & 0x7FFF)); } pub fn get_battery_levels(energy: u32) -> u32 { @@ -50,7 +62,7 @@ pub fn get_energy_score(energy: u32) -> u32 { } pub fn create_energy_array(e0: u32, e1: u32, e2: u32, e3: u32) -> [u32; 4] { - return [e0,e1,e2,e3]; + return [e0, e1, e2, e3]; } pub fn get_path_energy(array: [u32; 4], index: u32) -> u32 { @@ -196,4 +208,3 @@ pub fn estimate_path_lifetime(energy: u32, drain_rate: u32) -> u32 { } return (battery / drain_rate); } - diff --git a/gen/rust/etx.rs b/gen/rust/etx.rs index 2e433ccf..59c0d900 100644 --- a/gen/rust/etx.rs +++ b/gen/rust/etx.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 6 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const OPTIMISTIC: u8 = 230; diff --git a/gen/rust/failure_predictor.rs b/gen/rust/failure_predictor.rs index e5760375..3951ae1b 100644 --- a/gen/rust/failure_predictor.rs +++ b/gen/rust/failure_predictor.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 17 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_NODES: u32 = 8; @@ -10,7 +13,8 @@ pub const CRITICAL_THRESHOLD: u32 = 85; pub const HISTORY_SIZE: u32 = 10; pub fn create_health_metrics(cpu: u32, memory: u32, errors: u32, temp: u32) -> u32 { - return (((((cpu & 0xFF) << 24) | ((memory & 0xFF) << 16)) | ((errors & 0xFF) << 8)) | (temp & 0xFF)); + return (((((cpu & 0xFF) << 24) | ((memory & 0xFF) << 16)) | ((errors & 0xFF) << 8)) + | (temp & 0xFF)); } pub fn get_cpu_usage(metrics: u32) -> u32 { @@ -30,7 +34,8 @@ pub fn get_temperature(metrics: u32) -> u32 { } pub fn create_risk_score(risk: u32, confidence: u32, trend: u32, pred_time: u32) -> u32 { - return (((((risk & 0xFF) << 24) | ((confidence & 0xFF) << 16)) | ((trend & 0x3) << 14)) | (pred_time & 0x3FFF)); + return (((((risk & 0xFF) << 24) | ((confidence & 0xFF) << 16)) | ((trend & 0x3) << 14)) + | (pred_time & 0x3FFF)); } pub fn get_risk_level(score: u32) -> u32 { @@ -49,8 +54,17 @@ pub fn get_prediction_time(score: u32) -> u32 { return (score & 0x3FFF); } -pub fn create_health_array(h0: u32, h1: u32, h2: u32, h3: u32, h4: u32, h5: u32, h6: u32, h7: u32) -> [u32; 8] { - return [h0,h1,h2,h3,h4,h5,h6,h7]; +pub fn create_health_array( + h0: u32, + h1: u32, + h2: u32, + h3: u32, + h4: u32, + h5: u32, + h6: u32, + h7: u32, +) -> [u32; 8] { + return [h0, h1, h2, h3, h4, h5, h6, h7]; } pub fn get_health_metrics(array: [u32; 8], index: u32) -> u32 { @@ -177,4 +191,3 @@ pub fn find_most_at_risk(health_array: [u32; 8]) -> u32 { } return highest_risk_node; } - diff --git a/gen/rust/fault_detection.rs b/gen/rust/fault_detection.rs index 8440a946..212090fb 100644 --- a/gen/rust/fault_detection.rs +++ b/gen/rust/fault_detection.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 17 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_NODES: u32 = 8; @@ -11,8 +14,15 @@ pub const HEARTBEAT_TIMEOUT: u32 = 10000; pub const LINK_QUALITY_POOR: u32 = 30; -pub fn create_node_state(is_alive: u32, failure_count: u32, last_heartbeat: u32, link_quality: u32) -> u32 { - return (((((is_alive & 0x1) << 31) | ((failure_count & 0x7F) << 24)) | ((last_heartbeat & 0xFFFF) << 8)) | (link_quality & 0xFF)); +pub fn create_node_state( + is_alive: u32, + failure_count: u32, + last_heartbeat: u32, + link_quality: u32, +) -> u32 { + return (((((is_alive & 0x1) << 31) | ((failure_count & 0x7F) << 24)) + | ((last_heartbeat & 0xFFFF) << 8)) + | (link_quality & 0xFF)); } pub fn get_is_alive(state: u32) -> u32 { @@ -31,8 +41,17 @@ pub fn get_link_quality(state: u32) -> u32 { return (state & 0xFF); } -pub fn create_node_table(n0: u32, n1: u32, n2: u32, n3: u32, n4: u32, n5: u32, n6: u32, n7: u32) -> [u32; 8] { - return [n0,n1,n2,n3,n4,n5,n6,n7]; +pub fn create_node_table( + n0: u32, + n1: u32, + n2: u32, + n3: u32, + n4: u32, + n5: u32, + n6: u32, + n7: u32, +) -> [u32; 8] { + return [n0, n1, n2, n3, n4, n5, n6, n7]; } pub fn get_node_state(table: [u32; 8], index: u32) -> u32 { @@ -130,4 +149,3 @@ pub fn count_failed_nodes(table: [u32; 8]) -> u32 { } return count; } - diff --git a/gen/rust/flow_control.rs b/gen/rust/flow_control.rs index 1e6b8fb0..5eaf8131 100644 --- a/gen/rust/flow_control.rs +++ b/gen/rust/flow_control.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 3 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_FLOWS: u32 = 8; diff --git a/gen/rust/fpga_synthesis_report.rs b/gen/rust/fpga_synthesis_report.rs index d59d7075..874e5a29 100644 --- a/gen/rust/fpga_synthesis_report.rs +++ b/gen/rust/fpga_synthesis_report.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 17 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const RESOURCE_LUT: u32 = 1; @@ -16,7 +19,8 @@ pub const TARGET_FREQ_100MHZ: u32 = 100; pub const TARGET_FREQ_150MHZ: u32 = 150; pub fn create_synthesis_result(utilization: u32, timing_slack: u32, achieved_freq: u32) -> u32 { - return ((((utilization & 0xFFF) << 20) | ((timing_slack & 0xFFF) << 8)) | (achieved_freq & 0xFF)); + return ((((utilization & 0xFFF) << 20) | ((timing_slack & 0xFFF) << 8)) + | (achieved_freq & 0xFF)); } pub fn extract_utilization(result: u32) -> u32 { @@ -57,7 +61,8 @@ pub fn frequency_achievable(result: u32, target_freq: u32) -> bool { } pub fn create_resource_summary(lut_used: u32, ff_used: u32, dsp_used: u32, bram_used: u32) -> u32 { - return (((((lut_used & 0xFFF) << 20) | ((ff_used & 0xFFF) << 8)) | ((dsp_used & 0xF) << 4)) | (bram_used & 0xF)); + return (((((lut_used & 0xFFF) << 20) | ((ff_used & 0xFFF) << 8)) | ((dsp_used & 0xF) << 4)) + | (bram_used & 0xF)); } pub fn extract_lut(summary: u32) -> u32 { @@ -75,4 +80,3 @@ pub fn extract_dsp(summary: u32) -> u32 { pub fn extract_bram(summary: u32) -> u32 { return (summary & 0xF); } - diff --git a/gen/rust/frame_buffer.rs b/gen/rust/frame_buffer.rs index 8e8ebda3..fed825d4 100644 --- a/gen/rust/frame_buffer.rs +++ b/gen/rust/frame_buffer.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 10 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub fn get_src(meta: u32) -> u8 { return (((meta >> 1) & 15) as u8); diff --git a/gen/rust/gf16_format.rs b/gen/rust/gf16_format.rs index ff592819..2a40f4db 100644 --- a/gen/rust/gf16_format.rs +++ b/gen/rust/gf16_format.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 6 test(s), 2 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const M_BITS: u32 = 9; @@ -46,4 +49,3 @@ pub fn is_inf(bits: u32) -> bool { pub fn is_zero(bits: u32) -> bool { return ((bits & 32767) == 0); } - diff --git a/gen/rust/hardware_validation.rs b/gen/rust/hardware_validation.rs index 443afc69..237ec4e2 100644 --- a/gen/rust/hardware_validation.rs +++ b/gen/rust/hardware_validation.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 17 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const VAL_PENDING: u32 = 0; @@ -18,7 +21,8 @@ pub const TEST_FPGA_BOARD: u32 = 3; pub const TEST_REAL_WORLD: u32 = 4; pub fn create_test_result(state: u32, test_type: u32, errors: u32, iterations: u32) -> u32 { - return (((((state & 0x3) << 30) | ((test_type & 0xF) << 26)) | ((errors & 0x3FF) << 16)) | (iterations & 0xFFFF)); + return (((((state & 0x3) << 30) | ((test_type & 0xF) << 26)) | ((errors & 0x3FF) << 16)) + | (iterations & 0xFFFF)); } pub fn extract_state(result: u32) -> u32 { @@ -53,11 +57,13 @@ pub fn bit_accurate(reference: u32, implementation: u32, tolerance_mask: u32) -> } pub fn fpga_board_ready(result: u32) -> bool { - return ((extract_state(result) == VAL_PASSED) && (extract_test_type(result) == TEST_FPGA_BOARD)); + return ((extract_state(result) == VAL_PASSED) + && (extract_test_type(result) == TEST_FPGA_BOARD)); } pub fn create_packet_capture(src: u32, dst: u32, payload: u32, timestamp: u32) -> u32 { - return (((((src & 0xFF) << 24) | ((dst & 0xFF) << 16)) | ((payload & 0xFF) << 8)) | (timestamp & 0xFF)); + return (((((src & 0xFF) << 24) | ((dst & 0xFF) << 16)) | ((payload & 0xFF) << 8)) + | (timestamp & 0xFF)); } pub fn extract_capture_src(capture: u32) -> u32 { @@ -91,4 +97,3 @@ pub fn extract_metric_value(metric: u32) -> u32 { pub fn extract_metric_unit(metric: u32) -> u32 { return (metric & 0xF); } - diff --git a/gen/rust/health_dashboard.rs b/gen/rust/health_dashboard.rs index 65f7d46a..c488cdf5 100644 --- a/gen/rust/health_dashboard.rs +++ b/gen/rust/health_dashboard.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 4 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_NODES: u32 = 8; diff --git a/gen/rust/health_monitoring.rs b/gen/rust/health_monitoring.rs index 1f42c872..0de69a8d 100644 --- a/gen/rust/health_monitoring.rs +++ b/gen/rust/health_monitoring.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 9 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_CHECKS: u32 = 8; @@ -12,7 +15,8 @@ pub const HEALTH_HEALTHY: u32 = 2; pub const CHECK_INTERVAL: u32 = 1000; pub fn create_health_check(check_type: u32, result: u32, value: u32, timestamp: u32) -> u32 { - return (((((check_type & 0xF) << 28) | ((result & 0x3) << 26)) | ((value & 0xFF) << 8)) | (timestamp & 0xFF)); + return (((((check_type & 0xF) << 28) | ((result & 0x3) << 26)) | ((value & 0xFF) << 8)) + | (timestamp & 0xFF)); } pub fn get_check_type(check: u32) -> u32 { @@ -55,8 +59,17 @@ pub const RESULT_FAIL: u32 = 2; pub const RESULT_SKIP: u32 = 3; -pub fn create_health_array(c0: u32, c1: u32, c2: u32, c3: u32, c4: u32, c5: u32, c6: u32, c7: u32) -> [u32; 8] { - return [c0,c1,c2,c3,c4,c5,c6,c7]; +pub fn create_health_array( + c0: u32, + c1: u32, + c2: u32, + c3: u32, + c4: u32, + c5: u32, + c6: u32, + c7: u32, +) -> [u32; 8] { + return [c0, c1, c2, c3, c4, c5, c6, c7]; } pub fn get_health_check(array: [u32; 8], index: u32) -> u32 { @@ -76,27 +89,27 @@ pub fn update_health_check(array: [u32; 8], index: u32, new_check: u32) -> [u32; let a6: u32 = array[6]; let a7: u32 = array[7]; if (index == 0) { - return [new_check,a1,a2,a3,a4,a5,a6,a7]; + return [new_check, a1, a2, a3, a4, a5, a6, a7]; } if (index == 1) { - return [a0,new_check,a2,a3,a4,a5,a6,a7]; + return [a0, new_check, a2, a3, a4, a5, a6, a7]; } if (index == 2) { - return [a0,a1,new_check,a3,a4,a5,a6,a7]; + return [a0, a1, new_check, a3, a4, a5, a6, a7]; } if (index == 3) { - return [a0,a1,a2,new_check,a4,a5,a6,a7]; + return [a0, a1, a2, new_check, a4, a5, a6, a7]; } if (index == 4) { - return [a0,a1,a2,a3,new_check,a5,a6,a7]; + return [a0, a1, a2, a3, new_check, a5, a6, a7]; } if (index == 5) { - return [a0,a1,a2,a3,a4,new_check,a6,a7]; + return [a0, a1, a2, a3, a4, new_check, a6, a7]; } if (index == 6) { - return [a0,a1,a2,a3,a4,a5,new_check,a7]; + return [a0, a1, a2, a3, a4, a5, new_check, a7]; } - return [a0,a1,a2,a3,a4,a5,a6,new_check]; + return [a0, a1, a2, a3, a4, a5, a6, new_check]; } pub fn calculate_overall_health(array: [u32; 8]) -> u32 { @@ -223,7 +236,9 @@ pub fn is_check_failing(array: [u32; 8], check_type: u32) -> bool { if ((check_type == CHECK_CPU) && (get_check_type(get_health_check(array, 0)) == CHECK_CPU)) { return (get_check_result(get_health_check(array, 0)) == RESULT_FAIL); } else { - if ((check_type == CHECK_MEMORY) && (get_check_type(get_health_check(array, 1)) == CHECK_MEMORY)) { + if ((check_type == CHECK_MEMORY) + && (get_check_type(get_health_check(array, 1)) == CHECK_MEMORY)) + { return (get_check_result(get_health_check(array, 1)) == RESULT_FAIL); } } @@ -286,4 +301,3 @@ pub fn get_health_percentage(array: [u32; 8]) -> u32 { } return ((passing * 100) / total); } - diff --git a/gen/rust/hello.rs b/gen/rust/hello.rs index 9653462d..b0551522 100644 --- a/gen/rust/hello.rs +++ b/gen/rust/hello.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 6 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_HEARD: u8 = 3; @@ -21,7 +24,15 @@ pub fn u32_byte(w: u32, idx: usize) -> u8 { } } -pub fn hello_byte(src: u32, seq: u32, heard0: u32, heard1: u32, heard2: u32, n: u8, idx: usize) -> u8 { +pub fn hello_byte( + src: u32, + seq: u32, + heard0: u32, + heard1: u32, + heard2: u32, + n: u8, + idx: usize, +) -> u8 { if (idx < 4) { return u32_byte(src, idx); } else { @@ -72,4 +83,3 @@ pub fn reports_hearing(heard0: u32, heard1: u32, heard2: u32, n: u8, me: u32) -> return false; } } - diff --git a/gen/rust/integration_framework.rs b/gen/rust/integration_framework.rs index 9964570a..df92893a 100644 --- a/gen/rust/integration_framework.rs +++ b/gen/rust/integration_framework.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 2 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_MODULES: u32 = 16; @@ -9,8 +12,15 @@ pub const MAX_EVENTS: u32 = 64; pub const INTEGRATION_VERSION: u32 = 1; -pub fn create_module_registration(module_id: u32, module_type: u32, priority: u32, status: u32) -> u32 { - return (((((module_id & 0xFF) << 24) | ((module_type & 0xF) << 20)) | ((priority & 0xF) << 16)) | (status & 0xFFFF)); +pub fn create_module_registration( + module_id: u32, + module_type: u32, + priority: u32, + status: u32, +) -> u32 { + return (((((module_id & 0xFF) << 24) | ((module_type & 0xF) << 20)) + | ((priority & 0xF) << 16)) + | (status & 0xFFFF)); } pub fn get_registered_module_id(registration: u32) -> u32 { @@ -52,7 +62,8 @@ pub const STATUS_ERROR: u32 = 3; pub const STATUS_OFFLINE: u32 = 4; pub fn create_integration_message(msg_id: u32, source: u32, dest: u32, msg_type: u32) -> u32 { - return (((((msg_id & 0xFF) << 24) | ((source & 0xFF) << 16)) | ((dest & 0xFF) << 8)) | (msg_type & 0xFF)); + return (((((msg_id & 0xFF) << 24) | ((source & 0xFF) << 16)) | ((dest & 0xFF) << 8)) + | (msg_type & 0xFF)); } pub fn get_integration_message_id(message: u32) -> u32 { @@ -100,7 +111,11 @@ pub fn send_message(modules: [u32; MAX_MODULES as usize], message: u32) -> u32 { return 0; } -pub fn receive_message(messages: [u32; MAX_MESSAGES as usize], message_count: u32, module_id: u32) -> u32 { +pub fn receive_message( + messages: [u32; MAX_MESSAGES as usize], + message_count: u32, + module_id: u32, +) -> u32 { let mut i: u32 = 0; while (i < message_count) { let dest: u32 = get_integration_message_dest(messages[(i) as usize]); @@ -113,7 +128,8 @@ pub fn receive_message(messages: [u32; MAX_MESSAGES as usize], message_count: u3 } pub fn create_event(event_id: u32, event_type: u32, source: u32, data: u32) -> u32 { - return (((((event_id & 0xFF) << 24) | ((event_type & 0xF) << 20)) | ((source & 0xFF) << 12)) | (data & 0xFFF)); + return (((((event_id & 0xFF) << 24) | ((event_type & 0xF) << 20)) | ((source & 0xFF) << 12)) + | (data & 0xFFF)); } pub fn get_event_id(event: u32) -> u32 { @@ -142,7 +158,11 @@ pub const EVENT_SIMULATION_STEP: u32 = 3; pub const EVENT_VISUALIZATION_UPDATE: u32 = 4; -pub fn subscribe_to_event(module_id: u32, event_type: u32, subscriptions: [u32; MAX_EVENTS as usize]) -> u32 { +pub fn subscribe_to_event( + module_id: u32, + event_type: u32, + subscriptions: [u32; MAX_EVENTS as usize], +) -> u32 { let subscription_id: u32 = ((module_id * 10) + event_type); let mut i: u32 = 0; while (i < MAX_EVENTS) { @@ -155,7 +175,11 @@ pub fn subscribe_to_event(module_id: u32, event_type: u32, subscriptions: [u32; return 0; } -pub fn publish_event(event: u32, subscriptions: [u32; MAX_EVENTS as usize], modules: [u32; MAX_MODULES as usize]) -> u32 { +pub fn publish_event( + event: u32, + subscriptions: [u32; MAX_EVENTS as usize], + modules: [u32; MAX_MODULES as usize], +) -> u32 { let event_type: u32 = get_event_type(event); let mut notified_count: u32 = 0; let mut i: u32 = 0; @@ -174,8 +198,15 @@ pub fn publish_event(event: u32, subscriptions: [u32; MAX_EVENTS as usize], modu return notified_count; } -pub fn create_state_sync(module_id: u32, state_version: u32, state_data: u32, checksum: u32) -> u32 { - return (((((module_id & 0xFF) << 24) | ((state_version & 0xFF) << 16)) | ((state_data & 0xFF) << 8)) | (checksum & 0xFF)); +pub fn create_state_sync( + module_id: u32, + state_version: u32, + state_data: u32, + checksum: u32, +) -> u32 { + return (((((module_id & 0xFF) << 24) | ((state_version & 0xFF) << 16)) + | ((state_data & 0xFF) << 8)) + | (checksum & 0xFF)); } pub fn get_sync_module_id(sync: u32) -> u32 { @@ -194,7 +225,11 @@ pub fn get_sync_checksum(sync: u32) -> u32 { return (sync & 0xFF); } -pub fn synchronize_states(modules: [u32; MAX_MODULES as usize], module_count: u32, sync_requests: u32) -> u32 { +pub fn synchronize_states( + modules: [u32; MAX_MODULES as usize], + module_count: u32, + sync_requests: u32, +) -> u32 { let mut synced_count: u32 = 0; let mut i: u32 = 0; while (i < module_count) { @@ -212,8 +247,15 @@ pub fn synchronize_states(modules: [u32; MAX_MODULES as usize], module_count: u3 return synced_count; } -pub fn create_error_propagation(source_id: u32, error_code: u32, severity: u32, timestamp: u32) -> u32 { - return (((((source_id & 0xFF) << 24) | ((error_code & 0xFF) << 16)) | ((severity & 0xF) << 12)) | (timestamp & 0xFFF)); +pub fn create_error_propagation( + source_id: u32, + error_code: u32, + severity: u32, + timestamp: u32, +) -> u32 { + return (((((source_id & 0xFF) << 24) | ((error_code & 0xFF) << 16)) + | ((severity & 0xF) << 12)) + | (timestamp & 0xFFF)); } pub fn get_error_source(err_word: u32) -> u32 { @@ -240,7 +282,11 @@ pub const SEVERITY_ERROR: u32 = 2; pub const SEVERITY_CRITICAL: u32 = 3; -pub fn propagate_error(err_word: u32, modules: [u32; MAX_MODULES as usize], module_count: u32) -> u32 { +pub fn propagate_error( + err_word: u32, + modules: [u32; MAX_MODULES as usize], + module_count: u32, +) -> u32 { let severity: u32 = get_error_severity(err_word); let mut notified_count: u32 = 0; let mut i: u32 = 0; @@ -266,11 +312,17 @@ pub fn propagate_error(err_word: u32, modules: [u32; MAX_MODULES as usize], modu return notified_count; } -pub fn load_module(module_id: u32, module_type: u32, priority: u32, modules: [u32; MAX_MODULES as usize]) -> u32 { +pub fn load_module( + module_id: u32, + module_type: u32, + priority: u32, + modules: [u32; MAX_MODULES as usize], +) -> u32 { let mut i: u32 = 0; while (i < MAX_MODULES) { if (get_registered_module_id(modules[(i) as usize]) == 0) { - modules[(i) as usize] = create_module_registration(module_id, module_type, priority, STATUS_IDLE); + modules[(i) as usize] = + create_module_registration(module_id, module_type, priority, STATUS_IDLE); return 1; } i = (i + 1); @@ -291,8 +343,15 @@ pub fn unload_module(module_id: u32, modules: [u32; MAX_MODULES as usize]) -> u3 return 0; } -pub fn create_dependency(module_id: u32, depends_on: u32, dependency_type: u32, required: u32) -> u32 { - return (((((module_id & 0xFF) << 24) | ((depends_on & 0xFF) << 16)) | ((dependency_type & 0xF) << 12)) | (required & 0xFFF)); +pub fn create_dependency( + module_id: u32, + depends_on: u32, + dependency_type: u32, + required: u32, +) -> u32 { + return (((((module_id & 0xFF) << 24) | ((depends_on & 0xFF) << 16)) + | ((dependency_type & 0xF) << 12)) + | (required & 0xFFF)); } pub fn get_dependency_module_id(dep: u32) -> u32 { @@ -311,7 +370,12 @@ pub fn get_dependency_required(dep: u32) -> u32 { return (dep & 0xFFF); } -pub fn check_dependencies(module_id: u32, dependencies: [u32; MAX_MODULES as usize], loaded_modules: [u32; MAX_MODULES as usize], module_count: u32) -> u32 { +pub fn check_dependencies( + module_id: u32, + dependencies: [u32; MAX_MODULES as usize], + loaded_modules: [u32; MAX_MODULES as usize], + module_count: u32, +) -> u32 { let mut satisfied: u32 = 1; let mut i: u32 = 0; while (i < MAX_MODULES) { @@ -340,8 +404,15 @@ pub fn check_dependencies(module_id: u32, dependencies: [u32; MAX_MODULES as usi return satisfied; } -pub fn create_resource_request(module_id: u32, resource_type: u32, amount: u32, priority: u32) -> u32 { - return (((((module_id & 0xFF) << 24) | ((resource_type & 0xF) << 20)) | ((amount & 0xFF) << 12)) | (priority & 0xFFF)); +pub fn create_resource_request( + module_id: u32, + resource_type: u32, + amount: u32, + priority: u32, +) -> u32 { + return (((((module_id & 0xFF) << 24) | ((resource_type & 0xF) << 20)) + | ((amount & 0xFF) << 12)) + | (priority & 0xFFF)); } pub fn get_resource_request_module(req: u32) -> u32 { @@ -368,7 +439,11 @@ pub const RESOURCE_BANDWIDTH: u32 = 2; pub const RESOURCE_STORAGE: u32 = 3; -pub fn allocate_resources(requests: [u32; MAX_MESSAGES as usize], request_count: u32, available_resources: u32) -> u32 { +pub fn allocate_resources( + requests: [u32; MAX_MESSAGES as usize], + request_count: u32, + available_resources: u32, +) -> u32 { let mut total_requested: u32 = 0; let mut allocated_count: u32 = 0; let mut i: u32 = 0; @@ -395,11 +470,25 @@ pub fn allocate_resources(requests: [u32; MAX_MESSAGES as usize], request_count: } } -pub fn create_integration_report(loaded_modules: u32, active_messages: u32, events_processed: u32, errors_handled: u32) -> u32 { - return (((((loaded_modules & 0xFF) << 24) | ((active_messages & 0xFF) << 16)) | ((events_processed & 0xFF) << 8)) | (errors_handled & 0xFF)); -} - -pub fn generate_integration_stats(modules: [u32; MAX_MODULES as usize], module_count: u32, messages: [u32; MAX_MESSAGES as usize], message_count: u32, events: [u32; MAX_EVENTS as usize], event_count: u32) -> u32 { +pub fn create_integration_report( + loaded_modules: u32, + active_messages: u32, + events_processed: u32, + errors_handled: u32, +) -> u32 { + return (((((loaded_modules & 0xFF) << 24) | ((active_messages & 0xFF) << 16)) + | ((events_processed & 0xFF) << 8)) + | (errors_handled & 0xFF)); +} + +pub fn generate_integration_stats( + modules: [u32; MAX_MODULES as usize], + module_count: u32, + messages: [u32; MAX_MESSAGES as usize], + message_count: u32, + events: [u32; MAX_EVENTS as usize], + event_count: u32, +) -> u32 { let mut active_modules: u32 = 0; let mut active_messages: u32 = 0; let mut events_processed: u32 = 0; @@ -422,7 +511,12 @@ pub fn generate_integration_stats(modules: [u32; MAX_MODULES as usize], module_c events_processed = (events_processed + 1); k = (k + 1); } - return create_integration_report(active_modules, active_messages, events_processed, errors_handled); + return create_integration_report( + active_modules, + active_messages, + events_processed, + errors_handled, + ); } pub fn validate_integration_health(modules: [u32; MAX_MODULES as usize], module_count: u32) -> u32 { @@ -446,4 +540,3 @@ pub fn validate_integration_health(modules: [u32; MAX_MODULES as usize], module_ } return (((active_percentage & 0xFF) << 24) | ((error_count & 0xFF) << 16)); } - diff --git a/gen/rust/integration_tests.rs b/gen/rust/integration_tests.rs index eecc7ed2..ea707c13 100644 --- a/gen/rust/integration_tests.rs +++ b/gen/rust/integration_tests.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 10 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const VERSION: u8 = 1; @@ -39,4 +42,3 @@ pub fn mesh_ip(id: u32) -> (u8, u8, u8, u8) { pub const ST_IDLE: u8 = 0; pub const ST_TX_WAIT: u8 = 3; - diff --git a/gen/rust/key_management.rs b/gen/rust/key_management.rs index cd3db816..5be95798 100644 --- a/gen/rust/key_management.rs +++ b/gen/rust/key_management.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 13 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_KEYS: u32 = 4; @@ -12,7 +15,8 @@ pub const KEY_INVALID: u32 = 0; pub const ROTATION_INTERVAL: u32 = 30000; pub fn create_key_entry(valid: u32, key_id: u32, key_value: u32, timestamp: u32) -> u32 { - return (((((valid & 0x1) << 31) | ((key_id & 0x7F) << 24)) | ((key_value & 0xFFFF) << 8)) | (timestamp & 0xFF)); + return (((((valid & 0x1) << 31) | ((key_id & 0x7F) << 24)) | ((key_value & 0xFFFF) << 8)) + | (timestamp & 0xFF)); } pub fn get_key_valid(entry: u32) -> u32 { @@ -32,7 +36,7 @@ pub fn get_key_timestamp(entry: u32) -> u32 { } pub fn create_key_store(k0: u32, k1: u32, k2: u32, k3: u32) -> [u32; 4] { - return [k0,k1,k2,k3]; + return [k0, k1, k2, k3]; } pub fn set_key_slot(store: [u32; 4], index: u32, entry: u32) -> [u32; 4] { @@ -41,15 +45,15 @@ pub fn set_key_slot(store: [u32; 4], index: u32, entry: u32) -> [u32; 4] { let k2: u32 = store[2]; let k3: u32 = store[3]; if (index == 0) { - return [entry,k1,k2,k3]; + return [entry, k1, k2, k3]; } if (index == 1) { - return [k0,entry,k2,k3]; + return [k0, entry, k2, k3]; } if (index == 2) { - return [k0,k1,entry,k3]; + return [k0, k1, entry, k3]; } - return [k0,k1,k2,entry]; + return [k0, k1, k2, entry]; } pub fn get_key_entry(store: [u32; 4], index: u32) -> u32 { @@ -60,16 +64,24 @@ pub fn get_key_entry(store: [u32; 4], index: u32) -> u32 { } pub fn find_key_by_id(store: [u32; 4], key_id: u32) -> u32 { - if ((get_key_id(get_key_entry(store, 0)) == key_id) && (get_key_valid(get_key_entry(store, 0)) == KEY_VALID)) { + if ((get_key_id(get_key_entry(store, 0)) == key_id) + && (get_key_valid(get_key_entry(store, 0)) == KEY_VALID)) + { return 0; } else { - if ((get_key_id(get_key_entry(store, 1)) == key_id) && (get_key_valid(get_key_entry(store, 1)) == KEY_VALID)) { + if ((get_key_id(get_key_entry(store, 1)) == key_id) + && (get_key_valid(get_key_entry(store, 1)) == KEY_VALID)) + { return 1; } else { - if ((get_key_id(get_key_entry(store, 2)) == key_id) && (get_key_valid(get_key_entry(store, 2)) == KEY_VALID)) { + if ((get_key_id(get_key_entry(store, 2)) == key_id) + && (get_key_valid(get_key_entry(store, 2)) == KEY_VALID)) + { return 2; } else { - if ((get_key_id(get_key_entry(store, 3)) == key_id) && (get_key_valid(get_key_entry(store, 3)) == KEY_VALID)) { + if ((get_key_id(get_key_entry(store, 3)) == key_id) + && (get_key_valid(get_key_entry(store, 3)) == KEY_VALID)) + { return 3; } } @@ -80,16 +92,32 @@ pub fn find_key_by_id(store: [u32; 4], key_id: u32) -> u32 { pub fn add_key(store: [u32; 4], key_id: u32, key_value: u32, timestamp: u32) -> [u32; 4] { if (get_key_valid(get_key_entry(store, 0)) == KEY_INVALID) { - return set_key_slot(store, 0, create_key_entry(KEY_VALID, key_id, key_value, timestamp)); + return set_key_slot( + store, + 0, + create_key_entry(KEY_VALID, key_id, key_value, timestamp), + ); } else { if (get_key_valid(get_key_entry(store, 1)) == KEY_INVALID) { - return set_key_slot(store, 1, create_key_entry(KEY_VALID, key_id, key_value, timestamp)); + return set_key_slot( + store, + 1, + create_key_entry(KEY_VALID, key_id, key_value, timestamp), + ); } else { if (get_key_valid(get_key_entry(store, 2)) == KEY_INVALID) { - return set_key_slot(store, 2, create_key_entry(KEY_VALID, key_id, key_value, timestamp)); + return set_key_slot( + store, + 2, + create_key_entry(KEY_VALID, key_id, key_value, timestamp), + ); } else { if (get_key_valid(get_key_entry(store, 3)) == KEY_INVALID) { - return set_key_slot(store, 3, create_key_entry(KEY_VALID, key_id, key_value, timestamp)); + return set_key_slot( + store, + 3, + create_key_entry(KEY_VALID, key_id, key_value, timestamp), + ); } } } @@ -101,7 +129,12 @@ pub fn invalidate_key(store: [u32; 4], key_id: u32) -> [u32; 4] { let index = find_key_by_id(store, key_id); if (index != 0xFF) { let entry = get_key_entry(store, index); - let new_entry = create_key_entry(KEY_INVALID, get_key_id(entry), get_key_value(entry), get_key_timestamp(entry)); + let new_entry = create_key_entry( + KEY_INVALID, + get_key_id(entry), + get_key_value(entry), + get_key_timestamp(entry), + ); return set_key_slot(store, index, new_entry); } return store; @@ -177,4 +210,3 @@ pub fn count_valid_keys(store: [u32; 4]) -> u32 { } return count; } - diff --git a/gen/rust/link_quality_monitor.rs b/gen/rust/link_quality_monitor.rs index 64c1b8f6..fb2e6670 100644 --- a/gen/rust/link_quality_monitor.rs +++ b/gen/rust/link_quality_monitor.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 6 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const ALPHA_Q8: u8 = 0x20; @@ -26,12 +29,16 @@ pub fn update_ewma(current: u8, sample: u8) -> u8 { } pub fn calculate_trend(history: [u8; 8]) -> i8 { - let recent_avg: u8 = ((((((history[7] as u16) + (history[6] as u16)) + (history[5] as u16)) + (history[4] as u16)) >> 2) as u8); - let older_avg: u8 = ((((((history[3] as u16) + (history[2] as u16)) + (history[1] as u16)) + (history[0] as u16)) >> 2) as u8); + let recent_avg: u8 = ((((((history[7] as u16) + (history[6] as u16)) + (history[5] as u16)) + + (history[4] as u16)) + >> 2) as u8); + let older_avg: u8 = ((((((history[3] as u16) + (history[2] as u16)) + (history[1] as u16)) + + (history[0] as u16)) + >> 2) as u8); if (recent_avg > older_avg) { return ((recent_avg - older_avg) as i8); } - return -(((older_avg - recent_avg) as i8)); + return -((older_avg - recent_avg) as i8); } pub fn predict_next_etx(current: u8, trend: i8) -> u8 { @@ -74,4 +81,3 @@ pub fn classify_quality(score: u8) -> u8 { } return 4; } - diff --git a/gen/rust/link_statistics.rs b/gen/rust/link_statistics.rs index d3497415..4ac294ab 100644 --- a/gen/rust/link_statistics.rs +++ b/gen/rust/link_statistics.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 4 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub fn get_sent(stats: u32) -> u16 { return ((stats & 0xFFFF) as u16); @@ -20,4 +23,3 @@ pub fn inc_recv(stats: u32) -> u32 { pub fn reset() -> u32 { return 0; } - diff --git a/gen/rust/lite_crypto.rs b/gen/rust/lite_crypto.rs index 170f4cf7..110b0e1d 100644 --- a/gen/rust/lite_crypto.rs +++ b/gen/rust/lite_crypto.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 13 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const PSK_SIZE: u32 = 16; @@ -9,7 +12,10 @@ pub const CHACHA20_STATE_SIZE: u32 = 16; pub fn md5_process_block(block: u64, state: u64) -> (u32, u32) { let compressed: u64 = (block ^ state); - return ((((compressed >> 32) & 0xFFFFFFFF) as u32), ((compressed & 0xFFFFFFFF) as u32)); + return ( + (((compressed >> 32) & 0xFFFFFFFF) as u32), + ((compressed & 0xFFFFFFFF) as u32), + ); } pub fn md5_digest(hash1: u32, hash2: u32) -> u64 { @@ -33,4 +39,3 @@ pub fn hmac_md5(key: u32, message: u32) -> u32 { pub fn verify_hmac(key: u32, message: u32, received_mac: u32) -> bool { return (hmac_md5(key, message) == received_mac); } - diff --git a/gen/rust/load_predictor.rs b/gen/rust/load_predictor.rs index 8d67cad3..db4b7470 100644 --- a/gen/rust/load_predictor.rs +++ b/gen/rust/load_predictor.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 4 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_NODES: u32 = 8; @@ -12,7 +15,8 @@ pub const WARNING_THRESHOLD: u32 = 70; pub const PREDICTION_WINDOW: u32 = 5; pub fn create_load_metrics(bandwidth: u32, cpu: u32, packets: u32, queue: u32) -> u32 { - return (((((bandwidth & 0xFF) << 24) | ((cpu & 0xFF) << 16)) | ((packets & 0xFF) << 8)) | (queue & 0xFF)); + return (((((bandwidth & 0xFF) << 24) | ((cpu & 0xFF) << 16)) | ((packets & 0xFF) << 8)) + | (queue & 0xFF)); } pub fn get_bandwidth_usage(metrics: u32) -> u32 { @@ -32,7 +36,8 @@ pub fn get_queue_depth(metrics: u32) -> u32 { } pub fn create_prediction(load: u32, confidence: u32, trend: u32, horizon: u32) -> u32 { - return (((((load & 0xFF) << 24) | ((confidence & 0xFF) << 16)) | ((trend & 0x3) << 14)) | (horizon & 0x3FFF)); + return (((((load & 0xFF) << 24) | ((confidence & 0xFF) << 16)) | ((trend & 0x3) << 14)) + | (horizon & 0x3FFF)); } pub fn get_predicted_load(prediction: u32) -> u32 { @@ -70,8 +75,8 @@ pub fn detect_trend(history: [u32; HISTORY_SIZE as usize], count: u32) -> u32 { if (count < 3) { return 0; } - let recent: u32 = get_bandwidth_usage(history[((count - 1)) as usize]); - let previous: u32 = get_bandwidth_usage(history[((count - 3)) as usize]); + let recent: u32 = get_bandwidth_usage(history[(count - 1) as usize]); + let previous: u32 = get_bandwidth_usage(history[(count - 3) as usize]); let mut diff: u32 = 0; if (recent > previous) { diff = (recent - previous); @@ -93,7 +98,7 @@ pub fn predict_load(history: [u32; HISTORY_SIZE as usize], count: u32) -> u32 { if (count == 0) { return 0; } - let current: u32 = get_bandwidth_usage(history[((count - 1)) as usize]); + let current: u32 = get_bandwidth_usage(history[(count - 1) as usize]); let trend: u32 = detect_trend(history, count); let avg: u32 = calculate_moving_average(history, count); let mut predicted: u32 = current; @@ -250,7 +255,12 @@ pub fn calculate_load_imbalance(node_metrics: [u32; MAX_NODES as usize], node_co return imbalance; } -pub fn recommend_rerouting(prediction: u32, current_node: u32, node_metrics: [u32; MAX_NODES as usize], node_count: u32) -> u32 { +pub fn recommend_rerouting( + prediction: u32, + current_node: u32, + node_metrics: [u32; MAX_NODES as usize], + node_count: u32, +) -> u32 { if ((is_congestion_predicted(prediction)) == 0) { return current_node; } @@ -261,4 +271,3 @@ pub fn recommend_rerouting(prediction: u32, current_node: u32, node_metrics: [u3 return current_node; } } - diff --git a/gen/rust/local_processing.rs b/gen/rust/local_processing.rs index b72d6287..9d6c4a79 100644 --- a/gen/rust/local_processing.rs +++ b/gen/rust/local_processing.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 3 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_TASKS: u32 = 8; @@ -14,7 +17,8 @@ pub const TASK_PRIORITY_MEDIUM: u32 = 1; pub const TASK_PRIORITY_LOW: u32 = 2; pub fn create_task(task_id: u32, priority: u32, size: u32, time: u32) -> u32 { - return (((((task_id & 0xFF) << 24) | ((priority & 0x3) << 22)) | ((size & 0xFF) << 14)) | (time & 0x3FFF)); + return (((((task_id & 0xFF) << 24) | ((priority & 0x3) << 22)) | ((size & 0xFF) << 14)) + | (time & 0x3FFF)); } pub fn get_task_id(task: u32) -> u32 { @@ -34,7 +38,8 @@ pub fn get_processing_time(task: u32) -> u32 { } pub fn create_result(task_id: u32, status: u32, size: u32, value: u32) -> u32 { - return (((((task_id & 0xFF) << 24) | ((status & 0x3) << 22)) | ((size & 0xFF) << 14)) | (value & 0x3FFF)); + return (((((task_id & 0xFF) << 24) | ((status & 0x3) << 22)) | ((size & 0xFF) << 14)) + | (value & 0x3FFF)); } pub fn get_result_task_id(result: u32) -> u32 { @@ -144,7 +149,11 @@ pub fn can_accept_task(tasks: [u32; MAX_TASKS as usize], new_task: u32) -> u32 { } } -pub fn find_completed_result(results: [u32; MAX_RESULTS as usize], task_id: u32, count: u32) -> u32 { +pub fn find_completed_result( + results: [u32; MAX_RESULTS as usize], + task_id: u32, + count: u32, +) -> u32 { let mut i: u32 = 0; while (i < count) { let result_task_id: u32 = get_result_task_id(results[(i) as usize]); @@ -157,7 +166,11 @@ pub fn find_completed_result(results: [u32; MAX_RESULTS as usize], task_id: u32, return MAX_RESULTS; } -pub fn calculate_efficiency(tasks: [u32; MAX_TASKS as usize], results: [u32; MAX_RESULTS as usize], result_count: u32) -> u32 { +pub fn calculate_efficiency( + tasks: [u32; MAX_TASKS as usize], + results: [u32; MAX_RESULTS as usize], + result_count: u32, +) -> u32 { let mut total_input: u32 = 0; let mut total_output: u32 = 0; let mut i: u32 = 0; @@ -202,7 +215,11 @@ pub fn filter_data(data_values: [u32; MAX_RESULTS as usize], count: u32, thresho return filtered_count; } -pub fn make_local_decision(tasks: [u32; MAX_TASKS as usize], results: [u32; MAX_RESULTS as usize], result_count: u32) -> u32 { +pub fn make_local_decision( + tasks: [u32; MAX_TASKS as usize], + results: [u32; MAX_RESULTS as usize], + result_count: u32, +) -> u32 { let efficiency: u32 = calculate_efficiency(tasks, results, result_count); let pending: u32 = count_pending_tasks(tasks); if ((efficiency > 50) && (pending < (MAX_TASKS / 2))) { @@ -213,7 +230,8 @@ pub fn make_local_decision(tasks: [u32; MAX_TASKS as usize], results: [u32; MAX_ } pub fn create_resource_state(cpu: u32, memory: u32, tasks: u32, available: u32) -> u32 { - return (((((cpu & 0xFF) << 24) | ((memory & 0xFF) << 16)) | ((tasks & 0xFF) << 8)) | (available & 0xFF)); + return (((((cpu & 0xFF) << 24) | ((memory & 0xFF) << 16)) | ((tasks & 0xFF) << 8)) + | (available & 0xFF)); } pub fn get_cpu_usage(state: u32) -> u32 { @@ -259,4 +277,3 @@ pub fn has_resources(state: u32, required_cpu: u32, required_memory: u32) -> u32 return 0; } } - diff --git a/gen/rust/m3_multihop.rs b/gen/rust/m3_multihop.rs index fc0803ca..3335a498 100644 --- a/gen/rust/m3_multihop.rs +++ b/gen/rust/m3_multihop.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 9 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const NODE_A: u32 = 1; @@ -120,3 +123,46 @@ pub fn udp_packet_byte(seq: u16, byte_index: u8, data_byte: u8) -> u8 { return 0xBB; } +pub const ST_IDLE: u8 = 0; + +pub const ST_RUNNING: u8 = 1; + +pub const ST_COMPLETE: u8 = 2; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PerfCounters { + pub packets_sent: u32, + pub packets_delivered: u32, + pub packets_lost: u32, + pub bytes_sent: u32, + pub test_duration_ms: u32, +} + +pub fn calculate_throughput_mbps(counters: PerfCounters) -> u32 { + let bits: u64 = ((counters.bytes_sent as u64) * 8); + let duration_sec: u64 = ((counters.test_duration_ms as u64) / 1000); + if (duration_sec == 0) { + 0; + } else { + (((bits / duration_sec) / 1_000_000) as u32); + } +} + +pub fn calculate_loss_pct(counters: PerfCounters) -> u8 { + if (counters.packets_sent == 0) { + 0; + } else { + let lost: u32 = (counters.packets_sent - counters.packets_delivered); + let loss_p10: u32 = ((lost * 1000) / counters.packets_sent); + ((loss_p10 / 10) as u8); + } +} + +pub fn meets_targets(counters: PerfCounters, hop_count: u8) -> bool { + let throughput: u32 = calculate_throughput_mbps(counters); + let target_throughput: u32 = (TARGET_THROUGHPUT_MBPS * (hop_count as u32)); + let loss_pct: u8 = calculate_loss_pct(counters); + ((throughput >= target_throughput) && ((loss_pct as u32) < TARGET_PACKET_LOSS_PCT)); +} + +pub fn test_next_state(current_state: u8, test_complete: bool) -> u8 {} diff --git a/gen/rust/mesh_node_sim.rs b/gen/rust/mesh_node_sim.rs index 3d375e9d..ba9f1fc8 100644 --- a/gen/rust/mesh_node_sim.rs +++ b/gen/rust/mesh_node_sim.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 12 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const NODE_1: u32 = 1; @@ -30,15 +33,26 @@ pub fn is_link_good(link: u32, threshold: u8) -> bool { } pub fn create_2node_mesh(quality: u8) -> (u32, u32) { - return (create_link_quality(NODE_1, NODE_2, quality), create_link_quality(NODE_2, NODE_1, quality)); + return ( + create_link_quality(NODE_1, NODE_2, quality), + create_link_quality(NODE_2, NODE_1, quality), + ); } pub fn create_3node_mesh(q12: u8, q23: u8, q31: u8) -> (u32, u32, u32) { - return (create_link_quality(NODE_1, NODE_2, q12), create_link_quality(NODE_2, NODE_3, q23), create_link_quality(NODE_3, NODE_1, q31)); + return ( + create_link_quality(NODE_1, NODE_2, q12), + create_link_quality(NODE_2, NODE_3, q23), + create_link_quality(NODE_3, NODE_1, q31), + ); } pub fn create_4node_line(q12: u8, q23: u8, q34: u8) -> (u32, u32, u32) { - return (create_link_quality(NODE_1, NODE_2, q12), create_link_quality(NODE_2, NODE_3, q23), create_link_quality(NODE_3, NODE_4, q34)); + return ( + create_link_quality(NODE_1, NODE_2, q12), + create_link_quality(NODE_2, NODE_3, q23), + create_link_quality(NODE_3, NODE_4, q34), + ); } pub fn calculate_hops(from: u32, to: u32, topology: u8) -> u8 { @@ -51,21 +65,39 @@ pub fn calculate_hops(from: u32, to: u32, topology: u8) -> u8 { } } else { if (topology == 3) { - if (((((((from == NODE_1) && (to == NODE_2)) || ((from == NODE_2) && (to == NODE_1))) || ((from == NODE_2) && (to == NODE_3))) || ((from == NODE_3) && (to == NODE_2))) || ((from == NODE_3) && (to == NODE_1))) || ((from == NODE_1) && (to == NODE_3))) { + if (((((((from == NODE_1) && (to == NODE_2)) + || ((from == NODE_2) && (to == NODE_1))) + || ((from == NODE_2) && (to == NODE_3))) + || ((from == NODE_3) && (to == NODE_2))) + || ((from == NODE_3) && (to == NODE_1))) + || ((from == NODE_1) && (to == NODE_3))) + { return 1; } } else { if (topology == 4) { - if (((((((from == NODE_1) && (to == NODE_2)) || ((from == NODE_2) && (to == NODE_1))) || ((from == NODE_2) && (to == NODE_3))) || ((from == NODE_3) && (to == NODE_2))) || ((from == NODE_3) && (to == NODE_4))) || ((from == NODE_4) && (to == NODE_3))) { + if (((((((from == NODE_1) && (to == NODE_2)) + || ((from == NODE_2) && (to == NODE_1))) + || ((from == NODE_2) && (to == NODE_3))) + || ((from == NODE_3) && (to == NODE_2))) + || ((from == NODE_3) && (to == NODE_4))) + || ((from == NODE_4) && (to == NODE_3))) + { return 1; } else { - if (((from == NODE_1) && (to == NODE_3)) || ((from == NODE_3) && (to == NODE_1))) { + if (((from == NODE_1) && (to == NODE_3)) + || ((from == NODE_3) && (to == NODE_1))) + { return 2; } else { - if (((from == NODE_2) && (to == NODE_4)) || ((from == NODE_4) && (to == NODE_2))) { + if (((from == NODE_2) && (to == NODE_4)) + || ((from == NODE_4) && (to == NODE_2))) + { return 2; } else { - if (((from == NODE_1) && (to == NODE_4)) || ((from == NODE_4) && (to == NODE_1))) { + if (((from == NODE_1) && (to == NODE_4)) + || ((from == NODE_4) && (to == NODE_1))) + { return 3; } } @@ -76,4 +108,3 @@ pub fn calculate_hops(from: u32, to: u32, topology: u8) -> u8 { } return 255; } - diff --git a/gen/rust/mesh_protocol_stack.rs b/gen/rust/mesh_protocol_stack.rs index 0d0785cc..9f2d3ccd 100644 --- a/gen/rust/mesh_protocol_stack.rs +++ b/gen/rust/mesh_protocol_stack.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 15 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_NODES: u32 = 3; @@ -12,7 +15,8 @@ pub const NODE_B: u32 = 2; pub const NODE_C: u32 = 3; pub fn build_packet(src: u32, dst: u32, ttl: u8, payload: u8) -> u32 { - return (((((src & 0xFF) << 24) | ((dst & 0xFF) << 16)) | (((ttl as u32) & 0xF) << 12)) | ((payload as u32) & 0xFF)); + return (((((src & 0xFF) << 24) | ((dst & 0xFF) << 16)) | (((ttl as u32) & 0xF) << 12)) + | ((payload as u32) & 0xFF)); } pub fn extract_src(packet: u32) -> u32 { @@ -33,7 +37,10 @@ pub fn extract_payload(packet: u32) -> u8 { pub fn decrement_ttl(packet: u32) -> (u32, bool) { if (extract_ttl(packet) > 0) { - return (((packet & 0xFFFF0FFF) | ((((extract_ttl(packet) - 1) as u32) & 0xF) << 12)), (extract_ttl(packet) == 1)); + return ( + ((packet & 0xFFFF0FFF) | ((((extract_ttl(packet) - 1) as u32) & 0xF) << 12)), + (extract_ttl(packet) == 1), + ); } else { return (packet, true); } @@ -83,6 +90,9 @@ pub fn forward_packet(packet: u32, current_node: u32) -> (u32, bool, u32) { if (route_packet(current_node, extract_dst(new_pkt), 0) == 0) { return (new_pkt, false, 0); } - return (new_pkt, false, route_packet(current_node, extract_dst(new_pkt), 0)); + return ( + new_pkt, + false, + route_packet(current_node, extract_dst(new_pkt), 0), + ); } - diff --git a/gen/rust/mesh_routing.rs b/gen/rust/mesh_routing.rs index 513f6981..8b63aa68 100644 --- a/gen/rust/mesh_routing.rs +++ b/gen/rust/mesh_routing.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 22 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const DEFAULT_TTL: u8 = 8; diff --git a/gen/rust/modem_frame.rs b/gen/rust/modem_frame.rs index 7a201ee0..aa5a72fb 100644 --- a/gen/rust/modem_frame.rs +++ b/gen/rust/modem_frame.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 9 test(s), 3 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const PREAMBLE_LEN: usize = 13; @@ -38,4 +41,3 @@ pub fn is_synced(corr_peak: usize) -> bool { pub fn sync_margin_pct() -> usize { return ((SYNC_THRESHOLD * 100) / PEAK); } - diff --git a/gen/rust/multipath_router.rs b/gen/rust/multipath_router.rs index 0332d4dc..ce6d64a5 100644 --- a/gen/rust/multipath_router.rs +++ b/gen/rust/multipath_router.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 5 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_PATHS: u8 = 3; @@ -13,7 +16,7 @@ pub fn select_path_index(etx_values: [u8; 3]) -> u8 { if (etx_values[1] < min_etx) { best_idx = 1; } - if (etx_values[2] < etx_values[((best_idx as usize)) as usize]) { + if (etx_values[2] < etx_values[(best_idx as usize) as usize]) { best_idx = 2; } return best_idx; @@ -51,4 +54,3 @@ pub fn path_reliability(etx: u8, loss_rate: u8) -> u8 { let unreliability: u8 = ((product / 256) as u8); return (255 - unreliability); } - diff --git a/gen/rust/multipath_routing.rs b/gen/rust/multipath_routing.rs index 91d78492..998e5dd4 100644 --- a/gen/rust/multipath_routing.rs +++ b/gen/rust/multipath_routing.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 16 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_PATHS: u32 = 4; diff --git a/gen/rust/network_analytics.rs b/gen/rust/network_analytics.rs index 19da156e..473b37b8 100644 --- a/gen/rust/network_analytics.rs +++ b/gen/rust/network_analytics.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 18 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_NODES: u32 = 8; @@ -12,7 +15,8 @@ pub const TRAFFIC_HIGH: u32 = 400; pub const ANOMALY_THRESHOLD: u32 = 200; pub fn create_traffic_stats(sent: u32, recv: u32, packets: u32, errors: u32) -> u32 { - return (((((sent & 0xFF) << 24) | ((recv & 0xFF) << 16)) | ((packets & 0xFF) << 8)) | (errors & 0xFF)); + return (((((sent & 0xFF) << 24) | ((recv & 0xFF) << 16)) | ((packets & 0xFF) << 8)) + | (errors & 0xFF)); } pub fn get_bytes_sent(stats: u32) -> u32 { @@ -32,7 +36,9 @@ pub fn get_error_count(stats: u32) -> u32 { } pub fn create_analysis_data(node_id: u32, traffic: u32, window_start: u32, pattern: u32) -> u64 { - return (((((node_id as u64) << 48) | ((traffic as u64) << 24)) | ((window_start as u64) << 12)) | (pattern as u64)); + return (((((node_id as u64) << 48) | ((traffic as u64) << 24)) + | ((window_start as u64) << 12)) + | (pattern as u64)); } pub fn get_analysis_node_id(data: u64) -> u32 { @@ -104,12 +110,23 @@ pub fn detect_pattern(stats: u32, previous_stats: u32) -> u32 { return PATTERN_NORMAL; } -pub fn update_traffic(stats: u32, sent_add: u32, recv_add: u32, packets_add: u32, errors_add: u32) -> u32 { +pub fn update_traffic( + stats: u32, + sent_add: u32, + recv_add: u32, + packets_add: u32, + errors_add: u32, +) -> u32 { let sent = get_bytes_sent(stats); let recv = get_bytes_recv(stats); let packets = get_packet_count(stats); let errors = get_error_count(stats); - return create_traffic_stats((sent + sent_add), (recv + recv_add), (packets + packets_add), (errors + errors_add)); + return create_traffic_stats( + (sent + sent_add), + (recv + recv_add), + (packets + packets_add), + (errors + errors_add), + ); } pub fn needs_attention(data: u64) -> bool { @@ -130,4 +147,3 @@ pub fn calculate_utilization(stats: u32, max_capacity: u32) -> u32 { pub fn is_congested(stats: u32, max_capacity: u32) -> bool { return (calculate_utilization(stats, max_capacity) > 80); } - diff --git a/gen/rust/network_coding.rs b/gen/rust/network_coding.rs index 887f10a6..6688016b 100644 --- a/gen/rust/network_coding.rs +++ b/gen/rust/network_coding.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 18 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_PACKETS: u32 = 4; @@ -8,7 +11,8 @@ pub const CODING_WINDOW: u32 = 1000; pub const MAX_GENERATION_SIZE: u32 = 4; pub fn create_packet(src: u32, dst: u32, payload: u32, seq: u32) -> u32 { - return (((((src & 0xFF) << 24) | ((dst & 0xFF) << 16)) | ((payload & 0xFF) << 8)) | (seq & 0xFF)); + return (((((src & 0xFF) << 24) | ((dst & 0xFF) << 16)) | ((payload & 0xFF) << 8)) + | (seq & 0xFF)); } pub fn get_packet_src(packet: u32) -> u32 { @@ -28,7 +32,8 @@ pub fn get_packet_seq(packet: u32) -> u32 { } pub fn create_coded_packet(coeff: u32, payload: u32, generation: u32, seq: u32) -> u32 { - return (((((coeff & 0xF) << 28) | ((payload & 0xFF) << 20)) | ((generation & 0xFF) << 12)) | (seq & 0xFFF)); + return (((((coeff & 0xF) << 28) | ((payload & 0xFF) << 20)) | ((generation & 0xFF) << 12)) + | (seq & 0xFFF)); } pub fn get_coeff_vector(coded: u32) -> u32 { @@ -61,7 +66,12 @@ pub fn decode_xoded_packet(coded: u32, known_pkt: u32) -> u32 { let coded_payload = get_coded_payload(coded); let known_payload = get_packet_payload(known_pkt); let decoded_payload = (coded_payload ^ known_payload); - return create_packet(get_packet_src(known_pkt), get_packet_dst(known_pkt), decoded_payload, get_coded_seq(coded)); + return create_packet( + get_packet_src(known_pkt), + get_packet_dst(known_pkt), + decoded_payload, + get_coded_seq(coded), + ); } pub fn same_generation(pkt1: u32, pkt2: u32) -> bool { @@ -93,7 +103,7 @@ pub fn linear_code_packets(pkt1: u32, pkt2: u32, coeff1: u32, coeff2: u32) -> u3 } pub fn create_coded_generation(p0: u32, p1: u32, p2: u32, p3: u32) -> [u32; 4] { - return [p0,p1,p2,p3]; + return [p0, p1, p2, p3]; } pub fn get_coded_packet_gen(gen: [u32; 4], index: u32) -> u32 { @@ -134,4 +144,3 @@ pub fn calculate_coding_gain(original: u32, coded: u32) -> u32 { } return (original - coded); } - diff --git a/gen/rust/network_metrics.rs b/gen/rust/network_metrics.rs index 80fadcf0..622a39f1 100644 --- a/gen/rust/network_metrics.rs +++ b/gen/rust/network_metrics.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 8 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub fn get_sent(metrics: u32) -> u32 { return metrics; @@ -35,4 +38,3 @@ pub fn success_rate(sent: u32, success: u32) -> u8 { return 0; } } - diff --git a/gen/rust/network_orchestrator.rs b/gen/rust/network_orchestrator.rs index 82ad975c..a90f0219 100644 --- a/gen/rust/network_orchestrator.rs +++ b/gen/rust/network_orchestrator.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 3 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_NODES: u32 = 8; @@ -10,7 +13,8 @@ pub const OPTIMIZATION_INTERVAL: u32 = 1000; pub const COORDINATION_TIMEOUT: u32 = 500; pub fn create_network_policy(policy_id: u32, priority: u32, scope: u32, parameter: u32) -> u32 { - return (((((policy_id & 0xFF) << 24) | ((priority & 0xFF) << 16)) | ((scope & 0xF) << 12)) | (parameter & 0xFFF)); + return (((((policy_id & 0xFF) << 24) | ((priority & 0xFF) << 16)) | ((scope & 0xF) << 12)) + | (parameter & 0xFFF)); } pub fn get_policy_id(policy: u32) -> u32 { @@ -38,7 +42,8 @@ pub const SCOPE_NETWORK: u32 = 2; pub const SCOPE_GLOBAL: u32 = 3; pub fn create_coordination_state(coordinator_id: u32, state: u32, phase: u32, timeout: u32) -> u32 { - return (((((coordinator_id & 0xFF) << 24) | ((state & 0xF) << 20)) | ((phase & 0xF) << 16)) | (timeout & 0xFFFF)); + return (((((coordinator_id & 0xFF) << 24) | ((state & 0xF) << 20)) | ((phase & 0xF) << 16)) + | (timeout & 0xFFFF)); } pub fn get_coordinator_id(state: u32) -> u32 { @@ -84,7 +89,12 @@ pub fn advance_phase(state: u32) -> u32 { if (phase >= 3) { return create_coordination_state(coordinator_id, STATE_EXECUTING, 0, timeout); } else { - return create_coordination_state(coordinator_id, STATE_NEGOTIATING, (phase + 1), timeout); + return create_coordination_state( + coordinator_id, + STATE_NEGOTIATING, + (phase + 1), + timeout, + ); } } else { if (coord_state == STATE_EXECUTING) { @@ -149,8 +159,14 @@ pub fn find_highest_priority_policy(policies: [u32; MAX_POLICIES as usize], scop return policy_index; } -pub fn create_optimization_request(request_id: u32, opt_type: u32, target: u32, priority: u32) -> u32 { - return (((((request_id & 0xFF) << 24) | ((opt_type & 0xF) << 20)) | ((target & 0xFF) << 12)) | (priority & 0xFFF)); +pub fn create_optimization_request( + request_id: u32, + opt_type: u32, + target: u32, + priority: u32, +) -> u32 { + return (((((request_id & 0xFF) << 24) | ((opt_type & 0xF) << 20)) | ((target & 0xFF) << 12)) + | (priority & 0xFFF)); } pub fn get_optimization_request_id(request: u32) -> u32 { @@ -200,7 +216,9 @@ pub fn process_optimization(request: u32, policies: [u32; MAX_POLICIES as usize] } pub fn create_network_action(action_id: u32, action_type: u32, target: u32, parameter: u32) -> u32 { - return (((((action_id & 0xFF) << 24) | ((action_type & 0xF) << 20)) | ((target & 0xFF) << 12)) | (parameter & 0xFFF)); + return (((((action_id & 0xFF) << 24) | ((action_type & 0xF) << 20)) + | ((target & 0xFF) << 12)) + | (parameter & 0xFFF)); } pub fn get_action_id(action: u32) -> u32 { @@ -250,7 +268,12 @@ pub fn execute_action(action: u32, current_time: u32) -> u32 { } } -pub fn coordinate_nodes(node_states: [u32; MAX_NODES as usize], node_count: u32, coordinator_id: u32, current_time: u32) -> u32 { +pub fn coordinate_nodes( + node_states: [u32; MAX_NODES as usize], + node_count: u32, + coordinator_id: u32, + current_time: u32, +) -> u32 { let coord_state: u32 = initiate_coordination(0, coordinator_id, current_time); let mut participating_nodes: u32 = 0; let mut i: u32 = 0; @@ -282,7 +305,11 @@ pub fn calculate_optimization_score(metrics: [u32; MAX_NODES as usize], metric_c } } -pub fn detect_optimization_opportunity(load_metrics: [u32; MAX_NODES as usize], energy_metrics: [u32; MAX_NODES as usize], node_count: u32) -> u32 { +pub fn detect_optimization_opportunity( + load_metrics: [u32; MAX_NODES as usize], + energy_metrics: [u32; MAX_NODES as usize], + node_count: u32, +) -> u32 { let load_score: u32 = calculate_optimization_score(load_metrics, node_count); let energy_score: u32 = calculate_optimization_score(energy_metrics, node_count); if ((load_score > 70) || (energy_score < 30)) { @@ -311,4 +338,3 @@ pub fn monitor_network_health(node_states: [u32; MAX_NODES as usize], node_count return 0; } } - diff --git a/gen/rust/network_simulator.rs b/gen/rust/network_simulator.rs index 4524d459..1c9e73ff 100644 --- a/gen/rust/network_simulator.rs +++ b/gen/rust/network_simulator.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 2 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_NODES: u32 = 32; @@ -10,7 +13,9 @@ pub const MAX_PACKETS: u32 = 64; pub const SIMULATION_TICK_MS: u32 = 10; pub fn create_sim_event(event_id: u32, timestamp: u32, event_type: u32, node_id: u32) -> u32 { - return (((((event_id & 0xFF) << 24) | ((timestamp & 0xFFFF) << 8)) | ((event_type & 0xF) << 4)) | (node_id & 0xF)); + return (((((event_id & 0xFF) << 24) | ((timestamp & 0xFFFF) << 8)) + | ((event_type & 0xF) << 4)) + | (node_id & 0xF)); } pub fn get_event_id(event: u32) -> u32 { @@ -42,7 +47,8 @@ pub const EVENT_TIMER_EXPIRE: u32 = 4; pub const EVENT_STATE_CHANGE: u32 = 5; pub fn create_node_state(node_id: u32, status: u32, energy: u32, position: u32) -> u32 { - return (((((node_id & 0xF) << 28) | ((status & 0xF) << 24)) | ((energy & 0xFF) << 16)) | (position & 0xFFFF)); + return (((((node_id & 0xF) << 28) | ((status & 0xF) << 24)) | ((energy & 0xFF) << 16)) + | (position & 0xFFFF)); } pub fn get_node_id(state: u32) -> u32 { @@ -95,7 +101,8 @@ pub fn update_node_energy(state: u32, energy_delta: u32) -> u32 { } pub fn create_link_state(source: u32, dest: u32, quality: u32, latency: u32) -> u32 { - return (((((source & 0xF) << 28) | ((dest & 0xF) << 24)) | ((quality & 0xFF) << 16)) | (latency & 0xFFFF)); + return (((((source & 0xF) << 28) | ((dest & 0xF) << 24)) | ((quality & 0xFF) << 16)) + | (latency & 0xFFFF)); } pub fn get_link_source(link: u32) -> u32 { @@ -131,7 +138,9 @@ pub fn is_link_operational(link: u32) -> u32 { } pub fn create_packet(packet_id: u32, source: u32, dest: u32, size: u32, sequence: u32) -> u32 { - return ((((((packet_id & 0xFF) << 24) | ((source & 0xF) << 20)) | ((dest & 0xF) << 16)) | ((size & 0xFF) << 8)) | (sequence & 0xFF)); + return ((((((packet_id & 0xFF) << 24) | ((source & 0xF) << 20)) | ((dest & 0xF) << 16)) + | ((size & 0xFF) << 8)) + | (sequence & 0xFF)); } pub fn get_packet_id(packet: u32) -> u32 { @@ -185,7 +194,11 @@ pub fn advance_simulation(state: u32, time_delta: u32) -> u32 { return create_sim_state(new_time, event_count, node_count); } -pub fn process_event(event: u32, node_states: [u32; MAX_NODES as usize], link_states: [u32; MAX_NODES as usize]) -> u32 { +pub fn process_event( + event: u32, + node_states: [u32; MAX_NODES as usize], + link_states: [u32; MAX_NODES as usize], +) -> u32 { let event_type: u32 = get_event_type(event); let node_id: u32 = get_event_node_id(event); if (event_type == EVENT_PACKET_SEND) { @@ -214,7 +227,8 @@ pub fn process_event(event: u32, node_states: [u32; MAX_NODES as usize], link_st } pub fn create_sim_stats(sent: u32, recv: u32, dropped: u32, latency: u32) -> u32 { - return (((((sent & 0xFF) << 24) | ((recv & 0xFF) << 16)) | ((dropped & 0xFF) << 8)) | (latency & 0xFF)); + return (((((sent & 0xFF) << 24) | ((recv & 0xFF) << 16)) | ((dropped & 0xFF) << 8)) + | (latency & 0xFF)); } pub fn get_packets_sent(stats: u32) -> u32 { @@ -261,7 +275,11 @@ pub fn create_topology(node_count: u32, density: u32) -> u32 { return link_count; } -pub fn inject_fault(fault_type: u32, target_id: u32, node_states: [u32; MAX_NODES as usize]) -> u32 { +pub fn inject_fault( + fault_type: u32, + target_id: u32, + node_states: [u32; MAX_NODES as usize], +) -> u32 { if (fault_type == EVENT_NODE_FAILURE) { let current_state: u32 = node_states[(target_id) as usize]; node_states[(target_id) as usize] = update_node_status(current_state, NODE_FAILED); @@ -275,7 +293,13 @@ pub fn inject_fault(fault_type: u32, target_id: u32, node_states: [u32; MAX_NODE } } -pub fn run_simulation_step(state: u32, events: [u32; MAX_EVENTS as usize], event_count: u32, node_states: [u32; MAX_NODES as usize], link_states: [u32; MAX_NODES as usize]) -> u32 { +pub fn run_simulation_step( + state: u32, + events: [u32; MAX_EVENTS as usize], + event_count: u32, + node_states: [u32; MAX_NODES as usize], + link_states: [u32; MAX_NODES as usize], +) -> u32 { let current_time: u32 = get_sim_time(state); let mut processed_count: u32 = 0; let mut i: u32 = 0; @@ -288,12 +312,17 @@ pub fn run_simulation_step(state: u32, events: [u32; MAX_EVENTS as usize], event i = (i + 1); } let new_state: u32 = advance_simulation(state, SIMULATION_TICK_MS); - return create_sim_state(get_sim_time(new_state), (get_sim_event_count(new_state) - processed_count), get_sim_node_count(new_state)); + return create_sim_state( + get_sim_time(new_state), + (get_sim_event_count(new_state) - processed_count), + get_sim_node_count(new_state), + ); } pub fn generate_simulation_report(stats: u32, duration: u32, node_count: u32) -> u32 { let delivery_ratio: u32 = calculate_delivery_ratio(stats); let avg_latency: u32 = calculate_average_latency(stats); - return (((((delivery_ratio & 0xFF) << 24) | ((avg_latency & 0xFF) << 16)) | ((duration & 0xFF) << 8)) | (node_count & 0xFF)); + return (((((delivery_ratio & 0xFF) << 24) | ((avg_latency & 0xFF) << 16)) + | ((duration & 0xFF) << 8)) + | (node_count & 0xFF)); } - diff --git a/gen/rust/olsr_routing.rs b/gen/rust/olsr_routing.rs index 6e6bedf3..80d66cb4 100644 --- a/gen/rust/olsr_routing.rs +++ b/gen/rust/olsr_routing.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 6 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_NEIGHBORS: u32 = 4; @@ -30,7 +33,7 @@ pub fn is_valid(entry: u32, time: u32) -> bool { } pub fn get_id_at(table: [u32; 4], index: u32) -> u32 { - return get_id(table[((index as usize)) as usize]); + return get_id(table[(index as usize) as usize]); } pub fn find_index(table: [u32; 4], target_id: u32) -> u32 { @@ -77,7 +80,10 @@ pub fn best_of_two(a: u32, b: u32) -> u32 { } pub fn get_best_neighbor(table: [u32; 4]) -> u32 { - return get_id(best_of_two(best_of_two(table[0], table[1]), best_of_two(table[2], table[3]))); + return get_id(best_of_two( + best_of_two(table[0], table[1]), + best_of_two(table[2], table[3]), + )); } pub fn mask_if_id(entry: u32, best_id: u32) -> u32 { @@ -89,7 +95,10 @@ pub fn mask_if_id(entry: u32, best_id: u32) -> u32 { } pub fn get_second_best(table: [u32; 4], best_id: u32) -> u32 { - return get_id(best_of_two(best_of_two(mask_if_id(table[0], best_id), mask_if_id(table[1], best_id)), best_of_two(mask_if_id(table[2], best_id), mask_if_id(table[3], best_id)))); + return get_id(best_of_two( + best_of_two(mask_if_id(table[0], best_id), mask_if_id(table[1], best_id)), + best_of_two(mask_if_id(table[2], best_id), mask_if_id(table[3], best_id)), + )); } pub fn select_mprs(table: [u32; 4]) -> u32 { @@ -107,6 +116,6 @@ pub fn one_if_present(entry: u32) -> u32 { } pub fn count_neighbors(table: [u32; 4]) -> u32 { - return (((one_if_present(table[0]) + one_if_present(table[1])) + one_if_present(table[2])) + one_if_present(table[3])); + return (((one_if_present(table[0]) + one_if_present(table[1])) + one_if_present(table[2])) + + one_if_present(table[3])); } - diff --git a/gen/rust/packet_loss_injection.rs b/gen/rust/packet_loss_injection.rs index e6fa277a..d842c8fb 100644 --- a/gen/rust/packet_loss_injection.rs +++ b/gen/rust/packet_loss_injection.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 15 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const ERROR_NONE: u8 = 0; @@ -22,7 +25,8 @@ pub fn inject_bit_flip(packet: u32, bit_pos: u8) -> u32 { } pub fn calculate_crc(packet: u32) -> u16 { - return ((((((packet >> 24) & 0xFF) + ((packet >> 16) & 0xFF)) + ((packet >> 8) & 0xFF)) + (packet & 0xFF)) as u16); + return ((((((packet >> 24) & 0xFF) + ((packet >> 16) & 0xFF)) + ((packet >> 8) & 0xFF)) + + (packet & 0xFF)) as u16); } pub fn verify_crc(packet: u32, received_crc: u16) -> bool { @@ -52,4 +56,3 @@ pub fn check_replay(packet: u32, last_seq: u32) -> bool { pub fn extract_sequence(packet: u32) -> u32 { return (packet & 0xFFFF); } - diff --git a/gen/rust/packet_queue.rs b/gen/rust/packet_queue.rs index 3f1e87cb..4536c09d 100644 --- a/gen/rust/packet_queue.rs +++ b/gen/rust/packet_queue.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 9 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const QUEUE_SIZE: u8 = 8; @@ -50,4 +53,3 @@ pub fn size(state: u32) -> u8 { pub fn clear() -> u32 { return 0; } - diff --git a/gen/rust/pattern_predictor.rs b/gen/rust/pattern_predictor.rs index 64e19e31..bc336442 100644 --- a/gen/rust/pattern_predictor.rs +++ b/gen/rust/pattern_predictor.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 16 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_SAMPLES: u32 = 16; @@ -8,7 +11,8 @@ pub const PATTERN_WINDOW: u32 = 8; pub const ANOMALY_THRESHOLD: u32 = 50; pub fn create_sample(value: u32, timestamp: u32, sequence: u32, valid: u32) -> u32 { - return (((((value & 0xFF) << 24) | ((timestamp & 0xFF) << 16)) | ((sequence & 0xFF) << 8)) | (valid & 0x1)); + return (((((value & 0xFF) << 24) | ((timestamp & 0xFF) << 16)) | ((sequence & 0xFF) << 8)) + | (valid & 0x1)); } pub fn get_sample_value(sample: u32) -> u32 { @@ -27,8 +31,14 @@ pub fn get_sample_valid(sample: u32) -> u32 { return (sample & 0x1); } -pub fn create_pattern_storage(samples: u32, pattern_count: u32, trend: u32, last_update: u32) -> u32 { - return (((((samples & 0xFFFF) << 16) | ((pattern_count & 0xFF) << 8)) | (trend & 0x3)) | (last_update & 0x1)); +pub fn create_pattern_storage( + samples: u32, + pattern_count: u32, + trend: u32, + last_update: u32, +) -> u32 { + return (((((samples & 0xFFFF) << 16) | ((pattern_count & 0xFF) << 8)) | (trend & 0x3)) + | (last_update & 0x1)); } pub fn get_pattern_samples(storage: u32) -> u32 { @@ -43,8 +53,27 @@ pub fn get_trend_direction(storage: u32) -> u32 { return (storage & 0x3); } -pub fn create_sample_array(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: u32, s7: u32, s8: u32, s9: u32, s10: u32, s11: u32, s12: u32, s13: u32, s14: u32, s15: u32) -> [u32; 16] { - return [s0,s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13,s14,s15]; +pub fn create_sample_array( + s0: u32, + s1: u32, + s2: u32, + s3: u32, + s4: u32, + s5: u32, + s6: u32, + s7: u32, + s8: u32, + s9: u32, + s10: u32, + s11: u32, + s12: u32, + s13: u32, + s14: u32, + s15: u32, +) -> [u32; 16] { + return [ + s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, + ]; } pub fn get_sample_at(array: [u32; 16], index: u32) -> u32 { @@ -201,4 +230,3 @@ pub fn calculate_variance(array: [u32; 16], samples: u32) -> u32 { } return (sum_sq_diff / samples); } - diff --git a/gen/rust/performance_benchmarks.rs b/gen/rust/performance_benchmarks.rs index 4591778c..4cf7a0eb 100644 --- a/gen/rust/performance_benchmarks.rs +++ b/gen/rust/performance_benchmarks.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 16 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_QUEUE_SIZE: u32 = 16; @@ -25,7 +28,11 @@ pub fn queue_tail(queue: u32) -> u32 { pub fn queue_enqueue(queue: u32) -> u32 { if (queue_count(queue) < MAX_QUEUE_SIZE) { - return create_queue((queue_count(queue) + 1), queue_head(queue), ((queue_tail(queue) + 1) % MAX_QUEUE_SIZE)); + return create_queue( + (queue_count(queue) + 1), + queue_head(queue), + ((queue_tail(queue) + 1) % MAX_QUEUE_SIZE), + ); } else { return queue; } @@ -33,7 +40,11 @@ pub fn queue_enqueue(queue: u32) -> u32 { pub fn queue_dequeue(queue: u32) -> u32 { if (queue_count(queue) > 0) { - return create_queue((queue_count(queue) - 1), ((queue_head(queue) + 1) % MAX_QUEUE_SIZE), queue_tail(queue)); + return create_queue( + (queue_count(queue) - 1), + ((queue_head(queue) + 1) % MAX_QUEUE_SIZE), + queue_tail(queue), + ); } else { return queue; } @@ -70,4 +81,3 @@ pub fn microseconds_to_ticks(us: u32) -> u32 { pub fn ticks_to_milliseconds(ticks: u32) -> u32 { return (ticks / 10); } - diff --git a/gen/rust/performance_profiler.rs b/gen/rust/performance_profiler.rs index 3840f113..04cf0772 100644 --- a/gen/rust/performance_profiler.rs +++ b/gen/rust/performance_profiler.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 2 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_SAMPLES: u32 = 64; @@ -10,7 +13,8 @@ pub const PROFILING_INTERVAL_MS: u32 = 100; pub const OVERHEAD_THRESHOLD: u32 = 5; pub fn create_perf_sample(func_id: u32, cpu: u32, memory: u32, timestamp: u32) -> u32 { - return (((((func_id & 0xFF) << 24) | ((cpu & 0xFF) << 16)) | ((memory & 0xFF) << 8)) | (timestamp & 0xFF)); + return (((((func_id & 0xFF) << 24) | ((cpu & 0xFF) << 16)) | ((memory & 0xFF) << 8)) + | (timestamp & 0xFF)); } pub fn get_sample_function_id(sample: u32) -> u32 { @@ -46,7 +50,8 @@ pub fn get_profile_total_cpu(profile: u32) -> u32 { } pub fn create_hotspot(func_id: u32, score: u32, rank: u32, impact: u32) -> u32 { - return (((((func_id & 0xFF) << 24) | ((score & 0xFF) << 16)) | ((rank & 0xFF) << 8)) | (impact & 0xFF)); + return (((((func_id & 0xFF) << 24) | ((score & 0xFF) << 16)) | ((rank & 0xFF) << 8)) + | (impact & 0xFF)); } pub fn get_hotspot_function_id(hotspot: u32) -> u32 { @@ -65,7 +70,11 @@ pub fn get_hotspot_impact(hotspot: u32) -> u32 { return (hotspot & 0xFF); } -pub fn calculate_average_cpu(samples: [u32; MAX_SAMPLES as usize], sample_count: u32, func_id: u32) -> u32 { +pub fn calculate_average_cpu( + samples: [u32; MAX_SAMPLES as usize], + sample_count: u32, + func_id: u32, +) -> u32 { let mut total_cpu: u32 = 0; let mut matching_samples: u32 = 0; let mut i: u32 = 0; @@ -83,7 +92,11 @@ pub fn calculate_average_cpu(samples: [u32; MAX_SAMPLES as usize], sample_count: } } -pub fn calculate_average_memory(samples: [u32; MAX_SAMPLES as usize], sample_count: u32, func_id: u32) -> u32 { +pub fn calculate_average_memory( + samples: [u32; MAX_SAMPLES as usize], + sample_count: u32, + func_id: u32, +) -> u32 { let mut total_memory: u32 = 0; let mut matching_samples: u32 = 0; let mut i: u32 = 0; @@ -141,7 +154,8 @@ pub fn is_overhead_acceptable(overhead_percentage: u32) -> u32 { } pub fn create_allocation(alloc_id: u32, size: u32, lifetime: u32, pool: u32) -> u32 { - return (((((alloc_id & 0xFF) << 24) | ((size & 0xFF) << 16)) | ((lifetime & 0xFF) << 8)) | (pool & 0xFF)); + return (((((alloc_id & 0xFF) << 24) | ((size & 0xFF) << 16)) | ((lifetime & 0xFF) << 8)) + | (pool & 0xFF)); } pub fn get_allocation_id(alloc: u32) -> u32 { @@ -160,7 +174,12 @@ pub fn get_allocation_pool(alloc: u32) -> u32 { return (alloc & 0xFF); } -pub fn track_allocation(allocations: [u32; MAX_SAMPLES as usize], alloc_id: u32, size: u32, pool: u32) -> u32 { +pub fn track_allocation( + allocations: [u32; MAX_SAMPLES as usize], + alloc_id: u32, + size: u32, + pool: u32, +) -> u32 { let mut i: u32 = 0; while (i < MAX_SAMPLES) { if (get_allocation_id(allocations[(i) as usize]) == 0) { @@ -183,7 +202,11 @@ pub fn calculate_total_memory(allocations: [u32; MAX_SAMPLES as usize], sample_c return total_memory; } -pub fn detect_memory_leak(allocations: [u32; MAX_SAMPLES as usize], current_count: u32, previous_count: u32) -> u32 { +pub fn detect_memory_leak( + allocations: [u32; MAX_SAMPLES as usize], + current_count: u32, + previous_count: u32, +) -> u32 { if (current_count > previous_count) { let growth: u32 = (current_count - previous_count); if (growth > 5) { @@ -194,7 +217,8 @@ pub fn detect_memory_leak(allocations: [u32; MAX_SAMPLES as usize], current_coun } pub fn create_call_stack_entry(depth: u32, func_id: u32, parent_id: u32, cpu_contrib: u32) -> u32 { - return (((((depth & 0xFF) << 24) | ((func_id & 0xFF) << 16)) | ((parent_id & 0xFF) << 8)) | (cpu_contrib & 0xFF)); + return (((((depth & 0xFF) << 24) | ((func_id & 0xFF) << 16)) | ((parent_id & 0xFF) << 8)) + | (cpu_contrib & 0xFF)); } pub fn get_stack_depth(entry: u32) -> u32 { @@ -233,8 +257,15 @@ pub fn analyze_call_tree(call_stack: [u32; MAX_SAMPLES as usize], stack_size: u3 return ((((max_depth & 0xFF) << 24) | ((total_cpu & 0xFF) << 16)) | ((avg_cpu & 0xFF) << 8)); } -pub fn create_performance_report(total_cpu: u32, total_mem: u32, hotspots: u32, overhead: u32) -> u32 { - return (((((total_cpu & 0xFF) << 24) | ((total_mem & 0xFF) << 16)) | ((hotspots & 0xFF) << 8)) | (overhead & 0xFF)); +pub fn create_performance_report( + total_cpu: u32, + total_mem: u32, + hotspots: u32, + overhead: u32, +) -> u32 { + return (((((total_cpu & 0xFF) << 24) | ((total_mem & 0xFF) << 16)) + | ((hotspots & 0xFF) << 8)) + | (overhead & 0xFF)); } pub fn get_report_total_cpu(report: u32) -> u32 { @@ -270,7 +301,9 @@ pub fn generate_recommendations(report: u32, hotspot: u32) -> u32 { if (overhead > OVERHEAD_THRESHOLD) { rec_reduce_overhead = 1; } - return (((((rec_optimize_cpu & 0x1) << 3) | ((rec_optimize_memory & 0x1) << 2)) | ((rec_reduce_overhead & 0x1) << 1)) | (rec_parallelize & 0x1)); + return (((((rec_optimize_cpu & 0x1) << 3) | ((rec_optimize_memory & 0x1) << 2)) + | ((rec_reduce_overhead & 0x1) << 1)) + | (rec_parallelize & 0x1)); } pub fn calculate_improvement_opportunity(current_performance: u32, target_performance: u32) -> u32 { @@ -281,4 +314,3 @@ pub fn calculate_improvement_opportunity(current_performance: u32, target_perfor let opportunity: u32 = ((gap * 100) / target_performance); return opportunity; } - diff --git a/gen/rust/power_monitoring.rs b/gen/rust/power_monitoring.rs index c227cfb9..4eb8e84e 100644 --- a/gen/rust/power_monitoring.rs +++ b/gen/rust/power_monitoring.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 20 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_NODES: u32 = 8; @@ -16,7 +19,9 @@ pub const POWER_ECO: u32 = 1; pub const POWER_EMERGENCY: u32 = 2; pub fn create_power_state(battery: u32, power_mode: u32, consumption: u32, uptime: u32) -> u32 { - return (((((battery & 0xFF) << 24) | ((power_mode & 0x3) << 22)) | ((consumption & 0x3FF) << 12)) | (uptime & 0xFFF)); + return (((((battery & 0xFF) << 24) | ((power_mode & 0x3) << 22)) + | ((consumption & 0x3FF) << 12)) + | (uptime & 0xFFF)); } pub fn get_battery_level(state: u32) -> u32 { @@ -122,4 +127,3 @@ pub fn should_sleep(state: u32, current_time: u32, sleep_start: u32, sleep_end: } return false; } - diff --git a/gen/rust/production_deployment.rs b/gen/rust/production_deployment.rs index f44bd57f..f57e2a39 100644 --- a/gen/rust/production_deployment.rs +++ b/gen/rust/production_deployment.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 15 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const DEPLOY_PENDING: u32 = 0; @@ -20,7 +23,8 @@ pub const STEP_VERIFY: u32 = 3; pub const STEP_MONITOR: u32 = 4; pub fn create_deployment(state: u32, step: u32, progress: u32, device_id: u32) -> u32 { - return (((((state & 0x7) << 29) | ((step & 0xF) << 25)) | ((progress & 0x1F) << 20)) | (device_id & 0xFFFFF)); + return (((((state & 0x7) << 29) | ((step & 0xF) << 25)) | ((progress & 0x1F) << 20)) + | (device_id & 0xFFFFF)); } pub fn extract_deploy_state(deploy: u32) -> u32 { @@ -40,7 +44,8 @@ pub fn extract_device_id(deploy: u32) -> u32 { } pub fn deployment_complete(deploy: u32) -> bool { - return ((extract_deploy_state(deploy) == DEPLOY_ACTIVE) && (extract_deploy_progress(deploy) == 31)); + return ((extract_deploy_state(deploy) == DEPLOY_ACTIVE) + && (extract_deploy_progress(deploy) == 31)); } pub fn create_bitstream_info(size: u32, checksum: u32, version: u32) -> u32 { @@ -111,4 +116,3 @@ pub fn checklist_monitoring(checklist: u32) -> bool { pub fn checklist_complete(checklist: u32) -> bool { return (checklist == 0xF); } - diff --git a/gen/rust/production_scenarios.rs b/gen/rust/production_scenarios.rs index 3a8a2d48..491b8dd3 100644 --- a/gen/rust/production_scenarios.rs +++ b/gen/rust/production_scenarios.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 14 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const STATE_COLD_START: u8 = 0; @@ -36,7 +39,11 @@ pub fn discover_neighbor(state_word: u32) -> u32 { return create_node_state(STATE_DISCOVERING, 0, node_uptime(state_word)); } else { if (node_state_of(state_word) == STATE_DISCOVERING) { - return create_node_state(STATE_CONNECTED, (node_neighbors(state_word) + 1), node_uptime(state_word)); + return create_node_state( + STATE_CONNECTED, + (node_neighbors(state_word) + 1), + node_uptime(state_word), + ); } else { return state_word; } @@ -60,12 +67,20 @@ pub fn recover_from_partition(node_state: u32) -> u32 { } pub fn node_join(existing_node: u32) -> u32 { - return create_node_state(node_state_of(existing_node), (node_neighbors(existing_node) + 1), node_uptime(existing_node)); + return create_node_state( + node_state_of(existing_node), + (node_neighbors(existing_node) + 1), + node_uptime(existing_node), + ); } pub fn node_leave(existing_node: u32) -> u32 { if (node_neighbors(existing_node) > 0) { - return create_node_state(node_state_of(existing_node), (node_neighbors(existing_node) - 1), node_uptime(existing_node)); + return create_node_state( + node_state_of(existing_node), + (node_neighbors(existing_node) - 1), + node_uptime(existing_node), + ); } else { return existing_node; } @@ -90,4 +105,3 @@ pub fn battery_drain(uptime: u32, drain_rate: u32) -> u32 { pub fn check_max_hops(ttl: u8, max_hops: u8) -> bool { return ((ttl > 0) && (ttl <= max_hops)); } - diff --git a/gen/rust/quarantine_manager.rs b/gen/rust/quarantine_manager.rs index cfbd4613..d25872a7 100644 --- a/gen/rust/quarantine_manager.rs +++ b/gen/rust/quarantine_manager.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 3 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_NODES: u32 = 8; diff --git a/gen/rust/redundancy_management.rs b/gen/rust/redundancy_management.rs index a94a9fcc..79dffebf 100644 --- a/gen/rust/redundancy_management.rs +++ b/gen/rust/redundancy_management.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 16 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_PATHS: u32 = 4; @@ -10,7 +13,8 @@ pub const PATH_VALID: u32 = 1; pub const PATH_INVALID: u32 = 0; pub fn create_path(valid: u32, hop1: u32, hop2: u32, hop3: u32) -> u32 { - return (((((valid & 0x1) << 24) | ((hop1 & 0xFF) << 16)) | ((hop2 & 0xFF) << 8)) | (hop3 & 0xFF)); + return (((((valid & 0x1) << 24) | ((hop1 & 0xFF) << 16)) | ((hop2 & 0xFF) << 8)) + | (hop3 & 0xFF)); } pub fn get_path_valid(path: u32) -> u32 { @@ -30,7 +34,7 @@ pub fn get_hop3(path: u32) -> u32 { } pub fn create_path_set(p0: u32, p1: u32, p2: u32, p3: u32) -> [u32; 4] { - return [p0,p1,p2,p3]; + return [p0, p1, p2, p3]; } pub fn set_slot4(array: [u32; 4], index: u32, value: u32) -> [u32; 4] { @@ -39,15 +43,15 @@ pub fn set_slot4(array: [u32; 4], index: u32, value: u32) -> [u32; 4] { let a2: u32 = array[2]; let a3: u32 = array[3]; if (index == 0) { - return [value,a1,a2,a3]; + return [value, a1, a2, a3]; } if (index == 1) { - return [a0,value,a2,a3]; + return [a0, value, a2, a3]; } if (index == 2) { - return [a0,a1,value,a3]; + return [a0, a1, value, a3]; } - return [a0,a1,a2,value]; + return [a0, a1, a2, value]; } pub fn get_path(path_set: [u32; 4], index: u32) -> u32 { @@ -183,4 +187,3 @@ pub fn failover(path_set: [u32; 4], failed_path: u32) -> [u32; 4] { } return path_set; } - diff --git a/gen/rust/resource_scheduler.rs b/gen/rust/resource_scheduler.rs index 05a15a51..54c45942 100644 --- a/gen/rust/resource_scheduler.rs +++ b/gen/rust/resource_scheduler.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 18 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_TASKS: u32 = 8; @@ -14,7 +17,8 @@ pub const PRIORITY_MEDIUM: u32 = 1; pub const PRIORITY_LOW: u32 = 2; pub fn create_task_resource(cpu_req: u32, mem_req: u32, priority: u32, task_id: u32) -> u32 { - return (((((cpu_req & 0xFF) << 24) | ((mem_req & 0xFF) << 16)) | ((priority & 0x3) << 14)) | (task_id & 0x3FFF)); + return (((((cpu_req & 0xFF) << 24) | ((mem_req & 0xFF) << 16)) | ((priority & 0x3) << 14)) + | (task_id & 0x3FFF)); } pub fn get_cpu_req(resource: u32) -> u32 { @@ -33,8 +37,15 @@ pub fn get_task_id(resource: u32) -> u32 { return (resource & 0x3FFF); } -pub fn create_system_state(used_cpu: u32, used_mem: u32, active_tasks: u32, sched_tick: u32) -> u32 { - return (((((used_cpu & 0xFF) << 24) | ((used_mem & 0xFF) << 16)) | ((active_tasks & 0xFF) << 8)) | (sched_tick & 0xFF)); +pub fn create_system_state( + used_cpu: u32, + used_mem: u32, + active_tasks: u32, + sched_tick: u32, +) -> u32 { + return (((((used_cpu & 0xFF) << 24) | ((used_mem & 0xFF) << 16)) + | ((active_tasks & 0xFF) << 8)) + | (sched_tick & 0xFF)); } pub fn get_used_cpu(state: u32) -> u32 { @@ -53,8 +64,17 @@ pub fn get_sched_tick(state: u32) -> u32 { return (state & 0xFF); } -pub fn create_task_array(t0: u32, t1: u32, t2: u32, t3: u32, t4: u32, t5: u32, t6: u32, t7: u32) -> [u32; 8] { - return [t0,t1,t2,t3,t4,t5,t6,t7]; +pub fn create_task_array( + t0: u32, + t1: u32, + t2: u32, + t3: u32, + t4: u32, + t5: u32, + t6: u32, + t7: u32, +) -> [u32; 8] { + return [t0, t1, t2, t3, t4, t5, t6, t7]; } pub fn get_task_resource(array: [u32; 8], index: u32) -> u32 { @@ -202,30 +222,45 @@ pub fn increment_tick(state: u32) -> u32 { pub fn count_tasks_by_priority(task_array: [u32; 8], priority: u32) -> u32 { let mut count = 0; - if ((get_task_resource(task_array, 0) != 0) && (get_priority(get_task_resource(task_array, 0)) == priority)) { + if ((get_task_resource(task_array, 0) != 0) + && (get_priority(get_task_resource(task_array, 0)) == priority)) + { count = (count + 1); } - if ((get_task_resource(task_array, 1) != 0) && (get_priority(get_task_resource(task_array, 1)) == priority)) { + if ((get_task_resource(task_array, 1) != 0) + && (get_priority(get_task_resource(task_array, 1)) == priority)) + { count = (count + 1); } - if ((get_task_resource(task_array, 2) != 0) && (get_priority(get_task_resource(task_array, 2)) == priority)) { + if ((get_task_resource(task_array, 2) != 0) + && (get_priority(get_task_resource(task_array, 2)) == priority)) + { count = (count + 1); } - if ((get_task_resource(task_array, 3) != 0) && (get_priority(get_task_resource(task_array, 3)) == priority)) { + if ((get_task_resource(task_array, 3) != 0) + && (get_priority(get_task_resource(task_array, 3)) == priority)) + { count = (count + 1); } - if ((get_task_resource(task_array, 4) != 0) && (get_priority(get_task_resource(task_array, 4)) == priority)) { + if ((get_task_resource(task_array, 4) != 0) + && (get_priority(get_task_resource(task_array, 4)) == priority)) + { count = (count + 1); } - if ((get_task_resource(task_array, 5) != 0) && (get_priority(get_task_resource(task_array, 5)) == priority)) { + if ((get_task_resource(task_array, 5) != 0) + && (get_priority(get_task_resource(task_array, 5)) == priority)) + { count = (count + 1); } - if ((get_task_resource(task_array, 6) != 0) && (get_priority(get_task_resource(task_array, 6)) == priority)) { + if ((get_task_resource(task_array, 6) != 0) + && (get_priority(get_task_resource(task_array, 6)) == priority)) + { count = (count + 1); } - if ((get_task_resource(task_array, 7) != 0) && (get_priority(get_task_resource(task_array, 7)) == priority)) { + if ((get_task_resource(task_array, 7) != 0) + && (get_priority(get_task_resource(task_array, 7)) == priority)) + { count = (count + 1); } return count; } - diff --git a/gen/rust/routing_etx.rs b/gen/rust/routing_etx.rs index 6d677ccb..4ae31694 100644 --- a/gen/rust/routing_etx.rs +++ b/gen/rust/routing_etx.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 14 test(s), 2 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MILLI: u32 = 1000; @@ -58,4 +61,3 @@ pub fn learn_ok(is_self_route: u32, feasible: bool) -> bool { } return feasible; } - diff --git a/gen/rust/rti_alert.rs b/gen/rust/rti_alert.rs index b6f2f3df..cc617b27 100644 --- a/gen/rust/rti_alert.rs +++ b/gen/rust/rti_alert.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 4 test(s), 2 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const SEV_CATASTROPHIC: u8 = 4; @@ -24,4 +27,3 @@ pub fn alert_severity(anom_sev: u32) -> u8 { } } } - diff --git a/gen/rust/rti_security.rs b/gen/rust/rti_security.rs index b2a5ddfa..a3ea8ef3 100644 --- a/gen/rust/rti_security.rs +++ b/gen/rust/rti_security.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 26 test(s), 4 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_ZONES: u8 = 16; @@ -137,4 +140,3 @@ pub fn notification_priority(level: u8) -> u8 { } return 1; } - diff --git a/gen/rust/self_healing.rs b/gen/rust/self_healing.rs index 01469543..242d4dda 100644 --- a/gen/rust/self_healing.rs +++ b/gen/rust/self_healing.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 22 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const RECOVERY_COOLDOWN: u32 = 5000; @@ -9,8 +12,15 @@ pub const RECOVERY_SUCCESS: u32 = 1; pub const RECOVERY_FAILED: u32 = 0; -pub fn create_recovery_state(attempts: u32, last_attempt: u32, in_progress: u32, success_count: u32) -> u32 { - return (((((attempts & 0xF) << 28) | ((last_attempt & 0xFFFF) << 12)) | ((in_progress & 0x1) << 8)) | (success_count & 0xFF)); +pub fn create_recovery_state( + attempts: u32, + last_attempt: u32, + in_progress: u32, + success_count: u32, +) -> u32 { + return (((((attempts & 0xF) << 28) | ((last_attempt & 0xFFFF) << 12)) + | ((in_progress & 0x1) << 8)) + | (success_count & 0xFF)); } pub fn get_attempts(state: u32) -> u32 { @@ -71,8 +81,15 @@ pub fn is_recovery_failed(state: u32) -> bool { return (get_attempts(state) >= MAX_RECOVERY_ATTEMPTS); } -pub fn create_network_state(healthy_nodes: u32, total_nodes: u32, degraded_links: u32, total_links: u32) -> u32 { - return (((((healthy_nodes & 0xFF) << 24) | ((total_nodes & 0xFF) << 16)) | ((degraded_links & 0xFF) << 8)) | (total_links & 0xFF)); +pub fn create_network_state( + healthy_nodes: u32, + total_nodes: u32, + degraded_links: u32, + total_links: u32, +) -> u32 { + return (((((healthy_nodes & 0xFF) << 24) | ((total_nodes & 0xFF) << 16)) + | ((degraded_links & 0xFF) << 8)) + | (total_links & 0xFF)); } pub fn get_healthy_nodes(state: u32) -> u32 { @@ -123,11 +140,14 @@ pub fn should_initiate_healing(recovery_state: u32, network_state: u32, current_ return 2; } -pub fn update_network_after_recovery(network_state: u32, nodes_recovered: u32, links_restored: u32) -> u32 { +pub fn update_network_after_recovery( + network_state: u32, + nodes_recovered: u32, + links_restored: u32, +) -> u32 { let healthy = (get_healthy_nodes(network_state) + nodes_recovered); let total = get_total_nodes(network_state); let degraded = (get_degraded_links(network_state) - links_restored); let total_links = get_total_links(network_state); return create_network_state(healthy, total, degraded, total_links); } - diff --git a/gen/rust/swarm_coordinator.rs b/gen/rust/swarm_coordinator.rs index e429d095..67d2cf75 100644 --- a/gen/rust/swarm_coordinator.rs +++ b/gen/rust/swarm_coordinator.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 16 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_NODES: u32 = 8; @@ -14,7 +17,8 @@ pub const VOTE_NO: u32 = 0; pub const VOTE_ABSTAIN: u32 = 2; pub fn create_proposal(proposal_id: u32, node_id: u32, value: u32, timestamp: u32) -> u32 { - return (((((proposal_id & 0x3F) << 26) | ((node_id & 0x3F) << 20)) | ((value & 0xFF) << 12)) | (timestamp & 0xFFF)); + return (((((proposal_id & 0x3F) << 26) | ((node_id & 0x3F) << 20)) | ((value & 0xFF) << 12)) + | (timestamp & 0xFFF)); } pub fn get_proposal_id(proposal: u32) -> u32 { @@ -34,7 +38,8 @@ pub fn get_proposal_timestamp(proposal: u32) -> u32 { } pub fn create_vote(node_id: u32, vote: u32, proposal_id: u32, timestamp: u32) -> u32 { - return (((((node_id & 0xFF) << 24) | ((vote & 0x3) << 22)) | ((proposal_id & 0xFF) << 14)) | (timestamp & 0x3FFF)); + return (((((node_id & 0xFF) << 24) | ((vote & 0x3) << 22)) | ((proposal_id & 0xFF) << 14)) + | (timestamp & 0x3FFF)); } pub fn get_vote_node(vote: u32) -> u32 { @@ -53,8 +58,17 @@ pub fn get_vote_timestamp(vote: u32) -> u32 { return (vote & 0x3FFF); } -pub fn create_vote_array(v0: u32, v1: u32, v2: u32, v3: u32, v4: u32, v5: u32, v6: u32, v7: u32) -> [u32; 8] { - return [v0,v1,v2,v3,v4,v5,v6,v7]; +pub fn create_vote_array( + v0: u32, + v1: u32, + v2: u32, + v3: u32, + v4: u32, + v5: u32, + v6: u32, + v7: u32, +) -> [u32; 8] { + return [v0, v1, v2, v3, v4, v5, v6, v7]; } pub fn get_vote(array: [u32; 8], index: u32) -> u32 { @@ -171,35 +185,51 @@ pub fn proposal_passes(yes_count: u32, no_count: u32) -> bool { pub fn calculate_consensus_value(vote_array: [u32; 8], proposal_id: u32) -> u32 { let mut sum = 0; let mut count = 0; - if ((get_proposal_node(get_vote(vote_array, 0)) == proposal_id) && (get_proposal_timestamp(get_vote(vote_array, 0)) != 0)) { + if ((get_proposal_node(get_vote(vote_array, 0)) == proposal_id) + && (get_proposal_timestamp(get_vote(vote_array, 0)) != 0)) + { sum = (sum + get_proposal_value(get_vote(vote_array, 0))); count = (count + 1); } - if ((get_proposal_node(get_vote(vote_array, 1)) == proposal_id) && (get_proposal_timestamp(get_vote(vote_array, 1)) != 0)) { + if ((get_proposal_node(get_vote(vote_array, 1)) == proposal_id) + && (get_proposal_timestamp(get_vote(vote_array, 1)) != 0)) + { sum = (sum + get_proposal_value(get_vote(vote_array, 1))); count = (count + 1); } - if ((get_proposal_node(get_vote(vote_array, 2)) == proposal_id) && (get_proposal_timestamp(get_vote(vote_array, 2)) != 0)) { + if ((get_proposal_node(get_vote(vote_array, 2)) == proposal_id) + && (get_proposal_timestamp(get_vote(vote_array, 2)) != 0)) + { sum = (sum + get_proposal_value(get_vote(vote_array, 2))); count = (count + 1); } - if ((get_proposal_node(get_vote(vote_array, 3)) == proposal_id) && (get_proposal_timestamp(get_vote(vote_array, 3)) != 0)) { + if ((get_proposal_node(get_vote(vote_array, 3)) == proposal_id) + && (get_proposal_timestamp(get_vote(vote_array, 3)) != 0)) + { sum = (sum + get_proposal_value(get_vote(vote_array, 3))); count = (count + 1); } - if ((get_proposal_node(get_vote(vote_array, 4)) == proposal_id) && (get_proposal_timestamp(get_vote(vote_array, 4)) != 0)) { + if ((get_proposal_node(get_vote(vote_array, 4)) == proposal_id) + && (get_proposal_timestamp(get_vote(vote_array, 4)) != 0)) + { sum = (sum + get_proposal_value(get_vote(vote_array, 4))); count = (count + 1); } - if ((get_proposal_node(get_vote(vote_array, 5)) == proposal_id) && (get_proposal_timestamp(get_vote(vote_array, 5)) != 0)) { + if ((get_proposal_node(get_vote(vote_array, 5)) == proposal_id) + && (get_proposal_timestamp(get_vote(vote_array, 5)) != 0)) + { sum = (sum + get_proposal_value(get_vote(vote_array, 5))); count = (count + 1); } - if ((get_proposal_node(get_vote(vote_array, 6)) == proposal_id) && (get_proposal_timestamp(get_vote(vote_array, 6)) != 0)) { + if ((get_proposal_node(get_vote(vote_array, 6)) == proposal_id) + && (get_proposal_timestamp(get_vote(vote_array, 6)) != 0)) + { sum = (sum + get_proposal_value(get_vote(vote_array, 6))); count = (count + 1); } - if ((get_proposal_node(get_vote(vote_array, 7)) == proposal_id) && (get_proposal_timestamp(get_vote(vote_array, 7)) != 0)) { + if ((get_proposal_node(get_vote(vote_array, 7)) == proposal_id) + && (get_proposal_timestamp(get_vote(vote_array, 7)) != 0)) + { sum = (sum + get_proposal_value(get_vote(vote_array, 7))); count = (count + 1); } @@ -215,4 +245,3 @@ pub fn cooperative_decision(neighbor_values: u32, my_value: u32, weight_neighbor let weighted_self = ((my_value * (100 - weight_neighbors)) / 100); return (weighted_neighbors + weighted_self); } - diff --git a/gen/rust/test_framework.rs b/gen/rust/test_framework.rs index 30cfe767..c0b9000b 100644 --- a/gen/rust/test_framework.rs +++ b/gen/rust/test_framework.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 2 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_TESTS: u32 = 32; @@ -10,7 +13,8 @@ pub const MAX_SUITES: u32 = 8; pub const COVERAGE_TARGET: u32 = 90; pub fn create_test_result(test_id: u32, status: u32, assertions: u32, failures: u32) -> u32 { - return (((((test_id & 0xFF) << 24) | ((status & 0x3) << 22)) | ((assertions & 0xFF) << 14)) | (failures & 0x3FFF)); + return (((((test_id & 0xFF) << 24) | ((status & 0x3) << 22)) | ((assertions & 0xFF) << 14)) + | (failures & 0x3FFF)); } pub fn get_test_id(result: u32) -> u32 { @@ -38,7 +42,8 @@ pub const STATUS_SKIP: u32 = 2; pub const STATUS_ERROR: u32 = 3; pub fn create_test_case(test_id: u32, function_id: u32, input: u32, expected: u32) -> u32 { - return (((((test_id & 0xFF) << 24) | ((function_id & 0xFF) << 16)) | ((input & 0xFF) << 8)) | (expected & 0xFF)); + return (((((test_id & 0xFF) << 24) | ((function_id & 0xFF) << 16)) | ((input & 0xFF) << 8)) + | (expected & 0xFF)); } pub fn get_test_case_id(test_case: u32) -> u32 { @@ -58,7 +63,8 @@ pub fn get_expected_output(test_case: u32) -> u32 { } pub fn create_assertion(assert_type: u32, actual: u32, expected: u32, line: u32) -> u32 { - return (((((assert_type & 0xF) << 28) | ((actual & 0xFF) << 20)) | ((expected & 0xFF) << 12)) | (line & 0xFFF)); + return (((((assert_type & 0xF) << 28) | ((actual & 0xFF) << 20)) | ((expected & 0xFF) << 12)) + | (line & 0xFFF)); } pub fn get_assertion_type(assertion: u32) -> u32 { @@ -162,7 +168,9 @@ pub fn run_test_case(test_case: u32, function_ptr: u32) -> u32 { } pub fn create_test_suite(suite_id: u32, test_count: u32, setup_id: u32, teardown_id: u32) -> u32 { - return (((((suite_id & 0xFF) << 24) | ((test_count & 0xFF) << 16)) | ((setup_id & 0xFF) << 8)) | (teardown_id & 0xFF)); + return (((((suite_id & 0xFF) << 24) | ((test_count & 0xFF) << 16)) + | ((setup_id & 0xFF) << 8)) + | (teardown_id & 0xFF)); } pub fn get_suite_id(suite: u32) -> u32 { @@ -203,7 +211,8 @@ pub fn run_test_suite(suite: u32, tests: [u32; MAX_TESTS as usize], test_count: } pub fn create_coverage_data(func_id: u32, branches: u32, covered: u32, lines: u32) -> u32 { - return (((((func_id & 0xFF) << 24) | ((branches & 0xFF) << 16)) | ((covered & 0xFF) << 8)) | (lines & 0xFF)); + return (((((func_id & 0xFF) << 24) | ((branches & 0xFF) << 16)) | ((covered & 0xFF) << 8)) + | (lines & 0xFF)); } pub fn get_coverage_function_id(coverage: u32) -> u32 { @@ -249,7 +258,8 @@ pub fn aggregate_coverage(coverage_data: [u32; MAX_TESTS as usize], count: u32) } pub fn create_property_test(prop_id: u32, generators: u32, tests: u32, failures: u32) -> u32 { - return (((((prop_id & 0xFF) << 24) | ((generators & 0xFF) << 16)) | ((tests & 0xFF) << 8)) | (failures & 0xFF)); + return (((((prop_id & 0xFF) << 24) | ((generators & 0xFF) << 16)) | ((tests & 0xFF) << 8)) + | (failures & 0xFF)); } pub fn get_property_id(prop_test: u32) -> u32 { @@ -300,7 +310,8 @@ pub fn run_property_test(prop_id: u32, generator_count: u32, test_count: u32) -> } pub fn create_test_summary(total: u32, passed: u32, failed: u32, skipped: u32) -> u32 { - return (((((total & 0xFF) << 24) | ((passed & 0xFF) << 16)) | ((failed & 0xFF) << 8)) | (skipped & 0xFF)); + return (((((total & 0xFF) << 24) | ((passed & 0xFF) << 16)) | ((failed & 0xFF) << 8)) + | (skipped & 0xFF)); } pub fn get_total_tests(summary: u32) -> u32 { @@ -354,6 +365,6 @@ pub fn generate_test_report(summary: u32, coverage: u32, duration_ms: u32) -> u3 } } } - return ((((pass_rate & 0xFF) << 24) | ((coverage_pct & 0xFF) << 16)) | ((duration_ms & 0xFFFF) << 0)); + return ((((pass_rate & 0xFF) << 24) | ((coverage_pct & 0xFF) << 16)) + | ((duration_ms & 0xFFFF) << 0)); } - diff --git a/gen/rust/test_validator.rs b/gen/rust/test_validator.rs index ed0e384c..34c0fc20 100644 --- a/gen/rust/test_validator.rs +++ b/gen/rust/test_validator.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 2 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_ERRORS: u32 = 16; @@ -10,7 +13,8 @@ pub const MAX_FUNCTIONS: u32 = 64; pub const VIOLATION_THRESHOLD: u32 = 3; pub fn create_validation_error(error_id: u32, error_type: u32, line: u32, severity: u32) -> u32 { - return (((((error_id & 0xFF) << 24) | ((error_type & 0xF) << 20)) | ((line & 0xFF) << 12)) | (severity & 0xFFF)); + return (((((error_id & 0xFF) << 24) | ((error_type & 0xF) << 20)) | ((line & 0xFF) << 12)) + | (severity & 0xFFF)); } pub fn get_error_id(err_word: u32) -> u32 { @@ -45,8 +49,14 @@ pub const SEVERITY_WARNING: u32 = 1; pub const SEVERITY_INFO: u32 = 2; -pub fn create_function_signature(func_id: u32, params: u32, return_type: u32, visibility: u32) -> u32 { - return (((((func_id & 0xFF) << 24) | ((params & 0xF) << 20)) | ((return_type & 0xF) << 16)) | (visibility & 0xFFFF)); +pub fn create_function_signature( + func_id: u32, + params: u32, + return_type: u32, + visibility: u32, +) -> u32 { + return (((((func_id & 0xFF) << 24) | ((params & 0xF) << 20)) | ((return_type & 0xF) << 16)) + | (visibility & 0xFFFF)); } pub fn get_sig_function_id(sig: u32) -> u32 { @@ -78,8 +88,15 @@ pub fn validate_function_signature(sig: u32) -> u32 { return 0; } -pub fn create_constraint_check(constraint_id: u32, status: u32, description: u32, line: u32) -> u32 { - return (((((constraint_id & 0xFF) << 24) | ((status & 0x3) << 22)) | ((description & 0xFF) << 14)) | (line & 0x3FFF)); +pub fn create_constraint_check( + constraint_id: u32, + status: u32, + description: u32, + line: u32, +) -> u32 { + return (((((constraint_id & 0xFF) << 24) | ((status & 0x3) << 22)) + | ((description & 0xFF) << 14)) + | (line & 0x3FFF)); } pub fn get_constraint_id(check: u32) -> u32 { @@ -140,7 +157,9 @@ pub fn check_integer_only(line_content: u32) -> u32 { } pub fn create_type_check(var_id: u32, declared_type: u32, inferred_type: u32, line: u32) -> u32 { - return (((((var_id & 0xFF) << 24) | ((declared_type & 0xF) << 20)) | ((inferred_type & 0xF) << 16)) | (line & 0xFFFF)); + return (((((var_id & 0xFF) << 24) | ((declared_type & 0xF) << 20)) + | ((inferred_type & 0xF) << 16)) + | (line & 0xFFFF)); } pub fn get_type_var_id(check: u32) -> u32 { @@ -165,12 +184,19 @@ pub fn perform_type_check(check: u32) -> u32 { if (declared == inferred) { return 0; } else { - return create_validation_error(get_type_var_id(check), ERROR_TYPE_MISMATCH, get_type_line(check), SEVERITY_ERROR); + return create_validation_error( + get_type_var_id(check), + ERROR_TYPE_MISMATCH, + get_type_line(check), + SEVERITY_ERROR, + ); } } pub fn create_unused_check(var_id: u32, usage_count: u32, first_use: u32, last_use: u32) -> u32 { - return (((((var_id & 0xFF) << 24) | ((usage_count & 0xFF) << 16)) | ((first_use & 0xFF) << 8)) | (last_use & 0xFF)); + return (((((var_id & 0xFF) << 24) | ((usage_count & 0xFF) << 16)) + | ((first_use & 0xFF) << 8)) + | (last_use & 0xFF)); } pub fn get_unused_var_id(check: u32) -> u32 { @@ -192,14 +218,20 @@ pub fn get_last_use(check: u32) -> u32 { pub fn check_unused_variable(check: u32) -> u32 { let usage_count: u32 = get_usage_count(check); if (usage_count == 0) { - return create_validation_error(get_unused_var_id(check), ERROR_UNUSED_VARIABLE, get_first_use(check), SEVERITY_WARNING); + return create_validation_error( + get_unused_var_id(check), + ERROR_UNUSED_VARIABLE, + get_first_use(check), + SEVERITY_WARNING, + ); } else { return 0; } } pub fn create_validation_summary(errors: u32, warnings: u32, info: u32, status: u32) -> u32 { - return (((((errors & 0xFF) << 24) | ((warnings & 0xFF) << 16)) | ((info & 0xFF) << 8)) | (status & 0xFF)); + return (((((errors & 0xFF) << 24) | ((warnings & 0xFF) << 16)) | ((info & 0xFF) << 8)) + | (status & 0xFF)); } pub fn get_error_count(summary: u32) -> u32 { @@ -224,7 +256,12 @@ pub const VALIDATION_FAIL: u32 = 1; pub const VALIDATION_WARNING: u32 = 2; -pub fn run_validation(errors: [u32; MAX_ERRORS as usize], error_count: u32, warnings: [u32; MAX_WARNINGS as usize], warning_count: u32) -> u32 { +pub fn run_validation( + errors: [u32; MAX_ERRORS as usize], + error_count: u32, + warnings: [u32; MAX_WARNINGS as usize], + warning_count: u32, +) -> u32 { let mut total_errors: u32 = 0; let mut total_warnings: u32 = 0; let mut total_info: u32 = 0; @@ -258,8 +295,15 @@ pub fn run_validation(errors: [u32; MAX_ERRORS as usize], error_count: u32, warn return create_validation_summary(total_errors, total_warnings, total_info, status); } -pub fn create_quality_metrics(complexity: u32, readability: u32, maintainability: u32, tech_debt: u32) -> u32 { - return (((((complexity & 0xFF) << 24) | ((readability & 0xFF) << 16)) | ((maintainability & 0xFF) << 8)) | (tech_debt & 0xFF)); +pub fn create_quality_metrics( + complexity: u32, + readability: u32, + maintainability: u32, + tech_debt: u32, +) -> u32 { + return (((((complexity & 0xFF) << 24) | ((readability & 0xFF) << 16)) + | ((maintainability & 0xFF) << 8)) + | (tech_debt & 0xFF)); } pub fn get_complexity(metrics: u32) -> u32 { @@ -318,6 +362,6 @@ pub fn generate_validation_report(summary: u32, metrics: u32, filename_id: u32) let errors: u32 = get_error_count(summary); let warnings: u32 = get_warning_count(summary); let quality_ok: u32 = is_quality_acceptable(metrics); - return (((((status & 0xF) << 28) | ((errors & 0xFF) << 20)) | ((warnings & 0xFF) << 12)) | (quality_ok & 0xFFF)); + return (((((status & 0xF) << 28) | ((errors & 0xFF) << 20)) | ((warnings & 0xFF) << 12)) + | (quality_ok & 0xFFF)); } - diff --git a/gen/rust/timer.rs b/gen/rust/timer.rs index a2150d3d..17df51aa 100644 --- a/gen/rust/timer.rs +++ b/gen/rust/timer.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 8 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const BASE_MS: u16 = 10; @@ -30,4 +33,3 @@ pub fn tick_counter(counter: u16) -> u16 { pub fn is_expired(counter: u16) -> bool { return (counter == 0); } - diff --git a/gen/rust/timing_closure.rs b/gen/rust/timing_closure.rs index 648aba22..fa257fa5 100644 --- a/gen/rust/timing_closure.rs +++ b/gen/rust/timing_closure.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 18 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const TIMING_PASS: u32 = 0; @@ -96,4 +99,3 @@ pub fn extract_critical_paths(report: u32) -> u32 { pub fn timing_closure_achieved(report: u32, target_freq: u32) -> bool { return ((extract_grade(report) == TIMING_PASS) && (extract_max_freq(report) >= target_freq)); } - diff --git a/gen/rust/topology_visualizer.rs b/gen/rust/topology_visualizer.rs index 1eb3ce5e..dc44c434 100644 --- a/gen/rust/topology_visualizer.rs +++ b/gen/rust/topology_visualizer.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 2 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_NODES: u32 = 32; @@ -10,7 +13,8 @@ pub const MAX_LAYERS: u32 = 8; pub const CANVAS_SIZE: u32 = 1024; pub fn create_visual_node(node_id: u32, x: u32, y: u32, status: u32) -> u32 { - return (((((node_id & 0xFF) << 24) | ((x & 0xFF) << 16)) | ((y & 0xFF) << 8)) | (status & 0xFF)); + return (((((node_id & 0xFF) << 24) | ((x & 0xFF) << 16)) | ((y & 0xFF) << 8)) + | (status & 0xFF)); } pub fn get_viz_node_id(node: u32) -> u32 { @@ -38,7 +42,8 @@ pub const STATUS_FAILED: u32 = 2; pub const STATUS_WARNING: u32 = 3; pub fn create_visual_edge(source: u32, dest: u32, quality: u32, edge_type: u32) -> u32 { - return (((((source & 0xFF) << 24) | ((dest & 0xFF) << 16)) | ((quality & 0xFF) << 8)) | (edge_type & 0xFF)); + return (((((source & 0xFF) << 24) | ((dest & 0xFF) << 16)) | ((quality & 0xFF) << 8)) + | (edge_type & 0xFF)); } pub fn get_viz_edge_source(edge: u32) -> u32 { @@ -111,8 +116,15 @@ pub fn get_status_color(status: u32) -> u32 { } } -pub fn create_layout_params(algorithm: u32, iterations: u32, temperature: u32, cooling: u32) -> u32 { - return (((((algorithm & 0xFF) << 24) | ((iterations & 0xFF) << 16)) | ((temperature & 0xFF) << 8)) | (cooling & 0xFF)); +pub fn create_layout_params( + algorithm: u32, + iterations: u32, + temperature: u32, + cooling: u32, +) -> u32 { + return (((((algorithm & 0xFF) << 24) | ((iterations & 0xFF) << 16)) + | ((temperature & 0xFF) << 8)) + | (cooling & 0xFF)); } pub fn get_layout_algorithm(params: u32) -> u32 { @@ -139,7 +151,13 @@ pub const ALGORITHM_HIERARCHICAL: u32 = 2; pub const ALGORITHM_GRID: u32 = 3; -pub fn calculate_force_layout(nodes: [u32; MAX_NODES as usize], edges: [u32; MAX_EDGES as usize], node_count: u32, edge_count: u32, params: u32) -> u32 { +pub fn calculate_force_layout( + nodes: [u32; MAX_NODES as usize], + edges: [u32; MAX_EDGES as usize], + node_count: u32, + edge_count: u32, + params: u32, +) -> u32 { let iterations: u32 = get_layout_iterations(params); let mut temperature: u32 = get_layout_temperature(params); let mut placed_nodes: u32 = 0; @@ -178,8 +196,7 @@ pub fn calculate_force_layout(nodes: [u32; MAX_NODES as usize], edges: [u32; MAX while (l < edge_count) { let source: u32 = get_viz_edge_source(edges[(l) as usize]); let dest: u32 = get_viz_edge_dest(edges[(l) as usize]); - if ((source == node_id) || (dest == node_id)) { - } + if ((source == node_id) || (dest == node_id)) {} l = (l + 1); } j = (j + 1); @@ -210,7 +227,12 @@ pub fn calculate_circular_layout(nodes: [u32; MAX_NODES as usize], node_count: u return node_count; } -pub fn calculate_hierarchical_layout(nodes: [u32; MAX_NODES as usize], edges: [u32; MAX_EDGES as usize], node_count: u32, edge_count: u32) -> u32 { +pub fn calculate_hierarchical_layout( + nodes: [u32; MAX_NODES as usize], + edges: [u32; MAX_EDGES as usize], + node_count: u32, + edge_count: u32, +) -> u32 { let level_count: u32 = 4; let nodes_per_level: u32 = (node_count / level_count); let mut i: u32 = 0; @@ -232,7 +254,13 @@ pub fn calculate_hierarchical_layout(nodes: [u32; MAX_NODES as usize], edges: [u return node_count; } -pub fn apply_layout(nodes: [u32; MAX_NODES as usize], edges: [u32; MAX_EDGES as usize], node_count: u32, edge_count: u32, params: u32) -> u32 { +pub fn apply_layout( + nodes: [u32; MAX_NODES as usize], + edges: [u32; MAX_EDGES as usize], + node_count: u32, + edge_count: u32, + params: u32, +) -> u32 { let algorithm: u32 = get_layout_algorithm(params); if (algorithm == ALGORITHM_FORCE_DIRECTED) { return calculate_force_layout(nodes, edges, node_count, edge_count, params); @@ -254,7 +282,8 @@ pub fn render_node(node: u32, size: u32, color: u32) -> u32 { let y: u32 = get_node_y_position(node); let status: u32 = get_node_visual_status(node); let node_color: u32 = get_status_color(status); - return (((((x & 0xFF) << 24) | ((y & 0xFF) << 16)) | ((size & 0xFF) << 8)) | (node_color & 0xFF)); + return (((((x & 0xFF) << 24) | ((y & 0xFF) << 16)) | ((size & 0xFF) << 8)) + | (node_color & 0xFF)); } pub fn render_edge(edge: u32, nodes: [u32; MAX_NODES as usize], thickness: u32) -> u32 { @@ -288,10 +317,16 @@ pub fn render_edge(edge: u32, nodes: [u32; MAX_NODES as usize], thickness: u32) edge_color = COLOR_RED; } } - return (((((source_x & 0xFF) << 24) | ((source_y & 0xFF) << 16)) | ((dest_x & 0xFF) << 8)) | (dest_y & 0xFF)); + return (((((source_x & 0xFF) << 24) | ((source_y & 0xFF) << 16)) | ((dest_x & 0xFF) << 8)) + | (dest_y & 0xFF)); } -pub fn create_visualization_frame(nodes: [u32; MAX_NODES as usize], edges: [u32; MAX_EDGES as usize], node_count: u32, edge_count: u32) -> u32 { +pub fn create_visualization_frame( + nodes: [u32; MAX_NODES as usize], + edges: [u32; MAX_EDGES as usize], + node_count: u32, + edge_count: u32, +) -> u32 { let mut frame_size: u32 = 0; let mut i: u32 = 0; while (i < node_count) { @@ -325,12 +360,19 @@ pub fn optimize_rendering(node_count: u32, edge_count: u32, target_fps: u32) -> } } -pub fn generate_topology_visualization(nodes: [u32; MAX_NODES as usize], edges: [u32; MAX_EDGES as usize], node_count: u32, edge_count: u32, layout_params: u32) -> u32 { +pub fn generate_topology_visualization( + nodes: [u32; MAX_NODES as usize], + edges: [u32; MAX_EDGES as usize], + node_count: u32, + edge_count: u32, + layout_params: u32, +) -> u32 { let layout_result: u32 = apply_layout(nodes, edges, node_count, edge_count, layout_params); let frame: u32 = create_visualization_frame(nodes, edges, node_count, edge_count); let fps: u32 = 30; let detail_level: u32 = optimize_rendering(node_count, edge_count, fps); let complexity: u32 = calculate_viz_complexity(node_count, edge_count); - return (((((layout_result & 0xFF) << 24) | ((frame & 0xFF) << 16)) | ((detail_level & 0xFF) << 8)) | (complexity & 0xFF)); + return (((((layout_result & 0xFF) << 24) | ((frame & 0xFF) << 16)) + | ((detail_level & 0xFF) << 8)) + | (complexity & 0xFF)); } - diff --git a/gen/rust/traffic_animator.rs b/gen/rust/traffic_animator.rs index 658a3ef2..0503aff2 100644 --- a/gen/rust/traffic_animator.rs +++ b/gen/rust/traffic_animator.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 2 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_PACKETS: u32 = 64; @@ -10,7 +13,8 @@ pub const ANIMATION_FPS: u32 = 30; pub const MAX_FRAMES: u32 = 1200; pub fn create_anim_packet(packet_id: u32, source: u32, dest: u32, progress: u32) -> u32 { - return (((((packet_id & 0xFF) << 24) | ((source & 0xFF) << 16)) | ((dest & 0xFF) << 8)) | (progress & 0xFF)); + return (((((packet_id & 0xFF) << 24) | ((source & 0xFF) << 16)) | ((dest & 0xFF) << 8)) + | (progress & 0xFF)); } pub fn get_anim_packet_id(packet: u32) -> u32 { @@ -41,8 +45,15 @@ pub fn update_packet_progress(packet: u32, delta: u32) -> u32 { return create_anim_packet(packet_id, source, dest, new_progress); } -pub fn create_animation_path(path_id: u32, node_count: u32, current_pos: u32, path_type: u32) -> u32 { - return (((((path_id & 0xFF) << 24) | ((node_count & 0xFF) << 16)) | ((current_pos & 0xFF) << 8)) | (path_type & 0xFF)); +pub fn create_animation_path( + path_id: u32, + node_count: u32, + current_pos: u32, + path_type: u32, +) -> u32 { + return (((((path_id & 0xFF) << 24) | ((node_count & 0xFF) << 16)) + | ((current_pos & 0xFF) << 8)) + | (path_type & 0xFF)); } pub fn get_anim_path_id(path: u32) -> u32 { @@ -69,8 +80,15 @@ pub const PATH_BROADCAST: u32 = 2; pub const PATH_GATHER: u32 = 3; -pub fn create_animation_frame(frame_id: u32, timestamp: u32, packet_count: u32, duration: u32) -> u32 { - return (((((frame_id & 0xFF) << 24) | ((timestamp & 0xFF) << 16)) | ((packet_count & 0xFF) << 8)) | (duration & 0xFF)); +pub fn create_animation_frame( + frame_id: u32, + timestamp: u32, + packet_count: u32, + duration: u32, +) -> u32 { + return (((((frame_id & 0xFF) << 24) | ((timestamp & 0xFF) << 16)) + | ((packet_count & 0xFF) << 8)) + | (duration & 0xFF)); } pub fn get_anim_frame_id(frame: u32) -> u32 { @@ -90,7 +108,8 @@ pub fn get_anim_frame_duration(frame: u32) -> u32 { } pub fn create_traffic_stats(total_packets: u32, bytes: u32, dropped: u32, latency: u32) -> u32 { - return (((((total_packets & 0xFF) << 24) | ((bytes & 0xFF) << 16)) | ((dropped & 0xFF) << 8)) | (latency & 0xFF)); + return (((((total_packets & 0xFF) << 24) | ((bytes & 0xFF) << 16)) | ((dropped & 0xFF) << 8)) + | (latency & 0xFF)); } pub fn get_traffic_total_packets(stats: u32) -> u32 { @@ -110,7 +129,8 @@ pub fn get_traffic_avg_latency(stats: u32) -> u32 { } pub fn create_packet_color(ptype: u32, priority: u32, size: u32, color: u32) -> u32 { - return (((((ptype & 0xF) << 28) | ((priority & 0xF) << 24)) | ((size & 0xFF) << 16)) | (color & 0xFFFF)); + return (((((ptype & 0xF) << 28) | ((priority & 0xF) << 24)) | ((size & 0xFF) << 16)) + | (color & 0xFFFF)); } pub fn get_packet_color_type(color: u32) -> u32 { @@ -158,7 +178,8 @@ pub fn get_packet_visual_color(packet_type: u32, priority: u32) -> u32 { } pub fn create_animation_timeline(current: u32, total: u32, loops: u32, speed: u32) -> u32 { - return (((((current & 0xFF) << 24) | ((total & 0xFF) << 16)) | ((loops & 0xFF) << 8)) | (speed & 0xFF)); + return (((((current & 0xFF) << 24) | ((total & 0xFF) << 16)) | ((loops & 0xFF) << 8)) + | (speed & 0xFF)); } pub fn get_timeline_current_frame(timeline: u32) -> u32 { @@ -191,8 +212,15 @@ pub fn advance_animation_frame(timeline: u32) -> u32 { return create_animation_timeline(new_current, total, new_loops, speed); } -pub fn create_traffic_pattern(pattern_id: u32, burst_size: u32, interval: u32, duration: u32) -> u32 { - return (((((pattern_id & 0xFF) << 24) | ((burst_size & 0xFF) << 16)) | ((interval & 0xFF) << 8)) | (duration & 0xFF)); +pub fn create_traffic_pattern( + pattern_id: u32, + burst_size: u32, + interval: u32, + duration: u32, +) -> u32 { + return (((((pattern_id & 0xFF) << 24) | ((burst_size & 0xFF) << 16)) + | ((interval & 0xFF) << 8)) + | (duration & 0xFF)); } pub fn get_pattern_id(pattern: u32) -> u32 { @@ -223,7 +251,13 @@ pub fn generate_traffic_burst(pattern: u32, source: u32, dest: u32) -> u32 { return packet_count; } -pub fn calculate_packet_position(source_x: u32, source_y: u32, dest_x: u32, dest_y: u32, progress: u32) -> u32 { +pub fn calculate_packet_position( + source_x: u32, + source_y: u32, + dest_x: u32, + dest_y: u32, + progress: u32, +) -> u32 { let mut current_x: u32 = source_x; if (dest_x >= source_x) { current_x = (source_x + (((dest_x - source_x) * progress) / 100)); @@ -239,7 +273,11 @@ pub fn calculate_packet_position(source_x: u32, source_y: u32, dest_x: u32, dest return (((current_x & 0xFF) << 24) | ((current_y & 0xFF) << 16)); } -pub fn update_animation_packets(packets: [u32; MAX_PACKETS as usize], packet_count: u32, speed: u32) -> u32 { +pub fn update_animation_packets( + packets: [u32; MAX_PACKETS as usize], + packet_count: u32, + speed: u32, +) -> u32 { let mut updated_count: u32 = 0; let mut completed_count: u32 = 0; let mut i: u32 = 0; @@ -260,10 +298,17 @@ pub fn update_animation_packets(packets: [u32; MAX_PACKETS as usize], packet_cou } i = (i + 1); } - return ((((updated_count & 0xFF) << 24) | ((completed_count & 0xFF) << 16)) | ((packet_count & 0xFF) << 8)); + return ((((updated_count & 0xFF) << 24) | ((completed_count & 0xFF) << 16)) + | ((packet_count & 0xFF) << 8)); } -pub fn render_animation_frame(packets: [u32; MAX_PACKETS as usize], packet_count: u32, paths: [u32; MAX_PATHS as usize], path_count: u32, frame_id: u32) -> u32 { +pub fn render_animation_frame( + packets: [u32; MAX_PACKETS as usize], + packet_count: u32, + paths: [u32; MAX_PATHS as usize], + path_count: u32, + frame_id: u32, +) -> u32 { let timestamp: u32 = (frame_id * (1000 / ANIMATION_FPS)); let duration: u32 = (1000 / ANIMATION_FPS); return create_animation_frame(frame_id, timestamp, packet_count, duration); @@ -285,7 +330,11 @@ pub fn optimize_animation_performance(packet_count: u32, target_fps: u32) -> u32 } } -pub fn generate_traffic_heat_map(packets: [u32; MAX_PACKETS as usize], packet_count: u32, node_count: u32) -> u32 { +pub fn generate_traffic_heat_map( + packets: [u32; MAX_PACKETS as usize], + packet_count: u32, + node_count: u32, +) -> u32 { let mut traffic_counts: [u32; 32] = [0; 32]; let mut max_traffic: u32 = 0; let mut i: u32 = 0; @@ -320,10 +369,18 @@ pub fn generate_traffic_heat_map(packets: [u32; MAX_PACKETS as usize], packet_co if (total_active > 0) { avg_traffic = (total_traffic / total_active); } - return ((((max_traffic & 0xFF) << 24) | ((total_active & 0xFF) << 16)) | ((avg_traffic & 0xFF) << 8)); -} - -pub fn generate_traffic_animation(packets: [u32; MAX_PACKETS as usize], packet_count: u32, paths: [u32; MAX_PATHS as usize], path_count: u32, node_count: u32, duration_frames: u32) -> u32 { + return ((((max_traffic & 0xFF) << 24) | ((total_active & 0xFF) << 16)) + | ((avg_traffic & 0xFF) << 8)); +} + +pub fn generate_traffic_animation( + packets: [u32; MAX_PACKETS as usize], + packet_count: u32, + paths: [u32; MAX_PATHS as usize], + path_count: u32, + node_count: u32, + duration_frames: u32, +) -> u32 { let total_frames: u32 = duration_frames; let current_frame: u32 = 0; let complexity: u32 = calculate_animation_complexity(packet_count, path_count, node_count); @@ -332,11 +389,20 @@ pub fn generate_traffic_animation(packets: [u32; MAX_PACKETS as usize], packet_c let timeline: u32 = create_animation_timeline(0, total_frames, 0, 1); let heat_map: u32 = generate_traffic_heat_map(packets, actual_packet_count, node_count); let max_traffic: u32 = ((heat_map >> 24) & 0xFF); - return (((((total_frames & 0xFF) << 24) | ((complexity & 0xFF) << 16)) | ((actual_packet_count & 0xFF) << 8)) | (max_traffic & 0xFF)); + return (((((total_frames & 0xFF) << 24) | ((complexity & 0xFF) << 16)) + | ((actual_packet_count & 0xFF) << 8)) + | (max_traffic & 0xFF)); } -pub fn create_animation_controls(play_pause: u32, step_forward: u32, step_backward: u32, reset: u32) -> u32 { - return (((((play_pause & 0x1) << 3) | ((step_forward & 0x1) << 2)) | ((step_backward & 0x1) << 1)) | (reset & 0x1)); +pub fn create_animation_controls( + play_pause: u32, + step_forward: u32, + step_backward: u32, + reset: u32, +) -> u32 { + return (((((play_pause & 0x1) << 3) | ((step_forward & 0x1) << 2)) + | ((step_backward & 0x1) << 1)) + | (reset & 0x1)); } pub fn process_animation_control(control: u32, timeline: u32) -> u32 { @@ -371,4 +437,3 @@ pub fn calculate_animation_stats(frames: [u32; MAX_FRAMES as usize], frame_count } return create_traffic_stats(total_packets, total_bytes, 0, avg_latency); } - diff --git a/gen/rust/transport_tx_fsm.rs b/gen/rust/transport_tx_fsm.rs index 3d5bf83a..01121736 100644 --- a/gen/rust/transport_tx_fsm.rs +++ b/gen/rust/transport_tx_fsm.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 17 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const ST_IDLE: u8 = 0; @@ -144,4 +147,3 @@ pub fn header_byte(kind: u8, src: u32, dst: u32, ttl: u8, idx: usize) -> u8 { } } } - diff --git a/gen/rust/tri_a2a.rs b/gen/rust/tri_a2a.rs index d31d9f3c..15cb7df8 100644 --- a/gen/rust/tri_a2a.rs +++ b/gen/rust/tri_a2a.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 22 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const KIND_DATA: u32 = 1; diff --git a/gen/rust/tri_a2a_card.rs b/gen/rust/tri_a2a_card.rs new file mode 100644 index 00000000..6c7e9b9c --- /dev/null +++ b/gen/rust/tri_a2a_card.rs @@ -0,0 +1,144 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 8 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. + +pub const FMT_GF_BINARY: u32 = 0; + +pub const FMT_GFT: u32 = 1; + +pub const HI_GF16: u32 = 0x16; + +pub const HI_GFT16: u32 = 0xA6; + +pub const HI_GFT8: u32 = 0xA8; + +pub const HI_GFT4: u32 = 0xA4; + +pub const HI_GFT32: u32 = 0xA5; + +pub const HI_GFT64: u32 = 0xA3; + +pub const HI_GFT128: u32 = 0xA2; + +pub fn family_bit(family: u32) -> u32 { + return (1 << family); +} + +pub fn make_card(family_mask: u32, width_mask: u32) -> u32 { + return ((family_mask << 16) | (width_mask & 0xFFFF)); +} + +pub fn card_families(card: u32) -> u32 { + return (card >> 16); +} + +pub fn card_widths(card: u32) -> u32 { + return (card & 0xFFFF); +} + +pub fn hosts_family(card: u32, family: u32) -> bool { + return ((card_families(card) & family_bit(family)) != 0); +} + +pub fn hosts_width(card: u32, width: u32) -> bool { + return ((card_widths(card) & width) != 0); +} + +pub fn can_serve(card: u32, family: u32, width: u32) -> bool { + if hosts_family(card, family) { + return hosts_width(card, width); + } else { + return (card != card); + } +} + +pub fn skill_hi(skill: u32) -> u32 { + return ((skill >> 8) & 0xFF); +} + +pub fn skill_card_family(skill: u32) -> u32 { + if (skill_hi(skill) == HI_GFT4) { + return FMT_GFT; + } + if (skill_hi(skill) == HI_GFT8) { + return FMT_GFT; + } + if (skill_hi(skill) == HI_GFT16) { + return FMT_GFT; + } + if (skill_hi(skill) == HI_GFT32) { + return FMT_GFT; + } + if (skill_hi(skill) == HI_GFT64) { + return FMT_GFT; + } + if (skill_hi(skill) == HI_GFT128) { + return FMT_GFT; + } + return FMT_GF_BINARY; +} + +pub fn skill_card_width(skill: u32) -> u32 { + if (skill_hi(skill) == HI_GFT4) { + return 4; + } + if (skill_hi(skill) == HI_GFT8) { + return 8; + } + if (skill_hi(skill) == HI_GFT32) { + return 32; + } + if (skill_hi(skill) == HI_GFT64) { + return 64; + } + if (skill_hi(skill) == HI_GFT128) { + return 128; + } + return 16; +} + +pub fn can_serve_skill(card: u32, skill: u32) -> bool { + return can_serve(card, skill_card_family(skill), skill_card_width(skill)); +} + +pub const GF_OP_ADD: u32 = 0x10; + +pub const GF_OP_MUL: u32 = 0x11; + +pub fn op_bit(op: u32) -> u32 { + return (1 << (op & 0xF)); +} + +pub fn make_card_ops(family_mask: u32, width_mask: u32, op_mask: u32) -> u32 { + return (((op_mask << 24) | (family_mask << 16)) | (width_mask & 0xFFFF)); +} + +pub fn card_ops(card: u32) -> u32 { + return ((card >> 24) & 0xFF); +} + +pub fn hosts_op(card: u32, op: u32) -> bool { + return ((card_ops(card) & op_bit(op)) != 0); +} + +pub fn can_serve_op(card: u32, family: u32, width: u32, op: u32) -> bool { + if can_serve(card, family, width) { + return hosts_op(card, op); + } else { + return (card != card); + } +} + +pub fn skill_op_suffix(skill: u32) -> u32 { + return (skill & 0xFF); +} + +pub fn can_serve_skill_op(card: u32, skill: u32) -> bool { + if can_serve_skill(card, skill) { + return hosts_op(card, skill_op_suffix(skill)); + } else { + return (card != card); + } +} diff --git a/gen/rust/tri_a2a_wire.rs b/gen/rust/tri_a2a_wire.rs new file mode 100644 index 00000000..5ed3ba27 --- /dev/null +++ b/gen/rust/tri_a2a_wire.rs @@ -0,0 +1,108 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 7 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. + +pub const OFF_CLASS: u32 = 0; + +pub const OFF_TASK: u32 = 1; + +pub const OFF_SKILL: u32 = 5; + +pub const OFF_BODY: u32 = 7; + +pub const HDR_LEN: u32 = 7; + +pub const MSG_TASK_ASSIGN: u32 = 1; + +pub const MSG_TASK_RESULT: u32 = 2; + +pub const MSG_HEARTBEAT: u32 = 3; + +pub fn task_id(b1: u32, b2: u32, b3: u32, b4: u32) -> u32 { + return ((((b1 << 24) | (b2 << 16)) | (b3 << 8)) | b4); +} + +pub fn skill_id(b5: u32, b6: u32) -> u32 { + return ((b5 << 8) | b6); +} + +pub fn body_offset() -> u32 { + return OFF_BODY; +} + +pub fn class_valid(msg_class: u32) -> bool { + if (msg_class == MSG_TASK_ASSIGN) { + return (msg_class == msg_class); + } else { + if (msg_class == MSG_TASK_RESULT) { + return (msg_class == msg_class); + } else { + return (msg_class == MSG_HEARTBEAT); + } + } +} + +pub fn body_has_receipt(msg_class: u32) -> bool { + return (msg_class == MSG_TASK_RESULT); +} + +pub const SIG_LEN: u32 = 64; + +pub fn body_has_signature(msg_class: u32) -> bool { + return (msg_class == MSG_TASK_RESULT); +} + +pub fn sig_offset(receipt_body_len: u32) -> u32 { + return (OFF_BODY + receipt_body_len); +} + +pub fn signed_result_len(receipt_body_len: u32) -> u32 { + return ((OFF_BODY + receipt_body_len) + SIG_LEN); +} + +pub const OFF_ASSIGN_OP: u32 = 0; + +pub const OFF_ASSIGN_A_OFF: u32 = 1; + +pub const OFF_ASSIGN_A_MANT: u32 = 2; + +pub const OFF_ASSIGN_B_OFF: u32 = 4; + +pub const OFF_ASSIGN_B_MANT: u32 = 5; + +pub const ASSIGN_BODY_LEN: u32 = 7; + +pub fn assign_mant(hi: u32, lo: u32) -> u32 { + return ((hi << 8) | lo); +} + +pub const SHA_PAD_W: u32 = 0x80000000; + +pub const OPERAND_BITS: u32 = 160; + +pub fn operand_pre(idx: u32, op: u32, a_off: u32, a_mant: u32, b_off: u32, b_mant: u32) -> u32 { + if (idx == 0) { + return op; + } + if (idx == 1) { + return a_off; + } + if (idx == 2) { + return a_mant; + } + if (idx == 3) { + return b_off; + } + if (idx == 4) { + return b_mant; + } + if (idx == 5) { + return SHA_PAD_W; + } + if (idx == 15) { + return OPERAND_BITS; + } + return 0; +} diff --git a/gen/rust/tri_challenge.rs b/gen/rust/tri_challenge.rs index e2c75362..cd627de1 100644 --- a/gen/rust/tri_challenge.rs +++ b/gen/rust/tri_challenge.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 15 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const DEFENDER_HONEST: u32 = 1; @@ -176,7 +179,19 @@ pub fn dispute_rung_min_bps(min_bps: u32, gf_et: u32) -> u32 { } } -pub fn may_open_dispute_rung(open_count: u32, risk: u32, reward: u32, bond: u32, min_bps: u32, gf_et: u32) -> bool { - return may_open_dispute(open_count, risk, reward, bond, dispute_rung_min_bps(min_bps, gf_et)); +pub fn may_open_dispute_rung( + open_count: u32, + risk: u32, + reward: u32, + bond: u32, + min_bps: u32, + gf_et: u32, +) -> bool { + return may_open_dispute( + open_count, + risk, + reward, + bond, + dispute_rung_min_bps(min_bps, gf_et), + ); } - diff --git a/gen/rust/tri_compute_account.rs b/gen/rust/tri_compute_account.rs index b6d6d755..13eecdc5 100644 --- a/gen/rust/tri_compute_account.rs +++ b/gen/rust/tri_compute_account.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 21 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub fn total(balance: u32, locked: u32) -> u32 { return (balance + locked); diff --git a/gen/rust/tri_compute_bitnet.rs b/gen/rust/tri_compute_bitnet.rs index d2a0ece7..1c48356b 100644 --- a/gen/rust/tri_compute_bitnet.rs +++ b/gen/rust/tri_compute_bitnet.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 11 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const OP_BITNET: u32 = 0x20; diff --git a/gen/rust/tri_compute_bond.rs b/gen/rust/tri_compute_bond.rs index 572b99e9..56996c8c 100644 --- a/gen/rust/tri_compute_bond.rs +++ b/gen/rust/tri_compute_bond.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 8 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const ST_FREE: u32 = 0; diff --git a/gen/rust/tri_compute_challenge.rs b/gen/rust/tri_compute_challenge.rs index 80707c56..e40c8f14 100644 --- a/gen/rust/tri_compute_challenge.rs +++ b/gen/rust/tri_compute_challenge.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 38 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const RESOLVE_HONEST: u32 = 0; diff --git a/gen/rust/tri_compute_gfvalid.rs b/gen/rust/tri_compute_gfvalid.rs index 97405548..e2cf6d95 100644 --- a/gen/rust/tri_compute_gfvalid.rs +++ b/gen/rust/tri_compute_gfvalid.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 11 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub fn is_finite_gf(result: u32, exp_bits: u32, mant_bits: u32) -> bool { let exp_mask: u32 = ((1 << exp_bits) - 1); diff --git a/gen/rust/tri_compute_optimistic.rs b/gen/rust/tri_compute_optimistic.rs new file mode 100644 index 00000000..e7d23eec --- /dev/null +++ b/gen/rust/tri_compute_optimistic.rs @@ -0,0 +1,69 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 5 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. + +pub const PENDING: u32 = 0; + +pub const FINALIZED: u32 = 1; + +pub const REVERSED: u32 = 2; + +pub fn provisional_balance(prev_balance: u32, reward: u32, bond_ok: u32) -> u32 { + if (bond_ok == 1) { + return (prev_balance + reward); + } else { + return prev_balance; + } +} + +pub fn window_open(now_epoch: u32, settled_at: u32, window: u32) -> bool { + return (now_epoch < (settled_at + window)); +} + +pub const GFT16_ET: u32 = 4; + +pub const BASE_WINDOW: u32 = 64; + +pub const WINDOW_PER_TRIT: u32 = 16; + +pub fn window_for_rung(gf_et: u32) -> u32 { + if (gf_et <= GFT16_ET) { + return BASE_WINDOW; + } else { + return (BASE_WINDOW + ((gf_et - GFT16_ET) * WINDOW_PER_TRIT)); + } +} + +pub fn window_open_rung(now_epoch: u32, settled_at: u32, gf_et: u32) -> bool { + return window_open(now_epoch, settled_at, window_for_rung(gf_et)); +} + +pub fn settle_state(window_is_open: u32, slashed: u32) -> u32 { + if (slashed == 1) { + return REVERSED; + } else { + if (window_is_open == 1) { + return PENDING; + } else { + return FINALIZED; + } + } +} + +pub fn balance_after_settle(provisional_bal: u32, reward: u32, state: u32) -> u32 { + if (state == REVERSED) { + if (provisional_bal < reward) { + return 0; + } else { + return (provisional_bal - reward); + } + } else { + return provisional_bal; + } +} + +pub fn can_finalize(state: u32) -> bool { + return (state == FINALIZED); +} diff --git a/gen/rust/tri_compute_payout.rs b/gen/rust/tri_compute_payout.rs new file mode 100644 index 00000000..f531fe3e --- /dev/null +++ b/gen/rust/tri_compute_payout.rs @@ -0,0 +1,33 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 6 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. + +pub fn weighted(raw_work: u32, rep: u32) -> u32 { + let prod: u64 = ((raw_work as u64) * (rep as u64)); + if (prod > 4294967295) { + return 4294967295; + } else { + return (prod as u32); + } +} + +pub fn total_weighted3(w0: u32, w1: u32, w2: u32) -> u32 { + let sum: u64 = (((w0 as u64) + (w1 as u64)) + (w2 as u64)); + if (sum > 4294967295) { + return 4294967295; + } else { + return (sum as u32); + } +} + +pub fn payout(total_pool: u32, my_weighted: u32, total_weighted: u32) -> u32 { + if (total_weighted == 0) { + return 0; + } else { + let num: u64 = ((total_pool as u64) * (my_weighted as u64)); + let den: u64 = (total_weighted as u64); + return ((num / den) as u32); + } +} diff --git a/gen/rust/tri_compute_pool.rs b/gen/rust/tri_compute_pool.rs index f1259fcc..3b67cf55 100644 --- a/gen/rust/tri_compute_pool.rs +++ b/gen/rust/tri_compute_pool.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 13 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub fn total_work3(w0: u32, w1: u32, w2: u32) -> u32 { let sum: u64 = (((w0 as u64) + (w1 as u64)) + (w2 as u64)); diff --git a/gen/rust/tri_compute_receipt.rs b/gen/rust/tri_compute_receipt.rs new file mode 100644 index 00000000..4591711c --- /dev/null +++ b/gen/rust/tri_compute_receipt.rs @@ -0,0 +1,495 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 22 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. + +pub const RECEIPT_GENESIS: u32 = 0x54524352; + +pub const R_C: u32 = 0x9E3779B9; + +pub const R_C2: u32 = 0x85EBCA77; + +pub const TAG_RECEIPT: u32 = 0x54524350; + +pub const SHA_PAD: u32 = 0x80000000; + +pub const DIGEST_MSG_BITS: u32 = 288; + +pub const TAG_LEDGER: u32 = 0x54524C47; + +pub const LEDGER_GENESIS: u32 = 0x54524C30; + +pub const LEDGER_MSG_BITS: u32 = 608; + +pub const MERKLE_MSG_BITS: u32 = 512; + +pub const TAG_INPUT: u32 = 0x54524942; + +pub const GF_ADD: u32 = 0x10; + +pub const GF_MUL: u32 = 0x11; + +pub const GF16: u32 = 16; + +pub fn rotl(x: u32, k: u32) -> u32 { + return ((x << k) | (x >> (32 - k))); +} + +pub fn mix32(x: u32) -> u32 { + let a: u32 = (x ^ (x >> 16)); + let b: u32 = (a).wrapping_add((a << 3)); + let c: u32 = (b ^ (b >> 11)); + let d: u32 = (c).wrapping_add((c << 15)); + return (d ^ (d >> 16)); +} + +pub fn receipt_leaf(executor: u32, task: u32, in_hash: u32, out: u32, epoch: u32) -> u32 { + let a: u32 = mix32((executor ^ rotl(task, 7))); + let b: u32 = mix32((a ^ rotl(in_hash, 13))); + let c: u32 = mix32((b ^ rotl(out, 19))); + return mix32((c ^ rotl(epoch, 5))); +} + +pub fn receipt_step(prev_head: u32, leaf: u32) -> u32 { + return mix32((prev_head ^ mix32((leaf ^ R_C)))); +} + +pub fn verify_leaf( + executor: u32, + task: u32, + in_hash: u32, + out: u32, + epoch: u32, + claimed: u32, +) -> bool { + return (receipt_leaf(executor, task, in_hash, out, epoch) == claimed); +} + +pub fn verify_chain3(l0: u32, l1: u32, l2: u32, claimed: u32) -> bool { + let h0: u32 = receipt_step(RECEIPT_GENESIS, l0); + let h1: u32 = receipt_step(h0, l1); + let h2: u32 = receipt_step(h1, l2); + return (h2 == claimed); +} + +pub fn receipt_leaf_hi(executor: u32, task: u32, in_hash: u32, out: u32, epoch: u32) -> u32 { + let a: u32 = mix32(((executor ^ R_C2) + rotl(task, 11))); + let b: u32 = mix32((a ^ rotl(in_hash, 17))); + let c: u32 = mix32((b ^ rotl(out, 23))); + return mix32((c ^ rotl(epoch, 29))); +} + +pub fn verify_leaf64( + executor: u32, + task: u32, + in_hash: u32, + out: u32, + epoch: u32, + claimed_lo: u32, + claimed_hi: u32, +) -> bool { + let lo: u32 = receipt_leaf(executor, task, in_hash, out, epoch); + let hi: u32 = receipt_leaf_hi(executor, task, in_hash, out, epoch); + if (lo == claimed_lo) { + return (hi == claimed_hi); + } else { + return (lo != lo); + } +} + +pub fn receipt_leaf_bound( + device_id: u32, + executor: u32, + task: u32, + in_hash: u32, + out: u32, + epoch: u32, +) -> u32 { + let base: u32 = receipt_leaf(executor, task, in_hash, out, epoch); + return mix32((base ^ mix32((device_id ^ rotl(executor, 3))))); +} + +pub fn sign_digest( + device_id: u32, + executor: u32, + task: u32, + in_hash: u32, + out: u32, + epoch: u32, + prev_head: u32, +) -> u32 { + let bound: u32 = receipt_leaf_bound(device_id, executor, task, in_hash, out, epoch); + let hi: u32 = receipt_leaf_hi(executor, task, in_hash, out, epoch); + return mix32((mix32((bound ^ prev_head)) ^ mix32((hi ^ R_C2)))); +} + +pub fn sign_digest_req( + request_id: u32, + device_id: u32, + executor: u32, + task: u32, + in_hash: u32, + out: u32, + epoch: u32, + prev_head: u32, +) -> u32 { + let base: u32 = sign_digest(device_id, executor, task, in_hash, out, epoch, prev_head); + return mix32((base ^ mix32((request_id ^ rotl(executor, 11))))); +} + +pub fn digest_pre( + idx: u32, + request_id: u32, + device_id: u32, + executor: u32, + task: u32, + in_hash: u32, + out: u32, + epoch: u32, + prev_head: u32, +) -> u32 { + if (idx == 0) { + return TAG_RECEIPT; + } + if (idx == 1) { + return request_id; + } + if (idx == 2) { + return device_id; + } + if (idx == 3) { + return executor; + } + if (idx == 4) { + return task; + } + if (idx == 5) { + return in_hash; + } + if (idx == 6) { + return out; + } + if (idx == 7) { + return epoch; + } + if (idx == 8) { + return prev_head; + } + if (idx == 9) { + return SHA_PAD; + } + if (idx == 15) { + return DIGEST_MSG_BITS; + } + return 0; +} + +pub fn receipt_leaf_gf( + gf_width: u32, + gf_op: u32, + a: u32, + b: u32, + gf_result: u32, + device_id: u32, + executor: u32, + epoch: u32, +) -> u32 { + let opsel: u32 = mix32(((gf_width << 8) ^ gf_op)); + let ab: u32 = mix32((a ^ rotl(b, 7))); + return receipt_leaf_bound(device_id, executor, opsel, ab, gf_result, epoch); +} + +pub const FMT_GF_BINARY: u32 = 0; + +pub const FMT_GFT: u32 = 1; + +pub const GFT16_RUNG_ET: u32 = 4; + +pub const GFT32_RUNG_ET: u32 = 6; + +pub const GFT64_RUNG_ET: u32 = 9; + +pub const GFT128_RUNG_ET: u32 = 14; + +pub fn receipt_leaf_gf_fmt( + fmt_family: u32, + gf_width: u32, + gf_op: u32, + a: u32, + b: u32, + gf_result: u32, + device_id: u32, + executor: u32, + epoch: u32, +) -> u32 { + let base: u32 = receipt_leaf_gf(gf_width, gf_op, a, b, gf_result, device_id, executor, epoch); + return mix32((base ^ mix32((fmt_family ^ rotl(gf_width, 9))))); +} + +pub fn receipt_leaf_gf_rung( + fmt_family: u32, + gf_width: u32, + gf_et: u32, + gf_op: u32, + a: u32, + b: u32, + gf_result: u32, + device_id: u32, + executor: u32, + epoch: u32, +) -> u32 { + let base: u32 = receipt_leaf_gf_fmt( + fmt_family, gf_width, gf_op, a, b, gf_result, device_id, executor, epoch, + ); + return mix32((base ^ mix32((gf_et ^ rotl(fmt_family, 13))))); +} + +pub fn chain_step_full(prev_head: u32, digest: u32) -> u32 { + return mix32((prev_head ^ mix32((digest ^ R_C2)))); +} + +pub fn ledger_entry_pre( + idx: u32, + ph0: u32, + ph1: u32, + ph2: u32, + ph3: u32, + ph4: u32, + ph5: u32, + ph6: u32, + ph7: u32, + d0: u32, + d1: u32, + d2: u32, + d3: u32, + d4: u32, + d5: u32, + d6: u32, + d7: u32, + balance: u32, + epoch: u32, +) -> u32 { + if (idx == 0) { + return ph0; + } + if (idx == 1) { + return ph1; + } + if (idx == 2) { + return ph2; + } + if (idx == 3) { + return ph3; + } + if (idx == 4) { + return ph4; + } + if (idx == 5) { + return ph5; + } + if (idx == 6) { + return ph6; + } + if (idx == 7) { + return ph7; + } + if (idx == 8) { + return d0; + } + if (idx == 9) { + return d1; + } + if (idx == 10) { + return d2; + } + if (idx == 11) { + return d3; + } + if (idx == 12) { + return d4; + } + if (idx == 13) { + return d5; + } + if (idx == 14) { + return d6; + } + if (idx == 15) { + return d7; + } + if (idx == 16) { + return balance; + } + if (idx == 17) { + return epoch; + } + if (idx == 18) { + return TAG_LEDGER; + } + if (idx == 19) { + return SHA_PAD; + } + if (idx == 31) { + return LEDGER_MSG_BITS; + } + return 0; +} + +pub fn merkle_pair_pre( + idx: u32, + l0: u32, + l1: u32, + l2: u32, + l3: u32, + l4: u32, + l5: u32, + l6: u32, + l7: u32, + r0: u32, + r1: u32, + r2: u32, + r3: u32, + r4: u32, + r5: u32, + r6: u32, + r7: u32, +) -> u32 { + if (idx == 0) { + return l0; + } + if (idx == 1) { + return l1; + } + if (idx == 2) { + return l2; + } + if (idx == 3) { + return l3; + } + if (idx == 4) { + return l4; + } + if (idx == 5) { + return l5; + } + if (idx == 6) { + return l6; + } + if (idx == 7) { + return l7; + } + if (idx == 8) { + return r0; + } + if (idx == 9) { + return r1; + } + if (idx == 10) { + return r2; + } + if (idx == 11) { + return r3; + } + if (idx == 12) { + return r4; + } + if (idx == 13) { + return r5; + } + if (idx == 14) { + return r6; + } + if (idx == 15) { + return r7; + } + if (idx == 16) { + return SHA_PAD; + } + if (idx == 31) { + return MERKLE_MSG_BITS; + } + return 0; +} + +pub fn input_digest_pre( + idx: u32, + request_id: u32, + device: u32, + executor: u32, + task: u32, + oh0: u32, + oh1: u32, + oh2: u32, + oh3: u32, + oh4: u32, + oh5: u32, + oh6: u32, + oh7: u32, + out: u32, + epoch: u32, + prev_head: u32, +) -> u32 { + if (idx == 0) { + return TAG_INPUT; + } + if (idx == 1) { + return request_id; + } + if (idx == 2) { + return device; + } + if (idx == 3) { + return executor; + } + if (idx == 4) { + return task; + } + if (idx == 5) { + return oh0; + } + if (idx == 6) { + return oh1; + } + if (idx == 7) { + return oh2; + } + if (idx == 8) { + return oh3; + } + if (idx == 9) { + return oh4; + } + if (idx == 10) { + return oh5; + } + if (idx == 11) { + return oh6; + } + if (idx == 12) { + return oh7; + } + if (idx == 13) { + return out; + } + if (idx == 14) { + return epoch; + } + if (idx == 15) { + return prev_head; + } + if (idx == 16) { + return SHA_PAD; + } + if (idx == 31) { + return MERKLE_MSG_BITS; + } + return 0; +} + +pub fn verify_chain3_full(d0: u32, d1: u32, d2: u32, claimed: u32) -> bool { + let h0: u32 = chain_step_full(RECEIPT_GENESIS, d0); + let h1: u32 = chain_step_full(h0, d1); + let h2: u32 = chain_step_full(h1, d2); + return (h2 == claimed); +} diff --git a/gen/rust/tri_compute_reputation.rs b/gen/rust/tri_compute_reputation.rs index ce3ac814..4cb26e44 100644 --- a/gen/rust/tri_compute_reputation.rs +++ b/gen/rust/tri_compute_reputation.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 14 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const REP_INIT: u32 = 100; diff --git a/gen/rust/tri_compute_safety.rs b/gen/rust/tri_compute_safety.rs index d4e418f2..5bd4e41b 100644 --- a/gen/rust/tri_compute_safety.rs +++ b/gen/rust/tri_compute_safety.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 8 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub fn payable(fresh: u32, finite: u32, already_settled: u32) -> u32 { if (already_settled == 1) { diff --git a/gen/rust/tri_compute_settle.rs b/gen/rust/tri_compute_settle.rs index a60dd330..03b2c176 100644 --- a/gen/rust/tri_compute_settle.rs +++ b/gen/rust/tri_compute_settle.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 17 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const SETTLE_GENESIS: u32 = 0x54524353; diff --git a/gen/rust/tri_depin.rs b/gen/rust/tri_depin.rs index 9ff5124d..8f21a950 100644 --- a/gen/rust/tri_depin.rs +++ b/gen/rust/tri_depin.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 18 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const TRI_GENESIS: u32 = 0x54524921; @@ -27,7 +30,13 @@ pub fn epoch_seal(acc: u32, total_bytes: u32, node_key: u32, epoch: u32) -> u32 return mix32((workbind ^ idbind)); } -pub fn verify_epoch(claimed_seal: u32, acc: u32, total_bytes: u32, node_key: u32, epoch: u32) -> bool { +pub fn verify_epoch( + claimed_seal: u32, + acc: u32, + total_bytes: u32, + node_key: u32, + epoch: u32, +) -> bool { return (epoch_seal(acc, total_bytes, node_key, epoch) == claimed_seal); } @@ -40,7 +49,12 @@ pub fn bytes_add(total: u32, nbytes: u32) -> u32 { } } -pub fn relay_absorb_verified(acc: u32, computed_digest: u32, expected_digest: u32, nbytes: u32) -> u32 { +pub fn relay_absorb_verified( + acc: u32, + computed_digest: u32, + expected_digest: u32, + nbytes: u32, +) -> u32 { if (computed_digest == expected_digest) { return relay_absorb(acc, computed_digest, nbytes); } else { @@ -48,11 +62,15 @@ pub fn relay_absorb_verified(acc: u32, computed_digest: u32, expected_digest: u3 } } -pub fn bytes_add_verified(total: u32, nbytes: u32, computed_digest: u32, expected_digest: u32) -> u32 { +pub fn bytes_add_verified( + total: u32, + nbytes: u32, + computed_digest: u32, + expected_digest: u32, +) -> u32 { if (computed_digest == expected_digest) { return bytes_add(total, nbytes); } else { return total; } } - diff --git a/gen/rust/tri_fec.rs b/gen/rust/tri_fec.rs index d034f939..f39b02e8 100644 --- a/gen/rust/tri_fec.rs +++ b/gen/rust/tri_fec.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 5 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub fn fec_parity4(a: u32, b: u32, c: u32, d: u32) -> u32 { return (((a ^ b) ^ c) ^ d); @@ -12,4 +15,3 @@ pub fn fec_xor(a: u32, b: u32) -> u32 { pub fn fec_recover(parity: u32, survivors_xor: u32) -> u32 { return (parity ^ survivors_xor); } - diff --git a/gen/rust/tri_gft_add.rs b/gen/rust/tri_gft_add.rs new file mode 100644 index 00000000..654aaa95 --- /dev/null +++ b/gen/rust/tri_gft_add.rs @@ -0,0 +1,219 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 8 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. + +pub const MANT_ONE: u32 = 512; + +pub const SIG_BITS: u32 = 10; + +pub fn gft_add_sb_p(mb: u32, d: u32, mant_one: u32, sig_bits: u32) -> u32 { + if (d >= sig_bits) { + return 0; + } else { + return ((mant_one + mb) >> d); + } +} + +pub fn gft_add_offset_p( + offset_a: u32, + offset_b: u32, + ma: u32, + mb: u32, + offset_max: u32, + mant_one: u32, + sig_bits: u32, +) -> u32 { + let d: u32 = (offset_a - offset_b); + let sum: u32 = ((mant_one + ma) + gft_add_sb_p(mb, d, mant_one, sig_bits)); + if (sum >= (2 * mant_one)) { + let e: u32 = (offset_a + 1); + if (e >= offset_max) { + return offset_max; + } else { + return e; + } + } else { + return offset_a; + } +} + +pub fn gft_add_mant_p( + offset_a: u32, + offset_b: u32, + ma: u32, + mb: u32, + mant_one: u32, + sig_bits: u32, +) -> u32 { + let d: u32 = (offset_a - offset_b); + let sum: u32 = ((mant_one + ma) + gft_add_sb_p(mb, d, mant_one, sig_bits)); + if (sum >= (2 * mant_one)) { + return ((sum >> 1) - mant_one); + } else { + return (sum - mant_one); + } +} + +pub fn gft_add_sb(mb: u32, d: u32) -> u32 { + return gft_add_sb_p(mb, d, MANT_ONE, SIG_BITS); +} + +pub fn gft_add_offset(offset_a: u32, offset_b: u32, ma: u32, mb: u32, offset_max: u32) -> u32 { + return gft_add_offset_p(offset_a, offset_b, ma, mb, offset_max, MANT_ONE, SIG_BITS); +} + +pub fn gft_add_mant(offset_a: u32, offset_b: u32, ma: u32, mb: u32) -> u32 { + return gft_add_mant_p(offset_a, offset_b, ma, mb, MANT_ONE, SIG_BITS); +} + +pub fn gft_add_offset_c(oa: u32, ob: u32, ma: u32, mb: u32, offset_max: u32) -> u32 { + if (oa >= ob) { + return gft_add_offset(oa, ob, ma, mb, offset_max); + } else { + return gft_add_offset(ob, oa, mb, ma, offset_max); + } +} + +pub fn gft_add_mant_c(oa: u32, ob: u32, ma: u32, mb: u32) -> u32 { + if (oa >= ob) { + return gft_add_mant(oa, ob, ma, mb); + } else { + return gft_add_mant(ob, oa, mb, ma); + } +} + +pub fn verify_gft_add( + oa: u32, + ob: u32, + ma: u32, + mb: u32, + claimed_offset: u32, + claimed_mant: u32, + offset_max: u32, +) -> bool { + if (gft_add_offset_c(oa, ob, ma, mb, offset_max) == claimed_offset) { + return (gft_add_mant_c(oa, ob, ma, mb) == claimed_mant); + } else { + return (oa != oa); + } +} + +pub fn gft_add_offset_c_p( + oa: u32, + ob: u32, + ma: u32, + mb: u32, + offset_max: u32, + mant_one: u32, + sig_bits: u32, +) -> u32 { + if (oa >= ob) { + return gft_add_offset_p(oa, ob, ma, mb, offset_max, mant_one, sig_bits); + } else { + return gft_add_offset_p(ob, oa, mb, ma, offset_max, mant_one, sig_bits); + } +} + +pub fn gft_add_mant_c_p(oa: u32, ob: u32, ma: u32, mb: u32, mant_one: u32, sig_bits: u32) -> u32 { + if (oa >= ob) { + return gft_add_mant_p(oa, ob, ma, mb, mant_one, sig_bits); + } else { + return gft_add_mant_p(ob, oa, mb, ma, mant_one, sig_bits); + } +} + +pub fn verify_gft_add_p( + oa: u32, + ob: u32, + ma: u32, + mb: u32, + claimed_offset: u32, + claimed_mant: u32, + offset_max: u32, + mant_one: u32, + sig_bits: u32, +) -> bool { + if (gft_add_offset_c_p(oa, ob, ma, mb, offset_max, mant_one, sig_bits) == claimed_offset) { + return (gft_add_mant_c_p(oa, ob, ma, mb, mant_one, sig_bits) == claimed_mant); + } else { + return (oa != oa); + } +} + +pub fn gft_dot4_offset( + o0: u32, + m0: u32, + o1: u32, + m1: u32, + o2: u32, + m2: u32, + o3: u32, + m3: u32, + offset_max: u32, +) -> u32 { + let s01o: u32 = gft_add_offset_c(o0, o1, m0, m1, offset_max); + let s01m: u32 = gft_add_mant_c(o0, o1, m0, m1); + let s23o: u32 = gft_add_offset_c(o2, o3, m2, m3, offset_max); + let s23m: u32 = gft_add_mant_c(o2, o3, m2, m3); + return gft_add_offset_c(s01o, s23o, s01m, s23m, offset_max); +} + +pub fn gft_dot4_mant( + o0: u32, + m0: u32, + o1: u32, + m1: u32, + o2: u32, + m2: u32, + o3: u32, + m3: u32, + offset_max: u32, +) -> u32 { + let s01o: u32 = gft_add_offset_c(o0, o1, m0, m1, offset_max); + let s01m: u32 = gft_add_mant_c(o0, o1, m0, m1); + let s23o: u32 = gft_add_offset_c(o2, o3, m2, m3, offset_max); + let s23m: u32 = gft_add_mant_c(o2, o3, m2, m3); + return gft_add_mant_c(s01o, s23o, s01m, s23m); +} + +pub fn gft_dot4_offset_p( + o0: u32, + m0: u32, + o1: u32, + m1: u32, + o2: u32, + m2: u32, + o3: u32, + m3: u32, + offset_max: u32, + mant_one: u32, + sig_bits: u32, +) -> u32 { + let s01o: u32 = gft_add_offset_c_p(o0, o1, m0, m1, offset_max, mant_one, sig_bits); + let s01m: u32 = gft_add_mant_c_p(o0, o1, m0, m1, mant_one, sig_bits); + let s23o: u32 = gft_add_offset_c_p(o2, o3, m2, m3, offset_max, mant_one, sig_bits); + let s23m: u32 = gft_add_mant_c_p(o2, o3, m2, m3, mant_one, sig_bits); + return gft_add_offset_c_p(s01o, s23o, s01m, s23m, offset_max, mant_one, sig_bits); +} + +pub fn gft_dot4_mant_p( + o0: u32, + m0: u32, + o1: u32, + m1: u32, + o2: u32, + m2: u32, + o3: u32, + m3: u32, + offset_max: u32, + mant_one: u32, + sig_bits: u32, +) -> u32 { + let s01o: u32 = gft_add_offset_c_p(o0, o1, m0, m1, offset_max, mant_one, sig_bits); + let s01m: u32 = gft_add_mant_c_p(o0, o1, m0, m1, mant_one, sig_bits); + let s23o: u32 = gft_add_offset_c_p(o2, o3, m2, m3, offset_max, mant_one, sig_bits); + let s23m: u32 = gft_add_mant_c_p(o2, o3, m2, m3, mant_one, sig_bits); + return gft_add_mant_c_p(s01o, s23o, s01m, s23m, mant_one, sig_bits); +} diff --git a/gen/rust/tri_gft_arith.rs b/gen/rust/tri_gft_arith.rs new file mode 100644 index 00000000..c5d98a29 --- /dev/null +++ b/gen/rust/tri_gft_arith.rs @@ -0,0 +1,215 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 10 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. + +pub const GFT16_BIAS: u32 = 40; + +pub const GFT16_OFFSET_MAX: u32 = 80; + +pub fn gft_mul_offset(offset_a: u32, offset_b: u32, bias: u32, offset_max: u32) -> u32 { + let sum: u32 = (offset_a + offset_b); + if (sum < bias) { + return 0; + } else { + let result: u32 = (sum - bias); + if (result >= offset_max) { + return offset_max; + } else { + return result; + } + } +} + +pub fn verify_gft_mul_offset( + offset_a: u32, + offset_b: u32, + claimed: u32, + bias: u32, + offset_max: u32, +) -> bool { + return (gft_mul_offset(offset_a, offset_b, bias, offset_max) == claimed); +} + +pub fn gft_mul_sign(sign_a: u32, sign_b: u32) -> u32 { + return (sign_a ^ sign_b); +} + +pub const MANT_ONE: u32 = 512; + +pub fn gft_mul_mant_carry_p(ma: u32, mb: u32, mant_one: u32) -> u32 { + let prod: u32 = ((mant_one + ma) * (mant_one + mb)); + if (prod >= ((2 * mant_one) * mant_one)) { + return 1; + } else { + return 0; + } +} + +pub fn gft_mul_mant_p(ma: u32, mb: u32, mant_one: u32) -> u32 { + let prod: u32 = ((mant_one + ma) * (mant_one + mb)); + if (prod >= ((2 * mant_one) * mant_one)) { + return ((prod / (2 * mant_one)) - mant_one); + } else { + return ((prod / mant_one) - mant_one); + } +} + +pub fn gft_mul_offset_full_p( + offset_a: u32, + ma: u32, + offset_b: u32, + mb: u32, + bias: u32, + offset_max: u32, + mant_one: u32, +) -> u32 { + let carry: u32 = gft_mul_mant_carry_p(ma, mb, mant_one); + let sum: u32 = ((offset_a + offset_b) + carry); + if (sum < bias) { + return 0; + } else { + let result: u32 = (sum - bias); + if (result >= offset_max) { + return offset_max; + } else { + return result; + } + } +} + +pub fn verify_gft_mul_full_p( + offset_a: u32, + ma: u32, + offset_b: u32, + mb: u32, + claimed_offset: u32, + claimed_mant: u32, + bias: u32, + offset_max: u32, + mant_one: u32, +) -> bool { + if (gft_mul_offset_full_p(offset_a, ma, offset_b, mb, bias, offset_max, mant_one) + == claimed_offset) + { + return (gft_mul_mant_p(ma, mb, mant_one) == claimed_mant); + } else { + return (offset_a != offset_a); + } +} + +pub fn gft_mul_mant_carry_u64(ma: u64, mb: u64, mant_one: u64) -> u32 { + let prod: u64 = ((mant_one + ma) * (mant_one + mb)); + if (prod >= ((2 * mant_one) * mant_one)) { + return 1; + } else { + return 0; + } +} + +pub fn gft_mul_mant_u64(ma: u64, mb: u64, mant_one: u64) -> u32 { + let prod: u64 = ((mant_one + ma) * (mant_one + mb)); + if (prod >= ((2 * mant_one) * mant_one)) { + return (((prod / (2 * mant_one)) - mant_one) as u32); + } else { + return (((prod / mant_one) - mant_one) as u32); + } +} + +pub fn gft_mul_offset_full_u64( + offset_a: u32, + ma: u64, + offset_b: u32, + mb: u64, + bias: u32, + offset_max: u32, + mant_one: u64, +) -> u32 { + let carry: u32 = gft_mul_mant_carry_u64(ma, mb, mant_one); + let sum: u32 = ((offset_a + offset_b) + carry); + if (sum < bias) { + return 0; + } else { + let result: u32 = (sum - bias); + if (result >= offset_max) { + return offset_max; + } else { + return result; + } + } +} + +pub fn verify_gft_mul_full_u64( + offset_a: u32, + ma: u64, + offset_b: u32, + mb: u64, + claimed_offset: u32, + claimed_mant: u32, + bias: u32, + offset_max: u32, + mant_one: u64, +) -> bool { + if (gft_mul_offset_full_u64(offset_a, ma, offset_b, mb, bias, offset_max, mant_one) + == claimed_offset) + { + return (gft_mul_mant_u64(ma, mb, mant_one) == claimed_mant); + } else { + return (offset_a != offset_a); + } +} + +pub fn gft_mul_mant_carry(ma: u32, mb: u32) -> u32 { + return gft_mul_mant_carry_p(ma, mb, MANT_ONE); +} + +pub fn gft_mul_mant(ma: u32, mb: u32) -> u32 { + return gft_mul_mant_p(ma, mb, MANT_ONE); +} + +pub fn gft_mul_offset_full( + offset_a: u32, + ma: u32, + offset_b: u32, + mb: u32, + bias: u32, + offset_max: u32, +) -> u32 { + return gft_mul_offset_full_p(offset_a, ma, offset_b, mb, bias, offset_max, MANT_ONE); +} + +pub fn verify_gft_mul_full( + offset_a: u32, + ma: u32, + offset_b: u32, + mb: u32, + claimed_offset: u32, + claimed_mant: u32, + bias: u32, + offset_max: u32, +) -> bool { + if (gft_mul_offset_full(offset_a, ma, offset_b, mb, bias, offset_max) == claimed_offset) { + return (gft_mul_mant(ma, mb) == claimed_mant); + } else { + return (offset_a != offset_a); + } +} + +pub fn gft_result_encode(offset: u32, mant: u32) -> u32 { + return ((offset << 9) | (mant & 0x1FF)); +} + +pub fn gft_mul_result( + offset_a: u32, + ma: u32, + offset_b: u32, + mb: u32, + bias: u32, + offset_max: u32, +) -> u32 { + return gft_result_encode( + gft_mul_offset_full(offset_a, ma, offset_b, mb, bias, offset_max), + gft_mul_mant(ma, mb), + ); +} diff --git a/gen/rust/tri_gft_ladder.rs b/gen/rust/tri_gft_ladder.rs new file mode 100644 index 00000000..a3b4b0c4 --- /dev/null +++ b/gen/rust/tri_gft_ladder.rs @@ -0,0 +1,235 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 9 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. + +pub const GFT4_ET: u32 = 2; + +pub const GFT8_ET: u32 = 3; + +pub const GFT16_ET: u32 = 4; + +pub const GFT32_ET: u32 = 6; + +pub const GFT64_ET: u32 = 9; + +pub const GFT128_ET: u32 = 14; + +pub const GFT256_ET: u32 = 22; + +pub const GFT512_ET: u32 = 35; + +pub const GFT1024_ET: u32 = 56; + +pub const GFT4_MANT: u32 = 1; + +pub const GFT8_MANT: u32 = 4; + +pub const GFT16_MANT: u32 = 9; + +pub const GFT32_MANT: u32 = 25; + +pub const GFT64_MANT: u32 = 64; + +pub const GFT128_MANT: u32 = 169; + +pub const GFT256_MANT: u32 = 441; + +pub const GFT512_MANT: u32 = 1156; + +pub const GFT1024_MANT: u32 = 3025; + +pub fn fib(n: u32) -> u32 { + if (n == 0) { + return 0; + } + if (n == 1) { + return 1; + } + if (n == 2) { + return 1; + } + if (n == 3) { + return 2; + } + if (n == 4) { + return 3; + } + if (n == 5) { + return 5; + } + if (n == 6) { + return 8; + } + if (n == 7) { + return 13; + } + if (n == 8) { + return 21; + } + if (n == 9) { + return 34; + } + if (n == 10) { + return 55; + } + return 0; +} + +pub fn gft_et_of_rung(k: u32) -> u32 { + return (fib((k + 1)) + 1); +} + +pub fn gft_mant_of_rung(k: u32) -> u32 { + return (fib((k + 1)) * fib((k + 1))); +} + +pub fn gft_pow3(exp_trits: u32) -> u32 { + if (exp_trits == 2) { + return 9; + } + if (exp_trits == 3) { + return 27; + } + if (exp_trits == 4) { + return 81; + } + if (exp_trits == 5) { + return 243; + } + if (exp_trits == 6) { + return 729; + } + if (exp_trits == 7) { + return 2187; + } + if (exp_trits == 8) { + return 6561; + } + if (exp_trits == 9) { + return 19683; + } + if (exp_trits == 14) { + return 4782969; + } + return 0; +} + +pub fn gft_offset_max(exp_trits: u32) -> u32 { + return (gft_pow3(exp_trits) - 1); +} + +pub fn is_finite_gft_n(offset: u32, exp_trits: u32) -> bool { + return (offset != gft_offset_max(exp_trits)); +} + +pub fn gft_offset_in_range(offset: u32, exp_trits: u32) -> bool { + return (offset < gft_pow3(exp_trits)); +} + +pub fn gft_bias(exp_trits: u32) -> u32 { + return ((gft_pow3(exp_trits) - 1) / 2); +} + +pub fn gft_pow3_u64(exp_trits: u32) -> u64 { + if (exp_trits == 2) { + return 9; + } + if (exp_trits == 3) { + return 27; + } + if (exp_trits == 4) { + return 81; + } + if (exp_trits == 6) { + return 729; + } + if (exp_trits == 9) { + return 19683; + } + if (exp_trits == 14) { + return 4782969; + } + if (exp_trits == 22) { + return 31381059609; + } + if (exp_trits == 35) { + return 50031545098999707; + } + return 0; +} + +pub fn gft_offset_max_u64(exp_trits: u32) -> u64 { + return (gft_pow3_u64(exp_trits) - 1); +} + +pub fn gft_bias_u64(exp_trits: u32) -> u64 { + return ((gft_pow3_u64(exp_trits) - 1) / 2); +} + +pub fn gft_mant_bits(exp_trits: u32) -> u32 { + if (exp_trits == GFT4_ET) { + return GFT4_MANT; + } + if (exp_trits == GFT8_ET) { + return GFT8_MANT; + } + if (exp_trits == GFT16_ET) { + return GFT16_MANT; + } + if (exp_trits == GFT32_ET) { + return GFT32_MANT; + } + if (exp_trits == GFT64_ET) { + return GFT64_MANT; + } + if (exp_trits == GFT128_ET) { + return GFT128_MANT; + } + if (exp_trits == GFT256_ET) { + return GFT256_MANT; + } + if (exp_trits == GFT512_ET) { + return GFT512_MANT; + } + if (exp_trits == GFT1024_ET) { + return GFT1024_MANT; + } + return 0; +} + +pub fn gft_mant_one(exp_trits: u32) -> u32 { + return (1 << gft_mant_bits(exp_trits)); +} + +pub fn width_to_et(width: u32) -> u32 { + if (width == 4) { + return GFT4_ET; + } + if (width == 8) { + return GFT8_ET; + } + if (width == 16) { + return GFT16_ET; + } + if (width == 32) { + return GFT32_ET; + } + if (width == 64) { + return GFT64_ET; + } + if (width == 128) { + return GFT128_ET; + } + if (width == 256) { + return GFT256_ET; + } + if (width == 512) { + return GFT512_ET; + } + if (width == 1024) { + return GFT1024_ET; + } + return 0; +} diff --git a/gen/rust/tri_gft_sub.rs b/gen/rust/tri_gft_sub.rs new file mode 100644 index 00000000..7a90c94b --- /dev/null +++ b/gen/rust/tri_gft_sub.rs @@ -0,0 +1,626 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 8 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. + +pub const MANT_ONE: u32 = 512; + +pub const MANT_BITS: u32 = 9; + +pub const ALIGN_CAP: u32 = 22; + +pub fn hi_bit(x: u32) -> u32 { + if (x >= 1073741824) { + return 30; + } + if (x >= 536870912) { + return 29; + } + if (x >= 268435456) { + return 28; + } + if (x >= 134217728) { + return 27; + } + if (x >= 67108864) { + return 26; + } + if (x >= 33554432) { + return 25; + } + if (x >= 16777216) { + return 24; + } + if (x >= 8388608) { + return 23; + } + if (x >= 4194304) { + return 22; + } + if (x >= 2097152) { + return 21; + } + if (x >= 1048576) { + return 20; + } + if (x >= 524288) { + return 19; + } + if (x >= 262144) { + return 18; + } + if (x >= 131072) { + return 17; + } + if (x >= 65536) { + return 16; + } + if (x >= 32768) { + return 15; + } + if (x >= 16384) { + return 14; + } + if (x >= 8192) { + return 13; + } + if (x >= 4096) { + return 12; + } + if (x >= 2048) { + return 11; + } + if (x >= 1024) { + return 10; + } + if (x >= 512) { + return 9; + } + if (x >= 256) { + return 8; + } + if (x >= 128) { + return 7; + } + if (x >= 64) { + return 6; + } + if (x >= 32) { + return 5; + } + if (x >= 16) { + return 4; + } + if (x >= 8) { + return 3; + } + if (x >= 4) { + return 2; + } + if (x >= 2) { + return 1; + } + return 0; +} + +pub fn norm_sig_p(v: u32, hb: u32, mant_bits: u32) -> u32 { + if (hb >= mant_bits) { + return (v >> (hb - mant_bits)); + } else { + return (v << (mant_bits - hb)); + } +} + +pub fn gft_sub_offset_p( + offset_a: u32, + offset_b: u32, + ma: u32, + mb: u32, + mant_one: u32, + mant_bits: u32, +) -> u32 { + let d: u32 = (offset_a - offset_b); + if (d >= ALIGN_CAP) { + if (ma >= 1) { + return offset_a; + } else { + if (offset_a >= 1) { + return (offset_a - 1); + } else { + return 0; + } + } + } else { + let v: u32 = (((mant_one + ma) << d) - (mant_one + mb)); + if (v == 0) { + return 0; + } else { + let hb: u32 = hi_bit(v); + if ((offset_b + hb) < mant_bits) { + return 0; + } else { + return ((offset_b + hb) - mant_bits); + } + } + } +} + +pub fn gft_sub_mant_p( + offset_a: u32, + offset_b: u32, + ma: u32, + mb: u32, + mant_one: u32, + mant_bits: u32, +) -> u32 { + let d: u32 = (offset_a - offset_b); + if (d >= ALIGN_CAP) { + if (ma >= 1) { + return (ma - 1); + } else { + return (mant_one - 1); + } + } else { + let v: u32 = (((mant_one + ma) << d) - (mant_one + mb)); + if (v == 0) { + return 0; + } else { + let hb: u32 = hi_bit(v); + if ((offset_b + hb) < mant_bits) { + return 0; + } else { + return (norm_sig_p(v, hb, mant_bits) - mant_one); + } + } + } +} + +pub fn norm_sig(v: u32, hb: u32) -> u32 { + return norm_sig_p(v, hb, MANT_BITS); +} + +pub fn gft_sub_offset(offset_a: u32, offset_b: u32, ma: u32, mb: u32) -> u32 { + return gft_sub_offset_p(offset_a, offset_b, ma, mb, MANT_ONE, MANT_BITS); +} + +pub fn gft_sub_mant(offset_a: u32, offset_b: u32, ma: u32, mb: u32) -> u32 { + return gft_sub_mant_p(offset_a, offset_b, ma, mb, MANT_ONE, MANT_BITS); +} + +pub fn gft_sub_offset_c(oa: u32, ob: u32, ma: u32, mb: u32) -> u32 { + if (oa > ob) { + return gft_sub_offset(oa, ob, ma, mb); + } else { + if (ob > oa) { + return gft_sub_offset(ob, oa, mb, ma); + } else { + if (ma >= mb) { + return gft_sub_offset(oa, ob, ma, mb); + } else { + return gft_sub_offset(ob, oa, mb, ma); + } + } + } +} + +pub fn gft_sub_mant_c(oa: u32, ob: u32, ma: u32, mb: u32) -> u32 { + if (oa > ob) { + return gft_sub_mant(oa, ob, ma, mb); + } else { + if (ob > oa) { + return gft_sub_mant(ob, oa, mb, ma); + } else { + if (ma >= mb) { + return gft_sub_mant(oa, ob, ma, mb); + } else { + return gft_sub_mant(ob, oa, mb, ma); + } + } + } +} + +pub fn verify_gft_sub( + oa: u32, + ob: u32, + ma: u32, + mb: u32, + claimed_offset: u32, + claimed_mant: u32, +) -> bool { + if (gft_sub_offset_c(oa, ob, ma, mb) == claimed_offset) { + return (gft_sub_mant_c(oa, ob, ma, mb) == claimed_mant); + } else { + return (oa != oa); + } +} + +pub fn gft_sub_offset_c_p( + oa: u32, + ob: u32, + ma: u32, + mb: u32, + mant_one: u32, + mant_bits: u32, +) -> u32 { + if (oa > ob) { + return gft_sub_offset_p(oa, ob, ma, mb, mant_one, mant_bits); + } else { + if (ob > oa) { + return gft_sub_offset_p(ob, oa, mb, ma, mant_one, mant_bits); + } else { + if (ma >= mb) { + return gft_sub_offset_p(oa, ob, ma, mb, mant_one, mant_bits); + } else { + return gft_sub_offset_p(ob, oa, mb, ma, mant_one, mant_bits); + } + } + } +} + +pub fn gft_sub_mant_c_p(oa: u32, ob: u32, ma: u32, mb: u32, mant_one: u32, mant_bits: u32) -> u32 { + if (oa > ob) { + return gft_sub_mant_p(oa, ob, ma, mb, mant_one, mant_bits); + } else { + if (ob > oa) { + return gft_sub_mant_p(ob, oa, mb, ma, mant_one, mant_bits); + } else { + if (ma >= mb) { + return gft_sub_mant_p(oa, ob, ma, mb, mant_one, mant_bits); + } else { + return gft_sub_mant_p(ob, oa, mb, ma, mant_one, mant_bits); + } + } + } +} + +pub fn verify_gft_sub_p( + oa: u32, + ob: u32, + ma: u32, + mb: u32, + claimed_offset: u32, + claimed_mant: u32, + mant_one: u32, + mant_bits: u32, +) -> bool { + if (gft_sub_offset_c_p(oa, ob, ma, mb, mant_one, mant_bits) == claimed_offset) { + return (gft_sub_mant_c_p(oa, ob, ma, mb, mant_one, mant_bits) == claimed_mant); + } else { + return (oa != oa); + } +} + +pub fn hi_bit_u64(x: u64) -> u32 { + if ((x >> 63) != 0) { + return 63; + } + if ((x >> 62) != 0) { + return 62; + } + if ((x >> 61) != 0) { + return 61; + } + if ((x >> 60) != 0) { + return 60; + } + if ((x >> 59) != 0) { + return 59; + } + if ((x >> 58) != 0) { + return 58; + } + if ((x >> 57) != 0) { + return 57; + } + if ((x >> 56) != 0) { + return 56; + } + if ((x >> 55) != 0) { + return 55; + } + if ((x >> 54) != 0) { + return 54; + } + if ((x >> 53) != 0) { + return 53; + } + if ((x >> 52) != 0) { + return 52; + } + if ((x >> 51) != 0) { + return 51; + } + if ((x >> 50) != 0) { + return 50; + } + if ((x >> 49) != 0) { + return 49; + } + if ((x >> 48) != 0) { + return 48; + } + if ((x >> 47) != 0) { + return 47; + } + if ((x >> 46) != 0) { + return 46; + } + if ((x >> 45) != 0) { + return 45; + } + if ((x >> 44) != 0) { + return 44; + } + if ((x >> 43) != 0) { + return 43; + } + if ((x >> 42) != 0) { + return 42; + } + if ((x >> 41) != 0) { + return 41; + } + if ((x >> 40) != 0) { + return 40; + } + if ((x >> 39) != 0) { + return 39; + } + if ((x >> 38) != 0) { + return 38; + } + if ((x >> 37) != 0) { + return 37; + } + if ((x >> 36) != 0) { + return 36; + } + if ((x >> 35) != 0) { + return 35; + } + if ((x >> 34) != 0) { + return 34; + } + if ((x >> 33) != 0) { + return 33; + } + if ((x >> 32) != 0) { + return 32; + } + if ((x >> 31) != 0) { + return 31; + } + if ((x >> 30) != 0) { + return 30; + } + if ((x >> 29) != 0) { + return 29; + } + if ((x >> 28) != 0) { + return 28; + } + if ((x >> 27) != 0) { + return 27; + } + if ((x >> 26) != 0) { + return 26; + } + if ((x >> 25) != 0) { + return 25; + } + if ((x >> 24) != 0) { + return 24; + } + if ((x >> 23) != 0) { + return 23; + } + if ((x >> 22) != 0) { + return 22; + } + if ((x >> 21) != 0) { + return 21; + } + if ((x >> 20) != 0) { + return 20; + } + if ((x >> 19) != 0) { + return 19; + } + if ((x >> 18) != 0) { + return 18; + } + if ((x >> 17) != 0) { + return 17; + } + if ((x >> 16) != 0) { + return 16; + } + if ((x >> 15) != 0) { + return 15; + } + if ((x >> 14) != 0) { + return 14; + } + if ((x >> 13) != 0) { + return 13; + } + if ((x >> 12) != 0) { + return 12; + } + if ((x >> 11) != 0) { + return 11; + } + if ((x >> 10) != 0) { + return 10; + } + if ((x >> 9) != 0) { + return 9; + } + if ((x >> 8) != 0) { + return 8; + } + if ((x >> 7) != 0) { + return 7; + } + if ((x >> 6) != 0) { + return 6; + } + if ((x >> 5) != 0) { + return 5; + } + if ((x >> 4) != 0) { + return 4; + } + if ((x >> 3) != 0) { + return 3; + } + if ((x >> 2) != 0) { + return 2; + } + if ((x >> 1) != 0) { + return 1; + } + return 0; +} + +pub fn norm_sig_u64(v: u64, hb: u32, mant_bits: u32) -> u64 { + if (hb >= mant_bits) { + return (v >> (hb - mant_bits)); + } else { + return (v << (mant_bits - hb)); + } +} + +pub fn gft_sub_offset_u64( + offset_a: u32, + offset_b: u32, + ma: u64, + mb: u64, + mant_one: u64, + mant_bits: u32, + align_cap: u32, +) -> u32 { + let d: u32 = (offset_a - offset_b); + if (d >= align_cap) { + if (ma >= 1) { + return offset_a; + } else { + if (offset_a >= 1) { + return (offset_a - 1); + } else { + return 0; + } + } + } else { + let v: u64 = (((mant_one + ma) << d) - (mant_one + mb)); + if (v == 0) { + return 0; + } else { + let hb: u32 = hi_bit_u64(v); + if ((offset_b + hb) < mant_bits) { + return 0; + } else { + return ((offset_b + hb) - mant_bits); + } + } + } +} + +pub fn gft_sub_mant_u64( + offset_a: u32, + offset_b: u32, + ma: u64, + mb: u64, + mant_one: u64, + mant_bits: u32, + align_cap: u32, +) -> u32 { + let d: u32 = (offset_a - offset_b); + if (d >= align_cap) { + if (ma >= 1) { + return ((ma - 1) as u32); + } else { + return ((mant_one - 1) as u32); + } + } else { + let v: u64 = (((mant_one + ma) << d) - (mant_one + mb)); + if (v == 0) { + return 0; + } else { + let hb: u32 = hi_bit_u64(v); + if ((offset_b + hb) < mant_bits) { + return 0; + } else { + return ((norm_sig_u64(v, hb, mant_bits) - mant_one) as u32); + } + } + } +} + +pub fn gft_sub_offset_c_u64( + oa: u32, + ob: u32, + ma: u64, + mb: u64, + mant_one: u64, + mant_bits: u32, + align_cap: u32, +) -> u32 { + if (oa > ob) { + return gft_sub_offset_u64(oa, ob, ma, mb, mant_one, mant_bits, align_cap); + } else { + if (ob > oa) { + return gft_sub_offset_u64(ob, oa, mb, ma, mant_one, mant_bits, align_cap); + } else { + if (ma >= mb) { + return gft_sub_offset_u64(oa, ob, ma, mb, mant_one, mant_bits, align_cap); + } else { + return gft_sub_offset_u64(ob, oa, mb, ma, mant_one, mant_bits, align_cap); + } + } + } +} + +pub fn gft_sub_mant_c_u64( + oa: u32, + ob: u32, + ma: u64, + mb: u64, + mant_one: u64, + mant_bits: u32, + align_cap: u32, +) -> u32 { + if (oa > ob) { + return gft_sub_mant_u64(oa, ob, ma, mb, mant_one, mant_bits, align_cap); + } else { + if (ob > oa) { + return gft_sub_mant_u64(ob, oa, mb, ma, mant_one, mant_bits, align_cap); + } else { + if (ma >= mb) { + return gft_sub_mant_u64(oa, ob, ma, mb, mant_one, mant_bits, align_cap); + } else { + return gft_sub_mant_u64(ob, oa, mb, ma, mant_one, mant_bits, align_cap); + } + } + } +} + +pub fn verify_gft_sub_u64( + oa: u32, + ob: u32, + ma: u64, + mb: u64, + claimed_offset: u32, + claimed_mant: u32, + mant_one: u64, + mant_bits: u32, + align_cap: u32, +) -> bool { + if (gft_sub_offset_c_u64(oa, ob, ma, mb, mant_one, mant_bits, align_cap) == claimed_offset) { + return (gft_sub_mant_c_u64(oa, ob, ma, mb, mant_one, mant_bits, align_cap) + == claimed_mant); + } else { + return (oa != oa); + } +} diff --git a/gen/rust/tri_ilv.rs b/gen/rust/tri_ilv.rs index 5f052127..5a0006c3 100644 --- a/gen/rust/tri_ilv.rs +++ b/gen/rust/tri_ilv.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 7 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const DEPTH_CAP: u32 = 64; @@ -30,4 +33,3 @@ pub fn choose_depth(max_burst: u32) -> u32 { pub fn depth_survives(depth: u32, burst: u32) -> bool { return (depth >= burst); } - diff --git a/gen/rust/tri_ledger.rs b/gen/rust/tri_ledger.rs index 6cd78445..cff6279f 100644 --- a/gen/rust/tri_ledger.rs +++ b/gen/rust/tri_ledger.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 6 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const LEDGER_GENESIS: u32 = 0x54524C47; @@ -30,10 +33,17 @@ pub fn state_step(prev_state: u32, round_root: u32, epoch: u32) -> u32 { return mix32((prev_state ^ mix32((round_root ^ rotl(epoch, 13))))); } -pub fn verify_chain3(rr0: u32, e0: u32, rr1: u32, e1: u32, rr2: u32, e2: u32, claimed: u32) -> bool { +pub fn verify_chain3( + rr0: u32, + e0: u32, + rr1: u32, + e1: u32, + rr2: u32, + e2: u32, + claimed: u32, +) -> bool { let s0: u32 = state_step(LEDGER_GENESIS, rr0, e0); let s1: u32 = state_step(s0, rr1, e1); let s2: u32 = state_step(s1, rr2, e2); return (s2 == claimed); } - diff --git a/gen/rust/tri_merkle.rs b/gen/rust/tri_merkle.rs index b7dc1e2b..2db7ec6a 100644 --- a/gen/rust/tri_merkle.rs +++ b/gen/rust/tri_merkle.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 7 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const M_C: u32 = 0x9E3779B9; @@ -55,4 +58,3 @@ pub fn merkle_verify8(leaf: u32, s0: u32, s1: u32, s2: u32, idx: u32, root: u32) let n2: u32 = merkle_step(n1, s2, ((idx >> 2) & 1)); return (n2 == root); } - diff --git a/gen/rust/tri_node_identity.rs b/gen/rust/tri_node_identity.rs new file mode 100644 index 00000000..5d5dd0c6 --- /dev/null +++ b/gen/rust/tri_node_identity.rs @@ -0,0 +1,65 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 3 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. + +pub const SHA_PAD256: u32 = 0x80000000; + +pub const PUBKEY_BITS: u32 = 256; + +pub fn pubkey_pre( + idx: u32, + k0: u32, + k1: u32, + k2: u32, + k3: u32, + k4: u32, + k5: u32, + k6: u32, + k7: u32, +) -> u32 { + if (idx == 0) { + return k0; + } + if (idx == 1) { + return k1; + } + if (idx == 2) { + return k2; + } + if (idx == 3) { + return k3; + } + if (idx == 4) { + return k4; + } + if (idx == 5) { + return k5; + } + if (idx == 6) { + return k6; + } + if (idx == 7) { + return k7; + } + if (idx == 8) { + return SHA_PAD256; + } + if (idx == 15) { + return PUBKEY_BITS; + } + return 0; +} + +pub fn identity_matches(claimed_executor: u32, hashed_pubkey_lo: u32) -> bool { + return (claimed_executor == hashed_pubkey_lo); +} + +pub fn who_ok(sig_ok: u32, claimed_executor: u32, hashed_pubkey_lo: u32) -> bool { + if (sig_ok == 1) { + return (claimed_executor == hashed_pubkey_lo); + } else { + return (sig_ok != sig_ok); + } +} diff --git a/gen/rust/tri_receipt_verify.rs b/gen/rust/tri_receipt_verify.rs new file mode 100644 index 00000000..ad4465d2 --- /dev/null +++ b/gen/rust/tri_receipt_verify.rs @@ -0,0 +1,57 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 4 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. + +pub const OK: u32 = 0; + +pub const BAD_SIG: u32 = 1; + +pub const NOT_IN_BATCH: u32 = 2; + +pub const BAD_COMPUTE: u32 = 3; + +pub const GF_OP_ADD: u32 = 0x10; + +pub const GF_OP_MUL: u32 = 0x11; + +pub fn compute_ok_for_op(gf_op: u32, mul_ok: u32, add_ok: u32) -> u32 { + if (gf_op == GF_OP_MUL) { + return mul_ok; + } else { + if (gf_op == GF_OP_ADD) { + return add_ok; + } else { + return 0; + } + } +} + +pub fn receipt_accepted(sig_ok: u32, included: u32, compute_ok: u32) -> bool { + if (sig_ok == 1) { + if (included == 1) { + return (compute_ok == 1); + } else { + return (sig_ok != sig_ok); + } + } else { + return (sig_ok != sig_ok); + } +} + +pub fn reject_reason(sig_ok: u32, included: u32, compute_ok: u32) -> u32 { + if (sig_ok == 0) { + return BAD_SIG; + } else { + if (included == 0) { + return NOT_IN_BATCH; + } else { + if (compute_ok == 0) { + return BAD_COMPUTE; + } else { + return OK; + } + } + } +} diff --git a/gen/rust/tri_settle.rs b/gen/rust/tri_settle.rs index 1713ea2f..2ef89721 100644 --- a/gen/rust/tri_settle.rs +++ b/gen/rust/tri_settle.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 17 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const PPM: u32 = 1000000; diff --git a/gen/rust/tri_sha256.rs b/gen/rust/tri_sha256.rs index 90690cda..88243d06 100644 --- a/gen/rust/tri_sha256.rs +++ b/gen/rust/tri_sha256.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 19 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub fn rotr(x: u32, n: u32) -> u32 { return ((x >> n) | (x << (32 - n))); @@ -33,7 +36,33 @@ pub fn ssig1(x: u32) -> u32 { return ((rotr(x, 17) ^ rotr(x, 19)) ^ shr(x, 10)); } -pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: u32, s7: u32, w0: u32, w1: u32, w2: u32, w3: u32, w4: u32, w5: u32, w6: u32, w7: u32, w8: u32, w9: u32, w10: u32, w11: u32, w12: u32, w13: u32, w14: u32, w15: u32, which: u32) -> u32 { +pub fn sha256_compress( + s0: u32, + s1: u32, + s2: u32, + s3: u32, + s4: u32, + s5: u32, + s6: u32, + s7: u32, + w0: u32, + w1: u32, + w2: u32, + w3: u32, + w4: u32, + w5: u32, + w6: u32, + w7: u32, + w8: u32, + w9: u32, + w10: u32, + w11: u32, + w12: u32, + w13: u32, + w14: u32, + w15: u32, + which: u32, +) -> u32 { let w16: u32 = (((ssig1(w14)).wrapping_add(w9)).wrapping_add(ssig0(w1))).wrapping_add(w0); let w17: u32 = (((ssig1(w15)).wrapping_add(w10)).wrapping_add(ssig0(w2))).wrapping_add(w1); let w18: u32 = (((ssig1(w16)).wrapping_add(w11)).wrapping_add(ssig0(w3))).wrapping_add(w2); @@ -90,7 +119,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f0: u32 = s5; let g0: u32 = s6; let h0: u32 = s7; - let t1_0: u32 = ((((h0).wrapping_add(bsig1(e0))).wrapping_add(ch(e0, f0, g0))).wrapping_add(0x428A2F98)).wrapping_add(w0); + let t1_0: u32 = ((((h0).wrapping_add(bsig1(e0))).wrapping_add(ch(e0, f0, g0))) + .wrapping_add(0x428A2F98)) + .wrapping_add(w0); let t2_0: u32 = (bsig0(a0)).wrapping_add(maj(a0, b0, c0)); let a1: u32 = (t1_0).wrapping_add(t2_0); let b1: u32 = a0; @@ -100,7 +131,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f1: u32 = e0; let g1: u32 = f0; let h1: u32 = g0; - let t1_1: u32 = ((((h1).wrapping_add(bsig1(e1))).wrapping_add(ch(e1, f1, g1))).wrapping_add(0x71374491)).wrapping_add(w1); + let t1_1: u32 = ((((h1).wrapping_add(bsig1(e1))).wrapping_add(ch(e1, f1, g1))) + .wrapping_add(0x71374491)) + .wrapping_add(w1); let t2_1: u32 = (bsig0(a1)).wrapping_add(maj(a1, b1, c1)); let a2: u32 = (t1_1).wrapping_add(t2_1); let b2: u32 = a1; @@ -110,7 +143,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f2: u32 = e1; let g2: u32 = f1; let h2: u32 = g1; - let t1_2: u32 = ((((h2).wrapping_add(bsig1(e2))).wrapping_add(ch(e2, f2, g2))).wrapping_add(0xB5C0FBCF)).wrapping_add(w2); + let t1_2: u32 = ((((h2).wrapping_add(bsig1(e2))).wrapping_add(ch(e2, f2, g2))) + .wrapping_add(0xB5C0FBCF)) + .wrapping_add(w2); let t2_2: u32 = (bsig0(a2)).wrapping_add(maj(a2, b2, c2)); let a3: u32 = (t1_2).wrapping_add(t2_2); let b3: u32 = a2; @@ -120,7 +155,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f3: u32 = e2; let g3: u32 = f2; let h3: u32 = g2; - let t1_3: u32 = ((((h3).wrapping_add(bsig1(e3))).wrapping_add(ch(e3, f3, g3))).wrapping_add(0xE9B5DBA5)).wrapping_add(w3); + let t1_3: u32 = ((((h3).wrapping_add(bsig1(e3))).wrapping_add(ch(e3, f3, g3))) + .wrapping_add(0xE9B5DBA5)) + .wrapping_add(w3); let t2_3: u32 = (bsig0(a3)).wrapping_add(maj(a3, b3, c3)); let a4: u32 = (t1_3).wrapping_add(t2_3); let b4: u32 = a3; @@ -130,7 +167,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f4: u32 = e3; let g4: u32 = f3; let h4: u32 = g3; - let t1_4: u32 = ((((h4).wrapping_add(bsig1(e4))).wrapping_add(ch(e4, f4, g4))).wrapping_add(0x3956C25B)).wrapping_add(w4); + let t1_4: u32 = ((((h4).wrapping_add(bsig1(e4))).wrapping_add(ch(e4, f4, g4))) + .wrapping_add(0x3956C25B)) + .wrapping_add(w4); let t2_4: u32 = (bsig0(a4)).wrapping_add(maj(a4, b4, c4)); let a5: u32 = (t1_4).wrapping_add(t2_4); let b5: u32 = a4; @@ -140,7 +179,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f5: u32 = e4; let g5: u32 = f4; let h5: u32 = g4; - let t1_5: u32 = ((((h5).wrapping_add(bsig1(e5))).wrapping_add(ch(e5, f5, g5))).wrapping_add(0x59F111F1)).wrapping_add(w5); + let t1_5: u32 = ((((h5).wrapping_add(bsig1(e5))).wrapping_add(ch(e5, f5, g5))) + .wrapping_add(0x59F111F1)) + .wrapping_add(w5); let t2_5: u32 = (bsig0(a5)).wrapping_add(maj(a5, b5, c5)); let a6: u32 = (t1_5).wrapping_add(t2_5); let b6: u32 = a5; @@ -150,7 +191,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f6: u32 = e5; let g6: u32 = f5; let h6: u32 = g5; - let t1_6: u32 = ((((h6).wrapping_add(bsig1(e6))).wrapping_add(ch(e6, f6, g6))).wrapping_add(0x923F82A4)).wrapping_add(w6); + let t1_6: u32 = ((((h6).wrapping_add(bsig1(e6))).wrapping_add(ch(e6, f6, g6))) + .wrapping_add(0x923F82A4)) + .wrapping_add(w6); let t2_6: u32 = (bsig0(a6)).wrapping_add(maj(a6, b6, c6)); let a7: u32 = (t1_6).wrapping_add(t2_6); let b7: u32 = a6; @@ -160,7 +203,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f7: u32 = e6; let g7: u32 = f6; let h7: u32 = g6; - let t1_7: u32 = ((((h7).wrapping_add(bsig1(e7))).wrapping_add(ch(e7, f7, g7))).wrapping_add(0xAB1C5ED5)).wrapping_add(w7); + let t1_7: u32 = ((((h7).wrapping_add(bsig1(e7))).wrapping_add(ch(e7, f7, g7))) + .wrapping_add(0xAB1C5ED5)) + .wrapping_add(w7); let t2_7: u32 = (bsig0(a7)).wrapping_add(maj(a7, b7, c7)); let a8: u32 = (t1_7).wrapping_add(t2_7); let b8: u32 = a7; @@ -170,7 +215,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f8: u32 = e7; let g8: u32 = f7; let h8: u32 = g7; - let t1_8: u32 = ((((h8).wrapping_add(bsig1(e8))).wrapping_add(ch(e8, f8, g8))).wrapping_add(0xD807AA98)).wrapping_add(w8); + let t1_8: u32 = ((((h8).wrapping_add(bsig1(e8))).wrapping_add(ch(e8, f8, g8))) + .wrapping_add(0xD807AA98)) + .wrapping_add(w8); let t2_8: u32 = (bsig0(a8)).wrapping_add(maj(a8, b8, c8)); let a9: u32 = (t1_8).wrapping_add(t2_8); let b9: u32 = a8; @@ -180,7 +227,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f9: u32 = e8; let g9: u32 = f8; let h9: u32 = g8; - let t1_9: u32 = ((((h9).wrapping_add(bsig1(e9))).wrapping_add(ch(e9, f9, g9))).wrapping_add(0x12835B01)).wrapping_add(w9); + let t1_9: u32 = ((((h9).wrapping_add(bsig1(e9))).wrapping_add(ch(e9, f9, g9))) + .wrapping_add(0x12835B01)) + .wrapping_add(w9); let t2_9: u32 = (bsig0(a9)).wrapping_add(maj(a9, b9, c9)); let a10: u32 = (t1_9).wrapping_add(t2_9); let b10: u32 = a9; @@ -190,7 +239,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f10: u32 = e9; let g10: u32 = f9; let h10: u32 = g9; - let t1_10: u32 = ((((h10).wrapping_add(bsig1(e10))).wrapping_add(ch(e10, f10, g10))).wrapping_add(0x243185BE)).wrapping_add(w10); + let t1_10: u32 = ((((h10).wrapping_add(bsig1(e10))).wrapping_add(ch(e10, f10, g10))) + .wrapping_add(0x243185BE)) + .wrapping_add(w10); let t2_10: u32 = (bsig0(a10)).wrapping_add(maj(a10, b10, c10)); let a11: u32 = (t1_10).wrapping_add(t2_10); let b11: u32 = a10; @@ -200,7 +251,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f11: u32 = e10; let g11: u32 = f10; let h11: u32 = g10; - let t1_11: u32 = ((((h11).wrapping_add(bsig1(e11))).wrapping_add(ch(e11, f11, g11))).wrapping_add(0x550C7DC3)).wrapping_add(w11); + let t1_11: u32 = ((((h11).wrapping_add(bsig1(e11))).wrapping_add(ch(e11, f11, g11))) + .wrapping_add(0x550C7DC3)) + .wrapping_add(w11); let t2_11: u32 = (bsig0(a11)).wrapping_add(maj(a11, b11, c11)); let a12: u32 = (t1_11).wrapping_add(t2_11); let b12: u32 = a11; @@ -210,7 +263,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f12: u32 = e11; let g12: u32 = f11; let h12: u32 = g11; - let t1_12: u32 = ((((h12).wrapping_add(bsig1(e12))).wrapping_add(ch(e12, f12, g12))).wrapping_add(0x72BE5D74)).wrapping_add(w12); + let t1_12: u32 = ((((h12).wrapping_add(bsig1(e12))).wrapping_add(ch(e12, f12, g12))) + .wrapping_add(0x72BE5D74)) + .wrapping_add(w12); let t2_12: u32 = (bsig0(a12)).wrapping_add(maj(a12, b12, c12)); let a13: u32 = (t1_12).wrapping_add(t2_12); let b13: u32 = a12; @@ -220,7 +275,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f13: u32 = e12; let g13: u32 = f12; let h13: u32 = g12; - let t1_13: u32 = ((((h13).wrapping_add(bsig1(e13))).wrapping_add(ch(e13, f13, g13))).wrapping_add(0x80DEB1FE)).wrapping_add(w13); + let t1_13: u32 = ((((h13).wrapping_add(bsig1(e13))).wrapping_add(ch(e13, f13, g13))) + .wrapping_add(0x80DEB1FE)) + .wrapping_add(w13); let t2_13: u32 = (bsig0(a13)).wrapping_add(maj(a13, b13, c13)); let a14: u32 = (t1_13).wrapping_add(t2_13); let b14: u32 = a13; @@ -230,7 +287,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f14: u32 = e13; let g14: u32 = f13; let h14: u32 = g13; - let t1_14: u32 = ((((h14).wrapping_add(bsig1(e14))).wrapping_add(ch(e14, f14, g14))).wrapping_add(0x9BDC06A7)).wrapping_add(w14); + let t1_14: u32 = ((((h14).wrapping_add(bsig1(e14))).wrapping_add(ch(e14, f14, g14))) + .wrapping_add(0x9BDC06A7)) + .wrapping_add(w14); let t2_14: u32 = (bsig0(a14)).wrapping_add(maj(a14, b14, c14)); let a15: u32 = (t1_14).wrapping_add(t2_14); let b15: u32 = a14; @@ -240,7 +299,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f15: u32 = e14; let g15: u32 = f14; let h15: u32 = g14; - let t1_15: u32 = ((((h15).wrapping_add(bsig1(e15))).wrapping_add(ch(e15, f15, g15))).wrapping_add(0xC19BF174)).wrapping_add(w15); + let t1_15: u32 = ((((h15).wrapping_add(bsig1(e15))).wrapping_add(ch(e15, f15, g15))) + .wrapping_add(0xC19BF174)) + .wrapping_add(w15); let t2_15: u32 = (bsig0(a15)).wrapping_add(maj(a15, b15, c15)); let a16: u32 = (t1_15).wrapping_add(t2_15); let b16: u32 = a15; @@ -250,7 +311,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f16: u32 = e15; let g16: u32 = f15; let h16: u32 = g15; - let t1_16: u32 = ((((h16).wrapping_add(bsig1(e16))).wrapping_add(ch(e16, f16, g16))).wrapping_add(0xE49B69C1)).wrapping_add(w16); + let t1_16: u32 = ((((h16).wrapping_add(bsig1(e16))).wrapping_add(ch(e16, f16, g16))) + .wrapping_add(0xE49B69C1)) + .wrapping_add(w16); let t2_16: u32 = (bsig0(a16)).wrapping_add(maj(a16, b16, c16)); let a17: u32 = (t1_16).wrapping_add(t2_16); let b17: u32 = a16; @@ -260,7 +323,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f17: u32 = e16; let g17: u32 = f16; let h17: u32 = g16; - let t1_17: u32 = ((((h17).wrapping_add(bsig1(e17))).wrapping_add(ch(e17, f17, g17))).wrapping_add(0xEFBE4786)).wrapping_add(w17); + let t1_17: u32 = ((((h17).wrapping_add(bsig1(e17))).wrapping_add(ch(e17, f17, g17))) + .wrapping_add(0xEFBE4786)) + .wrapping_add(w17); let t2_17: u32 = (bsig0(a17)).wrapping_add(maj(a17, b17, c17)); let a18: u32 = (t1_17).wrapping_add(t2_17); let b18: u32 = a17; @@ -270,7 +335,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f18: u32 = e17; let g18: u32 = f17; let h18: u32 = g17; - let t1_18: u32 = ((((h18).wrapping_add(bsig1(e18))).wrapping_add(ch(e18, f18, g18))).wrapping_add(0x0FC19DC6)).wrapping_add(w18); + let t1_18: u32 = ((((h18).wrapping_add(bsig1(e18))).wrapping_add(ch(e18, f18, g18))) + .wrapping_add(0x0FC19DC6)) + .wrapping_add(w18); let t2_18: u32 = (bsig0(a18)).wrapping_add(maj(a18, b18, c18)); let a19: u32 = (t1_18).wrapping_add(t2_18); let b19: u32 = a18; @@ -280,7 +347,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f19: u32 = e18; let g19: u32 = f18; let h19: u32 = g18; - let t1_19: u32 = ((((h19).wrapping_add(bsig1(e19))).wrapping_add(ch(e19, f19, g19))).wrapping_add(0x240CA1CC)).wrapping_add(w19); + let t1_19: u32 = ((((h19).wrapping_add(bsig1(e19))).wrapping_add(ch(e19, f19, g19))) + .wrapping_add(0x240CA1CC)) + .wrapping_add(w19); let t2_19: u32 = (bsig0(a19)).wrapping_add(maj(a19, b19, c19)); let a20: u32 = (t1_19).wrapping_add(t2_19); let b20: u32 = a19; @@ -290,7 +359,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f20: u32 = e19; let g20: u32 = f19; let h20: u32 = g19; - let t1_20: u32 = ((((h20).wrapping_add(bsig1(e20))).wrapping_add(ch(e20, f20, g20))).wrapping_add(0x2DE92C6F)).wrapping_add(w20); + let t1_20: u32 = ((((h20).wrapping_add(bsig1(e20))).wrapping_add(ch(e20, f20, g20))) + .wrapping_add(0x2DE92C6F)) + .wrapping_add(w20); let t2_20: u32 = (bsig0(a20)).wrapping_add(maj(a20, b20, c20)); let a21: u32 = (t1_20).wrapping_add(t2_20); let b21: u32 = a20; @@ -300,7 +371,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f21: u32 = e20; let g21: u32 = f20; let h21: u32 = g20; - let t1_21: u32 = ((((h21).wrapping_add(bsig1(e21))).wrapping_add(ch(e21, f21, g21))).wrapping_add(0x4A7484AA)).wrapping_add(w21); + let t1_21: u32 = ((((h21).wrapping_add(bsig1(e21))).wrapping_add(ch(e21, f21, g21))) + .wrapping_add(0x4A7484AA)) + .wrapping_add(w21); let t2_21: u32 = (bsig0(a21)).wrapping_add(maj(a21, b21, c21)); let a22: u32 = (t1_21).wrapping_add(t2_21); let b22: u32 = a21; @@ -310,7 +383,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f22: u32 = e21; let g22: u32 = f21; let h22: u32 = g21; - let t1_22: u32 = ((((h22).wrapping_add(bsig1(e22))).wrapping_add(ch(e22, f22, g22))).wrapping_add(0x5CB0A9DC)).wrapping_add(w22); + let t1_22: u32 = ((((h22).wrapping_add(bsig1(e22))).wrapping_add(ch(e22, f22, g22))) + .wrapping_add(0x5CB0A9DC)) + .wrapping_add(w22); let t2_22: u32 = (bsig0(a22)).wrapping_add(maj(a22, b22, c22)); let a23: u32 = (t1_22).wrapping_add(t2_22); let b23: u32 = a22; @@ -320,7 +395,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f23: u32 = e22; let g23: u32 = f22; let h23: u32 = g22; - let t1_23: u32 = ((((h23).wrapping_add(bsig1(e23))).wrapping_add(ch(e23, f23, g23))).wrapping_add(0x76F988DA)).wrapping_add(w23); + let t1_23: u32 = ((((h23).wrapping_add(bsig1(e23))).wrapping_add(ch(e23, f23, g23))) + .wrapping_add(0x76F988DA)) + .wrapping_add(w23); let t2_23: u32 = (bsig0(a23)).wrapping_add(maj(a23, b23, c23)); let a24: u32 = (t1_23).wrapping_add(t2_23); let b24: u32 = a23; @@ -330,7 +407,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f24: u32 = e23; let g24: u32 = f23; let h24: u32 = g23; - let t1_24: u32 = ((((h24).wrapping_add(bsig1(e24))).wrapping_add(ch(e24, f24, g24))).wrapping_add(0x983E5152)).wrapping_add(w24); + let t1_24: u32 = ((((h24).wrapping_add(bsig1(e24))).wrapping_add(ch(e24, f24, g24))) + .wrapping_add(0x983E5152)) + .wrapping_add(w24); let t2_24: u32 = (bsig0(a24)).wrapping_add(maj(a24, b24, c24)); let a25: u32 = (t1_24).wrapping_add(t2_24); let b25: u32 = a24; @@ -340,7 +419,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f25: u32 = e24; let g25: u32 = f24; let h25: u32 = g24; - let t1_25: u32 = ((((h25).wrapping_add(bsig1(e25))).wrapping_add(ch(e25, f25, g25))).wrapping_add(0xA831C66D)).wrapping_add(w25); + let t1_25: u32 = ((((h25).wrapping_add(bsig1(e25))).wrapping_add(ch(e25, f25, g25))) + .wrapping_add(0xA831C66D)) + .wrapping_add(w25); let t2_25: u32 = (bsig0(a25)).wrapping_add(maj(a25, b25, c25)); let a26: u32 = (t1_25).wrapping_add(t2_25); let b26: u32 = a25; @@ -350,7 +431,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f26: u32 = e25; let g26: u32 = f25; let h26: u32 = g25; - let t1_26: u32 = ((((h26).wrapping_add(bsig1(e26))).wrapping_add(ch(e26, f26, g26))).wrapping_add(0xB00327C8)).wrapping_add(w26); + let t1_26: u32 = ((((h26).wrapping_add(bsig1(e26))).wrapping_add(ch(e26, f26, g26))) + .wrapping_add(0xB00327C8)) + .wrapping_add(w26); let t2_26: u32 = (bsig0(a26)).wrapping_add(maj(a26, b26, c26)); let a27: u32 = (t1_26).wrapping_add(t2_26); let b27: u32 = a26; @@ -360,7 +443,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f27: u32 = e26; let g27: u32 = f26; let h27: u32 = g26; - let t1_27: u32 = ((((h27).wrapping_add(bsig1(e27))).wrapping_add(ch(e27, f27, g27))).wrapping_add(0xBF597FC7)).wrapping_add(w27); + let t1_27: u32 = ((((h27).wrapping_add(bsig1(e27))).wrapping_add(ch(e27, f27, g27))) + .wrapping_add(0xBF597FC7)) + .wrapping_add(w27); let t2_27: u32 = (bsig0(a27)).wrapping_add(maj(a27, b27, c27)); let a28: u32 = (t1_27).wrapping_add(t2_27); let b28: u32 = a27; @@ -370,7 +455,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f28: u32 = e27; let g28: u32 = f27; let h28: u32 = g27; - let t1_28: u32 = ((((h28).wrapping_add(bsig1(e28))).wrapping_add(ch(e28, f28, g28))).wrapping_add(0xC6E00BF3)).wrapping_add(w28); + let t1_28: u32 = ((((h28).wrapping_add(bsig1(e28))).wrapping_add(ch(e28, f28, g28))) + .wrapping_add(0xC6E00BF3)) + .wrapping_add(w28); let t2_28: u32 = (bsig0(a28)).wrapping_add(maj(a28, b28, c28)); let a29: u32 = (t1_28).wrapping_add(t2_28); let b29: u32 = a28; @@ -380,7 +467,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f29: u32 = e28; let g29: u32 = f28; let h29: u32 = g28; - let t1_29: u32 = ((((h29).wrapping_add(bsig1(e29))).wrapping_add(ch(e29, f29, g29))).wrapping_add(0xD5A79147)).wrapping_add(w29); + let t1_29: u32 = ((((h29).wrapping_add(bsig1(e29))).wrapping_add(ch(e29, f29, g29))) + .wrapping_add(0xD5A79147)) + .wrapping_add(w29); let t2_29: u32 = (bsig0(a29)).wrapping_add(maj(a29, b29, c29)); let a30: u32 = (t1_29).wrapping_add(t2_29); let b30: u32 = a29; @@ -390,7 +479,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f30: u32 = e29; let g30: u32 = f29; let h30: u32 = g29; - let t1_30: u32 = ((((h30).wrapping_add(bsig1(e30))).wrapping_add(ch(e30, f30, g30))).wrapping_add(0x06CA6351)).wrapping_add(w30); + let t1_30: u32 = ((((h30).wrapping_add(bsig1(e30))).wrapping_add(ch(e30, f30, g30))) + .wrapping_add(0x06CA6351)) + .wrapping_add(w30); let t2_30: u32 = (bsig0(a30)).wrapping_add(maj(a30, b30, c30)); let a31: u32 = (t1_30).wrapping_add(t2_30); let b31: u32 = a30; @@ -400,7 +491,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f31: u32 = e30; let g31: u32 = f30; let h31: u32 = g30; - let t1_31: u32 = ((((h31).wrapping_add(bsig1(e31))).wrapping_add(ch(e31, f31, g31))).wrapping_add(0x14292967)).wrapping_add(w31); + let t1_31: u32 = ((((h31).wrapping_add(bsig1(e31))).wrapping_add(ch(e31, f31, g31))) + .wrapping_add(0x14292967)) + .wrapping_add(w31); let t2_31: u32 = (bsig0(a31)).wrapping_add(maj(a31, b31, c31)); let a32: u32 = (t1_31).wrapping_add(t2_31); let b32: u32 = a31; @@ -410,7 +503,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f32: u32 = e31; let g32: u32 = f31; let h32: u32 = g31; - let t1_32: u32 = ((((h32).wrapping_add(bsig1(e32))).wrapping_add(ch(e32, f32, g32))).wrapping_add(0x27B70A85)).wrapping_add(w32); + let t1_32: u32 = ((((h32).wrapping_add(bsig1(e32))).wrapping_add(ch(e32, f32, g32))) + .wrapping_add(0x27B70A85)) + .wrapping_add(w32); let t2_32: u32 = (bsig0(a32)).wrapping_add(maj(a32, b32, c32)); let a33: u32 = (t1_32).wrapping_add(t2_32); let b33: u32 = a32; @@ -420,7 +515,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f33: u32 = e32; let g33: u32 = f32; let h33: u32 = g32; - let t1_33: u32 = ((((h33).wrapping_add(bsig1(e33))).wrapping_add(ch(e33, f33, g33))).wrapping_add(0x2E1B2138)).wrapping_add(w33); + let t1_33: u32 = ((((h33).wrapping_add(bsig1(e33))).wrapping_add(ch(e33, f33, g33))) + .wrapping_add(0x2E1B2138)) + .wrapping_add(w33); let t2_33: u32 = (bsig0(a33)).wrapping_add(maj(a33, b33, c33)); let a34: u32 = (t1_33).wrapping_add(t2_33); let b34: u32 = a33; @@ -430,7 +527,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f34: u32 = e33; let g34: u32 = f33; let h34: u32 = g33; - let t1_34: u32 = ((((h34).wrapping_add(bsig1(e34))).wrapping_add(ch(e34, f34, g34))).wrapping_add(0x4D2C6DFC)).wrapping_add(w34); + let t1_34: u32 = ((((h34).wrapping_add(bsig1(e34))).wrapping_add(ch(e34, f34, g34))) + .wrapping_add(0x4D2C6DFC)) + .wrapping_add(w34); let t2_34: u32 = (bsig0(a34)).wrapping_add(maj(a34, b34, c34)); let a35: u32 = (t1_34).wrapping_add(t2_34); let b35: u32 = a34; @@ -440,7 +539,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f35: u32 = e34; let g35: u32 = f34; let h35: u32 = g34; - let t1_35: u32 = ((((h35).wrapping_add(bsig1(e35))).wrapping_add(ch(e35, f35, g35))).wrapping_add(0x53380D13)).wrapping_add(w35); + let t1_35: u32 = ((((h35).wrapping_add(bsig1(e35))).wrapping_add(ch(e35, f35, g35))) + .wrapping_add(0x53380D13)) + .wrapping_add(w35); let t2_35: u32 = (bsig0(a35)).wrapping_add(maj(a35, b35, c35)); let a36: u32 = (t1_35).wrapping_add(t2_35); let b36: u32 = a35; @@ -450,7 +551,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f36: u32 = e35; let g36: u32 = f35; let h36: u32 = g35; - let t1_36: u32 = ((((h36).wrapping_add(bsig1(e36))).wrapping_add(ch(e36, f36, g36))).wrapping_add(0x650A7354)).wrapping_add(w36); + let t1_36: u32 = ((((h36).wrapping_add(bsig1(e36))).wrapping_add(ch(e36, f36, g36))) + .wrapping_add(0x650A7354)) + .wrapping_add(w36); let t2_36: u32 = (bsig0(a36)).wrapping_add(maj(a36, b36, c36)); let a37: u32 = (t1_36).wrapping_add(t2_36); let b37: u32 = a36; @@ -460,7 +563,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f37: u32 = e36; let g37: u32 = f36; let h37: u32 = g36; - let t1_37: u32 = ((((h37).wrapping_add(bsig1(e37))).wrapping_add(ch(e37, f37, g37))).wrapping_add(0x766A0ABB)).wrapping_add(w37); + let t1_37: u32 = ((((h37).wrapping_add(bsig1(e37))).wrapping_add(ch(e37, f37, g37))) + .wrapping_add(0x766A0ABB)) + .wrapping_add(w37); let t2_37: u32 = (bsig0(a37)).wrapping_add(maj(a37, b37, c37)); let a38: u32 = (t1_37).wrapping_add(t2_37); let b38: u32 = a37; @@ -470,7 +575,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f38: u32 = e37; let g38: u32 = f37; let h38: u32 = g37; - let t1_38: u32 = ((((h38).wrapping_add(bsig1(e38))).wrapping_add(ch(e38, f38, g38))).wrapping_add(0x81C2C92E)).wrapping_add(w38); + let t1_38: u32 = ((((h38).wrapping_add(bsig1(e38))).wrapping_add(ch(e38, f38, g38))) + .wrapping_add(0x81C2C92E)) + .wrapping_add(w38); let t2_38: u32 = (bsig0(a38)).wrapping_add(maj(a38, b38, c38)); let a39: u32 = (t1_38).wrapping_add(t2_38); let b39: u32 = a38; @@ -480,7 +587,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f39: u32 = e38; let g39: u32 = f38; let h39: u32 = g38; - let t1_39: u32 = ((((h39).wrapping_add(bsig1(e39))).wrapping_add(ch(e39, f39, g39))).wrapping_add(0x92722C85)).wrapping_add(w39); + let t1_39: u32 = ((((h39).wrapping_add(bsig1(e39))).wrapping_add(ch(e39, f39, g39))) + .wrapping_add(0x92722C85)) + .wrapping_add(w39); let t2_39: u32 = (bsig0(a39)).wrapping_add(maj(a39, b39, c39)); let a40: u32 = (t1_39).wrapping_add(t2_39); let b40: u32 = a39; @@ -490,7 +599,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f40: u32 = e39; let g40: u32 = f39; let h40: u32 = g39; - let t1_40: u32 = ((((h40).wrapping_add(bsig1(e40))).wrapping_add(ch(e40, f40, g40))).wrapping_add(0xA2BFE8A1)).wrapping_add(w40); + let t1_40: u32 = ((((h40).wrapping_add(bsig1(e40))).wrapping_add(ch(e40, f40, g40))) + .wrapping_add(0xA2BFE8A1)) + .wrapping_add(w40); let t2_40: u32 = (bsig0(a40)).wrapping_add(maj(a40, b40, c40)); let a41: u32 = (t1_40).wrapping_add(t2_40); let b41: u32 = a40; @@ -500,7 +611,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f41: u32 = e40; let g41: u32 = f40; let h41: u32 = g40; - let t1_41: u32 = ((((h41).wrapping_add(bsig1(e41))).wrapping_add(ch(e41, f41, g41))).wrapping_add(0xA81A664B)).wrapping_add(w41); + let t1_41: u32 = ((((h41).wrapping_add(bsig1(e41))).wrapping_add(ch(e41, f41, g41))) + .wrapping_add(0xA81A664B)) + .wrapping_add(w41); let t2_41: u32 = (bsig0(a41)).wrapping_add(maj(a41, b41, c41)); let a42: u32 = (t1_41).wrapping_add(t2_41); let b42: u32 = a41; @@ -510,7 +623,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f42: u32 = e41; let g42: u32 = f41; let h42: u32 = g41; - let t1_42: u32 = ((((h42).wrapping_add(bsig1(e42))).wrapping_add(ch(e42, f42, g42))).wrapping_add(0xC24B8B70)).wrapping_add(w42); + let t1_42: u32 = ((((h42).wrapping_add(bsig1(e42))).wrapping_add(ch(e42, f42, g42))) + .wrapping_add(0xC24B8B70)) + .wrapping_add(w42); let t2_42: u32 = (bsig0(a42)).wrapping_add(maj(a42, b42, c42)); let a43: u32 = (t1_42).wrapping_add(t2_42); let b43: u32 = a42; @@ -520,7 +635,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f43: u32 = e42; let g43: u32 = f42; let h43: u32 = g42; - let t1_43: u32 = ((((h43).wrapping_add(bsig1(e43))).wrapping_add(ch(e43, f43, g43))).wrapping_add(0xC76C51A3)).wrapping_add(w43); + let t1_43: u32 = ((((h43).wrapping_add(bsig1(e43))).wrapping_add(ch(e43, f43, g43))) + .wrapping_add(0xC76C51A3)) + .wrapping_add(w43); let t2_43: u32 = (bsig0(a43)).wrapping_add(maj(a43, b43, c43)); let a44: u32 = (t1_43).wrapping_add(t2_43); let b44: u32 = a43; @@ -530,7 +647,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f44: u32 = e43; let g44: u32 = f43; let h44: u32 = g43; - let t1_44: u32 = ((((h44).wrapping_add(bsig1(e44))).wrapping_add(ch(e44, f44, g44))).wrapping_add(0xD192E819)).wrapping_add(w44); + let t1_44: u32 = ((((h44).wrapping_add(bsig1(e44))).wrapping_add(ch(e44, f44, g44))) + .wrapping_add(0xD192E819)) + .wrapping_add(w44); let t2_44: u32 = (bsig0(a44)).wrapping_add(maj(a44, b44, c44)); let a45: u32 = (t1_44).wrapping_add(t2_44); let b45: u32 = a44; @@ -540,7 +659,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f45: u32 = e44; let g45: u32 = f44; let h45: u32 = g44; - let t1_45: u32 = ((((h45).wrapping_add(bsig1(e45))).wrapping_add(ch(e45, f45, g45))).wrapping_add(0xD6990624)).wrapping_add(w45); + let t1_45: u32 = ((((h45).wrapping_add(bsig1(e45))).wrapping_add(ch(e45, f45, g45))) + .wrapping_add(0xD6990624)) + .wrapping_add(w45); let t2_45: u32 = (bsig0(a45)).wrapping_add(maj(a45, b45, c45)); let a46: u32 = (t1_45).wrapping_add(t2_45); let b46: u32 = a45; @@ -550,7 +671,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f46: u32 = e45; let g46: u32 = f45; let h46: u32 = g45; - let t1_46: u32 = ((((h46).wrapping_add(bsig1(e46))).wrapping_add(ch(e46, f46, g46))).wrapping_add(0xF40E3585)).wrapping_add(w46); + let t1_46: u32 = ((((h46).wrapping_add(bsig1(e46))).wrapping_add(ch(e46, f46, g46))) + .wrapping_add(0xF40E3585)) + .wrapping_add(w46); let t2_46: u32 = (bsig0(a46)).wrapping_add(maj(a46, b46, c46)); let a47: u32 = (t1_46).wrapping_add(t2_46); let b47: u32 = a46; @@ -560,7 +683,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f47: u32 = e46; let g47: u32 = f46; let h47: u32 = g46; - let t1_47: u32 = ((((h47).wrapping_add(bsig1(e47))).wrapping_add(ch(e47, f47, g47))).wrapping_add(0x106AA070)).wrapping_add(w47); + let t1_47: u32 = ((((h47).wrapping_add(bsig1(e47))).wrapping_add(ch(e47, f47, g47))) + .wrapping_add(0x106AA070)) + .wrapping_add(w47); let t2_47: u32 = (bsig0(a47)).wrapping_add(maj(a47, b47, c47)); let a48: u32 = (t1_47).wrapping_add(t2_47); let b48: u32 = a47; @@ -570,7 +695,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f48: u32 = e47; let g48: u32 = f47; let h48: u32 = g47; - let t1_48: u32 = ((((h48).wrapping_add(bsig1(e48))).wrapping_add(ch(e48, f48, g48))).wrapping_add(0x19A4C116)).wrapping_add(w48); + let t1_48: u32 = ((((h48).wrapping_add(bsig1(e48))).wrapping_add(ch(e48, f48, g48))) + .wrapping_add(0x19A4C116)) + .wrapping_add(w48); let t2_48: u32 = (bsig0(a48)).wrapping_add(maj(a48, b48, c48)); let a49: u32 = (t1_48).wrapping_add(t2_48); let b49: u32 = a48; @@ -580,7 +707,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f49: u32 = e48; let g49: u32 = f48; let h49: u32 = g48; - let t1_49: u32 = ((((h49).wrapping_add(bsig1(e49))).wrapping_add(ch(e49, f49, g49))).wrapping_add(0x1E376C08)).wrapping_add(w49); + let t1_49: u32 = ((((h49).wrapping_add(bsig1(e49))).wrapping_add(ch(e49, f49, g49))) + .wrapping_add(0x1E376C08)) + .wrapping_add(w49); let t2_49: u32 = (bsig0(a49)).wrapping_add(maj(a49, b49, c49)); let a50: u32 = (t1_49).wrapping_add(t2_49); let b50: u32 = a49; @@ -590,7 +719,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f50: u32 = e49; let g50: u32 = f49; let h50: u32 = g49; - let t1_50: u32 = ((((h50).wrapping_add(bsig1(e50))).wrapping_add(ch(e50, f50, g50))).wrapping_add(0x2748774C)).wrapping_add(w50); + let t1_50: u32 = ((((h50).wrapping_add(bsig1(e50))).wrapping_add(ch(e50, f50, g50))) + .wrapping_add(0x2748774C)) + .wrapping_add(w50); let t2_50: u32 = (bsig0(a50)).wrapping_add(maj(a50, b50, c50)); let a51: u32 = (t1_50).wrapping_add(t2_50); let b51: u32 = a50; @@ -600,7 +731,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f51: u32 = e50; let g51: u32 = f50; let h51: u32 = g50; - let t1_51: u32 = ((((h51).wrapping_add(bsig1(e51))).wrapping_add(ch(e51, f51, g51))).wrapping_add(0x34B0BCB5)).wrapping_add(w51); + let t1_51: u32 = ((((h51).wrapping_add(bsig1(e51))).wrapping_add(ch(e51, f51, g51))) + .wrapping_add(0x34B0BCB5)) + .wrapping_add(w51); let t2_51: u32 = (bsig0(a51)).wrapping_add(maj(a51, b51, c51)); let a52: u32 = (t1_51).wrapping_add(t2_51); let b52: u32 = a51; @@ -610,7 +743,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f52: u32 = e51; let g52: u32 = f51; let h52: u32 = g51; - let t1_52: u32 = ((((h52).wrapping_add(bsig1(e52))).wrapping_add(ch(e52, f52, g52))).wrapping_add(0x391C0CB3)).wrapping_add(w52); + let t1_52: u32 = ((((h52).wrapping_add(bsig1(e52))).wrapping_add(ch(e52, f52, g52))) + .wrapping_add(0x391C0CB3)) + .wrapping_add(w52); let t2_52: u32 = (bsig0(a52)).wrapping_add(maj(a52, b52, c52)); let a53: u32 = (t1_52).wrapping_add(t2_52); let b53: u32 = a52; @@ -620,7 +755,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f53: u32 = e52; let g53: u32 = f52; let h53: u32 = g52; - let t1_53: u32 = ((((h53).wrapping_add(bsig1(e53))).wrapping_add(ch(e53, f53, g53))).wrapping_add(0x4ED8AA4A)).wrapping_add(w53); + let t1_53: u32 = ((((h53).wrapping_add(bsig1(e53))).wrapping_add(ch(e53, f53, g53))) + .wrapping_add(0x4ED8AA4A)) + .wrapping_add(w53); let t2_53: u32 = (bsig0(a53)).wrapping_add(maj(a53, b53, c53)); let a54: u32 = (t1_53).wrapping_add(t2_53); let b54: u32 = a53; @@ -630,7 +767,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f54: u32 = e53; let g54: u32 = f53; let h54: u32 = g53; - let t1_54: u32 = ((((h54).wrapping_add(bsig1(e54))).wrapping_add(ch(e54, f54, g54))).wrapping_add(0x5B9CCA4F)).wrapping_add(w54); + let t1_54: u32 = ((((h54).wrapping_add(bsig1(e54))).wrapping_add(ch(e54, f54, g54))) + .wrapping_add(0x5B9CCA4F)) + .wrapping_add(w54); let t2_54: u32 = (bsig0(a54)).wrapping_add(maj(a54, b54, c54)); let a55: u32 = (t1_54).wrapping_add(t2_54); let b55: u32 = a54; @@ -640,7 +779,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f55: u32 = e54; let g55: u32 = f54; let h55: u32 = g54; - let t1_55: u32 = ((((h55).wrapping_add(bsig1(e55))).wrapping_add(ch(e55, f55, g55))).wrapping_add(0x682E6FF3)).wrapping_add(w55); + let t1_55: u32 = ((((h55).wrapping_add(bsig1(e55))).wrapping_add(ch(e55, f55, g55))) + .wrapping_add(0x682E6FF3)) + .wrapping_add(w55); let t2_55: u32 = (bsig0(a55)).wrapping_add(maj(a55, b55, c55)); let a56: u32 = (t1_55).wrapping_add(t2_55); let b56: u32 = a55; @@ -650,7 +791,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f56: u32 = e55; let g56: u32 = f55; let h56: u32 = g55; - let t1_56: u32 = ((((h56).wrapping_add(bsig1(e56))).wrapping_add(ch(e56, f56, g56))).wrapping_add(0x748F82EE)).wrapping_add(w56); + let t1_56: u32 = ((((h56).wrapping_add(bsig1(e56))).wrapping_add(ch(e56, f56, g56))) + .wrapping_add(0x748F82EE)) + .wrapping_add(w56); let t2_56: u32 = (bsig0(a56)).wrapping_add(maj(a56, b56, c56)); let a57: u32 = (t1_56).wrapping_add(t2_56); let b57: u32 = a56; @@ -660,7 +803,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f57: u32 = e56; let g57: u32 = f56; let h57: u32 = g56; - let t1_57: u32 = ((((h57).wrapping_add(bsig1(e57))).wrapping_add(ch(e57, f57, g57))).wrapping_add(0x78A5636F)).wrapping_add(w57); + let t1_57: u32 = ((((h57).wrapping_add(bsig1(e57))).wrapping_add(ch(e57, f57, g57))) + .wrapping_add(0x78A5636F)) + .wrapping_add(w57); let t2_57: u32 = (bsig0(a57)).wrapping_add(maj(a57, b57, c57)); let a58: u32 = (t1_57).wrapping_add(t2_57); let b58: u32 = a57; @@ -670,7 +815,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f58: u32 = e57; let g58: u32 = f57; let h58: u32 = g57; - let t1_58: u32 = ((((h58).wrapping_add(bsig1(e58))).wrapping_add(ch(e58, f58, g58))).wrapping_add(0x84C87814)).wrapping_add(w58); + let t1_58: u32 = ((((h58).wrapping_add(bsig1(e58))).wrapping_add(ch(e58, f58, g58))) + .wrapping_add(0x84C87814)) + .wrapping_add(w58); let t2_58: u32 = (bsig0(a58)).wrapping_add(maj(a58, b58, c58)); let a59: u32 = (t1_58).wrapping_add(t2_58); let b59: u32 = a58; @@ -680,7 +827,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f59: u32 = e58; let g59: u32 = f58; let h59: u32 = g58; - let t1_59: u32 = ((((h59).wrapping_add(bsig1(e59))).wrapping_add(ch(e59, f59, g59))).wrapping_add(0x8CC70208)).wrapping_add(w59); + let t1_59: u32 = ((((h59).wrapping_add(bsig1(e59))).wrapping_add(ch(e59, f59, g59))) + .wrapping_add(0x8CC70208)) + .wrapping_add(w59); let t2_59: u32 = (bsig0(a59)).wrapping_add(maj(a59, b59, c59)); let a60: u32 = (t1_59).wrapping_add(t2_59); let b60: u32 = a59; @@ -690,7 +839,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f60: u32 = e59; let g60: u32 = f59; let h60: u32 = g59; - let t1_60: u32 = ((((h60).wrapping_add(bsig1(e60))).wrapping_add(ch(e60, f60, g60))).wrapping_add(0x90BEFFFA)).wrapping_add(w60); + let t1_60: u32 = ((((h60).wrapping_add(bsig1(e60))).wrapping_add(ch(e60, f60, g60))) + .wrapping_add(0x90BEFFFA)) + .wrapping_add(w60); let t2_60: u32 = (bsig0(a60)).wrapping_add(maj(a60, b60, c60)); let a61: u32 = (t1_60).wrapping_add(t2_60); let b61: u32 = a60; @@ -700,7 +851,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f61: u32 = e60; let g61: u32 = f60; let h61: u32 = g60; - let t1_61: u32 = ((((h61).wrapping_add(bsig1(e61))).wrapping_add(ch(e61, f61, g61))).wrapping_add(0xA4506CEB)).wrapping_add(w61); + let t1_61: u32 = ((((h61).wrapping_add(bsig1(e61))).wrapping_add(ch(e61, f61, g61))) + .wrapping_add(0xA4506CEB)) + .wrapping_add(w61); let t2_61: u32 = (bsig0(a61)).wrapping_add(maj(a61, b61, c61)); let a62: u32 = (t1_61).wrapping_add(t2_61); let b62: u32 = a61; @@ -710,7 +863,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f62: u32 = e61; let g62: u32 = f61; let h62: u32 = g61; - let t1_62: u32 = ((((h62).wrapping_add(bsig1(e62))).wrapping_add(ch(e62, f62, g62))).wrapping_add(0xBEF9A3F7)).wrapping_add(w62); + let t1_62: u32 = ((((h62).wrapping_add(bsig1(e62))).wrapping_add(ch(e62, f62, g62))) + .wrapping_add(0xBEF9A3F7)) + .wrapping_add(w62); let t2_62: u32 = (bsig0(a62)).wrapping_add(maj(a62, b62, c62)); let a63: u32 = (t1_62).wrapping_add(t2_62); let b63: u32 = a62; @@ -720,7 +875,9 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: let f63: u32 = e62; let g63: u32 = f62; let h63: u32 = g62; - let t1_63: u32 = ((((h63).wrapping_add(bsig1(e63))).wrapping_add(ch(e63, f63, g63))).wrapping_add(0xC67178F2)).wrapping_add(w63); + let t1_63: u32 = ((((h63).wrapping_add(bsig1(e63))).wrapping_add(ch(e63, f63, g63))) + .wrapping_add(0xC67178F2)) + .wrapping_add(w63); let t2_63: u32 = (bsig0(a63)).wrapping_add(maj(a63, b63, c63)); let a64: u32 = (t1_63).wrapping_add(t2_63); let b64: u32 = a63; @@ -769,8 +926,29 @@ pub fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: } } -pub fn sha256_word(w0: u32, w1: u32, w2: u32, w3: u32, w4: u32, w5: u32, w6: u32, w7: u32, w8: u32, w9: u32, w10: u32, w11: u32, w12: u32, w13: u32, w14: u32, w15: u32, which: u32) -> u32 { - return sha256_compress(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19, w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15, which); +pub fn sha256_word( + w0: u32, + w1: u32, + w2: u32, + w3: u32, + w4: u32, + w5: u32, + w6: u32, + w7: u32, + w8: u32, + w9: u32, + w10: u32, + w11: u32, + w12: u32, + w13: u32, + w14: u32, + w15: u32, + which: u32, +) -> u32 { + return sha256_compress( + 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, + 0x5BE0CD19, w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15, which, + ); } pub const SHA_PAD_MARK: u32 = 0x80000000; @@ -786,4 +964,3 @@ pub fn sha256_pad2_word(idx: u32, total_bits: u32) -> u32 { } } } - diff --git a/gen/rust/tri_slash.rs b/gen/rust/tri_slash.rs index b0cc356a..00d52287 100644 --- a/gen/rust/tri_slash.rs +++ b/gen/rust/tri_slash.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 6 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MIN_BOND: u32 = 100; diff --git a/gen/rust/trust_manager.rs b/gen/rust/trust_manager.rs index 716f0c5f..d634a36f 100644 --- a/gen/rust/trust_manager.rs +++ b/gen/rust/trust_manager.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 17 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const MAX_NODES: u32 = 8; @@ -12,7 +15,8 @@ pub const TRUST_LOW: u32 = 20; pub const MAX_TRUST_SCORE: u32 = 100; pub fn create_trust_score(node_id: u32, score: u32, positive: u32, negative: u32) -> u32 { - return (((((node_id & 0xFF) << 24) | ((score & 0xFF) << 16)) | ((positive & 0xFF) << 8)) | (negative & 0xFF)); + return (((((node_id & 0xFF) << 24) | ((score & 0xFF) << 16)) | ((positive & 0xFF) << 8)) + | (negative & 0xFF)); } pub fn get_trust_node_id(score: u32) -> u32 { @@ -32,7 +36,8 @@ pub fn get_negative_interactions(score: u32) -> u32 { } pub fn create_trust_relationship(source: u32, destination: u32, level: u32, verified: u32) -> u32 { - return (((((source & 0x3F) << 26) | ((destination & 0x3F) << 20)) | ((level & 0xFF) << 12)) | (verified & 0xFFF)); + return (((((source & 0x3F) << 26) | ((destination & 0x3F) << 20)) | ((level & 0xFF) << 12)) + | (verified & 0xFFF)); } pub fn get_trust_source(rel: u32) -> u32 { @@ -51,8 +56,17 @@ pub fn get_trust_verified(rel: u32) -> u32 { return (rel & 0xFFF); } -pub fn create_trust_array(t0: u32, t1: u32, t2: u32, t3: u32, t4: u32, t5: u32, t6: u32, t7: u32) -> [u32; 8] { - return [t0,t1,t2,t3,t4,t5,t6,t7]; +pub fn create_trust_array( + t0: u32, + t1: u32, + t2: u32, + t3: u32, + t4: u32, + t5: u32, + t6: u32, + t7: u32, +) -> [u32; 8] { + return [t0, t1, t2, t3, t4, t5, t6, t7]; } pub fn get_trust_score(array: [u32; 8], index: u32) -> u32 { @@ -159,4 +173,3 @@ pub fn reward_node(current_score: u32, reward: u32) -> u32 { let new_score = calculate_trust_score(new_positive, negative); return create_trust_score(node_id, new_score, new_positive, negative); } - diff --git a/gen/rust/twr_timestamp.rs b/gen/rust/twr_timestamp.rs index c1324631..ab7ffb76 100644 --- a/gen/rust/twr_timestamp.rs +++ b/gen/rust/twr_timestamp.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 6 test(s), 0 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub fn tick(counter: u32) -> u32 { return (counter + 1); diff --git a/gen/rust/video_bridge.rs b/gen/rust/video_bridge.rs index 3f0d1371..d24f7429 100644 --- a/gen/rust/video_bridge.rs +++ b/gen/rust/video_bridge.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 65 test(s), 12 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const VSTREAM_TYPE: u8 = 8; @@ -236,4 +239,3 @@ pub fn max_nal_size() -> u16 { pub fn nal_fits(nal_size: u16) -> bool { return (nal_size <= 17850); } - diff --git a/gen/rust/wire.rs b/gen/rust/wire.rs index 404a8a16..94a906a5 100644 --- a/gen/rust/wire.rs +++ b/gen/rust/wire.rs @@ -1,5 +1,8 @@ // Generated from .t27 spec // DO NOT EDIT — generated by t27c +// NOT LOWERED BY THIS BACKEND: 8 test(s), 2 invariant(s). +// This backend emits declarations only. The spec's checks live in +// the Zig and Verilog outputs; do not read this file as verified. pub const VERSION: u8 = 1; @@ -60,4 +63,3 @@ pub fn parse_accepts(b0: u8, b1: u8) -> bool { return false; } } - diff --git a/gen/zig/access_control.zig b/gen/zig/access_control.zig index c9e38957..e4abd122 100644 --- a/gen/zig/access_control.zig +++ b/gen/zig/access_control.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_NODES: u32 = 8; @@ -95,78 +103,78 @@ fn check_resource_access(creds: u32, policy: u32, provided_token: u32) u32 { } test "create_node_creds_basic" { const creds = create_node_creds(5, ROLE_USER, 0x123, 1); - if (!(get_node_id(creds) == 5)) @panic("node id"); - if (!(get_role(creds) == ROLE_USER)) @panic("user role"); - if (!(get_auth_token(creds) == 0x123)) @panic("auth token"); - if (!(is_authorized(creds) == 1)) @panic("authorized"); + if (!(get_node_id(creds) == 5)) __t27_assert_fail("\n node id:\n get_node_id(creds) = {any}\n", .{ get_node_id(creds) }); + if (!(get_role(creds) == ROLE_USER)) __t27_assert_fail("\n user role:\n get_role(creds) = {any}\n ROLE_USER = {any}\n", .{ get_role(creds), ROLE_USER }); + if (!(get_auth_token(creds) == 0x123)) __t27_assert_fail("\n auth token:\n get_auth_token(creds) = {any}\n", .{ get_auth_token(creds) }); + if (!(is_authorized(creds) == 1)) __t27_assert_fail("\n authorized:\n is_authorized(creds) = {any}\n", .{ is_authorized(creds) }); } test "create_policy_basic" { const policy = create_policy(1, ROLE_USER, 0, 1, 1); - if (!(get_resource(policy) == 1)) @panic("resource"); - if (!(get_min_role(policy) == ROLE_USER)) @panic("min role"); - if (!(get_guest_perm(policy) == 0)) @panic("guest denied"); - if (!(get_user_perm(policy) == 1)) @panic("user permitted"); + if (!(get_resource(policy) == 1)) __t27_assert_fail("\n resource:\n get_resource(policy) = {any}\n", .{ get_resource(policy) }); + if (!(get_min_role(policy) == ROLE_USER)) __t27_assert_fail("\n min role:\n get_min_role(policy) = {any}\n ROLE_USER = {any}\n", .{ get_min_role(policy), ROLE_USER }); + if (!(get_guest_perm(policy) == 0)) __t27_assert_fail("\n guest denied:\n get_guest_perm(policy) = {any}\n", .{ get_guest_perm(policy) }); + if (!(get_user_perm(policy) == 1)) __t27_assert_fail("\n user permitted:\n get_user_perm(policy) = {any}\n", .{ get_user_perm(policy) }); } test "role_meets_minimum_true" { - if (!(role_meets_minimum(ROLE_USER, ROLE_GUEST) == true)) @panic("user >= guest"); - if (!(role_meets_minimum(ROLE_ADMIN, ROLE_USER) == true)) @panic("admin >= user"); + if (!(role_meets_minimum(ROLE_USER, ROLE_GUEST) == true)) __t27_assert_fail("\n user >= guest:\n role_meets_minimum(ROLE_USER, ROLE_GUEST) = {any}\n", .{ role_meets_minimum(ROLE_USER, ROLE_GUEST) }); + if (!(role_meets_minimum(ROLE_ADMIN, ROLE_USER) == true)) __t27_assert_fail("\n admin >= user:\n role_meets_minimum(ROLE_ADMIN, ROLE_USER) = {any}\n", .{ role_meets_minimum(ROLE_ADMIN, ROLE_USER) }); } test "role_meets_minimum_false" { - if (!(role_meets_minimum(ROLE_GUEST, ROLE_USER) == false)) @panic("guest < user"); - if (!(role_meets_minimum(ROLE_USER, ROLE_ADMIN) == false)) @panic("user < admin"); + if (!(role_meets_minimum(ROLE_GUEST, ROLE_USER) == false)) __t27_assert_fail("\n guest < user:\n role_meets_minimum(ROLE_GUEST, ROLE_USER) = {any}\n", .{ role_meets_minimum(ROLE_GUEST, ROLE_USER) }); + if (!(role_meets_minimum(ROLE_USER, ROLE_ADMIN) == false)) __t27_assert_fail("\n user < admin:\n role_meets_minimum(ROLE_USER, ROLE_ADMIN) = {any}\n", .{ role_meets_minimum(ROLE_USER, ROLE_ADMIN) }); } test "check_access_admin" { const policy = create_policy(1, ROLE_GUEST, 0, 0, 1); - if (!(check_access(policy, ROLE_ADMIN) == 1)) @panic("admin permitted"); + if (!(check_access(policy, ROLE_ADMIN) == 1)) __t27_assert_fail("\n admin permitted:\n check_access(policy, ROLE_ADMIN) = {any}\n", .{ check_access(policy, ROLE_ADMIN) }); } test "check_access_user" { const policy = create_policy(1, ROLE_USER, 0, 1, 1); - if (!(check_access(policy, ROLE_USER) == 1)) @panic("user permitted"); + if (!(check_access(policy, ROLE_USER) == 1)) __t27_assert_fail("\n user permitted:\n check_access(policy, ROLE_USER) = {any}\n", .{ check_access(policy, ROLE_USER) }); } test "check_access_guest_denied" { const policy = create_policy(1, ROLE_USER, 0, 1, 1); - if (!(check_access(policy, ROLE_GUEST) == 0)) @panic("guest denied (min role)"); + if (!(check_access(policy, ROLE_GUEST) == 0)) __t27_assert_fail("\n guest denied (min role):\n check_access(policy, ROLE_GUEST) = {any}\n", .{ check_access(policy, ROLE_GUEST) }); } test "verify_creds_valid" { const creds = create_node_creds(5, ROLE_USER, 0x123, 1); - if (!(verify_creds(creds, 0x123) == true)) @panic("valid credentials"); + if (!(verify_creds(creds, 0x123) == true)) __t27_assert_fail("\n valid credentials:\n verify_creds(creds, 0x123) = {any}\n", .{ verify_creds(creds, 0x123) }); } test "verify_creds_invalid_token" { const creds = create_node_creds(5, ROLE_USER, 0x123, 1); - if (!(verify_creds(creds, 0x999) == false)) @panic("invalid token"); + if (!(verify_creds(creds, 0x999) == false)) __t27_assert_fail("\n invalid token:\n verify_creds(creds, 0x999) = {any}\n", .{ verify_creds(creds, 0x999) }); } test "verify_creds_unauthorized" { const creds = create_node_creds(5, ROLE_USER, 0x123, 0); - if (!(verify_creds(creds, 0x123) == false)) @panic("unauthorized node"); + if (!(verify_creds(creds, 0x123) == false)) __t27_assert_fail("\n unauthorized node:\n verify_creds(creds, 0x123) = {any}\n", .{ verify_creds(creds, 0x123) }); } test "authorize_node_works" { const creds = create_node_creds(5, ROLE_USER, 0x123, 0); const new_creds = authorize_node(creds); - if (!(is_authorized(new_creds) == 1)) @panic("node authorized"); + if (!(is_authorized(new_creds) == 1)) __t27_assert_fail("\n node authorized:\n is_authorized(new_creds) = {any}\n", .{ is_authorized(new_creds) }); } test "revoke_node_works" { const creds = create_node_creds(5, ROLE_USER, 0x123, 1); const new_creds = revoke_node(creds); - if (!(is_authorized(new_creds) == 0)) @panic("node revoked"); + if (!(is_authorized(new_creds) == 0)) __t27_assert_fail("\n node revoked:\n is_authorized(new_creds) = {any}\n", .{ is_authorized(new_creds) }); } test "change_role_works" { const creds = create_node_creds(5, ROLE_USER, 0x123, 1); const new_creds = change_role(creds, ROLE_ADMIN); - if (!(get_role(new_creds) == ROLE_ADMIN)) @panic("role changed"); - if (!(is_authorized(new_creds) == 1)) @panic("authorization kept"); + if (!(get_role(new_creds) == ROLE_ADMIN)) __t27_assert_fail("\n role changed:\n get_role(new_creds) = {any}\n ROLE_ADMIN = {any}\n", .{ get_role(new_creds), ROLE_ADMIN }); + if (!(is_authorized(new_creds) == 1)) __t27_assert_fail("\n authorization kept:\n is_authorized(new_creds) = {any}\n", .{ is_authorized(new_creds) }); } test "check_resource_access_full_grant" { const creds = create_node_creds(5, ROLE_USER, 0x123, 1); const policy = create_policy(1, ROLE_GUEST, 0, 1, 1); - if (!(check_resource_access(creds, policy, 0x123) == 1)) @panic("access granted"); + if (!(check_resource_access(creds, policy, 0x123) == 1)) __t27_assert_fail("\n access granted:\n check_resource_access(creds, policy, 0x123) = {any}\n", .{ check_resource_access(creds, policy, 0x123) }); } test "check_resource_access_invalid_creds" { const creds = create_node_creds(5, ROLE_USER, 0x123, 1); const policy = create_policy(1, ROLE_GUEST, 0, 1, 1); - if (!(check_resource_access(creds, policy, 0x999) == 0)) @panic("access denied"); + if (!(check_resource_access(creds, policy, 0x999) == 0)) __t27_assert_fail("\n access denied:\n check_resource_access(creds, policy, 0x999) = {any}\n", .{ check_resource_access(creds, policy, 0x999) }); } test "check_resource_access_role_too_low" { const creds = create_node_creds(5, ROLE_GUEST, 0x123, 1); const policy = create_policy(1, ROLE_USER, 0, 1, 1); - if (!(check_resource_access(creds, policy, 0x123) == 0)) @panic("role too low"); + if (!(check_resource_access(creds, policy, 0x123) == 0)) __t27_assert_fail("\n role too low:\n check_resource_access(creds, policy, 0x123) = {any}\n", .{ check_resource_access(creds, policy, 0x123) }); } diff --git a/gen/zig/adaptive_retry.zig b/gen/zig/adaptive_retry.zig index 15383f22..a6f6e9bc 100644 --- a/gen/zig/adaptive_retry.zig +++ b/gen/zig/adaptive_retry.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} const BASE_DELAY_MS: u8 = 10; const MAX_RETRIES: u8 = 5; @@ -61,34 +69,34 @@ fn total_retry_time(max_retries: u8) u16 { } test "exponential_backoff_calculation" { const delay0: u16 = backoff_delay_ms(0); - if (!(delay0 == 10)) @panic("delay0 == 10"); + if (!(delay0 == 10)) __t27_assert_fail("\n delay0 == 10:\n delay0 = {any}\n", .{ delay0 }); const delay1: u16 = backoff_delay_ms(1); - if (!(delay1 == 20)) @panic("delay1 == 20"); + if (!(delay1 == 20)) __t27_assert_fail("\n delay1 == 20:\n delay1 = {any}\n", .{ delay1 }); const delay2: u16 = backoff_delay_ms(2); - if (!(delay2 == 40)) @panic("delay2 == 40"); + if (!(delay2 == 40)) __t27_assert_fail("\n delay2 == 40:\n delay2 = {any}\n", .{ delay2 }); const delay3: u16 = backoff_delay_ms(3); - if (!(delay3 == 80)) @panic("delay3 == 80"); + if (!(delay3 == 80)) __t27_assert_fail("\n delay3 == 80:\n delay3 = {any}\n", .{ delay3 }); } test "quality_based_retry_limits" { - if (!(max_retries_for_quality(0xCC) == 5)) @panic("max_retries_for_quality 0xCC == 5"); - if (!(max_retries_for_quality(0x80) == 3)) @panic("max_retries_for_quality 0x80 == 3"); - if (!(max_retries_for_quality(0x40) == 1)) @panic("max_retries_for_quality 0x40 == 1"); + if (!(max_retries_for_quality(0xCC) == 5)) __t27_assert_fail("\n max_retries_for_quality 0xCC == 5:\n max_retries_for_quality(0xCC) = {any}\n", .{ max_retries_for_quality(0xCC) }); + if (!(max_retries_for_quality(0x80) == 3)) __t27_assert_fail("\n max_retries_for_quality 0x80 == 3:\n max_retries_for_quality(0x80) = {any}\n", .{ max_retries_for_quality(0x80) }); + if (!(max_retries_for_quality(0x40) == 1)) __t27_assert_fail("\n max_retries_for_quality 0x40 == 1:\n max_retries_for_quality(0x40) = {any}\n", .{ max_retries_for_quality(0x40) }); } test "retry_permission_check" { - if (!(should_retry(0, 0xCC) == true)) @panic("should_retry 0 0xCC == true"); - if (!(should_retry(5, 0xCC) == false)) @panic("should_retry 5 0xCC == false"); - if (!(should_retry(0, 0x40) == true)) @panic("should_retry 0 0x40 == true"); - if (!(should_retry(1, 0x40) == false)) @panic("should_retry 1 0x40 == false"); + if (!(should_retry(0, 0xCC) == true)) __t27_assert_fail("\n should_retry 0 0xCC == true:\n should_retry(0, 0xCC) = {any}\n", .{ should_retry(0, 0xCC) }); + if (!(should_retry(5, 0xCC) == false)) __t27_assert_fail("\n should_retry 5 0xCC == false:\n should_retry(5, 0xCC) = {any}\n", .{ should_retry(5, 0xCC) }); + if (!(should_retry(0, 0x40) == true)) __t27_assert_fail("\n should_retry 0 0x40 == true:\n should_retry(0, 0x40) = {any}\n", .{ should_retry(0, 0x40) }); + if (!(should_retry(1, 0x40) == false)) __t27_assert_fail("\n should_retry 1 0x40 == false:\n should_retry(1, 0x40) = {any}\n", .{ should_retry(1, 0x40) }); } test "success_probability_calculation" { const prob1: u8 = retry_success_probability(0, 0xCC); - if (!(prob1 > 180)) @panic("prob1 > 180"); + if (!(prob1 > 180)) __t27_assert_fail("\n prob1 > 180:\n prob1 = {any}\n", .{ prob1 }); const prob2: u8 = retry_success_probability(3, 0xCC); - if (!(prob2 < prob1)) @panic("prob2 < prob1"); + if (!(prob2 < prob1)) __t27_assert_fail("\n prob2 < prob1:\n prob2 = {any}\n prob1 = {any}\n", .{ prob2, prob1 }); const prob3: u8 = retry_success_probability(0, 0x40); - if (!(prob3 < prob1)) @panic("prob3 < prob1"); + if (!(prob3 < prob1)) __t27_assert_fail("\n prob3 < prob1:\n prob3 = {any}\n prob1 = {any}\n", .{ prob3, prob1 }); } test "total_time_estimation" { const total: u16 = total_retry_time(5); - if (!(total == 310)) @panic("total == 310"); + if (!(total == 310)) __t27_assert_fail("\n total == 310:\n total = {any}\n", .{ total }); } diff --git a/gen/zig/adaptive_routing.zig b/gen/zig/adaptive_routing.zig index 1bb10267..353fbd6e 100644 --- a/gen/zig/adaptive_routing.zig +++ b/gen/zig/adaptive_routing.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_PATHS: u32 = 4; @@ -129,72 +137,72 @@ fn find_least_congested(metrics_array: [4]u32) u32 { } test "create_path_metrics_basic" { const metrics = create_path_metrics(50, 3, 100, 40); - if (!(get_latency(metrics) == 50)) @panic("latency"); - if (!(get_hops(metrics) == 3)) @panic("hops"); - if (!(get_bandwidth(metrics) == 100)) @panic("bandwidth"); - if (!(get_load(metrics) == 40)) @panic("load"); + if (!(get_latency(metrics) == 50)) __t27_assert_fail("\n latency:\n get_latency(metrics) = {any}\n", .{ get_latency(metrics) }); + if (!(get_hops(metrics) == 3)) __t27_assert_fail("\n hops:\n get_hops(metrics) = {any}\n", .{ get_hops(metrics) }); + if (!(get_bandwidth(metrics) == 100)) __t27_assert_fail("\n bandwidth:\n get_bandwidth(metrics) = {any}\n", .{ get_bandwidth(metrics) }); + if (!(get_load(metrics) == 40)) __t27_assert_fail("\n load:\n get_load(metrics) = {any}\n", .{ get_load(metrics) }); } test "create_selection_state_basic" { const state = create_selection_state(0, 1, METRIC_LATENCY, 1000); - if (!(get_primary_path(state) == 0)) @panic("primary"); - if (!(get_backup_path(state) == 1)) @panic("backup"); - if (!(get_metric_type(state) == METRIC_LATENCY)) @panic("metric type"); + if (!(get_primary_path(state) == 0)) __t27_assert_fail("\n primary:\n get_primary_path(state) = {any}\n", .{ get_primary_path(state) }); + if (!(get_backup_path(state) == 1)) __t27_assert_fail("\n backup:\n get_backup_path(state) = {any}\n", .{ get_backup_path(state) }); + if (!(get_metric_type(state) == METRIC_LATENCY)) __t27_assert_fail("\n metric type:\n get_metric_type(state) = {any}\n METRIC_LATENCY = {any}\n", .{ get_metric_type(state), METRIC_LATENCY }); } test "calculate_score_latency" { const metrics = create_path_metrics(10, 3, 100, 40); const score = calculate_score(metrics, METRIC_LATENCY); - if (!((score >= 25) and (score <= 26))) @panic("latency score"); + if (!((score >= 25) and (score <= 26))) __t27_assert_fail("\n latency score:\n score = {any}\n", .{ score }); } test "calculate_score_hops" { const metrics = create_path_metrics(50, 2, 100, 40); const score = calculate_score(metrics, METRIC_HOPS); - if (!((score >= 127) and (score <= 128))) @panic("hops score"); + if (!((score >= 127) and (score <= 128))) __t27_assert_fail("\n hops score:\n score = {any}\n", .{ score }); } test "calculate_score_bandwidth" { const metrics = create_path_metrics(50, 3, 150, 40); - if (!(calculate_score(metrics, METRIC_BANDWIDTH) == 150)) @panic("bandwidth score"); + if (!(calculate_score(metrics, METRIC_BANDWIDTH) == 150)) __t27_assert_fail("\n bandwidth score:\n calculate_score(metrics, METRIC_BANDWIDTH) = {any}\n", .{ calculate_score(metrics, METRIC_BANDWIDTH) }); } test "find_best_path_latency" { const array = create_path_metrics_array(create_path_metrics(100, 3, 100, 40), create_path_metrics(10, 3, 100, 40), create_path_metrics(50, 3, 100, 40), create_path_metrics(30, 3, 100, 40)); - if (!(find_best_path(array, METRIC_LATENCY) == 1)) @panic("path 1 has best latency"); + if (!(find_best_path(array, METRIC_LATENCY) == 1)) __t27_assert_fail("\n path 1 has best latency:\n find_best_path(array, METRIC_LATENCY) = {any}\n", .{ find_best_path(array, METRIC_LATENCY) }); } test "find_best_path_hops" { const array = create_path_metrics_array(create_path_metrics(50, 5, 100, 40), create_path_metrics(50, 3, 100, 40), create_path_metrics(50, 1, 100, 40), create_path_metrics(50, 4, 100, 40)); - if (!(find_best_path(array, METRIC_HOPS) == 2)) @panic("path 2 has fewest hops"); + if (!(find_best_path(array, METRIC_HOPS) == 2)) __t27_assert_fail("\n path 2 has fewest hops:\n find_best_path(array, METRIC_HOPS) = {any}\n", .{ find_best_path(array, METRIC_HOPS) }); } test "needs_update_true" { const state = create_selection_state(0, 1, METRIC_LATENCY, 1000); - if (!(needs_update(state, 7000) == true)) @panic("needs update"); + if (!(needs_update(state, 7000) == true)) __t27_assert_fail("\n needs update:\n needs_update(state, 7000) = {any}\n", .{ needs_update(state, 7000) }); } test "needs_update_false" { const state = create_selection_state(0, 1, METRIC_LATENCY, 5000); - if (!(needs_update(state, 7000) == false)) @panic("no update needed"); + if (!(needs_update(state, 7000) == false)) __t27_assert_fail("\n no update needed:\n needs_update(state, 7000) = {any}\n", .{ needs_update(state, 7000) }); } test "update_selection_works" { const state = create_selection_state(0, 1, METRIC_LATENCY, 1000); const new_state = update_selection(state, 2, 3, 8000); - if (!(get_primary_path(new_state) == 2)) @panic("primary updated"); - if (!(get_backup_path(new_state) == 3)) @panic("backup updated"); - if (!(get_last_update(new_state) == 8000)) @panic("time updated"); + if (!(get_primary_path(new_state) == 2)) __t27_assert_fail("\n primary updated:\n get_primary_path(new_state) = {any}\n", .{ get_primary_path(new_state) }); + if (!(get_backup_path(new_state) == 3)) __t27_assert_fail("\n backup updated:\n get_backup_path(new_state) = {any}\n", .{ get_backup_path(new_state) }); + if (!(get_last_update(new_state) == 8000)) __t27_assert_fail("\n time updated:\n get_last_update(new_state) = {any}\n", .{ get_last_update(new_state) }); } test "change_metric_type_works" { const state = create_selection_state(0, 1, METRIC_LATENCY, 1000); const new_state = change_metric_type(state, METRIC_BANDWIDTH); - if (!(get_metric_type(new_state) == METRIC_BANDWIDTH)) @panic("metric changed"); + if (!(get_metric_type(new_state) == METRIC_BANDWIDTH)) __t27_assert_fail("\n metric changed:\n get_metric_type(new_state) = {any}\n METRIC_BANDWIDTH = {any}\n", .{ get_metric_type(new_state), METRIC_BANDWIDTH }); } test "is_path_congested_true" { const metrics = create_path_metrics(50, 3, 100, 90); - if (!(is_path_congested(metrics) == true)) @panic("path congested"); + if (!(is_path_congested(metrics) == true)) __t27_assert_fail("\n path congested:\n is_path_congested(metrics) = {any}\n", .{ is_path_congested(metrics) }); } test "is_path_congested_false" { const metrics = create_path_metrics(50, 3, 100, 40); - if (!(is_path_congested(metrics) == false)) @panic("path not congested"); + if (!(is_path_congested(metrics) == false)) __t27_assert_fail("\n path not congested:\n is_path_congested(metrics) = {any}\n", .{ is_path_congested(metrics) }); } test "find_least_congested" { const array = create_path_metrics_array(create_path_metrics(50, 3, 100, 80), create_path_metrics(50, 3, 100, 30), create_path_metrics(50, 3, 100, 60), create_path_metrics(50, 3, 100, 90)); - if (!(find_least_congested(array) == 1)) @panic("path 1 least congested"); + if (!(find_least_congested(array) == 1)) __t27_assert_fail("\n path 1 least congested:\n find_least_congested(array) = {any}\n", .{ find_least_congested(array) }); } test "find_least_congested_all_equal" { const array = create_path_metrics_array(create_path_metrics(50, 3, 100, 50), create_path_metrics(50, 3, 100, 50), create_path_metrics(50, 3, 100, 50), create_path_metrics(50, 3, 100, 50)); - if (!(find_least_congested(array) == 0)) @panic("first path when equal"); + if (!(find_least_congested(array) == 0)) __t27_assert_fail("\n first path when equal:\n find_least_congested(array) = {any}\n", .{ find_least_congested(array) }); } diff --git a/gen/zig/anomaly_detector.zig b/gen/zig/anomaly_detector.zig index c74d1690..54035c46 100644 --- a/gen/zig/anomaly_detector.zig +++ b/gen/zig/anomaly_detector.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_METRICS: u32 = 16; @@ -305,33 +313,33 @@ fn calculate_anomaly_confidence(report: u32, historical_confidence: u32) u32 { } test "metric_reading_roundtrip" { const r = create_metric_reading(7, 200, 99, 55); - if (!(get_metric_id(r) == 7)) @panic("metric id"); - if (!(get_metric_value(r) == 200)) @panic("metric value"); - if (!(get_timestamp(r) == 99)) @panic("timestamp"); - if (!(get_confidence(r) == 55)) @panic("confidence"); + if (!(get_metric_id(r) == 7)) __t27_assert_fail("\n metric id:\n get_metric_id(r) = {any}\n", .{ get_metric_id(r) }); + if (!(get_metric_value(r) == 200)) __t27_assert_fail("\n metric value:\n get_metric_value(r) = {any}\n", .{ get_metric_value(r) }); + if (!(get_timestamp(r) == 99)) __t27_assert_fail("\n timestamp:\n get_timestamp(r) = {any}\n", .{ get_timestamp(r) }); + if (!(get_confidence(r) == 55)) __t27_assert_fail("\n confidence:\n get_confidence(r) = {any}\n", .{ get_confidence(r) }); } test "anomaly_report_roundtrip" { const rep = create_anomaly_report(9, 90, TYPE_PATTERN, 12345); - if (!(get_anomaly_metric_id(rep) == 9)) @panic("report metric id"); - if (!(get_severity(rep) == 90)) @panic("severity"); - if (!(get_anomaly_type(rep) == TYPE_PATTERN)) @panic("anomaly type"); - if (!(get_anomaly_confidence(rep) == 12345)) @panic("report confidence"); + if (!(get_anomaly_metric_id(rep) == 9)) __t27_assert_fail("\n report metric id:\n get_anomaly_metric_id(rep) = {any}\n", .{ get_anomaly_metric_id(rep) }); + if (!(get_severity(rep) == 90)) __t27_assert_fail("\n severity:\n get_severity(rep) = {any}\n", .{ get_severity(rep) }); + if (!(get_anomaly_type(rep) == TYPE_PATTERN)) __t27_assert_fail("\n anomaly type:\n get_anomaly_type(rep) = {any}\n TYPE_PATTERN = {any}\n", .{ get_anomaly_type(rep), TYPE_PATTERN }); + if (!(get_anomaly_confidence(rep) == 12345)) __t27_assert_fail("\n report confidence:\n get_anomaly_confidence(rep) = {any}\n", .{ get_anomaly_confidence(rep) }); } test "baseline_and_variance" { - const h: [16]u32 = .{ create_metric_reading(1,100,0,50), create_metric_reading(1,120,1,50), create_metric_reading(1,100,2,50), create_metric_reading(1,120,3,50), create_metric_reading(1,100,4,50), create_metric_reading(1,120,5,50), create_metric_reading(1,100,6,50), create_metric_reading(1,120,7,50), 0, 0, 0, 0, 0, 0, 0, 0 }; + const h: [16]u32 = .{ create_metric_reading(1, 100, 0, 50), create_metric_reading(1, 120, 1, 50), create_metric_reading(1, 100, 2, 50), create_metric_reading(1, 120, 3, 50), create_metric_reading(1, 100, 4, 50), create_metric_reading(1, 120, 5, 50), create_metric_reading(1, 100, 6, 50), create_metric_reading(1, 120, 7, 50), 0, 0, 0, 0, 0, 0, 0, 0 }; const b = calculate_baseline(h, 8); - if (!(b == 110)) @panic("baseline is the mean"); + if (!(b == 110)) __t27_assert_fail("\n baseline is the mean:\n b = {any}\n", .{ b }); const v = calculate_variance(h, 8, b); - if (!(v == 10)) @panic("variance is the mean absolute deviation"); + if (!(v == 10)) __t27_assert_fail("\n variance is the mean absolute deviation:\n v = {any}\n", .{ v }); } test "spike_and_drop_detection" { - if (!(detect_spike(150, 110, 10) == 1)) @panic("40 above baseline is a spike"); - if (!(detect_spike(130, 110, 10) == 0)) @panic("20 above baseline is noise"); - if (!(detect_drop(70, 110, 10) == 1)) @panic("40 below baseline is a drop"); - if (!(detect_drop(95, 110, 10) == 0)) @panic("15 below baseline is noise"); + if (!(detect_spike(150, 110, 10) == 1)) __t27_assert_fail("\n 40 above baseline is a spike:\n detect_spike(150, 110, 10) = {any}\n", .{ detect_spike(150, 110, 10) }); + if (!(detect_spike(130, 110, 10) == 0)) __t27_assert_fail("\n 20 above baseline is noise:\n detect_spike(130, 110, 10) = {any}\n", .{ detect_spike(130, 110, 10) }); + if (!(detect_drop(70, 110, 10) == 1)) __t27_assert_fail("\n 40 below baseline is a drop:\n detect_drop(70, 110, 10) = {any}\n", .{ detect_drop(70, 110, 10) }); + if (!(detect_drop(95, 110, 10) == 0)) __t27_assert_fail("\n 15 below baseline is noise:\n detect_drop(95, 110, 10) = {any}\n", .{ detect_drop(95, 110, 10) }); } test "severity_bands" { - if (!(calculate_severity(250, 100) == 90)) @panic("diff 150 is high severity"); - if (!(calculate_severity(170, 100) == 60)) @panic("diff 70 is medium severity"); - if (!(calculate_severity(120, 100) == 30)) @panic("diff 20 is low severity"); + if (!(calculate_severity(250, 100) == 90)) __t27_assert_fail("\n diff 150 is high severity:\n calculate_severity(250, 100) = {any}\n", .{ calculate_severity(250, 100) }); + if (!(calculate_severity(170, 100) == 60)) __t27_assert_fail("\n diff 70 is medium severity:\n calculate_severity(170, 100) = {any}\n", .{ calculate_severity(170, 100) }); + if (!(calculate_severity(120, 100) == 30)) __t27_assert_fail("\n diff 20 is low severity:\n calculate_severity(120, 100) = {any}\n", .{ calculate_severity(120, 100) }); } diff --git a/gen/zig/api_documenter.zig b/gen/zig/api_documenter.zig index b7b55a44..a450afa0 100644 --- a/gen/zig/api_documenter.zig +++ b/gen/zig/api_documenter.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_FUNCTIONS: u32 = 64; @@ -262,15 +270,15 @@ fn generate_documentation_report(func_docs: [MAX_FUNCTIONS]u32, func_count: u32, } test "function_doc_roundtrip" { const d = create_function_doc(8, 4, 2, 40000); - if (!(get_doc_function_id(d) == 8)) @panic("function id"); - if (!(get_doc_param_count(d) == 4)) @panic("param count"); - if (!(get_doc_return_type(d) == 2)) @panic("return type"); - if (!(get_doc_complexity(d) == 40000)) @panic("complexity"); + if (!(get_doc_function_id(d) == 8)) __t27_assert_fail("\n function id:\n get_doc_function_id(d) = {any}\n", .{ get_doc_function_id(d) }); + if (!(get_doc_param_count(d) == 4)) __t27_assert_fail("\n param count:\n get_doc_param_count(d) = {any}\n", .{ get_doc_param_count(d) }); + if (!(get_doc_return_type(d) == 2)) __t27_assert_fail("\n return type:\n get_doc_return_type(d) = {any}\n", .{ get_doc_return_type(d) }); + if (!(get_doc_complexity(d) == 40000)) __t27_assert_fail("\n complexity:\n get_doc_complexity(d) = {any}\n", .{ get_doc_complexity(d) }); } test "param_doc_roundtrip" { const p = create_param_doc(3, 5, 2, 100000); - if (!(get_param_doc_id(p) == 3)) @panic("param id"); - if (!(get_param_doc_type(p) == 5)) @panic("param type"); - if (!(get_param_direction(p) == 2)) @panic("direction"); - if (!(get_param_description_id(p) == 100000)) @panic("description id"); + if (!(get_param_doc_id(p) == 3)) __t27_assert_fail("\n param id:\n get_param_doc_id(p) = {any}\n", .{ get_param_doc_id(p) }); + if (!(get_param_doc_type(p) == 5)) __t27_assert_fail("\n param type:\n get_param_doc_type(p) = {any}\n", .{ get_param_doc_type(p) }); + if (!(get_param_direction(p) == 2)) __t27_assert_fail("\n direction:\n get_param_direction(p) = {any}\n", .{ get_param_direction(p) }); + if (!(get_param_description_id(p) == 100000)) __t27_assert_fail("\n description id:\n get_param_description_id(p) = {any}\n", .{ get_param_description_id(p) }); } diff --git a/gen/zig/area_optimization.zig b/gen/zig/area_optimization.zig index 24997f06..e6be50b8 100644 --- a/gen/zig/area_optimization.zig +++ b/gen/zig/area_optimization.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const OPT_NONE: u32 = 0; @@ -84,87 +92,87 @@ fn analyze_bit_width(min_val: u32, max_val: u32) u8 { } test "estimate_complexity_simple" { const complexity = estimate_complexity(10, 5, 16); - if (!(complexity == 280)) @panic("simple complexity"); + if (!(complexity == 280)) __t27_assert_fail("\n simple complexity:\n complexity = {any}\n", .{ complexity }); } test "estimate_complexity_high" { const complexity = estimate_complexity(50, 20, 32); - if (!(complexity == 1060)) @panic("high complexity"); + if (!(complexity == 1060)) __t27_assert_fail("\n high complexity:\n complexity = {any}\n", .{ complexity }); } test "calculate_sharing_savings_half" { const savings = calculate_sharing_savings(1000, 2); - if (!(savings == 500)) @panic("50% savings"); + if (!(savings == 500)) __t27_assert_fail("\n 50% savings:\n savings = {any}\n", .{ savings }); } test "calculate_sharing_savings_quarter" { const savings = calculate_sharing_savings(1000, 4); - if (!(savings == 750)) @panic("75% savings"); + if (!(savings == 750)) __t27_assert_fail("\n 75% savings:\n savings = {any}\n", .{ savings }); } test "calculate_sharing_savings_zero_factor" { const savings = calculate_sharing_savings(1000, 0); - if (!(savings == 0)) @panic("zero factor = no savings"); + if (!(savings == 0)) __t27_assert_fail("\n zero factor = no savings:\n savings = {any}\n", .{ savings }); } test "calculate_bitwidth_savings_reduces" { const savings = calculate_bitwidth_savings(32, 16, 100); - if (!(savings == 200)) @panic("200 bytes saved"); + if (!(savings == 200)) __t27_assert_fail("\n 200 bytes saved:\n savings = {any}\n", .{ savings }); } test "calculate_bitwidth_savings_no_reduction" { const savings = calculate_bitwidth_savings(16, 32, 100); - if (!(savings == 0)) @panic("no reduction = no savings"); + if (!(savings == 0)) __t27_assert_fail("\n no reduction = no savings:\n savings = {any}\n", .{ savings }); } test "const_folding_applicable_high_ratio" { - if (!(const_folding_applicable(100, 50) == true)) @panic("50% constants"); + if (!(const_folding_applicable(100, 50) == true)) __t27_assert_fail("\n 50% constants:\n const_folding_applicable(100, 50) = {any}\n", .{ const_folding_applicable(100, 50) }); } test "const_folding_applicable_low_ratio" { - if (!(const_folding_applicable(100, 20) == false)) @panic("20% constants"); + if (!(const_folding_applicable(100, 20) == false)) __t27_assert_fail("\n 20% constants:\n const_folding_applicable(100, 20) = {any}\n", .{ const_folding_applicable(100, 20) }); } test "fifo_to_ram_applicable_yes" { - if (!(fifo_to_ram_applicable(32, 16) == true)) @panic("deep+wide"); + if (!(fifo_to_ram_applicable(32, 16) == true)) __t27_assert_fail("\n deep+wide:\n fifo_to_ram_applicable(32, 16) = {any}\n", .{ fifo_to_ram_applicable(32, 16) }); } test "fifo_to_ram_applicable_shallow" { - if (!(fifo_to_ram_applicable(8, 16) == false)) @panic("too shallow"); + if (!(fifo_to_ram_applicable(8, 16) == false)) __t27_assert_fail("\n too shallow:\n fifo_to_ram_applicable(8, 16) = {any}\n", .{ fifo_to_ram_applicable(8, 16) }); } test "fifo_to_ram_applicable_narrow" { - if (!(fifo_to_ram_applicable(32, 4) == false)) @panic("too narrow"); + if (!(fifo_to_ram_applicable(32, 4) == false)) __t27_assert_fail("\n too narrow:\n fifo_to_ram_applicable(32, 4) = {any}\n", .{ fifo_to_ram_applicable(32, 4) }); } test "create_resource_type_correct" { const res = create_resource_type(1, 5000); - if (!(extract_resource_type(res) == 1)) @panic("type"); - if (!(extract_resource_amount(res) == 5000)) @panic("amount"); + if (!(extract_resource_type(res) == 1)) __t27_assert_fail("\n type:\n extract_resource_type(res) = {any}\n", .{ extract_resource_type(res) }); + if (!(extract_resource_amount(res) == 5000)) __t27_assert_fail("\n amount:\n extract_resource_amount(res) = {any}\n", .{ extract_resource_amount(res) }); } test "create_optimization_result_correct" { const result = create_optimization_result(2, 100, 70); - if (!(extract_strategy(result) == 2)) @panic("strategy"); - if (!(extract_original(result) == 100)) @panic("original"); - if (!(extract_optimized(result) == 70)) @panic("optimized"); + if (!(extract_strategy(result) == 2)) __t27_assert_fail("\n strategy:\n extract_strategy(result) = {any}\n", .{ extract_strategy(result) }); + if (!(extract_original(result) == 100)) __t27_assert_fail("\n original:\n extract_original(result) = {any}\n", .{ extract_original(result) }); + if (!(extract_optimized(result) == 70)) __t27_assert_fail("\n optimized:\n extract_optimized(result) = {any}\n", .{ extract_optimized(result) }); } test "calculate_savings_percentage_30" { const pct = calculate_savings_percentage(100, 70); - if (!(pct == 30)) @panic("30% savings"); + if (!(pct == 30)) __t27_assert_fail("\n 30% savings:\n pct = {any}\n", .{ pct }); } test "calculate_savings_percentage_zero" { const pct = calculate_savings_percentage(100, 100); - if (!(pct == 0)) @panic("0% savings"); + if (!(pct == 0)) __t27_assert_fail("\n 0% savings:\n pct = {any}\n", .{ pct }); } test "calculate_savings_percentage_negative" { const pct = calculate_savings_percentage(70, 100); - if (!(pct == 0)) @panic("negative = 0%"); + if (!(pct == 0)) __t27_assert_fail("\n negative = 0%:\n pct = {any}\n", .{ pct }); } test "optimization_worthwhile_yes" { const result = create_optimization_result(1, 100, 80); - if (!(optimization_worthwhile(result) == true)) @panic("20% savings"); + if (!(optimization_worthwhile(result) == true)) __t27_assert_fail("\n 20% savings:\n optimization_worthwhile(result) = {any}\n", .{ optimization_worthwhile(result) }); } test "optimization_worthwhile_no" { const result = create_optimization_result(1, 100, 95); - if (!(optimization_worthwhile(result) == false)) @panic("5% savings"); + if (!(optimization_worthwhile(result) == false)) __t27_assert_fail("\n 5% savings:\n optimization_worthwhile(result) = {any}\n", .{ optimization_worthwhile(result) }); } test "analyze_bit_width_8bit" { const bits = analyze_bit_width(0, 255); - if (!(bits == 8)) @panic("8-bit range"); + if (!(bits == 8)) __t27_assert_fail("\n 8-bit range:\n bits = {any}\n", .{ bits }); } test "analyze_bit_width_16bit" { const bits = analyze_bit_width(0, 65535); - if (!(bits == 16)) @panic("16-bit range"); + if (!(bits == 16)) __t27_assert_fail("\n 16-bit range:\n bits = {any}\n", .{ bits }); } test "analyze_bit_width_32bit" { const bits = analyze_bit_width(0, 0xFFFFFFFF); - if (!(bits == 32)) @panic("32-bit range"); + if (!(bits == 32)) __t27_assert_fail("\n 32-bit range:\n bits = {any}\n", .{ bits }); } diff --git a/gen/zig/auto_config.zig b/gen/zig/auto_config.zig index 56bd1298..1bb96985 100644 --- a/gen/zig/auto_config.zig +++ b/gen/zig/auto_config.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_NODES: u32 = 8; @@ -338,24 +346,24 @@ fn assign_node_role(node_id: u32, capabilities: u32) u32 { } test "config_param_roundtrip_wide_value" { const p = create_config_param(PARAM_HELLO_INTERVAL, 2000, SCOPE_NETWORK, STATUS_PENDING); - if (!(get_param_id(p) == PARAM_HELLO_INTERVAL)) @panic("param id"); - if (!(get_param_value(p) == 2000)) @panic("16-bit value survives"); - if (!(get_param_scope(p) == SCOPE_NETWORK)) @panic("scope"); - if (!(get_param_status(p) == STATUS_PENDING)) @panic("status"); + if (!(get_param_id(p) == PARAM_HELLO_INTERVAL)) __t27_assert_fail("\n param id:\n get_param_id(p) = {any}\n PARAM_HELLO_INTERVAL = {any}\n", .{ get_param_id(p), PARAM_HELLO_INTERVAL }); + if (!(get_param_value(p) == 2000)) __t27_assert_fail("\n 16-bit value survives:\n get_param_value(p) = {any}\n", .{ get_param_value(p) }); + if (!(get_param_scope(p) == SCOPE_NETWORK)) __t27_assert_fail("\n scope:\n get_param_scope(p) = {any}\n SCOPE_NETWORK = {any}\n", .{ get_param_scope(p), SCOPE_NETWORK }); + if (!(get_param_status(p) == STATUS_PENDING)) __t27_assert_fail("\n status:\n get_param_status(p) = {any}\n STATUS_PENDING = {any}\n", .{ get_param_status(p), STATUS_PENDING }); } test "default_table_values_survive" { - if (!(get_param_value(default_config_at(4)) == 2000)) @panic("hello interval"); - if (!(get_param_value(default_config_at(5)) == 10000)) @panic("route timeout"); - if (!(get_param_value(default_config_at(0)) == 50)) @panic("tx power"); + if (!(get_param_value(default_config_at(4)) == 2000)) __t27_assert_fail("\n hello interval:\n get_param_value(default_config_at(4)) = {any}\n", .{ get_param_value(default_config_at(4)) }); + if (!(get_param_value(default_config_at(5)) == 10000)) __t27_assert_fail("\n route timeout:\n get_param_value(default_config_at(5)) = {any}\n", .{ get_param_value(default_config_at(5)) }); + if (!(get_param_value(default_config_at(0)) == 50)) __t27_assert_fail("\n tx power:\n get_param_value(default_config_at(0)) = {any}\n", .{ get_param_value(default_config_at(0)) }); } test "config_lookup_finds_param" { const cfg: [16]u32 = .{ default_config_at(0), default_config_at(1), default_config_at(2), default_config_at(3), default_config_at(4), default_config_at(5), default_config_at(6), default_config_at(7), 0, 0, 0, 0, 0, 0, 0, 0 }; - if (!(get_config_value(cfg, PARAM_RETRY_LIMIT) == 3)) @panic("retry limit found"); - if (!(get_config_value(cfg, 99) == 0)) @panic("unknown param yields 0"); + if (!(get_config_value(cfg, PARAM_RETRY_LIMIT) == 3)) __t27_assert_fail("\n retry limit found:\n get_config_value(cfg, PARAM_RETRY_LIMIT) = {any}\n", .{ get_config_value(cfg, PARAM_RETRY_LIMIT) }); + if (!(get_config_value(cfg, 99) == 0)) __t27_assert_fail("\n unknown param yields 0:\n get_config_value(cfg, 99) = {any}\n", .{ get_config_value(cfg, 99) }); } test "node_role_assignment" { - if (!(assign_node_role(1, 0x1) == 1)) @panic("coordinator capability"); - if (!(assign_node_role(2, 0x2) == 2)) @panic("relay capability"); - if (!(assign_node_role(3, 0x4) == 3)) @panic("edge capability"); - if (!(assign_node_role(4, 0x0) == 0)) @panic("no capability is a normal node"); + if (!(assign_node_role(1, 0x1) == 1)) __t27_assert_fail("\n coordinator capability:\n assign_node_role(1, 0x1) = {any}\n", .{ assign_node_role(1, 0x1) }); + if (!(assign_node_role(2, 0x2) == 2)) __t27_assert_fail("\n relay capability:\n assign_node_role(2, 0x2) = {any}\n", .{ assign_node_role(2, 0x2) }); + if (!(assign_node_role(3, 0x4) == 3)) __t27_assert_fail("\n edge capability:\n assign_node_role(3, 0x4) = {any}\n", .{ assign_node_role(3, 0x4) }); + if (!(assign_node_role(4, 0x0) == 0)) __t27_assert_fail("\n no capability is a normal node:\n assign_node_role(4, 0x0) = {any}\n", .{ assign_node_role(4, 0x0) }); } diff --git a/gen/zig/bandwidth_allocator.zig b/gen/zig/bandwidth_allocator.zig index a8d47d82..b81e8363 100644 --- a/gen/zig/bandwidth_allocator.zig +++ b/gen/zig/bandwidth_allocator.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_FLOWS: u32 = 8; @@ -168,96 +176,96 @@ fn find_reclaimable_bandwidth(state: u32, flow_array: [8]u32) u32 { fn prioritize_bandwidth(flow_array: [8]u32, available_bw: u32) [8]u32 { const remaining_bw = available_bw; _ = remaining_bw; // dead after const-inlining - const @"f0" = get_flow_req(flow_array, 0); - const @"f1" = get_flow_req(flow_array, 1); - const @"f2" = get_flow_req(flow_array, 2); - const @"f3" = get_flow_req(flow_array, 3); - const @"f4" = get_flow_req(flow_array, 4); - const @"f5" = get_flow_req(flow_array, 5); - const @"f6" = get_flow_req(flow_array, 6); - const @"f7" = get_flow_req(flow_array, 7); - return create_flow_array(update_flow_bandwidth(@"f0", calculate_fair_share(available_bw, 8)), update_flow_bandwidth(@"f1", calculate_fair_share(available_bw, 8)), update_flow_bandwidth(@"f2", calculate_fair_share(available_bw, 8)), update_flow_bandwidth(@"f3", calculate_fair_share(available_bw, 8)), update_flow_bandwidth(@"f4", calculate_fair_share(available_bw, 8)), update_flow_bandwidth(@"f5", calculate_fair_share(available_bw, 8)), update_flow_bandwidth(@"f6", calculate_fair_share(available_bw, 8)), update_flow_bandwidth(@"f7", calculate_fair_share(available_bw, 8))); + const f0 = get_flow_req(flow_array, 0); + const f1 = get_flow_req(flow_array, 1); + const f2 = get_flow_req(flow_array, 2); + const f3 = get_flow_req(flow_array, 3); + const f4 = get_flow_req(flow_array, 4); + const f5 = get_flow_req(flow_array, 5); + const f6 = get_flow_req(flow_array, 6); + const f7 = get_flow_req(flow_array, 7); + return create_flow_array(update_flow_bandwidth(f0, calculate_fair_share(available_bw, 8)), update_flow_bandwidth(f1, calculate_fair_share(available_bw, 8)), update_flow_bandwidth(f2, calculate_fair_share(available_bw, 8)), update_flow_bandwidth(f3, calculate_fair_share(available_bw, 8)), update_flow_bandwidth(f4, calculate_fair_share(available_bw, 8)), update_flow_bandwidth(f5, calculate_fair_share(available_bw, 8)), update_flow_bandwidth(f6, calculate_fair_share(available_bw, 8)), update_flow_bandwidth(f7, calculate_fair_share(available_bw, 8))); } test "create_flow_requirement_basic" { const flow = create_flow_requirement(5, PRIORITY_HIGH, 50, 100); - if (!(get_flow_id(flow) == 5)) @panic("flow ID"); - if (!(get_flow_priority(flow) == PRIORITY_HIGH)) @panic("high priority"); - if (!(get_min_bandwidth(flow) == 50)) @panic("min bandwidth"); - if (!(get_current_bandwidth(flow) == 100)) @panic("current bandwidth"); + if (!(get_flow_id(flow) == 5)) __t27_assert_fail("\n flow ID:\n get_flow_id(flow) = {any}\n", .{ get_flow_id(flow) }); + if (!(get_flow_priority(flow) == PRIORITY_HIGH)) __t27_assert_fail("\n high priority:\n get_flow_priority(flow) = {any}\n PRIORITY_HIGH = {any}\n", .{ get_flow_priority(flow), PRIORITY_HIGH }); + if (!(get_min_bandwidth(flow) == 50)) __t27_assert_fail("\n min bandwidth:\n get_min_bandwidth(flow) = {any}\n", .{ get_min_bandwidth(flow) }); + if (!(get_current_bandwidth(flow) == 100)) __t27_assert_fail("\n current bandwidth:\n get_current_bandwidth(flow) = {any}\n", .{ get_current_bandwidth(flow) }); } test "create_allocation_state_basic" { const state = create_allocation_state(500, 3, 125, 10); - if (!(get_allocated_bw(state) == 500)) @panic("allocated bandwidth"); - if (!(get_pending_requests(state) == 3)) @panic("pending requests"); - if (!(get_fair_share(state) == 125)) @panic("fair share"); - if (!(get_last_update(state) == 10)) @panic("last update"); + if (!(get_allocated_bw(state) == 500)) __t27_assert_fail("\n allocated bandwidth:\n get_allocated_bw(state) = {any}\n", .{ get_allocated_bw(state) }); + if (!(get_pending_requests(state) == 3)) __t27_assert_fail("\n pending requests:\n get_pending_requests(state) = {any}\n", .{ get_pending_requests(state) }); + if (!(get_fair_share(state) == 125)) __t27_assert_fail("\n fair share:\n get_fair_share(state) = {any}\n", .{ get_fair_share(state) }); + if (!(get_last_update(state) == 10)) __t27_assert_fail("\n last update:\n get_last_update(state) = {any}\n", .{ get_last_update(state) }); } test "calculate_fair_share_normal" { const share = calculate_fair_share(1000, 8); - if (!(share == 125)) @panic("fair share for 8 flows"); + if (!(share == 125)) __t27_assert_fail("\n fair share for 8 flows:\n share = {any}\n", .{ share }); } test "calculate_fair_share_zero_flows" { - if (!(calculate_fair_share(1000, 0) == 0)) @panic("no flows = no share"); + if (!(calculate_fair_share(1000, 0) == 0)) __t27_assert_fail("\n no flows = no share:\n calculate_fair_share(1000, 0) = {any}\n", .{ calculate_fair_share(1000, 0) }); } test "allocate_bandwidth_high_priority" { const state = create_allocation_state(200, 1, 100, 0); const flow = create_flow_requirement(5, PRIORITY_HIGH, 50, 100); const new_state = allocate_bandwidth(state, flow, 300); - if (!(get_allocated_bw(new_state) >= 400)) @panic("high priority allocation"); + if (!(get_allocated_bw(new_state) >= 400)) __t27_assert_fail("\n high priority allocation:\n get_allocated_bw(new_state) = {any}\n", .{ get_allocated_bw(new_state) }); } test "allocate_bandwidth_medium_priority" { const state = create_allocation_state(200, 1, 100, 0); const flow = create_flow_requirement(5, PRIORITY_MEDIUM, 50, 100); const new_state = allocate_bandwidth(state, flow, 200); - if (!(get_allocated_bw(new_state) >= 200)) @panic("medium priority allocation"); + if (!(get_allocated_bw(new_state) >= 200)) __t27_assert_fail("\n medium priority allocation:\n get_allocated_bw(new_state) = {any}\n", .{ get_allocated_bw(new_state) }); } test "allocate_bandwidth_low_priority" { const state = create_allocation_state(200, 1, 100, 0); const flow = create_flow_requirement(5, PRIORITY_LOW, 50, 100); const new_state = allocate_bandwidth(state, flow, 200); - if (!(get_allocated_bw(new_state) >= 250)) @panic("low priority allocation"); + if (!(get_allocated_bw(new_state) >= 250)) __t27_assert_fail("\n low priority allocation:\n get_allocated_bw(new_state) = {any}\n", .{ get_allocated_bw(new_state) }); } test "needs_more_bandwidth_true" { const flow = create_flow_requirement(5, PRIORITY_HIGH, 100, 50); - if (!(needs_more_bandwidth(flow) == true)) @panic("needs more bandwidth"); + if (!(needs_more_bandwidth(flow) == true)) __t27_assert_fail("\n needs more bandwidth:\n needs_more_bandwidth(flow) = {any}\n", .{ needs_more_bandwidth(flow) }); } test "needs_more_bandwidth_false" { const flow = create_flow_requirement(5, PRIORITY_HIGH, 50, 100); - if (!(needs_more_bandwidth(flow) == false)) @panic("sufficient bandwidth"); + if (!(needs_more_bandwidth(flow) == false)) __t27_assert_fail("\n sufficient bandwidth:\n needs_more_bandwidth(flow) = {any}\n", .{ needs_more_bandwidth(flow) }); } test "update_flow_bandwidth_increase" { const flow = create_flow_requirement(5, PRIORITY_HIGH, 50, 100); const new_flow = update_flow_bandwidth(flow, 200); - if (!(get_current_bandwidth(new_flow) == 200)) @panic("bandwidth increased"); + if (!(get_current_bandwidth(new_flow) == 200)) __t27_assert_fail("\n bandwidth increased:\n get_current_bandwidth(new_flow) = {any}\n", .{ get_current_bandwidth(new_flow) }); } test "update_flow_bandwidth_respects_min" { const flow = create_flow_requirement(5, PRIORITY_HIGH, 50, 100); const new_flow = update_flow_bandwidth(flow, 30); - if (!(get_current_bandwidth(new_flow) == 50)) @panic("minimum bandwidth respected"); + if (!(get_current_bandwidth(new_flow) == 50)) __t27_assert_fail("\n minimum bandwidth respected:\n get_current_bandwidth(new_flow) = {any}\n", .{ get_current_bandwidth(new_flow) }); } test "update_flow_bandwidth_respects_max" { const flow = create_flow_requirement(5, PRIORITY_HIGH, 50, 100); const new_flow = update_flow_bandwidth(flow, 600); - if (!(get_current_bandwidth(new_flow) == MAX_BANDWIDTH)) @panic("maximum bandwidth respected"); + if (!(get_current_bandwidth(new_flow) == MAX_BANDWIDTH)) __t27_assert_fail("\n maximum bandwidth respected:\n get_current_bandwidth(new_flow) = {any}\n MAX_BANDWIDTH = {any}\n", .{ get_current_bandwidth(new_flow), MAX_BANDWIDTH }); } test "count_active_flows_full" { const flow_array = create_flow_array(create_flow_requirement(1, PRIORITY_HIGH, 50, 100), create_flow_requirement(2, PRIORITY_MEDIUM, 40, 80), create_flow_requirement(3, PRIORITY_LOW, 30, 60), create_flow_requirement(4, PRIORITY_HIGH, 70, 120), create_flow_requirement(5, PRIORITY_MEDIUM, 35, 70), create_flow_requirement(6, PRIORITY_LOW, 25, 50), create_flow_requirement(7, PRIORITY_HIGH, 60, 110), create_flow_requirement(8, PRIORITY_LOW, 20, 40)); - if (!(count_active_flows(flow_array) == 8)) @panic("8 active flows"); + if (!(count_active_flows(flow_array) == 8)) __t27_assert_fail("\n 8 active flows:\n count_active_flows(flow_array) = {any}\n", .{ count_active_flows(flow_array) }); } test "count_active_flows_partial" { const flow_array = create_flow_array(create_flow_requirement(1, PRIORITY_HIGH, 50, 100), create_flow_requirement(2, PRIORITY_MEDIUM, 40, 0), create_flow_requirement(3, PRIORITY_LOW, 30, 60), create_flow_requirement(4, PRIORITY_HIGH, 70, 0), 0, 0, 0, 0); - if (!(count_active_flows(flow_array) == 2)) @panic("2 active flows"); + if (!(count_active_flows(flow_array) == 2)) __t27_assert_fail("\n 2 active flows:\n count_active_flows(flow_array) = {any}\n", .{ count_active_flows(flow_array) }); } test "find_reclaimable_bandwidth" { const state = create_allocation_state(500, 1, 100, 0); const flow_array = create_flow_array(create_flow_requirement(1, PRIORITY_HIGH, 50, 100), create_flow_requirement(2, PRIORITY_MEDIUM, 40, 80), create_flow_requirement(3, PRIORITY_LOW, 30, 60), create_flow_requirement(4, PRIORITY_HIGH, 70, 120), 0, 0, 0, 0); const reclaimable = find_reclaimable_bandwidth(state, flow_array); const total_used = ((100 + 80) + 60) + 120; - if (!(reclaimable == (500 - total_used))) @panic("reclaimable bandwidth calculated"); + if (!(reclaimable == (500 - total_used))) __t27_assert_fail("\n reclaimable bandwidth calculated:\n reclaimable = {any}\n 500 - total_used = {any}\n", .{ reclaimable, 500 - total_used }); } test "prioritize_bandwidth_distributes" { const flow_array = create_flow_array(create_flow_requirement(1, PRIORITY_HIGH, 50, 100), create_flow_requirement(2, PRIORITY_MEDIUM, 40, 80), create_flow_requirement(3, PRIORITY_LOW, 30, 60), create_flow_requirement(4, PRIORITY_HIGH, 70, 120), 0, 0, 0, 0); const new_array = prioritize_bandwidth(flow_array, 800); - if (!(get_current_bandwidth(get_flow_req(new_array, 0)) == 100)) @panic("flow 0 bandwidth"); - if (!(get_current_bandwidth(get_flow_req(new_array, 1)) == 100)) @panic("flow 1 bandwidth"); + if (!(get_current_bandwidth(get_flow_req(new_array, 0)) == 100)) __t27_assert_fail("\n flow 0 bandwidth:\n get_current_bandwidth(get_flow_req(new_array, 0)) = {any}\n", .{ get_current_bandwidth(get_flow_req(new_array, 0)) }); + if (!(get_current_bandwidth(get_flow_req(new_array, 1)) == 100)) __t27_assert_fail("\n flow 1 bandwidth:\n get_current_bandwidth(get_flow_req(new_array, 1)) = {any}\n", .{ get_current_bandwidth(get_flow_req(new_array, 1)) }); } diff --git a/gen/zig/byte_utils.zig b/gen/zig/byte_utils.zig index 6d112499..75efc84e 100644 --- a/gen/zig/byte_utils.zig +++ b/gen/zig/byte_utils.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module fn get_bit(byte: u8, i: usize) u8 { @@ -38,25 +46,25 @@ fn swap_nibbles(byte: u8) u8 { } test "get_bit_lsb" { const bit = get_bit(0x01, 0); - if (!(bit == 1)) @panic("LSB is 1"); + if (!(bit == 1)) __t27_assert_fail("\n LSB is 1:\n bit = {any}\n", .{ bit }); } test "get_bit_msb" { const bit = get_bit(0x80, 7); - if (!(bit == 1)) @panic("MSB is 1"); + if (!(bit == 1)) __t27_assert_fail("\n MSB is 1:\n bit = {any}\n", .{ bit }); } test "low_nibble_test" { const nib = low_nibble(0xAB); - if (!(nib == 0x0B)) @panic("low nibble"); + if (!(nib == 0x0B)) __t27_assert_fail("\n low nibble:\n nib = {any}\n", .{ nib }); } test "high_nibble_test" { const nib = high_nibble(0xAB); - if (!(nib == 0x0A)) @panic("high nibble"); + if (!(nib == 0x0A)) __t27_assert_fail("\n high nibble:\n nib = {any}\n", .{ nib }); } test "combine_nibbles_test" { const byte = combine_nibbles(0x0A, 0x0B); - if (!(byte == 0xAB)) @panic("combine"); + if (!(byte == 0xAB)) __t27_assert_fail("\n combine:\n byte = {any}\n", .{ byte }); } test "swap_nibbles_test" { const result = swap_nibbles(0xAB); - if (!(result == 0xBA)) @panic("swap"); + if (!(result == 0xBA)) __t27_assert_fail("\n swap:\n result = {any}\n", .{ result }); } diff --git a/gen/zig/cache_management.zig b/gen/zig/cache_management.zig index 5089b19a..731e22d6 100644 --- a/gen/zig/cache_management.zig +++ b/gen/zig/cache_management.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_ENTRIES: u32 = 16; @@ -264,23 +272,23 @@ fn update_stats(stats: u32, hit: u32, evicted: u32) u32 { } test "cache_entry_roundtrip" { const e = create_cache_entry(9, 3, 40, 128); - if (!(get_data_id(e) == 9)) @panic("data id"); - if (!(get_access_count(e) == 3)) @panic("access count"); - if (!(get_age(e) == 40)) @panic("age"); - if (!(get_entry_size(e) == 128)) @panic("size"); + if (!(get_data_id(e) == 9)) __t27_assert_fail("\n data id:\n get_data_id(e) = {any}\n", .{ get_data_id(e) }); + if (!(get_access_count(e) == 3)) __t27_assert_fail("\n access count:\n get_access_count(e) = {any}\n", .{ get_access_count(e) }); + if (!(get_age(e) == 40)) __t27_assert_fail("\n age:\n get_age(e) = {any}\n", .{ get_age(e) }); + if (!(get_entry_size(e) == 128)) __t27_assert_fail("\n size:\n get_entry_size(e) = {any}\n", .{ get_entry_size(e) }); } test "access_count_saturates" { const e = create_cache_entry(1, 254, 0, 8); const e2 = update_access_count(e); - if (!(get_access_count(e2) == 255)) @panic("increments"); + if (!(get_access_count(e2) == 255)) __t27_assert_fail("\n increments:\n get_access_count(e2) = {any}\n", .{ get_access_count(e2) }); const e3 = update_access_count(e2); - if (!(get_access_count(e3) == 255)) @panic("saturates at 255"); + if (!(get_access_count(e3) == 255)) __t27_assert_fail("\n saturates at 255:\n get_access_count(e3) = {any}\n", .{ get_access_count(e3) }); } test "eviction_prefers_cold_then_old" { - const cache: [16]u32 = .{ create_cache_entry(1,5,10,8), create_cache_entry(2,1,10,8), create_cache_entry(3,1,200,8), create_cache_entry(4,9,250,8), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - if (!(find_eviction_candidate(cache) == 2)) @panic("coldest then oldest wins"); + const cache: [16]u32 = .{ create_cache_entry(1, 5, 10, 8), create_cache_entry(2, 1, 10, 8), create_cache_entry(3, 1, 200, 8), create_cache_entry(4, 9, 250, 8), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + if (!(find_eviction_candidate(cache) == 2)) __t27_assert_fail("\n coldest then oldest wins:\n find_eviction_candidate(cache) = {any}\n", .{ find_eviction_candidate(cache) }); } test "hit_rate_calculation" { - if (!(calculate_hit_rate(75, 100) == 75)) @panic("75 percent"); - if (!(calculate_hit_rate(0, 0) == 0)) @panic("no accesses is 0"); + if (!(calculate_hit_rate(75, 100) == 75)) __t27_assert_fail("\n 75 percent:\n calculate_hit_rate(75, 100) = {any}\n", .{ calculate_hit_rate(75, 100) }); + if (!(calculate_hit_rate(0, 0) == 0)) __t27_assert_fail("\n no accesses is 0:\n calculate_hit_rate(0, 0) = {any}\n", .{ calculate_hit_rate(0, 0) }); } diff --git a/gen/zig/compression_engine.zig b/gen/zig/compression_engine.zig index 4a3128e0..70c7ad3f 100644 --- a/gen/zig/compression_engine.zig +++ b/gen/zig/compression_engine.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_BLOCKS: u32 = 16; @@ -266,18 +274,18 @@ fn calculate_compression_speed(original_size: u32, compressed_size: u32, time_ms } test "block_info_roundtrip" { const info = create_block_info(200, 90, METHOD_RLE, 12345); - if (!(get_original_size(info) == 200)) @panic("original size"); - if (!(get_compressed_size(info) == 90)) @panic("compressed size"); - if (!(get_compression_method(info) == METHOD_RLE)) @panic("method"); - if (!(get_compression_quality(info) == 12345)) @panic("quality"); + if (!(get_original_size(info) == 200)) __t27_assert_fail("\n original size:\n get_original_size(info) = {any}\n", .{ get_original_size(info) }); + if (!(get_compressed_size(info) == 90)) __t27_assert_fail("\n compressed size:\n get_compressed_size(info) = {any}\n", .{ get_compressed_size(info) }); + if (!(get_compression_method(info) == METHOD_RLE)) __t27_assert_fail("\n method:\n get_compression_method(info) = {any}\n METHOD_RLE = {any}\n", .{ get_compression_method(info), METHOD_RLE }); + if (!(get_compression_quality(info) == 12345)) __t27_assert_fail("\n quality:\n get_compression_quality(info) = {any}\n", .{ get_compression_quality(info) }); } test "compression_ratio" { - if (!(calculate_compression_ratio(200, 100) == 200)) @panic("2x ratio is 200"); - if (!(calculate_compression_ratio(100, 0) == 100)) @panic("zero compressed guards"); + if (!(calculate_compression_ratio(200, 100) == 200)) __t27_assert_fail("\n 2x ratio is 200:\n calculate_compression_ratio(200, 100) = {any}\n", .{ calculate_compression_ratio(200, 100) }); + if (!(calculate_compression_ratio(100, 0) == 100)) __t27_assert_fail("\n zero compressed guards:\n calculate_compression_ratio(100, 0) = {any}\n", .{ calculate_compression_ratio(100, 0) }); } test "rle_single_run_roundtrip" { const c = compress_rle(0x1111, 4); - if (!(c == 0x41)) @panic("run of four ones"); + if (!(c == 0x41)) __t27_assert_fail("\n run of four ones:\n c = {any}\n", .{ c }); const d = decompress_rle(c); - if (!(d == 0x1111)) @panic("roundtrip restores the run"); + if (!(d == 0x1111)) __t27_assert_fail("\n roundtrip restores the run:\n d = {any}\n", .{ d }); } diff --git a/gen/zig/congestion_control.zig b/gen/zig/congestion_control.zig index 031c3ff6..59228c68 100644 --- a/gen/zig/congestion_control.zig +++ b/gen/zig/congestion_control.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_FLOWS: u32 = 8; @@ -205,32 +213,32 @@ fn reset_after_timeout(congestion: u32) u32 { } test "congestion_state_roundtrip" { const st = create_congestion_state(32, 16, STATE_FAST_RECOVERY, 5000); - if (!(get_cwnd(st) == 32)) @panic("cwnd"); - if (!(get_ssthresh(st) == 16)) @panic("ssthresh"); - if (!(get_congestion_state(st) == STATE_FAST_RECOVERY)) @panic("state"); - if (!(get_loss_count(st) == 5000)) @panic("loss count"); + if (!(get_cwnd(st) == 32)) __t27_assert_fail("\n cwnd:\n get_cwnd(st) = {any}\n", .{ get_cwnd(st) }); + if (!(get_ssthresh(st) == 16)) __t27_assert_fail("\n ssthresh:\n get_ssthresh(st) = {any}\n", .{ get_ssthresh(st) }); + if (!(get_congestion_state(st) == STATE_FAST_RECOVERY)) __t27_assert_fail("\n state:\n get_congestion_state(st) = {any}\n STATE_FAST_RECOVERY = {any}\n", .{ get_congestion_state(st), STATE_FAST_RECOVERY }); + if (!(get_loss_count(st) == 5000)) __t27_assert_fail("\n loss count:\n get_loss_count(st) = {any}\n", .{ get_loss_count(st) }); } test "slow_start_doubles_until_threshold" { var st = initialize_congestion(); - if (!(get_cwnd(st) == INITIAL_WINDOW)) @panic("initial window"); + if (!(get_cwnd(st) == INITIAL_WINDOW)) __t27_assert_fail("\n initial window:\n get_cwnd(st) = {any}\n INITIAL_WINDOW = {any}\n", .{ get_cwnd(st), INITIAL_WINDOW }); st = on_ack(st); - if (!(get_cwnd(st) == 8)) @panic("4 doubles to 8"); + if (!(get_cwnd(st) == 8)) __t27_assert_fail("\n 4 doubles to 8:\n get_cwnd(st) = {any}\n", .{ get_cwnd(st) }); st = on_ack(st); st = on_ack(st); st = on_ack(st); - if (!(get_cwnd(st) == 64)) @panic("window reaches the cap"); - if (!(get_congestion_state(st) == STATE_CONGESTION_AVOIDANCE)) @panic("leaves slow start"); + if (!(get_cwnd(st) == 64)) __t27_assert_fail("\n window reaches the cap:\n get_cwnd(st) = {any}\n", .{ get_cwnd(st) }); + if (!(get_congestion_state(st) == STATE_CONGESTION_AVOIDANCE)) __t27_assert_fail("\n leaves slow start:\n get_congestion_state(st) = {any}\n STATE_CONGESTION_AVOIDANCE = {any}\n", .{ get_congestion_state(st), STATE_CONGESTION_AVOIDANCE }); st = on_ack(st); - if (!(get_cwnd(st) == MAX_WINDOW)) @panic("linear growth is capped at MAX_WINDOW"); + if (!(get_cwnd(st) == MAX_WINDOW)) __t27_assert_fail("\n linear growth is capped at MAX_WINDOW:\n get_cwnd(st) = {any}\n MAX_WINDOW = {any}\n", .{ get_cwnd(st), MAX_WINDOW }); } test "loss_threshold_resets_window" { var st = create_congestion_state(40, 64, STATE_CONGESTION_AVOIDANCE, 0); st = on_loss(st); st = on_loss(st); - if (!(get_cwnd(st) == 40)) @panic("two losses keep the window"); + if (!(get_cwnd(st) == 40)) __t27_assert_fail("\n two losses keep the window:\n get_cwnd(st) = {any}\n", .{ get_cwnd(st) }); st = on_loss(st); - if (!(get_cwnd(st) == MIN_WINDOW)) @panic("third loss collapses the window"); - if (!(get_ssthresh(st) == 20)) @panic("ssthresh is half the old window"); - if (!(get_congestion_state(st) == STATE_SLOW_START)) @panic("back to slow start"); - if (!(get_loss_count(st) == 0)) @panic("loss counter cleared"); + if (!(get_cwnd(st) == MIN_WINDOW)) __t27_assert_fail("\n third loss collapses the window:\n get_cwnd(st) = {any}\n MIN_WINDOW = {any}\n", .{ get_cwnd(st), MIN_WINDOW }); + if (!(get_ssthresh(st) == 20)) __t27_assert_fail("\n ssthresh is half the old window:\n get_ssthresh(st) = {any}\n", .{ get_ssthresh(st) }); + if (!(get_congestion_state(st) == STATE_SLOW_START)) __t27_assert_fail("\n back to slow start:\n get_congestion_state(st) = {any}\n STATE_SLOW_START = {any}\n", .{ get_congestion_state(st), STATE_SLOW_START }); + if (!(get_loss_count(st) == 0)) __t27_assert_fail("\n loss counter cleared:\n get_loss_count(st) = {any}\n", .{ get_loss_count(st) }); } diff --git a/gen/zig/crc16.zig b/gen/zig/crc16.zig index c3ec87aa..cedd70f2 100644 --- a/gen/zig/crc16.zig +++ b/gen/zig/crc16.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const CRC16_CCITT_POLY: u16 = 0x1021; @@ -25,17 +33,17 @@ fn verify_crc16_4bytes(b0: u8, b1: u8, b2: u8, b3: u8, crc_received: u16) bool { } test "crc_update_byte_changes" { const crc = crc_update_byte(0xFFFF, 0); - if (!(crc != 0xFFFF)) @panic("changes"); + if (!(crc != 0xFFFF)) __t27_assert_fail("\n changes:\n crc = {any}\n", .{ crc }); } test "crc16_4bytes_reproducible" { const crc1 = crc16_4bytes(1, 2, 3, 4); const crc2 = crc16_4bytes(1, 2, 3, 4); - if (!(crc1 == crc2)) @panic("reproducible"); + if (!(crc1 == crc2)) __t27_assert_fail("\n reproducible:\n crc1 = {any}\n crc2 = {any}\n", .{ crc1, crc2 }); } test "crc16_4bytes_different" { const crc1 = crc16_4bytes(1, 2, 3, 4); const crc2 = crc16_4bytes(1, 2, 3, 5); - if (!(crc1 != crc2)) @panic("different"); + if (!(crc1 != crc2)) __t27_assert_fail("\n different:\n crc1 = {any}\n crc2 = {any}\n", .{ crc1, crc2 }); } test "verify_crc16_valid" { const crc_calc = crc16_4bytes(0xAA, 0xBB, 0xCC, 0xDD); @@ -45,10 +53,10 @@ test "verify_crc16_valid" { test "verify_crc16_invalid" { const crc_calc = crc16_4bytes(0xAA, 0xBB, 0xCC, 0xDD); const valid = verify_crc16_4bytes(0xAA, 0xBB, 0xCC, 0xFF, crc_calc); - if (!(valid == false)) @panic("invalid"); + if (!(valid == false)) __t27_assert_fail("\n invalid:\n valid = {any}\n", .{ valid }); } test "crc16_sensitivity" { const crc1 = crc16_4bytes(0x01, 0x02, 0x03, 0x04); const crc2 = crc16_4bytes(0x01, 0x02, 0x03, 0x05); - if (!(crc1 != crc2)) @panic("sensitive"); + if (!(crc1 != crc2)) __t27_assert_fail("\n sensitive:\n crc1 = {any}\n crc2 = {any}\n", .{ crc1, crc2 }); } diff --git a/gen/zig/cross_layer_optimizer.zig b/gen/zig/cross_layer_optimizer.zig index ede51294..7a5caf62 100644 --- a/gen/zig/cross_layer_optimizer.zig +++ b/gen/zig/cross_layer_optimizer.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_LAYERS: u32 = 4; @@ -172,104 +180,104 @@ fn switch_mode(state: u32, new_mode: u32) u32 { } test "create_layer_params_basic" { const params = create_layer_params(50, 100, 3, 64); - if (!(get_power(params) == 50)) @panic("power"); - if (!(get_rate(params) == 100)) @panic("rate"); - if (!(get_retries(params) == 3)) @panic("retries"); - if (!(get_window(params) == 64)) @panic("window"); + if (!(get_power(params) == 50)) __t27_assert_fail("\n power:\n get_power(params) = {any}\n", .{ get_power(params) }); + if (!(get_rate(params) == 100)) __t27_assert_fail("\n rate:\n get_rate(params) = {any}\n", .{ get_rate(params) }); + if (!(get_retries(params) == 3)) __t27_assert_fail("\n retries:\n get_retries(params) = {any}\n", .{ get_retries(params) }); + if (!(get_window(params) == 64)) __t27_assert_fail("\n window:\n get_window(params) = {any}\n", .{ get_window(params) }); } test "create_cross_layer_state_basic" { const state = create_cross_layer_state(MODE_MODERATE, 10, 1000, 1); - if (!(get_mode(state) == MODE_MODERATE)) @panic("mode"); - if (!(get_update_counter(state) == 10)) @panic("counter"); - if (!(get_last_sync(state) == 1000)) @panic("last sync"); - if (!(get_optimization_target(state) == 1)) @panic("target"); + if (!(get_mode(state) == MODE_MODERATE)) __t27_assert_fail("\n mode:\n get_mode(state) = {any}\n MODE_MODERATE = {any}\n", .{ get_mode(state), MODE_MODERATE }); + if (!(get_update_counter(state) == 10)) __t27_assert_fail("\n counter:\n get_update_counter(state) = {any}\n", .{ get_update_counter(state) }); + if (!(get_last_sync(state) == 1000)) __t27_assert_fail("\n last sync:\n get_last_sync(state) = {any}\n", .{ get_last_sync(state) }); + if (!(get_optimization_target(state) == 1)) __t27_assert_fail("\n target:\n get_optimization_target(state) = {any}\n", .{ get_optimization_target(state) }); } test "create_layer_array_basic" { const array = create_layer_array(create_layer_params(50, 100, 3, 64), create_layer_params(60, 120, 2, 128), create_layer_params(40, 80, 5, 32), create_layer_params(70, 150, 1, 256)); - if (!(get_power(get_layer_params(array, LAYER_PHY)) == 50)) @panic("PHY power"); - if (!(get_rate(get_layer_params(array, LAYER_MAC)) == 120)) @panic("MAC rate"); - if (!(get_retries(get_layer_params(array, LAYER_NETWORK)) == 5)) @panic("Network retries"); + if (!(get_power(get_layer_params(array, LAYER_PHY)) == 50)) __t27_assert_fail("\n PHY power:\n get_power(get_layer_params(array, LAYER_PHY)) = {any}\n", .{ get_power(get_layer_params(array, LAYER_PHY)) }); + if (!(get_rate(get_layer_params(array, LAYER_MAC)) == 120)) __t27_assert_fail("\n MAC rate:\n get_rate(get_layer_params(array, LAYER_MAC)) = {any}\n", .{ get_rate(get_layer_params(array, LAYER_MAC)) }); + if (!(get_retries(get_layer_params(array, LAYER_NETWORK)) == 5)) __t27_assert_fail("\n Network retries:\n get_retries(get_layer_params(array, LAYER_NETWORK)) = {any}\n", .{ get_retries(get_layer_params(array, LAYER_NETWORK)) }); } test "update_layer_params_phy" { const array = create_layer_array(create_layer_params(50, 100, 3, 64), create_layer_params(60, 120, 2, 128), create_layer_params(40, 80, 5, 32), create_layer_params(70, 150, 1, 256)); const new_array = update_layer_params(array, LAYER_PHY, create_layer_params(80, 150, 1, 128)); - if (!(get_power(get_layer_params(new_array, LAYER_PHY)) == 80)) @panic("PHY power updated"); + if (!(get_power(get_layer_params(new_array, LAYER_PHY)) == 80)) __t27_assert_fail("\n PHY power updated:\n get_power(get_layer_params(new_array, LAYER_PHY)) = {any}\n", .{ get_power(get_layer_params(new_array, LAYER_PHY)) }); } test "calculate_joint_metric_balanced" { const phy = create_layer_params(50, 100, 3, 64); const mac = create_layer_params(60, 120, 2, 128); const net = create_layer_params(40, 80, 5, 32); const metric = calculate_joint_metric(phy, mac, net); - if (!((metric > 0) and (metric < 255))) @panic("valid metric"); + if (!((metric > 0) and (metric < 255))) __t27_assert_fail("\n valid metric:\n metric = {any}\n", .{ metric }); } test "coordinate_power_conservative" { const state = create_cross_layer_state(MODE_CONSERVATIVE, 0, 0, 0); const phy = create_layer_params(100, 100, 3, 64); const mac = create_layer_params(80, 120, 2, 128); const new_phy, const new_mac = coordinate_power(state, phy, mac); - if (!(new_phy == 90)) @panic("PHY power reduced"); - if (!(new_mac == 75)) @panic("MAC power reduced"); + if (!(new_phy == 90)) __t27_assert_fail("\n PHY power reduced:\n new_phy = {any}\n", .{ new_phy }); + if (!(new_mac == 75)) __t27_assert_fail("\n MAC power reduced:\n new_mac = {any}\n", .{ new_mac }); } test "coordinate_power_aggressive" { const state = create_cross_layer_state(MODE_AGGRESSIVE, 0, 0, 0); const phy = create_layer_params(50, 100, 3, 64); const mac = create_layer_params(40, 120, 2, 128); const new_phy, const new_mac = coordinate_power(state, phy, mac); - if (!(new_phy == 60)) @panic("PHY power increased"); - if (!(new_mac == 45)) @panic("MAC power increased"); + if (!(new_phy == 60)) __t27_assert_fail("\n PHY power increased:\n new_phy = {any}\n", .{ new_phy }); + if (!(new_mac == 45)) __t27_assert_fail("\n MAC power increased:\n new_mac = {any}\n", .{ new_mac }); } test "coordinate_power_moderate" { const state = create_cross_layer_state(MODE_MODERATE, 0, 0, 0); const phy = create_layer_params(50, 100, 3, 64); const mac = create_layer_params(40, 120, 2, 128); const new_phy, const new_mac = coordinate_power(state, phy, mac); - if (!(new_phy == 50)) @panic("PHY power unchanged"); - if (!(new_mac == 40)) @panic("MAC power unchanged"); + if (!(new_phy == 50)) __t27_assert_fail("\n PHY power unchanged:\n new_phy = {any}\n", .{ new_phy }); + if (!(new_mac == 40)) __t27_assert_fail("\n MAC power unchanged:\n new_mac = {any}\n", .{ new_mac }); } test "optimize_for_target_latency" { const state = create_cross_layer_state(MODE_MODERATE, 0, 0, 0); const phy = create_layer_params(50, 100, 5, 64); const mac = create_layer_params(60, 100, 2, 128); const val1, const val2 = optimize_for_target(state, phy, mac); - if (!(val1 == 120)) @panic("rate increased for latency"); - if (!(val2 == 4)) @panic("retries decreased for latency"); + if (!(val1 == 120)) __t27_assert_fail("\n rate increased for latency:\n val1 = {any}\n", .{ val1 }); + if (!(val2 == 4)) __t27_assert_fail("\n retries decreased for latency:\n val2 = {any}\n", .{ val2 }); } test "optimize_for_target_throughput" { const state = create_cross_layer_state(MODE_MODERATE, 0, 0, 1); const phy = create_layer_params(50, 100, 5, 64); const mac = create_layer_params(60, 100, 2, 128); const val1, const val2 = optimize_for_target(state, phy, mac); - if (!(val1 == 255)) @panic("rate maximized for throughput"); - if (!(val2 == 138)) @panic("window increased for throughput"); + if (!(val1 == 255)) __t27_assert_fail("\n rate maximized for throughput:\n val1 = {any}\n", .{ val1 }); + if (!(val2 == 138)) __t27_assert_fail("\n window increased for throughput:\n val2 = {any}\n", .{ val2 }); } test "optimize_for_target_reliability" { const state = create_cross_layer_state(MODE_MODERATE, 0, 0, 2); const phy = create_layer_params(50, 100, 5, 64); const mac = create_layer_params(60, 100, 2, 128); const val1, const val2 = optimize_for_target(state, phy, mac); - if (!(val1 == 8)) @panic("retries increased for reliability"); - if (!(val2 == 65)) @panic("power increased for reliability"); + if (!(val1 == 8)) __t27_assert_fail("\n retries increased for reliability:\n val1 = {any}\n", .{ val1 }); + if (!(val2 == 65)) __t27_assert_fail("\n power increased for reliability:\n val2 = {any}\n", .{ val2 }); } test "needs_synchronization_true" { const state = create_cross_layer_state(MODE_MODERATE, 0, 1000, 0); - if (!(needs_synchronization(state, 1150) == true)) @panic("needs sync"); + if (!(needs_synchronization(state, 1150) == true)) __t27_assert_fail("\n needs sync:\n needs_synchronization(state, 1150) = {any}\n", .{ needs_synchronization(state, 1150) }); } test "needs_synchronization_false" { const state = create_cross_layer_state(MODE_MODERATE, 0, 1000, 0); - if (!(needs_synchronization(state, 1050) == false)) @panic("no sync needed"); + if (!(needs_synchronization(state, 1050) == false)) __t27_assert_fail("\n no sync needed:\n needs_synchronization(state, 1050) = {any}\n", .{ needs_synchronization(state, 1050) }); } test "increment_updates_works" { const state = create_cross_layer_state(MODE_MODERATE, 10, 1000, 0); const new_state = increment_updates(state); - if (!(get_update_counter(new_state) == 11)) @panic("counter incremented"); + if (!(get_update_counter(new_state) == 11)) __t27_assert_fail("\n counter incremented:\n get_update_counter(new_state) = {any}\n", .{ get_update_counter(new_state) }); } test "increment_updates_wraps" { const state = create_cross_layer_state(MODE_MODERATE, 255, 1000, 0); const new_state = increment_updates(state); - if (!(get_update_counter(new_state) == 0)) @panic("counter wrapped"); + if (!(get_update_counter(new_state) == 0)) __t27_assert_fail("\n counter wrapped:\n get_update_counter(new_state) = {any}\n", .{ get_update_counter(new_state) }); } test "switch_mode_works" { const state = create_cross_layer_state(MODE_MODERATE, 10, 1000, 0); const new_state = switch_mode(state, MODE_AGGRESSIVE); - if (!(get_mode(new_state) == MODE_AGGRESSIVE)) @panic("mode switched"); + if (!(get_mode(new_state) == MODE_AGGRESSIVE)) __t27_assert_fail("\n mode switched:\n get_mode(new_state) = {any}\n MODE_AGGRESSIVE = {any}\n", .{ get_mode(new_state), MODE_AGGRESSIVE }); } diff --git a/gen/zig/crypto_frame.zig b/gen/zig/crypto_frame.zig index 84b2b7dc..6734bec2 100644 --- a/gen/zig/crypto_frame.zig +++ b/gen/zig/crypto_frame.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const EPOCH_LEN: usize = 4; @@ -104,30 +112,78 @@ fn replay_next_bhi(seen_any: bool, top: u64, blo: u32, bhi: u32, ctr: u64) u32 { return bhi; } test "header_is_epoch_plus_counter" { + const h = EPOCH_LEN + COUNTER_LEN; + const co = ciphertext_offset(); + if (!(h == 12)) __t27_assert_fail("\n assertion failed:\n h = {any}\n", .{ h }); + if (!(co == 12)) __t27_assert_fail("\n assertion failed:\n co = {any}\n", .{ co }); } test "short_frame_rejected" { + const bad = frame_len_ok(11); + const ok = frame_len_ok(12); + if (!(bad == false)) __t27_assert_fail("\n assertion failed:\n bad = {any}\n", .{ bad }); + if (!(ok == true)) __t27_assert_fail("\n assertion failed:\n ok = {any}\n", .{ ok }); } test "ratchet_at_budget_reject_at_cap" { + const before = should_ratchet(1048575); + const at = should_ratchet(1048576); + const cap = must_reject(16777216); + const under_cap = must_reject(16777215); + if (!(before == false)) __t27_assert_fail("\n assertion failed:\n before = {any}\n", .{ before }); + if (!(at == true)) __t27_assert_fail("\n assertion failed:\n at = {any}\n", .{ at }); + if (!(cap == true)) __t27_assert_fail("\n assertion failed:\n cap = {any}\n", .{ cap }); + if (!(under_cap == false)) __t27_assert_fail("\n assertion failed:\n under_cap = {any}\n", .{ under_cap }); } test "nonce_layout_dir_epoch_ctr" { + const d = nonce_byte(1, 258, 5, 0); + const e_hi = nonce_byte(1, 258, 5, 1); + const e_lo = nonce_byte(1, 258, 5, 4); + const c_lo = nonce_byte(1, 258, 5, 11); + if (!(d == 1)) __t27_assert_fail("\n assertion failed:\n d = {any}\n", .{ d }); + if (!(e_hi == 0)) __t27_assert_fail("\n assertion failed:\n e_hi = {any}\n", .{ e_hi }); + if (!(e_lo == 2)) __t27_assert_fail("\n assertion failed:\n e_lo = {any}\n", .{ e_lo }); + if (!(c_lo == 5)) __t27_assert_fail("\n assertion failed:\n c_lo = {any}\n", .{ c_lo }); } test "rx_inverts_tx_direction" { + const a = rx_dir(0); + const b = rx_dir(1); + if (!(a == 1)) __t27_assert_fail("\n assertion failed:\n a = {any}\n", .{ a }); + if (!(b == 0)) __t27_assert_fail("\n assertion failed:\n b = {any}\n", .{ b }); } test "replay_first_and_duplicate" { + const first = replay_accept(false, 0, 0, 0, 7); + const blo = replay_next_blo(false, 0, 0, 0, 7); + const dup = replay_accept(true, 7, 1, 0, 7); + if (!(first == true)) __t27_assert_fail("\n assertion failed:\n first = {any}\n", .{ first }); + if (!(blo == 1)) __t27_assert_fail("\n assertion failed:\n blo = {any}\n", .{ blo }); + if (!(dup == false)) __t27_assert_fail("\n assertion failed:\n dup = {any}\n", .{ dup }); } test "replay_low_lane_in_window" { + const fresh = replay_accept(true, 10, 1, 0, 5); + const blo = replay_next_blo(true, 10, 1, 0, 5); + if (!(fresh == true)) __t27_assert_fail("\n assertion failed:\n fresh = {any}\n", .{ fresh }); + if (!(blo == 33)) __t27_assert_fail("\n assertion failed:\n blo = {any}\n", .{ blo }); } test "replay_high_lane_bit" { + const fresh = replay_accept(true, 40, 1, 0, 5); + const bhi = replay_next_bhi(true, 40, 1, 0, 5); + if (!(fresh == true)) __t27_assert_fail("\n assertion failed:\n fresh = {any}\n", .{ fresh }); + if (!(bhi == 8)) __t27_assert_fail("\n assertion failed:\n bhi = {any}\n", .{ bhi }); } test "replay_too_old_rejected" { + const old = replay_accept(true, 70, 1, 0, 5); + if (!(old == false)) __t27_assert_fail("\n assertion failed:\n old = {any}\n", .{ old }); } test "replay_forward_jump_carries_lane" { + const blo = replay_next_blo(true, 5, 1, 0, 8); + const bhi = replay_next_bhi(true, 5, 1, 0, 8); + if (!(blo == 9)) __t27_assert_fail("\n assertion failed:\n blo = {any}\n", .{ blo }); + if (!(bhi == 0)) __t27_assert_fail("\n assertion failed:\n bhi = {any}\n", .{ bhi }); } comptime { // invariant: routine_ratchet_below_hard_cap - // invariant: routine_ratchet_below_hard_cap verified (no statements) + if (!(REKEY_EVERY_FRAMES < REKEY_HARD_CAP)) __t27_assert_fail("\n assertion failed:\n REKEY_EVERY_FRAMES = {any}\n REKEY_HARD_CAP = {any}\n", .{ REKEY_EVERY_FRAMES, REKEY_HARD_CAP }); } comptime { // invariant: hard_cap_fits_seven_nonce_bytes - // invariant: hard_cap_fits_seven_nonce_bytes verified (no statements) + if (!(REKEY_HARD_CAP < 72057594037927936)) __t27_assert_fail("\n assertion failed:\n REKEY_HARD_CAP = {any}\n", .{ REKEY_HARD_CAP }); } diff --git a/gen/zig/discovery.zig b/gen/zig/discovery.zig index d1115e62..4036f5ab 100644 --- a/gen/zig/discovery.zig +++ b/gen/zig/discovery.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const HDR_LEN: usize = 17; @@ -26,22 +34,40 @@ fn is_fresh(now_ms: u64, ts_ms: u64) bool { } } test "empty_beacon_is_33_bytes" { + const l = hello_len(0); + if (!(l == 33)) __t27_assert_fail("\n assertion failed:\n l = {any}\n", .{ l }); } test "three_neighbors_is_45_bytes" { + const l = hello_len(3); + const m = mac_offset(3); + if (!(l == 45)) __t27_assert_fail("\n assertion failed:\n l = {any}\n", .{ l }); + if (!(m == 29)) __t27_assert_fail("\n assertion failed:\n m = {any}\n", .{ m }); } test "parse_accepts_exact_length" { + const ok = parse_len_ok(45, 3); + if (!(ok == true)) __t27_assert_fail("\n assertion failed:\n ok = {any}\n", .{ ok }); } test "parse_rejects_truncated" { + const short = parse_len_ok(44, 3); + const hdr = parse_len_ok(16, 0); + if (!(short == false)) __t27_assert_fail("\n assertion failed:\n short = {any}\n", .{ short }); + if (!(hdr == false)) __t27_assert_fail("\n assertion failed:\n hdr = {any}\n", .{ hdr }); } test "fresh_within_window_both_directions" { + const past = is_fresh(1000000, 500000); + const future = is_fresh(500000, 1000000); + if (!(past == true)) __t27_assert_fail("\n assertion failed:\n past = {any}\n", .{ past }); + if (!(future == true)) __t27_assert_fail("\n assertion failed:\n future = {any}\n", .{ future }); } test "stale_beyond_window_rejected" { + const stale = is_fresh(1000000, 300000); + if (!(stale == false)) __t27_assert_fail("\n assertion failed:\n stale = {any}\n", .{ stale }); } comptime { // invariant: header_is_17_bytes - // invariant: header_is_17_bytes verified (no statements) + if (!(HDR_LEN == 17)) __t27_assert_fail("\n assertion failed:\n HDR_LEN = {any}\n", .{ HDR_LEN }); } comptime { // invariant: mac_is_16_bytes - // invariant: mac_is_16_bytes verified (no statements) + if (!(MAC_LEN == 16)) __t27_assert_fail("\n assertion failed:\n MAC_LEN = {any}\n", .{ MAC_LEN }); } diff --git a/gen/zig/docs_generator.zig b/gen/zig/docs_generator.zig index 09f8e804..8e224519 100644 --- a/gen/zig/docs_generator.zig +++ b/gen/zig/docs_generator.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_SECTIONS: u32 = 16; @@ -256,15 +264,15 @@ fn validate_documentation(generated_doc: u32, expected_sections: u32, expected_f } test "output_format_roundtrip" { const f = create_output_format(9, 200, 5, 50000); - if (!(get_format_id(f) == 9)) @panic("format id"); - if (!(get_format_version(f) == 200)) @panic("version"); - if (!(get_format_compression(f) == 5)) @panic("compression"); - if (!(get_format_encoding(f) == 50000)) @panic("encoding"); + if (!(get_format_id(f) == 9)) __t27_assert_fail("\n format id:\n get_format_id(f) = {any}\n", .{ get_format_id(f) }); + if (!(get_format_version(f) == 200)) __t27_assert_fail("\n version:\n get_format_version(f) = {any}\n", .{ get_format_version(f) }); + if (!(get_format_compression(f) == 5)) __t27_assert_fail("\n compression:\n get_format_compression(f) = {any}\n", .{ get_format_compression(f) }); + if (!(get_format_encoding(f) == 50000)) __t27_assert_fail("\n encoding:\n get_format_encoding(f) = {any}\n", .{ get_format_encoding(f) }); } test "markdown_header_levels" { const h1 = generate_markdown_header(1, 7); - if (!(((h1 >> 8) & 0xFFFFFF) == 0x23)) @panic("level 1 prefix"); - if (!((h1 & 0xFF) == 7)) @panic("title id"); + if (!(((h1 >> 8) & 0xFFFFFF) == 0x23)) __t27_assert_fail("\n level 1 prefix:\n (h1 >> 8) & 0xFFFFFF = {any}\n", .{ (h1 >> 8) & 0xFFFFFF }); + if (!((h1 & 0xFF) == 7)) __t27_assert_fail("\n title id:\n h1 & 0xFF = {any}\n", .{ h1 & 0xFF }); const h3 = generate_markdown_header(3, 7); - if (!(((h3 >> 8) & 0xFFFFFF) == 0x232323)) @panic("level 3 prefix"); + if (!(((h3 >> 8) & 0xFFFFFF) == 0x232323)) __t27_assert_fail("\n level 3 prefix:\n (h3 >> 8) & 0xFFFFFF = {any}\n", .{ (h3 >> 8) & 0xFFFFFF }); } diff --git a/gen/zig/energy_aware_routing.zig b/gen/zig/energy_aware_routing.zig index 06f9de8d..89b94bfb 100644 --- a/gen/zig/energy_aware_routing.zig +++ b/gen/zig/energy_aware_routing.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_PATHS: u32 = 4; @@ -187,63 +195,63 @@ fn estimate_path_lifetime(energy: u32, drain_rate: u32) u32 { } test "create_energy_cost_basic" { const cost = create_energy_cost(50, 30, 20, 3); - if (!(get_tx_power(cost) == 50)) @panic("TX power"); - if (!(get_rx_power(cost) == 30)) @panic("RX power"); - if (!(get_processing_cost(cost) == 20)) @panic("processing"); - if (!(get_hop_count_cost(cost) == 3)) @panic("hop count"); + if (!(get_tx_power(cost) == 50)) __t27_assert_fail("\n TX power:\n get_tx_power(cost) = {any}\n", .{ get_tx_power(cost) }); + if (!(get_rx_power(cost) == 30)) __t27_assert_fail("\n RX power:\n get_rx_power(cost) = {any}\n", .{ get_rx_power(cost) }); + if (!(get_processing_cost(cost) == 20)) __t27_assert_fail("\n processing:\n get_processing_cost(cost) = {any}\n", .{ get_processing_cost(cost) }); + if (!(get_hop_count_cost(cost) == 3)) __t27_assert_fail("\n hop count:\n get_hop_count_cost(cost) = {any}\n", .{ get_hop_count_cost(cost) }); } test "create_path_energy_basic" { const energy = create_path_energy(80, 100, 1, 500); - if (!(get_battery_levels(energy) == 80)) @panic("battery"); - if (!(get_total_cost(energy) == 100)) @panic("cost"); - if (!(get_path_valid(energy) == 1)) @panic("valid"); - if (!(get_energy_score(energy) == 500)) @panic("score"); + if (!(get_battery_levels(energy) == 80)) __t27_assert_fail("\n battery:\n get_battery_levels(energy) = {any}\n", .{ get_battery_levels(energy) }); + if (!(get_total_cost(energy) == 100)) __t27_assert_fail("\n cost:\n get_total_cost(energy) = {any}\n", .{ get_total_cost(energy) }); + if (!(get_path_valid(energy) == 1)) __t27_assert_fail("\n valid:\n get_path_valid(energy) = {any}\n", .{ get_path_valid(energy) }); + if (!(get_energy_score(energy) == 500)) __t27_assert_fail("\n score:\n get_energy_score(energy) = {any}\n", .{ get_energy_score(energy) }); } test "calculate_total_energy_cost" { const cost = create_energy_cost(50, 30, 20, 3); const total = calculate_total_energy_cost(cost); - if (!(total == 300)) @panic("total energy"); + if (!(total == 300)) __t27_assert_fail("\n total energy:\n total = {any}\n", .{ total }); } test "calculate_energy_score_high_battery" { const cost = create_energy_cost(50, 30, 20, 3); const score = calculate_energy_score(80, cost); - if (!((score >= 26) and (score <= 27))) @panic("energy score"); + if (!((score >= 26) and (score <= 27))) __t27_assert_fail("\n energy score:\n score = {any}\n", .{ score }); } test "calculate_energy_score_low_cost" { const cost = create_energy_cost(20, 10, 10, 2); const score = calculate_energy_score(50, cost); - if (!(score == 62)) @panic("energy score"); + if (!(score == 62)) __t27_assert_fail("\n energy score:\n score = {any}\n", .{ score }); } test "is_path_viable_true" { const energy = create_path_energy(60, 100, 1, 500); - if (!(is_path_viable(energy) == true)) @panic("viable"); + if (!(is_path_viable(energy) == true)) __t27_assert_fail("\n viable:\n is_path_viable(energy) = {any}\n", .{ is_path_viable(energy) }); } test "is_path_viable_critical_battery" { const energy = create_path_energy(15, 100, 1, 500); - if (!(is_path_viable(energy) == false)) @panic("critical battery"); + if (!(is_path_viable(energy) == false)) __t27_assert_fail("\n critical battery:\n is_path_viable(energy) = {any}\n", .{ is_path_viable(energy) }); } test "is_path_viable_invalid_path" { const energy = create_path_energy(60, 100, 0, 500); - if (!(is_path_viable(energy) == false)) @panic("invalid path"); + if (!(is_path_viable(energy) == false)) __t27_assert_fail("\n invalid path:\n is_path_viable(energy) = {any}\n", .{ is_path_viable(energy) }); } test "find_energy_optimal_path_highest_score" { const array = create_energy_array(create_path_energy(60, 100, 1, 200), create_path_energy(80, 100, 1, 400), create_path_energy(70, 100, 1, 300), create_path_energy(50, 100, 1, 100)); - if (!(find_energy_optimal_path(array) == 1)) @panic("path 1 optimal"); + if (!(find_energy_optimal_path(array) == 1)) __t27_assert_fail("\n path 1 optimal:\n find_energy_optimal_path(array) = {any}\n", .{ find_energy_optimal_path(array) }); } test "find_min_cost_path" { const array = create_energy_array(create_path_energy(80, 150, 1, 200), create_path_energy(70, 80, 1, 300), create_path_energy(60, 120, 1, 250), create_path_energy(90, 200, 1, 400)); - if (!(find_min_cost_path(array) == 1)) @panic("path 1 minimum cost"); + if (!(find_min_cost_path(array) == 1)) __t27_assert_fail("\n path 1 minimum cost:\n find_min_cost_path(array) = {any}\n", .{ find_min_cost_path(array) }); } test "select_balanced_path_highest_battery" { const array = create_energy_array(create_path_energy(50, 100, 1, 200), create_path_energy(90, 100, 1, 300), create_path_energy(70, 100, 1, 250), create_path_energy(60, 100, 1, 150)); - if (!(select_balanced_path(array, 0) == 1)) @panic("path 1 selected"); + if (!(select_balanced_path(array, 0) == 1)) __t27_assert_fail("\n path 1 selected:\n select_balanced_path(array, 0) = {any}\n", .{ select_balanced_path(array, 0) }); } test "estimate_path_lifetime_normal" { const energy = create_path_energy(80, 100, 1, 500); const lifetime = estimate_path_lifetime(energy, 10); - if (!(lifetime == 8)) @panic("8 time units"); + if (!(lifetime == 8)) __t27_assert_fail("\n 8 time units:\n lifetime = {any}\n", .{ lifetime }); } test "estimate_path_lifetime_zero_drain" { const energy = create_path_energy(80, 100, 1, 500); - if (!(estimate_path_lifetime(energy, 0) == 0xFF)) @panic("infinite lifetime"); + if (!(estimate_path_lifetime(energy, 0) == 0xFF)) __t27_assert_fail("\n infinite lifetime:\n estimate_path_lifetime(energy, 0) = {any}\n", .{ estimate_path_lifetime(energy, 0) }); } diff --git a/gen/zig/etx.zig b/gen/zig/etx.zig index cd770d28..fbc643cd 100644 --- a/gen/zig/etx.zig +++ b/gen/zig/etx.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const OPTIMISTIC: u8 = 230; @@ -58,43 +66,43 @@ test "test_perfect_link" { const fwd = ewma_update(ewma_update(ewma_update(OPTIMISTIC, 255, ALPHA_HALF), 255, ALPHA_HALF), 255, ALPHA_HALF); const rev = ewma_update(ewma_update(ewma_update(OPTIMISTIC, 255, ALPHA_HALF), 255, ALPHA_HALF), 255, ALPHA_HALF); const etx = calc_etx(fwd, rev); - if (!((etx >= 200) and (etx <= 312))) @panic("ETX ~1.0 expected"); + if (!((etx >= 200) and (etx <= 312))) __t27_assert_fail("\n ETX ~1.0 expected:\n etx = {any}\n", .{ etx }); } test "test_half_forward" { const fwd = ewma_update(ewma_update(OPTIMISTIC, 255, ALPHA_HALF), 0, ALPHA_HALF); const rev = ewma_update(ewma_update(OPTIMISTIC, 255, ALPHA_HALF), 255, ALPHA_HALF); const etx = calc_etx(fwd, rev); - if (!((etx >= 384) and (etx <= 512))) @panic("ETX ~2.0 expected"); + if (!((etx >= 384) and (etx <= 512))) __t27_assert_fail("\n ETX ~2.0 expected:\n etx = {any}\n", .{ etx }); } test "test_dead_direction" { const fwd = ewma_update(ewma_update(OPTIMISTIC, 255, ALPHA_HALF), 255, ALPHA_HALF); const rev = ewma_update(ewma_update(ewma_update(OPTIMISTIC, 0, ALPHA_HALF), 0, ALPHA_HALF), 0, ALPHA_HALF); const etx = calc_etx(fwd, rev); - if (!(etx == 0xFFFF)) @panic("dead link should be infinite"); + if (!(etx == 0xFFFF)) __t27_assert_fail("\n dead link should be infinite:\n etx = {any}\n", .{ etx }); } test "test_force_dead" { const fwd = ewma_update(OPTIMISTIC, 255, 160); const rev = ewma_update(OPTIMISTIC, 255, 160); const etx_healthy = calc_etx(fwd, rev); - if (!(etx_healthy != 0xFFFF)) @panic("healthy link should be finite"); + if (!(etx_healthy != 0xFFFF)) __t27_assert_fail("\n healthy link should be finite:\n etx_healthy = {any}\n", .{ etx_healthy }); const etx_dead = calc_etx(0, 0); - if (!(etx_dead == 0xFFFF)) @panic("zeroed link should be infinite"); + if (!(etx_dead == 0xFFFF)) __t27_assert_fail("\n zeroed link should be infinite:\n etx_dead = {any}\n", .{ etx_dead }); const fwd2 = ewma_update(0, 255, 160); const rev2 = ewma_update(0, 255, 160); const etx_resurrect = calc_etx(fwd2, rev2); - if (!(etx_resurrect != 0xFFFF)) @panic("resurrected link should be finite"); + if (!(etx_resurrect != 0xFFFF)) __t27_assert_fail("\n resurrected link should be finite:\n etx_resurrect = {any}\n", .{ etx_resurrect }); } test "test_etx_buckets" { const etx_perfect = calc_etx(230, 230); - if (!((etx_perfect >= 200) and (etx_perfect <= 312))) @panic("perfect ETX ~1.0"); + if (!((etx_perfect >= 200) and (etx_perfect <= 312))) __t27_assert_fail("\n perfect ETX ~1.0:\n etx_perfect = {any}\n", .{ etx_perfect }); const etx_half = calc_etx(115, 230); - if (!((etx_half >= 384) and (etx_half <= 512))) @panic("half ETX ~2.0"); + if (!((etx_half >= 384) and (etx_half <= 512))) __t27_assert_fail("\n half ETX ~2.0:\n etx_half = {any}\n", .{ etx_half }); const etx_dead = calc_etx(230, 0); - if (!(etx_dead == 0xFFFF)) @panic("dead direction infinite"); + if (!(etx_dead == 0xFFFF)) __t27_assert_fail("\n dead direction infinite:\n etx_dead = {any}\n", .{ etx_dead }); } test "test_ewma_convergence" { const est1 = ewma_update(ewma_update(OPTIMISTIC, 255, ALPHA_HALF), 255, ALPHA_HALF); - if (!(est1 > OPTIMISTIC)) @panic("EWMA should increase"); + if (!(est1 > OPTIMISTIC)) __t27_assert_fail("\n EWMA should increase:\n est1 = {any}\n OPTIMISTIC = {any}\n", .{ est1, OPTIMISTIC }); const est2 = ewma_update(ewma_update(OPTIMISTIC, 0, ALPHA_HALF), 0, ALPHA_HALF); - if (!(est2 < OPTIMISTIC)) @panic("EWMA should decrease"); + if (!(est2 < OPTIMISTIC)) __t27_assert_fail("\n EWMA should decrease:\n est2 = {any}\n OPTIMISTIC = {any}\n", .{ est2, OPTIMISTIC }); } diff --git a/gen/zig/failure_predictor.zig b/gen/zig/failure_predictor.zig index f011aa79..53a1e9e9 100644 --- a/gen/zig/failure_predictor.zig +++ b/gen/zig/failure_predictor.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_NODES: u32 = 8; @@ -152,83 +160,83 @@ fn find_most_at_risk(health_array: [8]u32) u32 { } test "create_health_metrics_basic" { const metrics = create_health_metrics(60, 70, 5, 45); - if (!(get_cpu_usage(metrics) == 60)) @panic("CPU usage"); - if (!(get_memory_usage(metrics) == 70)) @panic("memory usage"); - if (!(get_error_rate(metrics) == 5)) @panic("error rate"); - if (!(get_temperature(metrics) == 45)) @panic("temperature"); + if (!(get_cpu_usage(metrics) == 60)) __t27_assert_fail("\n CPU usage:\n get_cpu_usage(metrics) = {any}\n", .{ get_cpu_usage(metrics) }); + if (!(get_memory_usage(metrics) == 70)) __t27_assert_fail("\n memory usage:\n get_memory_usage(metrics) = {any}\n", .{ get_memory_usage(metrics) }); + if (!(get_error_rate(metrics) == 5)) __t27_assert_fail("\n error rate:\n get_error_rate(metrics) = {any}\n", .{ get_error_rate(metrics) }); + if (!(get_temperature(metrics) == 45)) __t27_assert_fail("\n temperature:\n get_temperature(metrics) = {any}\n", .{ get_temperature(metrics) }); } test "create_risk_score_basic" { const score = create_risk_score(75, 80, 1, 1000); - if (!(get_risk_level(score) == 75)) @panic("risk level"); - if (!(get_confidence(score) == 80)) @panic("confidence"); - if (!(get_risk_trend(score) == 1)) @panic("trend"); - if (!(get_prediction_time(score) == 1000)) @panic("prediction time"); + if (!(get_risk_level(score) == 75)) __t27_assert_fail("\n risk level:\n get_risk_level(score) = {any}\n", .{ get_risk_level(score) }); + if (!(get_confidence(score) == 80)) __t27_assert_fail("\n confidence:\n get_confidence(score) = {any}\n", .{ get_confidence(score) }); + if (!(get_risk_trend(score) == 1)) __t27_assert_fail("\n trend:\n get_risk_trend(score) = {any}\n", .{ get_risk_trend(score) }); + if (!(get_prediction_time(score) == 1000)) __t27_assert_fail("\n prediction time:\n get_prediction_time(score) = {any}\n", .{ get_prediction_time(score) }); } test "calculate_health_score_healthy" { const metrics = create_health_metrics(20, 30, 2, 40); const score = calculate_health_score(metrics); - if (!(score >= 75)) @panic("healthy score"); + if (!(score >= 75)) __t27_assert_fail("\n healthy score:\n score = {any}\n", .{ score }); } test "calculate_health_score_degraded" { const metrics = create_health_metrics(80, 70, 15, 75); const score = calculate_health_score(metrics); - if (!(score < 40)) @panic("degraded score"); + if (!(score < 40)) __t27_assert_fail("\n degraded score:\n score = {any}\n", .{ score }); } test "predict_failure_probability_healthy" { const metrics = create_health_metrics(10, 20, 2, 30); - if (!(predict_failure_probability(metrics) == 0)) @panic("no failure"); + if (!(predict_failure_probability(metrics) == 0)) __t27_assert_fail("\n no failure:\n predict_failure_probability(metrics) = {any}\n", .{ predict_failure_probability(metrics) }); } test "predict_failure_probability_critical" { const metrics = create_health_metrics(90, 95, 40, 85); - if (!(predict_failure_probability(metrics) >= 80)) @panic("high failure prob"); + if (!(predict_failure_probability(metrics) >= 80)) __t27_assert_fail("\n high failure prob:\n predict_failure_probability(metrics) = {any}\n", .{ predict_failure_probability(metrics) }); } test "is_trending_failure_degrading" { const current = create_health_metrics(50, 60, 8, 48); const previous = create_health_metrics(40, 50, 5, 45); - if (!(is_trending_failure(current, previous) == 0)) @panic("not trending to failure"); + if (!(is_trending_failure(current, previous) == 0)) __t27_assert_fail("\n not trending to failure:\n is_trending_failure(current, previous) = {any}\n", .{ is_trending_failure(current, previous) }); } test "is_trending_failure_significant" { const current = create_health_metrics(80, 85, 20, 60); const previous = create_health_metrics(30, 35, 5, 40); - if (!(is_trending_failure(current, previous) == 1)) @panic("trending to failure"); + if (!(is_trending_failure(current, previous) == 1)) __t27_assert_fail("\n trending to failure:\n is_trending_failure(current, previous) = {any}\n", .{ is_trending_failure(current, previous) }); } test "predict_time_to_failure_healthy" { const metrics = create_health_metrics(10, 20, 2, 30); - if (!(predict_time_to_failure(metrics) == 0xFF)) @panic("no failure predicted"); + if (!(predict_time_to_failure(metrics) == 0xFF)) __t27_assert_fail("\n no failure predicted:\n predict_time_to_failure(metrics) = {any}\n", .{ predict_time_to_failure(metrics) }); } test "predict_time_to_failure_critical" { const metrics = create_health_metrics(95, 95, 60, 90); - if (!(predict_time_to_failure(metrics) == 5)) @panic("immediate failure"); + if (!(predict_time_to_failure(metrics) == 5)) __t27_assert_fail("\n immediate failure:\n predict_time_to_failure(metrics) = {any}\n", .{ predict_time_to_failure(metrics) }); } test "predict_time_to_failure_medium" { const metrics = create_health_metrics(60, 65, 20, 55); - if (!(predict_time_to_failure(metrics) == 50)) @panic("medium-term failure"); + if (!(predict_time_to_failure(metrics) == 50)) __t27_assert_fail("\n medium-term failure:\n predict_time_to_failure(metrics) = {any}\n", .{ predict_time_to_failure(metrics) }); } test "calculate_failure_risk_low" { const metrics = create_health_metrics(30, 40, 5, 45); const risk = calculate_failure_risk(metrics, 0); - if (!(risk < 30)) @panic("low risk"); + if (!(risk < 30)) __t27_assert_fail("\n low risk:\n risk = {any}\n", .{ risk }); } test "calculate_failure_risk_high_with_degradation" { const metrics = create_health_metrics(80, 85, 25, 70); const risk = calculate_failure_risk(metrics, 30); - if (!(risk >= 80)) @panic("high risk with degradation"); + if (!(risk >= 80)) __t27_assert_fail("\n high risk with degradation:\n risk = {any}\n", .{ risk }); } test "needs_immediate_action_true" { const metrics = create_health_metrics(97, 80, 10, 96); - if (!(needs_immediate_action(metrics) == true)) @panic("immediate action needed"); + if (!(needs_immediate_action(metrics) == true)) __t27_assert_fail("\n immediate action needed:\n needs_immediate_action(metrics) = {any}\n", .{ needs_immediate_action(metrics) }); } test "needs_immediate_action_false" { const metrics = create_health_metrics(60, 70, 5, 45); - if (!(needs_immediate_action(metrics) == false)) @panic("no immediate action"); + if (!(needs_immediate_action(metrics) == false)) __t27_assert_fail("\n no immediate action:\n needs_immediate_action(metrics) = {any}\n", .{ needs_immediate_action(metrics) }); } test "find_most_at_risk_middle" { const array = create_health_array(create_health_metrics(30, 40, 5, 45), create_health_metrics(90, 95, 60, 90), create_health_metrics(50, 60, 10, 55), create_health_metrics(40, 50, 8, 50), 0, 0, 0, 0); - if (!(find_most_at_risk(array) == 1)) @panic("node 1 most at-risk"); + if (!(find_most_at_risk(array) == 1)) __t27_assert_fail("\n node 1 most at-risk:\n find_most_at_risk(array) = {any}\n", .{ find_most_at_risk(array) }); } test "find_most_at_risk_all_healthy" { const array = create_health_array(create_health_metrics(30, 40, 5, 45), create_health_metrics(20, 30, 2, 40), create_health_metrics(25, 35, 3, 42), create_health_metrics(35, 45, 4, 48), 0, 0, 0, 0); const riskiest = find_most_at_risk(array); const risk = calculate_failure_risk(get_health_metrics(array, riskiest), 0); - if (!(risk < 30)) @panic("all nodes healthy"); + if (!(risk < 30)) __t27_assert_fail("\n all nodes healthy:\n risk = {any}\n", .{ risk }); } diff --git a/gen/zig/fault_detection.zig b/gen/zig/fault_detection.zig index 5c98de8b..94e52391 100644 --- a/gen/zig/fault_detection.zig +++ b/gen/zig/fault_detection.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_NODES: u32 = 8; @@ -115,79 +123,79 @@ fn count_failed_nodes(table: [8]u32) u32 { } test "create_node_state_basic" { const state = create_node_state(1, 0, 50, 80); - if (!(get_is_alive(state) == 1)) @panic("alive"); - if (!(get_failure_count(state) == 0)) @panic("no failures"); - if (!(get_last_heartbeat(state) == 50)) @panic("heartbeat"); - if (!(get_link_quality(state) == 80)) @panic("quality"); + if (!(get_is_alive(state) == 1)) __t27_assert_fail("\n alive:\n get_is_alive(state) = {any}\n", .{ get_is_alive(state) }); + if (!(get_failure_count(state) == 0)) __t27_assert_fail("\n no failures:\n get_failure_count(state) = {any}\n", .{ get_failure_count(state) }); + if (!(get_last_heartbeat(state) == 50)) __t27_assert_fail("\n heartbeat:\n get_last_heartbeat(state) = {any}\n", .{ get_last_heartbeat(state) }); + if (!(get_link_quality(state) == 80)) __t27_assert_fail("\n quality:\n get_link_quality(state) = {any}\n", .{ get_link_quality(state) }); } test "is_heartbeat_timeout_detects" { const state = create_node_state(1, 0, 100, 80); - if (!(is_heartbeat_timeout(state, 11000) == true)) @panic("timeout"); + if (!(is_heartbeat_timeout(state, 11000) == true)) __t27_assert_fail("\n timeout:\n is_heartbeat_timeout(state, 11000) = {any}\n", .{ is_heartbeat_timeout(state, 11000) }); } test "is_heartbeat_timeout_not_timeout" { const state = create_node_state(1, 0, 5000, 80); - if (!(is_heartbeat_timeout(state, 8000) == false)) @panic("not timeout"); + if (!(is_heartbeat_timeout(state, 8000) == false)) __t27_assert_fail("\n not timeout:\n is_heartbeat_timeout(state, 8000) = {any}\n", .{ is_heartbeat_timeout(state, 8000) }); } test "detect_node_failure_returns_1_when_timeout" { const state = create_node_state(1, 0, 100, 80); - if (!(detect_node_failure(state, 11000) == 1)) @panic("failure detected"); + if (!(detect_node_failure(state, 11000) == 1)) __t27_assert_fail("\n failure detected:\n detect_node_failure(state, 11000) = {any}\n", .{ detect_node_failure(state, 11000) }); } test "detect_node_failure_returns_0_when_ok" { const state = create_node_state(1, 0, 5000, 80); - if (!(detect_node_failure(state, 8000) == 0)) @panic("no failure"); + if (!(detect_node_failure(state, 8000) == 0)) __t27_assert_fail("\n no failure:\n detect_node_failure(state, 8000) = {any}\n", .{ detect_node_failure(state, 8000) }); } test "increment_failure_count_increments" { const state = create_node_state(1, 1, 5000, 80); const new_state = increment_failure_count(state); - if (!(get_failure_count(new_state) == 2)) @panic("incremented"); + if (!(get_failure_count(new_state) == 2)) __t27_assert_fail("\n incremented:\n get_failure_count(new_state) = {any}\n", .{ get_failure_count(new_state) }); } test "reset_failure_count_clears" { const state = create_node_state(1, 3, 5000, 80); const new_state = reset_failure_count(state, 8000); - if (!(get_failure_count(new_state) == 0)) @panic("cleared"); - if (!(get_last_heartbeat(new_state) == 8000)) @panic("time updated"); + if (!(get_failure_count(new_state) == 0)) __t27_assert_fail("\n cleared:\n get_failure_count(new_state) = {any}\n", .{ get_failure_count(new_state) }); + if (!(get_last_heartbeat(new_state) == 8000)) __t27_assert_fail("\n time updated:\n get_last_heartbeat(new_state) = {any}\n", .{ get_last_heartbeat(new_state) }); } test "is_node_failed_threshold" { const state = create_node_state(1, 3, 5000, 80); - if (!(is_node_failed(state) == true)) @panic("at threshold"); + if (!(is_node_failed(state) == true)) __t27_assert_fail("\n at threshold:\n is_node_failed(state) = {any}\n", .{ is_node_failed(state) }); } test "is_node_failed_below_threshold" { const state = create_node_state(1, 2, 5000, 80); - if (!(is_node_failed(state) == false)) @panic("below threshold"); + if (!(is_node_failed(state) == false)) __t27_assert_fail("\n below threshold:\n is_node_failed(state) = {any}\n", .{ is_node_failed(state) }); } test "is_node_warning" { const state = create_node_state(1, 2, 5000, 80); - if (!(is_node_warning(state) == true)) @panic("warning state"); + if (!(is_node_warning(state) == true)) __t27_assert_fail("\n warning state:\n is_node_warning(state) = {any}\n", .{ is_node_warning(state) }); } test "is_poor_link_detects" { const state = create_node_state(1, 0, 5000, 20); - if (!(is_poor_link(state) == true)) @panic("poor quality"); + if (!(is_poor_link(state) == true)) __t27_assert_fail("\n poor quality:\n is_poor_link(state) = {any}\n", .{ is_poor_link(state) }); } test "is_poor_link_good" { const state = create_node_state(1, 0, 5000, 80); - if (!(is_poor_link(state) == false)) @panic("good quality"); + if (!(is_poor_link(state) == false)) __t27_assert_fail("\n good quality:\n is_poor_link(state) = {any}\n", .{ is_poor_link(state) }); } test "update_link_quality_changes" { const state = create_node_state(1, 0, 5000, 50); const new_state = update_link_quality(state, 90); - if (!(get_link_quality(new_state) == 90)) @panic("quality updated"); + if (!(get_link_quality(new_state) == 90)) __t27_assert_fail("\n quality updated:\n get_link_quality(new_state) = {any}\n", .{ get_link_quality(new_state) }); } test "mark_node_dead" { const state = create_node_state(1, 0, 5000, 80); const new_state = mark_node_dead(state); - if (!(get_is_alive(new_state) == 0)) @panic("marked dead"); + if (!(get_is_alive(new_state) == 0)) __t27_assert_fail("\n marked dead:\n get_is_alive(new_state) = {any}\n", .{ get_is_alive(new_state) }); } test "mark_node_alive" { const state = create_node_state(0, 3, 5000, 80); const new_state = mark_node_alive(state, 8000); - if (!(get_is_alive(new_state) == 1)) @panic("marked alive"); - if (!(get_failure_count(new_state) == 0)) @panic("failures reset"); + if (!(get_is_alive(new_state) == 1)) __t27_assert_fail("\n marked alive:\n get_is_alive(new_state) = {any}\n", .{ get_is_alive(new_state) }); + if (!(get_failure_count(new_state) == 0)) __t27_assert_fail("\n failures reset:\n get_failure_count(new_state) = {any}\n", .{ get_failure_count(new_state) }); } test "count_failed_nodes_multiple" { const table = create_node_table(create_node_state(1, 3, 5000, 80), create_node_state(1, 0, 5000, 80), create_node_state(1, 4, 5000, 80), create_node_state(1, 0, 5000, 80), create_node_state(1, 0, 5000, 80), create_node_state(1, 5, 5000, 80), create_node_state(1, 0, 5000, 80), create_node_state(1, 0, 5000, 80)); - if (!(count_failed_nodes(table) == 3)) @panic("3 failed nodes"); + if (!(count_failed_nodes(table) == 3)) __t27_assert_fail("\n 3 failed nodes:\n count_failed_nodes(table) = {any}\n", .{ count_failed_nodes(table) }); } test "count_failed_nodes_zero" { const table = create_node_table(create_node_state(1, 0, 5000, 80), create_node_state(1, 0, 5000, 80), create_node_state(1, 0, 5000, 80), create_node_state(1, 0, 5000, 80), create_node_state(1, 0, 5000, 80), create_node_state(1, 0, 5000, 80), create_node_state(1, 0, 5000, 80), create_node_state(1, 0, 5000, 80)); - if (!(count_failed_nodes(table) == 0)) @panic("0 failed nodes"); + if (!(count_failed_nodes(table) == 0)) __t27_assert_fail("\n 0 failed nodes:\n count_failed_nodes(table) = {any}\n", .{ count_failed_nodes(table) }); } diff --git a/gen/zig/flow_control.zig b/gen/zig/flow_control.zig index bef92c38..0a6e6fa3 100644 --- a/gen/zig/flow_control.zig +++ b/gen/zig/flow_control.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_FLOWS: u32 = 8; @@ -202,27 +210,27 @@ fn release_backpressure(flows: [MAX_FLOWS]u32, flow_index: u32) u32 { } test "flow_state_roundtrip" { const f = create_flow_state(3, 7, 16, 9); - if (!(get_sender_id(f) == 3)) @panic("sender"); - if (!(get_receiver_id(f) == 7)) @panic("receiver"); - if (!(get_window_size(f) == 16)) @panic("window"); - if (!(get_credits(f) == 9)) @panic("credits"); + if (!(get_sender_id(f) == 3)) __t27_assert_fail("\n sender:\n get_sender_id(f) = {any}\n", .{ get_sender_id(f) }); + if (!(get_receiver_id(f) == 7)) __t27_assert_fail("\n receiver:\n get_receiver_id(f) = {any}\n", .{ get_receiver_id(f) }); + if (!(get_window_size(f) == 16)) __t27_assert_fail("\n window:\n get_window_size(f) = {any}\n", .{ get_window_size(f) }); + if (!(get_credits(f) == 9)) __t27_assert_fail("\n credits:\n get_credits(f) = {any}\n", .{ get_credits(f) }); } test "credit_lifecycle" { var f = create_flow_state(1, 2, 16, 1); f = consume_credit(f); - if (!(get_credits(f) == 0)) @panic("credit consumed"); + if (!(get_credits(f) == 0)) __t27_assert_fail("\n credit consumed:\n get_credits(f) = {any}\n", .{ get_credits(f) }); f = consume_credit(f); - if (!(get_credits(f) == 0)) @panic("no underflow at zero"); + if (!(get_credits(f) == 0)) __t27_assert_fail("\n no underflow at zero:\n get_credits(f) = {any}\n", .{ get_credits(f) }); f = add_credits(f, 100); - if (!(get_credits(f) == 16)) @panic("credits cap at the window"); + if (!(get_credits(f) == 16)) __t27_assert_fail("\n credits cap at the window:\n get_credits(f) = {any}\n", .{ get_credits(f) }); } test "backpressure_levels" { var f = create_flow_state(1, 2, 16, 2); - if (!(is_under_backpressure(f) == 1)) @panic("14 used is backpressure"); - if (!(calculate_backpressure_level(f) == 2)) @panic("high level"); + if (!(is_under_backpressure(f) == 1)) __t27_assert_fail("\n 14 used is backpressure:\n is_under_backpressure(f) = {any}\n", .{ is_under_backpressure(f) }); + if (!(calculate_backpressure_level(f) == 2)) __t27_assert_fail("\n high level:\n calculate_backpressure_level(f) = {any}\n", .{ calculate_backpressure_level(f) }); f = create_flow_state(1, 2, 16, 10); - if (!(is_under_backpressure(f) == 0)) @panic("6 used is fine"); - if (!(calculate_backpressure_level(f) == 1)) @panic("moderate level"); + if (!(is_under_backpressure(f) == 0)) __t27_assert_fail("\n 6 used is fine:\n is_under_backpressure(f) = {any}\n", .{ is_under_backpressure(f) }); + if (!(calculate_backpressure_level(f) == 1)) __t27_assert_fail("\n moderate level:\n calculate_backpressure_level(f) = {any}\n", .{ calculate_backpressure_level(f) }); f = create_flow_state(1, 2, 16, 14); - if (!(calculate_backpressure_level(f) == 0)) @panic("2 used is no backpressure"); + if (!(calculate_backpressure_level(f) == 0)) __t27_assert_fail("\n 2 used is no backpressure:\n calculate_backpressure_level(f) = {any}\n", .{ calculate_backpressure_level(f) }); } diff --git a/gen/zig/fpga_synthesis_report.zig b/gen/zig/fpga_synthesis_report.zig index 185374ce..4847185a 100644 --- a/gen/zig/fpga_synthesis_report.zig +++ b/gen/zig/fpga_synthesis_report.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const RESOURCE_LUT: u32 = 1; @@ -61,75 +69,75 @@ fn extract_bram(summary: u32) u32 { } test "create_synthesis_result_correct" { const result = create_synthesis_result(500, 100, 75); - if (!(extract_utilization(result) == 500)) @panic("utilization"); - if (!(extract_timing_slack(result) == 100)) @panic("slack"); - if (!(extract_achieved_freq(result) == 75)) @panic("frequency"); + if (!(extract_utilization(result) == 500)) __t27_assert_fail("\n utilization:\n extract_utilization(result) = {any}\n", .{ extract_utilization(result) }); + if (!(extract_timing_slack(result) == 100)) __t27_assert_fail("\n slack:\n extract_timing_slack(result) = {any}\n", .{ extract_timing_slack(result) }); + if (!(extract_achieved_freq(result) == 75)) __t27_assert_fail("\n frequency:\n extract_achieved_freq(result) = {any}\n", .{ extract_achieved_freq(result) }); } test "timing_met_positive_slack" { const result = create_synthesis_result(500, 50, 100); - if (!(timing_met(result) == true)) @panic("positive slack = met"); + if (!(timing_met(result) == true)) __t27_assert_fail("\n positive slack = met:\n timing_met(result) = {any}\n", .{ timing_met(result) }); } test "timing_met_zero_slack" { const result = create_synthesis_result(500, 0, 100); - if (!(timing_met(result) == false)) @panic("zero slack = not met"); + if (!(timing_met(result) == false)) __t27_assert_fail("\n zero slack = not met:\n timing_met(result) = {any}\n", .{ timing_met(result) }); } test "timing_met_negative_slack" { const result = create_synthesis_result(500, 0, 100); - if (!(timing_met(result) == false)) @panic("zero or less = not met"); + if (!(timing_met(result) == false)) __t27_assert_fail("\n zero or less = not met:\n timing_met(result) = {any}\n", .{ timing_met(result) }); } test "utilization_acceptable_under_80" { const result = create_synthesis_result(750, 50, 100); - if (!(utilization_acceptable(result) == true)) @panic("75% acceptable"); + if (!(utilization_acceptable(result) == true)) __t27_assert_fail("\n 75% acceptable:\n utilization_acceptable(result) = {any}\n", .{ utilization_acceptable(result) }); } test "utilization_acceptable_over_80" { const result = create_synthesis_result(850, 50, 100); - if (!(utilization_acceptable(result) == false)) @panic("85% not acceptable"); + if (!(utilization_acceptable(result) == false)) __t27_assert_fail("\n 85% not acceptable:\n utilization_acceptable(result) = {any}\n", .{ utilization_acceptable(result) }); } test "calculate_resource_percentage_half" { const pct = calculate_resource_percentage(50, 100); - if (!(pct == 50)) @panic("50% utilization"); + if (!(pct == 50)) __t27_assert_fail("\n 50% utilization:\n pct = {any}\n", .{ pct }); } test "calculate_resource_percentage_full" { const pct = calculate_resource_percentage(100, 100); - if (!(pct == 100)) @panic("100% utilization"); + if (!(pct == 100)) __t27_assert_fail("\n 100% utilization:\n pct = {any}\n", .{ pct }); } test "calculate_resource_percentage_zero_max" { const pct = calculate_resource_percentage(50, 0); - if (!(pct == 0)) @panic("zero max = 0%"); + if (!(pct == 0)) __t27_assert_fail("\n zero max = 0%:\n pct = {any}\n", .{ pct }); } test "estimate_total_resources_calculates" { const lut, const ff = estimate_total_resources(19, 500, 300); - if (!(lut == 9500)) @panic("total LUT"); - if (!(ff == 5700)) @panic("total FF"); + if (!(lut == 9500)) __t27_assert_fail("\n total LUT:\n lut = {any}\n", .{ lut }); + if (!(ff == 5700)) __t27_assert_fail("\n total FF:\n ff = {any}\n", .{ ff }); } test "frequency_achievable_met" { const result = create_synthesis_result(500, 50, 100); - if (!(frequency_achievable(result, 75) == true)) @panic("100MHz >= 75MHz"); + if (!(frequency_achievable(result, 75) == true)) __t27_assert_fail("\n 100MHz >= 75MHz:\n frequency_achievable(result, 75) = {any}\n", .{ frequency_achievable(result, 75) }); } test "frequency_achievable_not_met" { const result = create_synthesis_result(500, 50, 60); - if (!(frequency_achievable(result, 75) == false)) @panic("60MHz < 75MHz"); + if (!(frequency_achievable(result, 75) == false)) __t27_assert_fail("\n 60MHz < 75MHz:\n frequency_achievable(result, 75) = {any}\n", .{ frequency_achievable(result, 75) }); } test "create_resource_summary_correct" { const summary = create_resource_summary(1000, 800, 10, 5); - if (!(extract_lut(summary) == 1000)) @panic("LUT count"); - if (!(extract_ff(summary) == 800)) @panic("FF count"); - if (!(extract_dsp(summary) == 10)) @panic("DSP count"); - if (!(extract_bram(summary) == 5)) @panic("BRAM count"); + if (!(extract_lut(summary) == 1000)) __t27_assert_fail("\n LUT count:\n extract_lut(summary) = {any}\n", .{ extract_lut(summary) }); + if (!(extract_ff(summary) == 800)) __t27_assert_fail("\n FF count:\n extract_ff(summary) = {any}\n", .{ extract_ff(summary) }); + if (!(extract_dsp(summary) == 10)) __t27_assert_fail("\n DSP count:\n extract_dsp(summary) = {any}\n", .{ extract_dsp(summary) }); + if (!(extract_bram(summary) == 5)) __t27_assert_fail("\n BRAM count:\n extract_bram(summary) = {any}\n", .{ extract_bram(summary) }); } test "extract_lut_correct" { const summary = create_resource_summary(1500, 1200, 8, 4); - if (!(extract_lut(summary) == 1500)) @panic("LUT extraction"); + if (!(extract_lut(summary) == 1500)) __t27_assert_fail("\n LUT extraction:\n extract_lut(summary) = {any}\n", .{ extract_lut(summary) }); } test "extract_ff_correct" { const summary = create_resource_summary(1500, 1200, 8, 4); - if (!(extract_ff(summary) == 1200)) @panic("FF extraction"); + if (!(extract_ff(summary) == 1200)) __t27_assert_fail("\n FF extraction:\n extract_ff(summary) = {any}\n", .{ extract_ff(summary) }); } test "extract_dsp_correct" { const summary = create_resource_summary(1500, 1200, 8, 4); - if (!(extract_dsp(summary) == 8)) @panic("DSP extraction"); + if (!(extract_dsp(summary) == 8)) __t27_assert_fail("\n DSP extraction:\n extract_dsp(summary) = {any}\n", .{ extract_dsp(summary) }); } test "extract_bram_correct" { const summary = create_resource_summary(1500, 1200, 8, 4); - if (!(extract_bram(summary) == 4)) @panic("BRAM extraction"); + if (!(extract_bram(summary) == 4)) __t27_assert_fail("\n BRAM extraction:\n extract_bram(summary) = {any}\n", .{ extract_bram(summary) }); } diff --git a/gen/zig/frame_buffer.zig b/gen/zig/frame_buffer.zig index af8937b2..9add5ca9 100644 --- a/gen/zig/frame_buffer.zig +++ b/gen/zig/frame_buffer.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module fn get_src(meta: u32) u8 { @@ -24,42 +32,42 @@ fn empty_meta() u32 { return 0; } test "empty_meta_invalid" { - if (!(get_valid(empty_meta()) == false)) @panic("invalid"); + if (!(get_valid(empty_meta()) == false)) __t27_assert_fail("\n invalid:\n get_valid(empty_meta()) = {any}\n", .{ get_valid(empty_meta()) }); } test "create_meta_valid" { const meta = create_meta(1, 2, 8); if (!(get_valid(meta))) @panic("valid"); } test "get_src_field" { - if (!(get_src(create_meta(5, 2, 8)) == 5)) @panic("src"); + if (!(get_src(create_meta(5, 2, 8)) == 5)) __t27_assert_fail("\n src:\n get_src(create_meta(5, 2, 8)) = {any}\n", .{ get_src(create_meta(5, 2, 8)) }); } test "get_dst_field" { - if (!(get_dst(create_meta(1, 7, 8)) == 7)) @panic("dst"); + if (!(get_dst(create_meta(1, 7, 8)) == 7)) __t27_assert_fail("\n dst:\n get_dst(create_meta(1, 7, 8)) = {any}\n", .{ get_dst(create_meta(1, 7, 8)) }); } test "get_ttl_field" { - if (!(get_ttl(create_meta(1, 2, 15)) == 15)) @panic("ttl"); + if (!(get_ttl(create_meta(1, 2, 15)) == 15)) __t27_assert_fail("\n ttl:\n get_ttl(create_meta(1, 2, 15)) = {any}\n", .{ get_ttl(create_meta(1, 2, 15)) }); } test "roundtrip" { const meta = create_meta(3, 5, 10); - if (!(get_src(meta) == 3)) @panic("src"); - if (!(get_dst(meta) == 5)) @panic("dst"); - if (!(get_ttl(meta) == 10)) @panic("ttl"); + if (!(get_src(meta) == 3)) __t27_assert_fail("\n src:\n get_src(meta) = {any}\n", .{ get_src(meta) }); + if (!(get_dst(meta) == 5)) __t27_assert_fail("\n dst:\n get_dst(meta) = {any}\n", .{ get_dst(meta) }); + if (!(get_ttl(meta) == 10)) __t27_assert_fail("\n ttl:\n get_ttl(meta) = {any}\n", .{ get_ttl(meta) }); } test "invalid_flag" { - if (!(get_valid(0) == false)) @panic("zero invalid"); + if (!(get_valid(0) == false)) __t27_assert_fail("\n zero invalid:\n get_valid(0) = {any}\n", .{ get_valid(0) }); } test "field_independence" { const m1 = create_meta(1, 2, 3); const m2 = create_meta(4, 5, 6); - if (!(get_src(m1) == 1)) @panic("m1 src"); - if (!(get_dst(m2) == 5)) @panic("m2 dst"); + if (!(get_src(m1) == 1)) __t27_assert_fail("\n m1 src:\n get_src(m1) = {any}\n", .{ get_src(m1) }); + if (!(get_dst(m2) == 5)) __t27_assert_fail("\n m2 dst:\n get_dst(m2) = {any}\n", .{ get_dst(m2) }); } test "zero_ttl" { const meta = create_meta(1, 2, 0); - if (!(get_ttl(meta) == 0)) @panic("zero ok"); + if (!(get_ttl(meta) == 0)) __t27_assert_fail("\n zero ok:\n get_ttl(meta) = {any}\n", .{ get_ttl(meta) }); } test "max_values" { const meta = create_meta(15, 15, 15); - if (!(get_src(meta) == 15)) @panic("max src"); - if (!(get_dst(meta) == 15)) @panic("max dst"); + if (!(get_src(meta) == 15)) __t27_assert_fail("\n max src:\n get_src(meta) = {any}\n", .{ get_src(meta) }); + if (!(get_dst(meta) == 15)) __t27_assert_fail("\n max dst:\n get_dst(meta) = {any}\n", .{ get_dst(meta) }); } diff --git a/gen/zig/gf16_format.zig b/gen/zig/gf16_format.zig index 2e7227d0..6d486d90 100644 --- a/gen/zig/gf16_format.zig +++ b/gen/zig/gf16_format.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const M_BITS: u32 = 9; @@ -39,22 +47,52 @@ fn is_zero(bits: u32) bool { return (bits & 32767) == 0; } test "field_widths_fill_sixteen_bits" { + const total = (1 + E_BITS) + M_BITS; + if (!(total == 16)) __t27_assert_fail("\n assertion failed:\n total = {any}\n", .{ total }); } test "masks_match_widths" { + const m = M_MAX; + const e = E_MAX; + if (!(m == 511)) __t27_assert_fail("\n assertion failed:\n m = {any}\n", .{ m }); + if (!(e == 63)) __t27_assert_fail("\n assertion failed:\n e = {any}\n", .{ e }); } test "compose_extract_roundtrip" { + const bits = compose(1, 42, 300); + _ = bits; // dead after const-inlining + const s = sign_field(compose(1, 42, 300)); + const e = exponent_field(compose(1, 42, 300)); + const m = mantissa_field(compose(1, 42, 300)); + if (!(s == 1)) __t27_assert_fail("\n assertion failed:\n s = {any}\n", .{ s }); + if (!(e == 42)) __t27_assert_fail("\n assertion failed:\n e = {any}\n", .{ e }); + if (!(m == 300)) __t27_assert_fail("\n assertion failed:\n m = {any}\n", .{ m }); } test "nan_is_allones_exponent_nonzero_mantissa" { + const nan = is_nan(compose(0, 63, 1)); + const inf_not_nan = is_nan(compose(0, 63, 0)); + if (!(nan == true)) __t27_assert_fail("\n assertion failed:\n nan = {any}\n", .{ nan }); + if (!(inf_not_nan == false)) __t27_assert_fail("\n assertion failed:\n inf_not_nan = {any}\n", .{ inf_not_nan }); } test "inf_is_allones_exponent_zero_mantissa" { + const inf = is_inf(compose(0, 63, 0)); + const neg_inf = is_inf(compose(1, 63, 0)); + const normal = is_inf(compose(0, 42, 300)); + if (!(inf == true)) __t27_assert_fail("\n assertion failed:\n inf = {any}\n", .{ inf }); + if (!(neg_inf == true)) __t27_assert_fail("\n assertion failed:\n neg_inf = {any}\n", .{ neg_inf }); + if (!(normal == false)) __t27_assert_fail("\n assertion failed:\n normal = {any}\n", .{ normal }); } test "zero_ignores_sign" { + const pz = is_zero(0); + const nz = is_zero(compose(1, 0, 0)); + const not_zero = is_zero(compose(0, 0, 1)); + if (!(pz == true)) __t27_assert_fail("\n assertion failed:\n pz = {any}\n", .{ pz }); + if (!(nz == true)) __t27_assert_fail("\n assertion failed:\n nz = {any}\n", .{ nz }); + if (!(not_zero == false)) __t27_assert_fail("\n assertion failed:\n not_zero = {any}\n", .{ not_zero }); } comptime { // invariant: bias_is_31 - // invariant: bias_is_31 verified (no statements) + if (!(BIAS == 31)) __t27_assert_fail("\n assertion failed:\n BIAS = {any}\n", .{ BIAS }); } comptime { // invariant: mantissa_width_is_9 - // invariant: mantissa_width_is_9 verified (no statements) + if (!(M_BITS == 9)) __t27_assert_fail("\n assertion failed:\n M_BITS = {any}\n", .{ M_BITS }); } diff --git a/gen/zig/hardware_validation.zig b/gen/zig/hardware_validation.zig index cb24757a..38e7413b 100644 --- a/gen/zig/hardware_validation.zig +++ b/gen/zig/hardware_validation.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const VAL_PENDING: u32 = 0; @@ -72,74 +80,74 @@ fn extract_metric_unit(metric: u32) u32 { } test "create_test_result_correct" { const result = create_test_result(VAL_PASSED, TEST_SIMULATION, 0, 1000); - if (!(extract_state(result) == VAL_PASSED)) @panic("state"); - if (!(extract_test_type(result) == TEST_SIMULATION)) @panic("type"); - if (!(extract_errors(result) == 0)) @panic("errors"); - if (!(extract_iterations(result) == 1000)) @panic("iterations"); + if (!(extract_state(result) == VAL_PASSED)) __t27_assert_fail("\n state:\n extract_state(result) = {any}\n VAL_PASSED = {any}\n", .{ extract_state(result), VAL_PASSED }); + if (!(extract_test_type(result) == TEST_SIMULATION)) __t27_assert_fail("\n type:\n extract_test_type(result) = {any}\n TEST_SIMULATION = {any}\n", .{ extract_test_type(result), TEST_SIMULATION }); + if (!(extract_errors(result) == 0)) __t27_assert_fail("\n errors:\n extract_errors(result) = {any}\n", .{ extract_errors(result) }); + if (!(extract_iterations(result) == 1000)) __t27_assert_fail("\n iterations:\n extract_iterations(result) = {any}\n", .{ extract_iterations(result) }); } test "calculate_pass_rate_perfect" { const rate = calculate_pass_rate(100, 100); - if (!(rate == 100)) @panic("100% pass rate"); + if (!(rate == 100)) __t27_assert_fail("\n 100% pass rate:\n rate = {any}\n", .{ rate }); } test "calculate_pass_rate_half" { const rate = calculate_pass_rate(50, 100); - if (!(rate == 50)) @panic("50% pass rate"); + if (!(rate == 50)) __t27_assert_fail("\n 50% pass rate:\n rate = {any}\n", .{ rate }); } test "calculate_pass_rate_zero" { const rate = calculate_pass_rate(0, 100); - if (!(rate == 0)) @panic("0% pass rate"); + if (!(rate == 0)) __t27_assert_fail("\n 0% pass rate:\n rate = {any}\n", .{ rate }); } test "calculate_pass_rate_zero_total" { const rate = calculate_pass_rate(50, 0); - if (!(rate == 0)) @panic("zero total = 0%"); + if (!(rate == 0)) __t27_assert_fail("\n zero total = 0%:\n rate = {any}\n", .{ rate }); } test "test_passed_yes" { const result = create_test_result(VAL_PASSED, TEST_SIMULATION, 0, 100); - if (!(test_passed(result) == true)) @panic("no errors + passed state"); + if (!(test_passed(result) == true)) __t27_assert_fail("\n no errors + passed state:\n test_passed(result) = {any}\n", .{ test_passed(result) }); } test "test_passed_no_errors_but_pending" { const result = create_test_result(VAL_PENDING, TEST_SIMULATION, 0, 100); - if (!(test_passed(result) == false)) @panic("pending state"); + if (!(test_passed(result) == false)) __t27_assert_fail("\n pending state:\n test_passed(result) = {any}\n", .{ test_passed(result) }); } test "test_passed_errors" { const result = create_test_result(VAL_PASSED, TEST_SIMULATION, 5, 100); - if (!(test_passed(result) == false)) @panic("has errors"); + if (!(test_passed(result) == false)) __t27_assert_fail("\n has errors:\n test_passed(result) = {any}\n", .{ test_passed(result) }); } test "bit_accurate_exact_match" { - if (!(bit_accurate(0x12345678, 0x12345678, 0xFFFFFFFF) == true)) @panic("exact match"); + if (!(bit_accurate(0x12345678, 0x12345678, 0xFFFFFFFF) == true)) __t27_assert_fail("\n exact match:\n bit_accurate(0x12345678, 0x12345678, 0xFFFFFFFF) = {any}\n", .{ bit_accurate(0x12345678, 0x12345678, 0xFFFFFFFF) }); } test "bit_accurate_tolerance" { - if (!(bit_accurate(0x12345678, 0x12345670, 0x000000FF) == true)) @panic("tolerance OK"); + if (!(bit_accurate(0x12345678, 0x12345670, 0x000000FF) == true)) __t27_assert_fail("\n tolerance OK:\n bit_accurate(0x12345678, 0x12345670, 0x000000FF) = {any}\n", .{ bit_accurate(0x12345678, 0x12345670, 0x000000FF) }); } test "bit_accurate_fail" { - if (!(bit_accurate(0x12345678, 0x1234FF78, 0x000000FF) == false)) @panic("diff outside tolerated bits"); + if (!(bit_accurate(0x12345678, 0x1234FF78, 0x000000FF) == false)) __t27_assert_fail("\n diff outside tolerated bits:\n bit_accurate(0x12345678, 0x1234FF78, 0x000000FF) = {any}\n", .{ bit_accurate(0x12345678, 0x1234FF78, 0x000000FF) }); } test "fpga_board_ready_yes" { const result = create_test_result(VAL_PASSED, TEST_FPGA_BOARD, 0, 100); - if (!(fpga_board_ready(result) == true)) @panic("FPGA board ready"); + if (!(fpga_board_ready(result) == true)) __t27_assert_fail("\n FPGA board ready:\n fpga_board_ready(result) = {any}\n", .{ fpga_board_ready(result) }); } test "fpga_board_ready_no" { const result = create_test_result(VAL_PASSED, TEST_SIMULATION, 0, 100); - if (!(fpga_board_ready(result) == false)) @panic("not FPGA test"); + if (!(fpga_board_ready(result) == false)) __t27_assert_fail("\n not FPGA test:\n fpga_board_ready(result) = {any}\n", .{ fpga_board_ready(result) }); } test "create_packet_capture_correct" { const capture = create_packet_capture(1, 2, 0xAB, 100); - if (!(extract_capture_src(capture) == 1)) @panic("src"); - if (!(extract_capture_dst(capture) == 2)) @panic("dst"); - if (!(extract_capture_payload(capture) == 0xAB)) @panic("payload"); - if (!(extract_capture_timestamp(capture) == 100)) @panic("timestamp"); + if (!(extract_capture_src(capture) == 1)) __t27_assert_fail("\n src:\n extract_capture_src(capture) = {any}\n", .{ extract_capture_src(capture) }); + if (!(extract_capture_dst(capture) == 2)) __t27_assert_fail("\n dst:\n extract_capture_dst(capture) = {any}\n", .{ extract_capture_dst(capture) }); + if (!(extract_capture_payload(capture) == 0xAB)) __t27_assert_fail("\n payload:\n extract_capture_payload(capture) = {any}\n", .{ extract_capture_payload(capture) }); + if (!(extract_capture_timestamp(capture) == 100)) __t27_assert_fail("\n timestamp:\n extract_capture_timestamp(capture) = {any}\n", .{ extract_capture_timestamp(capture) }); } test "create_performance_metric_correct" { const metric = create_performance_metric(5, 1000, 1); - if (!(extract_metric_type(metric) == 5)) @panic("type"); - if (!(extract_metric_value(metric) == 1000)) @panic("value"); - if (!(extract_metric_unit(metric) == 1)) @panic("unit"); + if (!(extract_metric_type(metric) == 5)) __t27_assert_fail("\n type:\n extract_metric_type(metric) = {any}\n", .{ extract_metric_type(metric) }); + if (!(extract_metric_value(metric) == 1000)) __t27_assert_fail("\n value:\n extract_metric_value(metric) = {any}\n", .{ extract_metric_value(metric) }); + if (!(extract_metric_unit(metric) == 1)) __t27_assert_fail("\n unit:\n extract_metric_unit(metric) = {any}\n", .{ extract_metric_unit(metric) }); } test "extract_metric_value_large" { const metric = create_performance_metric(3, 0xFFFFFF, 2); - if (!(extract_metric_value(metric) == 0xFFFFFF)) @panic("max value"); + if (!(extract_metric_value(metric) == 0xFFFFFF)) __t27_assert_fail("\n max value:\n extract_metric_value(metric) = {any}\n", .{ extract_metric_value(metric) }); } test "extract_metric_type_boundary" { const metric = create_performance_metric(0xF, 1000, 0); - if (!(extract_metric_type(metric) == 0xF)) @panic("max type"); + if (!(extract_metric_type(metric) == 0xF)) __t27_assert_fail("\n max type:\n extract_metric_type(metric) = {any}\n", .{ extract_metric_type(metric) }); } diff --git a/gen/zig/health_dashboard.zig b/gen/zig/health_dashboard.zig index 1d2643ba..404cbf3d 100644 --- a/gen/zig/health_dashboard.zig +++ b/gen/zig/health_dashboard.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_NODES: u32 = 8; @@ -282,21 +290,21 @@ fn calculate_uptime(total_uptime: u32, total_time: u32) u32 { } test "health_metric_roundtrip" { const m = create_health_metric(4, METRIC_LATENCY, 35, 200); - if (!(get_health_node_id(m) == 4)) @panic("node id"); - if (!(get_health_metric_type(m) == METRIC_LATENCY)) @panic("metric type"); - if (!(get_health_value(m) == 35)) @panic("value"); - if (!(get_health_timestamp(m) == 200)) @panic("timestamp"); + if (!(get_health_node_id(m) == 4)) __t27_assert_fail("\n node id:\n get_health_node_id(m) = {any}\n", .{ get_health_node_id(m) }); + if (!(get_health_metric_type(m) == METRIC_LATENCY)) __t27_assert_fail("\n metric type:\n get_health_metric_type(m) = {any}\n METRIC_LATENCY = {any}\n", .{ get_health_metric_type(m), METRIC_LATENCY }); + if (!(get_health_value(m) == 35)) __t27_assert_fail("\n value:\n get_health_value(m) = {any}\n", .{ get_health_value(m) }); + if (!(get_health_timestamp(m) == 200)) __t27_assert_fail("\n timestamp:\n get_health_timestamp(m) = {any}\n", .{ get_health_timestamp(m) }); } test "node_health_mixes_metric_polarity" { - const ms: [16]u32 = .{ create_health_metric(1,METRIC_CPU,20,0), create_health_metric(1,METRIC_BANDWIDTH,90,1), create_health_metric(1,METRIC_LATENCY,30,2), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - if (!(calculate_node_health(ms, 3) == 80)) @panic("polarity-aware mean"); + const ms: [16]u32 = .{ create_health_metric(1, METRIC_CPU, 20, 0), create_health_metric(1, METRIC_BANDWIDTH, 90, 1), create_health_metric(1, METRIC_LATENCY, 30, 2), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + if (!(calculate_node_health(ms, 3) == 80)) __t27_assert_fail("\n polarity-aware mean:\n calculate_node_health(ms, 3) = {any}\n", .{ calculate_node_health(ms, 3) }); } test "node_health_saturates_out_of_range" { - const ms: [16]u32 = .{ create_health_metric(1,METRIC_LATENCY,200,0), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - if (!(calculate_node_health(ms, 1) == 0)) @panic("out-of-range metric floors at 0"); + const ms: [16]u32 = .{ create_health_metric(1, METRIC_LATENCY, 200, 0), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + if (!(calculate_node_health(ms, 1) == 0)) __t27_assert_fail("\n out-of-range metric floors at 0:\n calculate_node_health(ms, 1) = {any}\n", .{ calculate_node_health(ms, 1) }); } test "network_health_average" { const nodes: [8]u32 = .{ 90, 70, 80, 0, 0, 0, 0, 0 }; - if (!(calculate_network_health(nodes, 3) == 80)) @panic("network mean"); - if (!(calculate_network_health(nodes, 0) == 100)) @panic("no nodes is healthy"); + if (!(calculate_network_health(nodes, 3) == 80)) __t27_assert_fail("\n network mean:\n calculate_network_health(nodes, 3) = {any}\n", .{ calculate_network_health(nodes, 3) }); + if (!(calculate_network_health(nodes, 0) == 100)) __t27_assert_fail("\n no nodes is healthy:\n calculate_network_health(nodes, 0) = {any}\n", .{ calculate_network_health(nodes, 0) }); } diff --git a/gen/zig/health_monitoring.zig b/gen/zig/health_monitoring.zig index 67356347..272cffdd 100644 --- a/gen/zig/health_monitoring.zig +++ b/gen/zig/health_monitoring.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_CHECKS: u32 = 8; @@ -265,41 +273,41 @@ fn get_health_percentage(array: [8]u32) u32 { } test "create_health_check_basic" { const check = create_health_check(CHECK_CPU, RESULT_PASS, 50, 100); - if (!(get_check_type(check) == CHECK_CPU)) @panic("type"); - if (!(get_check_result(check) == RESULT_PASS)) @panic("result"); - if (!(get_check_value(check) == 50)) @panic("value"); - if (!(get_check_timestamp(check) == 100)) @panic("timestamp"); + if (!(get_check_type(check) == CHECK_CPU)) __t27_assert_fail("\n type:\n get_check_type(check) = {any}\n CHECK_CPU = {any}\n", .{ get_check_type(check), CHECK_CPU }); + if (!(get_check_result(check) == RESULT_PASS)) __t27_assert_fail("\n result:\n get_check_result(check) = {any}\n RESULT_PASS = {any}\n", .{ get_check_result(check), RESULT_PASS }); + if (!(get_check_value(check) == 50)) __t27_assert_fail("\n value:\n get_check_value(check) = {any}\n", .{ get_check_value(check) }); + if (!(get_check_timestamp(check) == 100)) __t27_assert_fail("\n timestamp:\n get_check_timestamp(check) = {any}\n", .{ get_check_timestamp(check) }); } test "calculate_overall_health_critical" { const array = create_health_array(create_health_check(CHECK_CPU, RESULT_PASS, 50, 100), create_health_check(CHECK_MEMORY, RESULT_FAIL, 90, 101), create_health_check(CHECK_DISK, RESULT_PASS, 40, 102), create_health_check(CHECK_NETWORK, RESULT_PASS, 60, 103), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0)); - if (!(calculate_overall_health(array) == HEALTH_CRITICAL)) @panic("critical health"); + if (!(calculate_overall_health(array) == HEALTH_CRITICAL)) __t27_assert_fail("\n critical health:\n calculate_overall_health(array) = {any}\n HEALTH_CRITICAL = {any}\n", .{ calculate_overall_health(array), HEALTH_CRITICAL }); } test "calculate_overall_health_warning" { const array = create_health_array(create_health_check(CHECK_CPU, RESULT_WARN, 70, 100), create_health_check(CHECK_MEMORY, RESULT_WARN, 80, 101), create_health_check(CHECK_DISK, RESULT_WARN, 75, 102), create_health_check(CHECK_NETWORK, RESULT_PASS, 60, 103), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0)); - if (!(calculate_overall_health(array) == HEALTH_WARNING)) @panic("warning health"); + if (!(calculate_overall_health(array) == HEALTH_WARNING)) __t27_assert_fail("\n warning health:\n calculate_overall_health(array) = {any}\n HEALTH_WARNING = {any}\n", .{ calculate_overall_health(array), HEALTH_WARNING }); } test "calculate_overall_health_healthy" { const array = create_health_array(create_health_check(CHECK_CPU, RESULT_PASS, 50, 100), create_health_check(CHECK_MEMORY, RESULT_PASS, 40, 101), create_health_check(CHECK_DISK, RESULT_PASS, 45, 102), create_health_check(CHECK_NETWORK, RESULT_PASS, 35, 103), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0)); - if (!(calculate_overall_health(array) == HEALTH_HEALTHY)) @panic("healthy"); + if (!(calculate_overall_health(array) == HEALTH_HEALTHY)) __t27_assert_fail("\n healthy:\n calculate_overall_health(array) = {any}\n HEALTH_HEALTHY = {any}\n", .{ calculate_overall_health(array), HEALTH_HEALTHY }); } test "count_failed_checks_multiple" { const array = create_health_array(create_health_check(CHECK_CPU, RESULT_FAIL, 95, 100), create_health_check(CHECK_MEMORY, RESULT_FAIL, 90, 101), create_health_check(CHECK_DISK, RESULT_PASS, 40, 102), create_health_check(CHECK_NETWORK, RESULT_FAIL, 85, 103), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0)); - if (!(count_failed_checks(array) == 3)) @panic("3 failed checks"); + if (!(count_failed_checks(array) == 3)) __t27_assert_fail("\n 3 failed checks:\n count_failed_checks(array) = {any}\n", .{ count_failed_checks(array) }); } test "count_warning_checks_multiple" { const array = create_health_array(create_health_check(CHECK_CPU, RESULT_WARN, 70, 100), create_health_check(CHECK_MEMORY, RESULT_WARN, 75, 101), create_health_check(CHECK_DISK, RESULT_PASS, 40, 102), create_health_check(CHECK_NETWORK, RESULT_WARN, 72, 103), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0)); - if (!(count_warning_checks(array) == 3)) @panic("3 warning checks"); + if (!(count_warning_checks(array) == 3)) __t27_assert_fail("\n 3 warning checks:\n count_warning_checks(array) = {any}\n", .{ count_warning_checks(array) }); } test "update_health_check_works" { const array = create_health_array(create_health_check(CHECK_CPU, RESULT_PASS, 50, 100), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0)); const new_array = update_health_check(array, 1, create_health_check(CHECK_MEMORY, RESULT_FAIL, 90, 200)); - if (!(get_check_result(get_health_check(new_array, 1)) == RESULT_FAIL)) @panic("check updated"); + if (!(get_check_result(get_health_check(new_array, 1)) == RESULT_FAIL)) __t27_assert_fail("\n check updated:\n get_check_result(get_health_check(new_array, 1)) = {any}\n RESULT_FAIL = {any}\n", .{ get_check_result(get_health_check(new_array, 1)), RESULT_FAIL }); } test "get_health_percentage_all_pass" { const array = create_health_array(create_health_check(CHECK_CPU, RESULT_PASS, 50, 100), create_health_check(CHECK_MEMORY, RESULT_PASS, 40, 101), create_health_check(CHECK_DISK, RESULT_PASS, 45, 102), create_health_check(CHECK_NETWORK, RESULT_PASS, 35, 103), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0), create_health_check(0, 0, 0, 0)); - if (!(get_health_percentage(array) == 100)) @panic("100% healthy"); + if (!(get_health_percentage(array) == 100)) __t27_assert_fail("\n 100% healthy:\n get_health_percentage(array) = {any}\n", .{ get_health_percentage(array) }); } test "get_health_percentage_some_fail" { const array = create_health_array(create_health_check(CHECK_CPU, RESULT_FAIL, 95, 100), create_health_check(CHECK_MEMORY, RESULT_PASS, 40, 101), create_health_check(CHECK_DISK, RESULT_FAIL, 90, 102), create_health_check(CHECK_NETWORK, RESULT_PASS, 35, 103), create_health_check(0, RESULT_SKIP, 0, 0), create_health_check(0, RESULT_SKIP, 0, 0), create_health_check(0, RESULT_SKIP, 0, 0), create_health_check(0, RESULT_SKIP, 0, 0)); - if (!(get_health_percentage(array) == 50)) @panic("50% healthy"); + if (!(get_health_percentage(array) == 50)) __t27_assert_fail("\n 50% healthy:\n get_health_percentage(array) = {any}\n", .{ get_health_percentage(array) }); } diff --git a/gen/zig/hello.zig b/gen/zig/hello.zig index 74d7f68c..4c2e6475 100644 --- a/gen/zig/hello.zig +++ b/gen/zig/hello.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_HEARD: u8 = 3; @@ -79,10 +87,10 @@ test "hello_roundtrips" { const seq = parse_hello_seq(b4, b5, b6, b7); const n, const valid = parse_hello_n_valid(b8); const heard0 = parse_hello_heard0(b9, b10, b11, b12); - if (!(src == 7)) @panic("src should be 7"); - if (!(seq == 42)) @panic("seq should be 42"); - if (!(n == 3)) @panic("n should be 3"); - if (!(heard0 == 1)) @panic("heard0 should be 1"); + if (!(src == 7)) __t27_assert_fail("\n src should be 7:\n src = {any}\n", .{ src }); + if (!(seq == 42)) __t27_assert_fail("\n seq should be 42:\n seq = {any}\n", .{ seq }); + if (!(n == 3)) __t27_assert_fail("\n n should be 3:\n n = {any}\n", .{ n }); + if (!(heard0 == 1)) __t27_assert_fail("\n heard0 should be 1:\n heard0 = {any}\n", .{ heard0 }); if (!(valid)) @panic("parse should be valid"); } test "empty_heard_list_ok" { @@ -104,7 +112,7 @@ test "empty_heard_list_ok" { _ = b7; // dead after const-inlining const b8 = hello_byte(9, 1, 0, 0, 0, 0, 8); const n, const valid = parse_hello_n_valid(b8); - if (!(n == 0)) @panic("n should be 0"); + if (!(n == 0)) __t27_assert_fail("\n n should be 0:\n n = {any}\n", .{ n }); if (!(valid)) @panic("empty heard list should be valid"); } test "max_heard_neighbors" { @@ -114,19 +122,19 @@ test "max_heard_neighbors" { _ = seq; // dead after const-inlining const n, const valid = parse_hello_n_valid(3); const heard0 = parse_hello_heard0(0, 0, 0, 5); - if (!(n == 3)) @panic("n should be 3"); - if (!(heard0 == 5)) @panic("heard0 should be 5"); + if (!(n == 3)) __t27_assert_fail("\n n should be 3:\n n = {any}\n", .{ n }); + if (!(heard0 == 5)) __t27_assert_fail("\n heard0 should be 5:\n heard0 = {any}\n", .{ heard0 }); if (!(valid)) @panic("max neighbors should be valid"); } test "not_in_heard_list" { const result = reports_hearing(1, 0, 0, 3, 5); - if (!(result == false)) @panic("5 not in heard list"); + if (!(result == false)) __t27_assert_fail("\n 5 not in heard list:\n result = {any}\n", .{ result }); } test "in_heard_list_first_position" { const result = reports_hearing(7, 0, 0, 3, 7); - if (!(result == true)) @panic("7 in heard list position 0"); + if (!(result == true)) __t27_assert_fail("\n 7 in heard list position 0:\n result = {any}\n", .{ result }); } test "n_exceeds_max_rejected" { _, const valid = parse_hello_n_valid(4); - if (!(valid == false)) @panic("n > MAX_HEARD should be invalid"); + if (!(valid == false)) __t27_assert_fail("\n n > MAX_HEARD should be invalid:\n valid = {any}\n", .{ valid }); } diff --git a/gen/zig/integration_framework.zig b/gen/zig/integration_framework.zig index 8c0e2663..368cefda 100644 --- a/gen/zig/integration_framework.zig +++ b/gen/zig/integration_framework.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_MODULES: u32 = 16; @@ -406,17 +414,17 @@ fn validate_integration_health(modules: [MAX_MODULES]u32, module_count: u32) u32 } test "module_registration_roundtrip" { const m = create_module_registration(7, 3, 9, 50000); - if (!(get_registered_module_id(m) == 7)) @panic("module id"); - if (!(get_registered_module_type(m) == 3)) @panic("module type"); - if (!(get_registered_module_priority(m) == 9)) @panic("priority"); - if (!(get_registered_module_status(m) == 50000)) @panic("status"); + if (!(get_registered_module_id(m) == 7)) __t27_assert_fail("\n module id:\n get_registered_module_id(m) = {any}\n", .{ get_registered_module_id(m) }); + if (!(get_registered_module_type(m) == 3)) __t27_assert_fail("\n module type:\n get_registered_module_type(m) = {any}\n", .{ get_registered_module_type(m) }); + if (!(get_registered_module_priority(m) == 9)) __t27_assert_fail("\n priority:\n get_registered_module_priority(m) = {any}\n", .{ get_registered_module_priority(m) }); + if (!(get_registered_module_status(m) == 50000)) __t27_assert_fail("\n status:\n get_registered_module_status(m) = {any}\n", .{ get_registered_module_status(m) }); } test "send_message_requires_active_destination" { - const mods: [16]u32 = .{ create_module_registration(1,0,1,STATUS_ACTIVE), create_module_registration(2,0,1,0), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + const mods: [16]u32 = .{ create_module_registration(1, 0, 1, STATUS_ACTIVE), create_module_registration(2, 0, 1, 0), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; const msg_ok = create_integration_message(1, 5, 1, 0); - if (!(send_message(mods, msg_ok) == 1)) @panic("active destination accepts"); + if (!(send_message(mods, msg_ok) == 1)) __t27_assert_fail("\n active destination accepts:\n send_message(mods, msg_ok) = {any}\n", .{ send_message(mods, msg_ok) }); const msg_down = create_integration_message(2, 5, 2, 0); - if (!(send_message(mods, msg_down) == 0)) @panic("inactive destination rejects"); + if (!(send_message(mods, msg_down) == 0)) __t27_assert_fail("\n inactive destination rejects:\n send_message(mods, msg_down) = {any}\n", .{ send_message(mods, msg_down) }); const msg_missing = create_integration_message(3, 5, 99, 0); - if (!(send_message(mods, msg_missing) == 0)) @panic("unknown destination rejects"); + if (!(send_message(mods, msg_missing) == 0)) __t27_assert_fail("\n unknown destination rejects:\n send_message(mods, msg_missing) = {any}\n", .{ send_message(mods, msg_missing) }); } diff --git a/gen/zig/integration_tests.zig b/gen/zig/integration_tests.zig index b330f40c..d55b06a1 100644 --- a/gen/zig/integration_tests.zig +++ b/gen/zig/integration_tests.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const VERSION: u8 = 1; @@ -50,19 +58,19 @@ test "wire_header_with_routing_dst" { const b9 = header_byte(kind, src, dst, ttl, 9); const b10 = header_byte(kind, src, dst, ttl, 10); _ = b10; // dead after const-inlining - if (!(b0 == VERSION)) @panic("version byte"); - if (!(b1 == kind)) @panic("kind byte"); + if (!(b0 == VERSION)) __t27_assert_fail("\n version byte:\n b0 = {any}\n VERSION = {any}\n", .{ b0, VERSION }); + if (!(b1 == kind)) __t27_assert_fail("\n kind byte:\n b1 = {any}\n kind = {any}\n", .{ b1, kind }); const dst_extracted = (((@as(u32, @intCast(b6)) << 24) | (@as(u32, @intCast(b7)) << 16)) | (@as(u32, @intCast(b8)) << 8)) | @as(u32, @intCast(b9)); - if (!(dst_extracted == dst)) @panic("dst matches"); + if (!(dst_extracted == dst)) __t27_assert_fail("\n dst matches:\n dst_extracted = {any}\n dst = {any}\n", .{ dst_extracted, dst }); } test "ip_mapping_roundtrip" { const a, const b, const c, const d = mesh_ip(50); const node_back = (((@as(u32, @intCast(a)) << 0) | (@as(u32, @intCast(b)) << 0)) | (@as(u32, @intCast(c)) << 0)) | (@as(u32, @intCast(d)) << 0); _ = node_back; // dead after const-inlining - if (!(a == MESH_NET_A)) @panic("network A"); - if (!(b == MESH_NET_B)) @panic("network B"); - if (!(c == MESH_NET_C)) @panic("network C"); - if (!(d == 50)) @panic("node ID preserved"); + if (!(a == MESH_NET_A)) __t27_assert_fail("\n network A:\n a = {any}\n MESH_NET_A = {any}\n", .{ a, MESH_NET_A }); + if (!(b == MESH_NET_B)) __t27_assert_fail("\n network B:\n b = {any}\n MESH_NET_B = {any}\n", .{ b, MESH_NET_B }); + if (!(c == MESH_NET_C)) __t27_assert_fail("\n network C:\n c = {any}\n MESH_NET_C = {any}\n", .{ c, MESH_NET_C }); + if (!(d == 50)) __t27_assert_fail("\n node ID preserved:\n d = {any}\n", .{ d }); } test "transport_builds_wire_header" { const kind = KIND_DATA; @@ -72,15 +80,15 @@ test "transport_builds_wire_header" { const b0 = header_byte(kind, src, dst, ttl, 0); const b1 = header_byte(kind, src, dst, ttl, 1); const b10 = header_byte(kind, src, dst, ttl, 10); - if (!(b0 == VERSION)) @panic("header version"); - if (!(b1 == kind)) @panic("header kind"); - if (!(b10 == ttl)) @panic("header ttl"); + if (!(b0 == VERSION)) __t27_assert_fail("\n header version:\n b0 = {any}\n VERSION = {any}\n", .{ b0, VERSION }); + if (!(b1 == kind)) __t27_assert_fail("\n header kind:\n b1 = {any}\n kind = {any}\n", .{ b1, kind }); + if (!(b10 == ttl)) __t27_assert_fail("\n header ttl:\n b10 = {any}\n ttl = {any}\n", .{ b10, ttl }); } test "queue_with_timer_timeout" { const queue_state = 0; _ = queue_state; // dead after const-inlining const timeout_base = 10; - if (!(timeout_base == 10)) @panic("base timeout 10ms"); + if (!(timeout_base == 10)) __t27_assert_fail("\n base timeout 10ms:\n timeout_base = {any}\n", .{ timeout_base }); } test "frame_metadata_queue_slot" { const src = 1; @@ -92,9 +100,9 @@ test "frame_metadata_queue_slot" { const dst_extracted = @as(u8, @intCast((meta >> 5) & 15)); const ttl_extracted = @as(u8, @intCast((meta >> 9) & 15)); if (!(valid)) @panic("metadata valid"); - if (!(src_extracted == src)) @panic("src roundtrip"); - if (!(dst_extracted == dst)) @panic("dst roundtrip"); - if (!(ttl_extracted == ttl)) @panic("ttl roundtrip"); + if (!(src_extracted == src)) __t27_assert_fail("\n src roundtrip:\n src_extracted = {any}\n src = {any}\n", .{ src_extracted, src }); + if (!(dst_extracted == dst)) __t27_assert_fail("\n dst roundtrip:\n dst_extracted = {any}\n dst = {any}\n", .{ dst_extracted, dst }); + if (!(ttl_extracted == ttl)) __t27_assert_fail("\n ttl roundtrip:\n ttl_extracted = {any}\n ttl = {any}\n", .{ ttl_extracted, ttl }); } test "full_packet_flow" { const kind = KIND_DATA; @@ -105,8 +113,8 @@ test "full_packet_flow" { const b1 = header_byte(kind, src, dst, ttl, 1); _ = b1; // dead after const-inlining const a, const b, const c, _ = mesh_ip(dst); - if (!(((a == MESH_NET_A) and (b == MESH_NET_B)) and (c == MESH_NET_C))) @panic("dst in mesh subnet"); - if (!(b0 == VERSION)) @panic("header version valid"); + if (!(((a == MESH_NET_A) and (b == MESH_NET_B)) and (c == MESH_NET_C))) __t27_assert_fail("\n dst in mesh subnet:\n a = {any}\n MESH_NET_A = {any}\n b = {any}\n MESH_NET_B = {any}\n c = {any}\n MESH_NET_C = {any}\n", .{ a, MESH_NET_A, b, MESH_NET_B, c, MESH_NET_C }); + if (!(b0 == VERSION)) __t27_assert_fail("\n header version valid:\n b0 = {any}\n VERSION = {any}\n", .{ b0, VERSION }); if (!(true)) @panic("full flow validated"); } test "routing_with_multiple_neighbors" { @@ -124,22 +132,22 @@ test "hello_beacon_with_mesh_ip" { const n_heard = 3; _ = n_heard; // dead after const-inlining const a, _, _, const d = mesh_ip(src); - if (!(a == MESH_NET_A)) @panic("HELLO src in mesh subnet"); - if (!(d == src)) @panic("node ID preserved"); + if (!(a == MESH_NET_A)) __t27_assert_fail("\n HELLO src in mesh subnet:\n a = {any}\n MESH_NET_A = {any}\n", .{ a, MESH_NET_A }); + if (!(d == src)) __t27_assert_fail("\n node ID preserved:\n d = {any}\n src = {any}\n", .{ d, src }); } test "timeout_with_backoff" { const timeout_0 = 10; const timeout_1 = 20; const timeout_2 = 40; - if (!(timeout_1 == (timeout_0 * 2))) @panic("doubles"); - if (!(timeout_2 == (timeout_1 * 2))) @panic("doubles again"); + if (!(timeout_1 == (timeout_0 * 2))) __t27_assert_fail("\n doubles:\n timeout_1 = {any}\n timeout_0 * 2 = {any}\n", .{ timeout_1, timeout_0 * 2 }); + if (!(timeout_2 == (timeout_1 * 2))) __t27_assert_fail("\n doubles again:\n timeout_2 = {any}\n timeout_1 * 2 = {any}\n", .{ timeout_2, timeout_1 * 2 }); } test "frame_metadata_fields" { const meta_data = ((1 | (@as(u32, @intCast(1 & 15)) << 1)) | (@as(u32, @intCast(2 & 15)) << 5)) | (@as(u32, @intCast(8 & 15)) << 9); const src = @as(u8, @intCast((meta_data >> 1) & 15)); const dst = @as(u8, @intCast((meta_data >> 5) & 15)); const ttl = @as(u8, @intCast((meta_data >> 9) & 15)); - if (!(src == 1)) @panic("src field"); - if (!(dst == 2)) @panic("dst field"); - if (!(ttl == 8)) @panic("ttl field"); + if (!(src == 1)) __t27_assert_fail("\n src field:\n src = {any}\n", .{ src }); + if (!(dst == 2)) __t27_assert_fail("\n dst field:\n dst = {any}\n", .{ dst }); + if (!(ttl == 8)) __t27_assert_fail("\n ttl field:\n ttl = {any}\n", .{ ttl }); } diff --git a/gen/zig/key_management.zig b/gen/zig/key_management.zig index c66331ba..4ae7a752 100644 --- a/gen/zig/key_management.zig +++ b/gen/zig/key_management.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_KEYS: u32 = 4; @@ -155,59 +163,59 @@ fn count_valid_keys(store: [4]u32) u32 { } test "create_key_entry_basic" { const entry = create_key_entry(1, 5, 0xABCD, 100); - if (!(get_key_valid(entry) == 1)) @panic("valid"); - if (!(get_key_id(entry) == 5)) @panic("id"); - if (!(get_key_value(entry) == 0xABCD)) @panic("value"); - if (!(get_key_timestamp(entry) == 100)) @panic("timestamp"); + if (!(get_key_valid(entry) == 1)) __t27_assert_fail("\n valid:\n get_key_valid(entry) = {any}\n", .{ get_key_valid(entry) }); + if (!(get_key_id(entry) == 5)) __t27_assert_fail("\n id:\n get_key_id(entry) = {any}\n", .{ get_key_id(entry) }); + if (!(get_key_value(entry) == 0xABCD)) __t27_assert_fail("\n value:\n get_key_value(entry) = {any}\n", .{ get_key_value(entry) }); + if (!(get_key_timestamp(entry) == 100)) __t27_assert_fail("\n timestamp:\n get_key_timestamp(entry) = {any}\n", .{ get_key_timestamp(entry) }); } test "find_key_by_id_found" { const store = create_key_store(create_key_entry(1, 1, 0x1111, 10), create_key_entry(1, 2, 0x2222, 20), create_key_entry(0, 3, 0x3333, 30), create_key_entry(1, 4, 0x4444, 40)); - if (!(find_key_by_id(store, 2) == 1)) @panic("found at index 1"); + if (!(find_key_by_id(store, 2) == 1)) __t27_assert_fail("\n found at index 1:\n find_key_by_id(store, 2) = {any}\n", .{ find_key_by_id(store, 2) }); } test "find_key_by_id_not_found" { const store = create_key_store(create_key_entry(1, 1, 0x1111, 10), create_key_entry(1, 2, 0x2222, 20), create_key_entry(0, 3, 0x3333, 30), create_key_entry(1, 4, 0x4444, 40)); - if (!(find_key_by_id(store, 99) == 0xFF)) @panic("not found"); + if (!(find_key_by_id(store, 99) == 0xFF)) __t27_assert_fail("\n not found:\n find_key_by_id(store, 99) = {any}\n", .{ find_key_by_id(store, 99) }); } test "find_key_by_id_invalid_ignored" { const store = create_key_store(create_key_entry(1, 1, 0x1111, 10), create_key_entry(0, 2, 0x2222, 20), create_key_entry(1, 3, 0x3333, 30), create_key_entry(1, 4, 0x4444, 40)); - if (!(find_key_by_id(store, 2) == 0xFF)) @panic("invalid key ignored"); + if (!(find_key_by_id(store, 2) == 0xFF)) __t27_assert_fail("\n invalid key ignored:\n find_key_by_id(store, 2) = {any}\n", .{ find_key_by_id(store, 2) }); } test "add_key_empty_slot" { const store = create_key_store(create_key_entry(0, 0, 0, 0), create_key_entry(0, 0, 0, 0), create_key_entry(0, 0, 0, 0), create_key_entry(0, 0, 0, 0)); const new_store = add_key(store, 5, 0xABCD, 100); - if (!(get_key_id(get_key_entry(new_store, 0)) == 5)) @panic("key added"); + if (!(get_key_id(get_key_entry(new_store, 0)) == 5)) __t27_assert_fail("\n key added:\n get_key_id(get_key_entry(new_store, 0)) = {any}\n", .{ get_key_id(get_key_entry(new_store, 0)) }); } test "invalidate_key_works" { const store = create_key_store(create_key_entry(1, 1, 0x1111, 10), create_key_entry(1, 2, 0x2222, 20), create_key_entry(1, 3, 0x3333, 30), create_key_entry(0, 0, 0, 0)); const new_store = invalidate_key(store, 2); - if (!(get_key_valid(get_key_entry(new_store, 1)) == 0)) @panic("key invalidated"); + if (!(get_key_valid(get_key_entry(new_store, 1)) == 0)) __t27_assert_fail("\n key invalidated:\n get_key_valid(get_key_entry(new_store, 1)) = {any}\n", .{ get_key_valid(get_key_entry(new_store, 1)) }); } test "needs_rotation_true" { const entry = create_key_entry(1, 1, 0x1111, 1000); - if (!(needs_rotation(entry, 35000) == true)) @panic("needs rotation"); + if (!(needs_rotation(entry, 35000) == true)) __t27_assert_fail("\n needs rotation:\n needs_rotation(entry, 35000) = {any}\n", .{ needs_rotation(entry, 35000) }); } test "needs_rotation_false" { const entry = create_key_entry(1, 1, 0x1111, 25000); - if (!(needs_rotation(entry, 30000) == false)) @panic("no rotation needed"); + if (!(needs_rotation(entry, 30000) == false)) __t27_assert_fail("\n no rotation needed:\n needs_rotation(entry, 30000) = {any}\n", .{ needs_rotation(entry, 30000) }); } test "needs_rotation_invalid" { const entry = create_key_entry(0, 1, 0x1111, 1000); - if (!(needs_rotation(entry, 35000) == false)) @panic("invalid key"); + if (!(needs_rotation(entry, 35000) == false)) __t27_assert_fail("\n invalid key:\n needs_rotation(entry, 35000) = {any}\n", .{ needs_rotation(entry, 35000) }); } test "rotate_key_works" { const store = create_key_store(create_key_entry(1, 1, 0x1111, 10000), create_key_entry(0, 0, 0, 0), create_key_entry(0, 0, 0, 0), create_key_entry(0, 0, 0, 0)); const new_store = rotate_key(store, 1, 0x9999, 50000); - if (!(get_key_value(get_key_entry(new_store, 0)) == 0x9999)) @panic("value updated"); + if (!(get_key_value(get_key_entry(new_store, 0)) == 0x9999)) __t27_assert_fail("\n value updated:\n get_key_value(get_key_entry(new_store, 0)) = {any}\n", .{ get_key_value(get_key_entry(new_store, 0)) }); } test "get_active_key_returns_latest" { const store = create_key_store(create_key_entry(1, 1, 0x1111, 10), create_key_entry(1, 2, 0x2222, 30), create_key_entry(1, 3, 0x3333, 20), create_key_entry(0, 0, 0, 0)); - if (!(get_active_key(store) == 0x2222)) @panic("latest key"); + if (!(get_active_key(store) == 0x2222)) __t27_assert_fail("\n latest key:\n get_active_key(store) = {any}\n", .{ get_active_key(store) }); } test "count_valid_keys_all" { const store = create_key_store(create_key_entry(1, 1, 0x1111, 10), create_key_entry(1, 2, 0x2222, 20), create_key_entry(1, 3, 0x3333, 30), create_key_entry(1, 4, 0x4444, 40)); - if (!(count_valid_keys(store) == 4)) @panic("4 valid keys"); + if (!(count_valid_keys(store) == 4)) __t27_assert_fail("\n 4 valid keys:\n count_valid_keys(store) = {any}\n", .{ count_valid_keys(store) }); } test "count_valid_keys_some" { const store = create_key_store(create_key_entry(1, 1, 0x1111, 10), create_key_entry(0, 2, 0x2222, 20), create_key_entry(1, 3, 0x3333, 30), create_key_entry(0, 4, 0x4444, 40)); - if (!(count_valid_keys(store) == 2)) @panic("2 valid keys"); + if (!(count_valid_keys(store) == 2)) __t27_assert_fail("\n 2 valid keys:\n count_valid_keys(store) = {any}\n", .{ count_valid_keys(store) }); } diff --git a/gen/zig/link_quality_monitor.zig b/gen/zig/link_quality_monitor.zig index f4674007..857f0c43 100644 --- a/gen/zig/link_quality_monitor.zig +++ b/gen/zig/link_quality_monitor.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} const ALPHA_Q8: u8 = 0x20; const ONE_MINUS_ALPHA_Q8: u8 = 0xE0; @@ -69,40 +77,40 @@ test "ewma_calculation" { const current: u8 = 0x40; const sample: u8 = 0x60; const new_etx: u8 = update_ewma(current, sample); - if (!(new_etx > current)) @panic("new_etx > current"); - if (!(new_etx < sample)) @panic("new_etx < sample"); + if (!(new_etx > current)) __t27_assert_fail("\n new_etx > current:\n new_etx = {any}\n current = {any}\n", .{ new_etx, current }); + if (!(new_etx < sample)) __t27_assert_fail("\n new_etx < sample:\n new_etx = {any}\n sample = {any}\n", .{ new_etx, sample }); } test "trend_detection" { const improving_history: [8]u8 = .{ 0x70, 0x68, 0x60, 0x58, 0x50, 0x48, 0x40, 0x38 }; const trend: i8 = calculate_trend(improving_history); - if (!(trend < 0)) @panic("trend < 0"); + if (!(trend < 0)) __t27_assert_fail("\n trend < 0:\n trend = {any}\n", .{ trend }); const worsening_history: [8]u8 = .{ 0x40, 0x48, 0x50, 0x58, 0x60, 0x68, 0x70, 0x78 }; const trend2: i8 = calculate_trend(worsening_history); - if (!(trend2 > 0)) @panic("trend2 > 0"); + if (!(trend2 > 0)) __t27_assert_fail("\n trend2 > 0:\n trend2 = {any}\n", .{ trend2 }); } test "etx_prediction" { const current: u8 = 0x60; const trend: i8 = 0x08; const predicted: u8 = predict_next_etx(current, trend); - if (!(predicted > current)) @panic("predicted > current"); - if (!(predicted < 0x70)) @panic("predicted < 0x70"); + if (!(predicted > current)) __t27_assert_fail("\n predicted > current:\n predicted = {any}\n current = {any}\n", .{ predicted, current }); + if (!(predicted < 0x70)) __t27_assert_fail("\n predicted < 0x70:\n predicted = {any}\n", .{ predicted }); } test "degradation_detection" { - if (!(is_degrading(0x70, 0x10) == true)) @panic("is_degrading 0x70 0x10 == true"); - if (!(is_degrading(0x70, -0x10) == false)) @panic("is_degrading 0x70 -0x10 == false"); - if (!(is_degrading(0x30, 0x10) == false)) @panic("is_degrading 0x30 0x10 == false"); + if (!(is_degrading(0x70, 0x10) == true)) __t27_assert_fail("\n is_degrading 0x70 0x10 == true:\n is_degrading(0x70, 0x10) = {any}\n", .{ is_degrading(0x70, 0x10) }); + if (!(is_degrading(0x70, -0x10) == false)) __t27_assert_fail("\n is_degrading 0x70 -0x10 == false:\n is_degrading(0x70, -0x10) = {any}\n", .{ is_degrading(0x70, -0x10) }); + if (!(is_degrading(0x30, 0x10) == false)) __t27_assert_fail("\n is_degrading 0x30 0x10 == false:\n is_degrading(0x30, 0x10) = {any}\n", .{ is_degrading(0x30, 0x10) }); } test "quality_score_calculation" { const etx: u8 = 0x50; const latency: u16 = 100; const score: u8 = quality_score(etx, latency); - if (!(score > 50)) @panic("score > 50"); - if (!(score < 200)) @panic("score < 200"); + if (!(score > 50)) __t27_assert_fail("\n score > 50:\n score = {any}\n", .{ score }); + if (!(score < 200)) __t27_assert_fail("\n score < 200:\n score = {any}\n", .{ score }); } test "quality_classification" { - if (!(classify_quality(30) == 0)) @panic("classify_quality 30 == 0"); - if (!(classify_quality(80) == 1)) @panic("classify_quality 80 == 1"); - if (!(classify_quality(125) == 2)) @panic("classify_quality 125 == 2"); - if (!(classify_quality(175) == 3)) @panic("classify_quality 175 == 3"); - if (!(classify_quality(225) == 4)) @panic("classify_quality 225 == 4"); + if (!(classify_quality(30) == 0)) __t27_assert_fail("\n classify_quality 30 == 0:\n classify_quality(30) = {any}\n", .{ classify_quality(30) }); + if (!(classify_quality(80) == 1)) __t27_assert_fail("\n classify_quality 80 == 1:\n classify_quality(80) = {any}\n", .{ classify_quality(80) }); + if (!(classify_quality(125) == 2)) __t27_assert_fail("\n classify_quality 125 == 2:\n classify_quality(125) = {any}\n", .{ classify_quality(125) }); + if (!(classify_quality(175) == 3)) __t27_assert_fail("\n classify_quality 175 == 3:\n classify_quality(175) = {any}\n", .{ classify_quality(175) }); + if (!(classify_quality(225) == 4)) __t27_assert_fail("\n classify_quality 225 == 4:\n classify_quality(225) = {any}\n", .{ classify_quality(225) }); } diff --git a/gen/zig/link_statistics.zig b/gen/zig/link_statistics.zig index 426c5204..d21509d2 100644 --- a/gen/zig/link_statistics.zig +++ b/gen/zig/link_statistics.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module fn get_sent(stats: u32) u16 { @@ -23,24 +31,24 @@ fn reset() u32 { test "inc_sent_increments" { const s1 = reset(); const s2 = inc_sent(s1); - if (!(get_sent(s2) == 1)) @panic("inc works"); + if (!(get_sent(s2) == 1)) __t27_assert_fail("\n inc works:\n get_sent(s2) = {any}\n", .{ get_sent(s2) }); } test "inc_recv_increments" { const s1 = reset(); const s2 = inc_recv(s1); - if (!(get_recv(s2) == 1)) @panic("inc works"); + if (!(get_recv(s2) == 1)) __t27_assert_fail("\n inc works:\n get_recv(s2) = {any}\n", .{ get_recv(s2) }); } test "both_counters" { const s1 = reset(); const s2 = inc_sent(s1); const s3 = inc_recv(s2); - if (!(get_sent(s3) == 1)) @panic("sent"); - if (!(get_recv(s3) == 1)) @panic("recv"); + if (!(get_sent(s3) == 1)) __t27_assert_fail("\n sent:\n get_sent(s3) = {any}\n", .{ get_sent(s3) }); + if (!(get_recv(s3) == 1)) __t27_assert_fail("\n recv:\n get_recv(s3) = {any}\n", .{ get_recv(s3) }); } test "reset_clears" { const s1 = reset(); const s2 = inc_sent(s1); _ = s2; // dead after const-inlining const s3 = reset(); - if (!(get_sent(s3) == 0)) @panic("clears"); + if (!(get_sent(s3) == 0)) __t27_assert_fail("\n clears:\n get_sent(s3) = {any}\n", .{ get_sent(s3) }); } diff --git a/gen/zig/lite_crypto.zig b/gen/zig/lite_crypto.zig index f45679fd..04a4b869 100644 --- a/gen/zig/lite_crypto.zig +++ b/gen/zig/lite_crypto.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const PSK_SIZE: u32 = 16; @@ -34,64 +42,64 @@ test "md5_process_block_compresses" { const block = 0x1234567890ABCDEF; const state = 0xABCDEF1234567890; const h1, const h2 = md5_process_block(block, state); - if (!((h1 != 0) or (h2 != 0))) @panic("compressed"); + if (!((h1 != 0) or (h2 != 0))) __t27_assert_fail("\n compressed:\n h1 = {any}\n h2 = {any}\n", .{ h1, h2 }); } test "md5_digest_returns_hash" { const h1, const h2 = md5_process_block(0x1234567890ABCDEF, 0); const hash = md5_digest(h1, h2); - if (!(hash == ((@as(u64, @intCast(h1)) << 32) | @as(u64, @intCast(h2))))) @panic("hash created"); + if (!(hash == ((@as(u64, @intCast(h1)) << 32) | @as(u64, @intCast(h2))))) __t27_assert_fail("\n hash created:\n hash = {any}\n (@as(u64, @intCast(h1)) << 32) | @as(u64, @intCast(h2)) = {any}\n", .{ hash, (@as(u64, @intCast(h1)) << 32) | @as(u64, @intCast(h2)) }); } test "quarter_round_changes_state" { const state = 0x01234567; const new_state = quarter_round(state, 0x89ABCDEF); - if (!(new_state != state)) @panic("state changed"); + if (!(new_state != state)) __t27_assert_fail("\n state changed:\n new_state = {any}\n state = {any}\n", .{ new_state, state }); } test "quarter_round_deterministic" { const state = 0x01234567; const result1 = quarter_round(state, 0x89ABCDEF); const result2 = quarter_round(state, 0x89ABCDEF); - if (!(result1 == result2)) @panic("deterministic"); + if (!(result1 == result2)) __t27_assert_fail("\n deterministic:\n result1 = {any}\n result2 = {any}\n", .{ result1, result2 }); } test "generate_psk_returns_key" { const key = generate_psk(0x12345678); - if (!(key == 0x12345678)) @panic("psk from seed"); + if (!(key == 0x12345678)) __t27_assert_fail("\n psk from seed:\n key = {any}\n", .{ key }); } test "hmac_md5_creates_mac" { const mac = hmac_md5(0xABCD, 0x1234); - if (!(mac == (0xABCD ^ 0x1234))) @panic("XOR MAC created"); + if (!(mac == (0xABCD ^ 0x1234))) __t27_assert_fail("\n XOR MAC created:\n mac = {any}\n 0xABCD ^ 0x1234 = {any}\n", .{ mac, 0xABCD ^ 0x1234 }); } test "verify_hmac_valid" { const mac = hmac_md5(0xABCD, 0x1234); - if (!(verify_hmac(0xABCD, 0x1234, mac) == true)) @panic("valid MAC"); + if (!(verify_hmac(0xABCD, 0x1234, mac) == true)) __t27_assert_fail("\n valid MAC:\n verify_hmac(0xABCD, 0x1234, mac) = {any}\n", .{ verify_hmac(0xABCD, 0x1234, mac) }); } test "verify_hmac_invalid" { const mac = hmac_md5(0xABCD, 0x1234); _ = mac; // dead after const-inlining - if (!(verify_hmac(0xABCD, 0x1234, 0x5678) == false)) @panic("invalid MAC"); + if (!(verify_hmac(0xABCD, 0x1234, 0x5678) == false)) __t27_assert_fail("\n invalid MAC:\n verify_hmac(0xABCD, 0x1234, 0x5678) = {any}\n", .{ verify_hmac(0xABCD, 0x1234, 0x5678) }); } test "quarter_round_different_inputs" { const state = 0x01234567; const result1 = quarter_round(state, 0x89ABCDEF); const result2 = quarter_round(state, 0x11111111); - if (!(result1 != result2)) @panic("different inputs produce different outputs"); + if (!(result1 != result2)) __t27_assert_fail("\n different inputs produce different outputs:\n result1 = {any}\n result2 = {any}\n", .{ result1, result2 }); } test "md5_different_blocks_produce_different_hashes" { const h1_a, const h2_a = md5_process_block(0x1234567890ABCDEF, 0); const h1_b, const h2_b = md5_process_block(0xFEDCBA0987654321, 0); - if (!((h1_a != h1_b) or (h2_a != h2_b))) @panic("different blocks produce different hashes"); + if (!((h1_a != h1_b) or (h2_a != h2_b))) __t27_assert_fail("\n different blocks produce different hashes:\n h1_a = {any}\n h1_b = {any}\n h2_a = {any}\n h2_b = {any}\n", .{ h1_a, h1_b, h2_a, h2_b }); } test "hmac_md5_same_key_different_messages" { const mac1 = hmac_md5(0xABCD, 0x1234); const mac2 = hmac_md5(0xABCD, 0x5678); - if (!(mac1 != mac2)) @panic("different messages produce different MACs"); + if (!(mac1 != mac2)) __t27_assert_fail("\n different messages produce different MACs:\n mac1 = {any}\n mac2 = {any}\n", .{ mac1, mac2 }); } test "generate_psk_deterministic" { const key1 = generate_psk(0xDEADBEEF); const key2 = generate_psk(0xDEADBEEF); - if (!(key1 == key2)) @panic("same seed produces same key"); + if (!(key1 == key2)) __t27_assert_fail("\n same seed produces same key:\n key1 = {any}\n key2 = {any}\n", .{ key1, key2 }); } test "generate_psk_different_seeds" { const key1 = generate_psk(0x11111111); const key2 = generate_psk(0x22222222); - if (!(key1 != key2)) @panic("different seeds produce different keys"); + if (!(key1 != key2)) __t27_assert_fail("\n different seeds produce different keys:\n key1 = {any}\n key2 = {any}\n", .{ key1, key2 }); } diff --git a/gen/zig/load_predictor.zig b/gen/zig/load_predictor.zig index e50c8575..33e0d1b2 100644 --- a/gen/zig/load_predictor.zig +++ b/gen/zig/load_predictor.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_NODES: u32 = 8; @@ -255,25 +263,25 @@ fn recommend_rerouting(prediction: u32, current_node: u32, node_metrics: [MAX_NO } test "load_metrics_roundtrip" { const m = create_load_metrics(80, 60, 200, 12); - if (!(get_bandwidth_usage(m) == 80)) @panic("bandwidth"); - if (!(get_cpu_usage(m) == 60)) @panic("cpu"); - if (!(get_packet_rate(m) == 200)) @panic("packets"); - if (!(get_queue_depth(m) == 12)) @panic("queue"); + if (!(get_bandwidth_usage(m) == 80)) __t27_assert_fail("\n bandwidth:\n get_bandwidth_usage(m) = {any}\n", .{ get_bandwidth_usage(m) }); + if (!(get_cpu_usage(m) == 60)) __t27_assert_fail("\n cpu:\n get_cpu_usage(m) = {any}\n", .{ get_cpu_usage(m) }); + if (!(get_packet_rate(m) == 200)) __t27_assert_fail("\n packets:\n get_packet_rate(m) = {any}\n", .{ get_packet_rate(m) }); + if (!(get_queue_depth(m) == 12)) __t27_assert_fail("\n queue:\n get_queue_depth(m) = {any}\n", .{ get_queue_depth(m) }); } test "prediction_roundtrip" { const p = create_prediction(90, 75, 2, 9000); - if (!(get_predicted_load(p) == 90)) @panic("load"); - if (!(get_confidence(p) == 75)) @panic("confidence"); - if (!(get_trend(p) == 2)) @panic("trend"); - if (!(get_time_horizon(p) == 9000)) @panic("horizon"); + if (!(get_predicted_load(p) == 90)) __t27_assert_fail("\n load:\n get_predicted_load(p) = {any}\n", .{ get_predicted_load(p) }); + if (!(get_confidence(p) == 75)) __t27_assert_fail("\n confidence:\n get_confidence(p) = {any}\n", .{ get_confidence(p) }); + if (!(get_trend(p) == 2)) __t27_assert_fail("\n trend:\n get_trend(p) = {any}\n", .{ get_trend(p) }); + if (!(get_time_horizon(p) == 9000)) __t27_assert_fail("\n horizon:\n get_time_horizon(p) = {any}\n", .{ get_time_horizon(p) }); } test "trend_detection_bands" { - const up: [16]u32 = .{ create_load_metrics(10,0,0,0), create_load_metrics(30,0,0,0), create_load_metrics(50,0,0,0), create_load_metrics(70,0,0,0), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - if (!(detect_trend(up, 4) == 1)) @panic("rising by 40 over the window"); - const flat: [16]u32 = .{ create_load_metrics(50,0,0,0), create_load_metrics(55,0,0,0), create_load_metrics(52,0,0,0), create_load_metrics(58,0,0,0), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - if (!(detect_trend(flat, 4) == 0)) @panic("8-point wobble is stable"); + const up: [16]u32 = .{ create_load_metrics(10, 0, 0, 0), create_load_metrics(30, 0, 0, 0), create_load_metrics(50, 0, 0, 0), create_load_metrics(70, 0, 0, 0), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + if (!(detect_trend(up, 4) == 1)) __t27_assert_fail("\n rising by 40 over the window:\n detect_trend(up, 4) = {any}\n", .{ detect_trend(up, 4) }); + const flat: [16]u32 = .{ create_load_metrics(50, 0, 0, 0), create_load_metrics(55, 0, 0, 0), create_load_metrics(52, 0, 0, 0), create_load_metrics(58, 0, 0, 0), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + if (!(detect_trend(flat, 4) == 0)) __t27_assert_fail("\n 8-point wobble is stable:\n detect_trend(flat, 4) = {any}\n", .{ detect_trend(flat, 4) }); } test "predict_load_no_underflow_when_average_leads" { - const h: [16]u32 = .{ create_load_metrics(100,0,0,0), create_load_metrics(100,0,0,0), create_load_metrics(0,0,0,0), create_load_metrics(25,0,0,0), create_load_metrics(50,0,0,0), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - if (!(predict_load(h, 5) == 50)) @panic("no growth credit when below average"); + const h: [16]u32 = .{ create_load_metrics(100, 0, 0, 0), create_load_metrics(100, 0, 0, 0), create_load_metrics(0, 0, 0, 0), create_load_metrics(25, 0, 0, 0), create_load_metrics(50, 0, 0, 0), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + if (!(predict_load(h, 5) == 50)) __t27_assert_fail("\n no growth credit when below average:\n predict_load(h, 5) = {any}\n", .{ predict_load(h, 5) }); } diff --git a/gen/zig/local_processing.zig b/gen/zig/local_processing.zig index 877eaaf2..09effab4 100644 --- a/gen/zig/local_processing.zig +++ b/gen/zig/local_processing.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_TASKS: u32 = 8; @@ -249,25 +257,25 @@ fn has_resources(state: u32, required_cpu: u32, required_memory: u32) u32 { } test "task_and_result_roundtrip" { const t = create_task(9, TASK_PRIORITY_MEDIUM, 200, 12345); - if (!(get_task_id(t) == 9)) @panic("task id"); - if (!(get_priority(t) == TASK_PRIORITY_MEDIUM)) @panic("priority"); - if (!(get_data_size(t) == 200)) @panic("size"); - if (!(get_processing_time(t) == 12345)) @panic("time"); + if (!(get_task_id(t) == 9)) __t27_assert_fail("\n task id:\n get_task_id(t) = {any}\n", .{ get_task_id(t) }); + if (!(get_priority(t) == TASK_PRIORITY_MEDIUM)) __t27_assert_fail("\n priority:\n get_priority(t) = {any}\n TASK_PRIORITY_MEDIUM = {any}\n", .{ get_priority(t), TASK_PRIORITY_MEDIUM }); + if (!(get_data_size(t) == 200)) __t27_assert_fail("\n size:\n get_data_size(t) = {any}\n", .{ get_data_size(t) }); + if (!(get_processing_time(t) == 12345)) __t27_assert_fail("\n time:\n get_processing_time(t) = {any}\n", .{ get_processing_time(t) }); const r = create_result(9, STATUS_COMPLETED, 200, 9999); - if (!(get_result_task_id(r) == 9)) @panic("result task id"); - if (!(get_status(r) == STATUS_COMPLETED)) @panic("status"); - if (!(get_result_value(r) == 9999)) @panic("value"); + if (!(get_result_task_id(r) == 9)) __t27_assert_fail("\n result task id:\n get_result_task_id(r) = {any}\n", .{ get_result_task_id(r) }); + if (!(get_status(r) == STATUS_COMPLETED)) __t27_assert_fail("\n status:\n get_status(r) = {any}\n STATUS_COMPLETED = {any}\n", .{ get_status(r), STATUS_COMPLETED }); + if (!(get_result_value(r) == 9999)) __t27_assert_fail("\n value:\n get_result_value(r) = {any}\n", .{ get_result_value(r) }); } test "process_and_aggregate" { const t = create_task(3, TASK_PRIORITY_HIGH, 10, 5); const r = process_task(t); - if (!(get_status(r) == STATUS_COMPLETED)) @panic("completed"); - if (!(get_result_value(r) == 50)) @panic("size times time"); - const rs: [16]u32 = .{ create_result(1,STATUS_COMPLETED,0,100), create_result(2,STATUS_COMPLETED,0,250), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - if (!(aggregate_results(rs, 2) == 350)) @panic("sum of result values"); + if (!(get_status(r) == STATUS_COMPLETED)) __t27_assert_fail("\n completed:\n get_status(r) = {any}\n STATUS_COMPLETED = {any}\n", .{ get_status(r), STATUS_COMPLETED }); + if (!(get_result_value(r) == 50)) __t27_assert_fail("\n size times time:\n get_result_value(r) = {any}\n", .{ get_result_value(r) }); + const rs: [16]u32 = .{ create_result(1, STATUS_COMPLETED, 0, 100), create_result(2, STATUS_COMPLETED, 0, 250), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + if (!(aggregate_results(rs, 2) == 350)) __t27_assert_fail("\n sum of result values:\n aggregate_results(rs, 2) = {any}\n", .{ aggregate_results(rs, 2) }); } test "highest_priority_skips_empty_slots" { - const ts: [8]u32 = .{ create_task(1,TASK_PRIORITY_LOW,1,1), create_task(2,TASK_PRIORITY_MEDIUM,1,1), create_task(3,TASK_PRIORITY_LOW,1,1), 0, 0, 0, 0, 0 }; - if (!(find_highest_priority_task(ts) == 1)) @panic("medium beats low, empties skipped"); - if (!(count_pending_tasks(ts) == 3)) @panic("three real tasks"); + const ts: [8]u32 = .{ create_task(1, TASK_PRIORITY_LOW, 1, 1), create_task(2, TASK_PRIORITY_MEDIUM, 1, 1), create_task(3, TASK_PRIORITY_LOW, 1, 1), 0, 0, 0, 0, 0 }; + if (!(find_highest_priority_task(ts) == 1)) __t27_assert_fail("\n medium beats low, empties skipped:\n find_highest_priority_task(ts) = {any}\n", .{ find_highest_priority_task(ts) }); + if (!(count_pending_tasks(ts) == 3)) __t27_assert_fail("\n three real tasks:\n count_pending_tasks(ts) = {any}\n", .{ count_pending_tasks(ts) }); } diff --git a/gen/zig/m3_multihop.zig b/gen/zig/m3_multihop.zig index 8c480825..33c6a03c 100644 --- a/gen/zig/m3_multihop.zig +++ b/gen/zig/m3_multihop.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} const NODE_A: u32 = 1; const NODE_B: u32 = 2; @@ -108,87 +116,126 @@ fn udp_packet_byte(seq: u16, byte_index: u8, data_byte: u8) u8 { return 0xBB; } test "expected_loss_rate_calculation" { - if (!(expected_loss_rate_p10(0) == 0x10)) @panic("expected_loss_rate_p10 0 == 0x10"); - if (!(expected_loss_rate_p10(10) > 0x10)) @panic("expected_loss_rate_p10 10 > 0x10"); - if (!(expected_loss_rate_p10(10) <= 0x40)) @panic("expected_loss_rate_p10 10 <= 0x40"); - if (!(expected_loss_rate_p10(36) == 0xC0)) @panic("expected_loss_rate_p10 36 == 0xC0"); + if (!(expected_loss_rate_p10(0) == 0x10)) __t27_assert_fail("\n expected_loss_rate_p10 0 == 0x10:\n expected_loss_rate_p10(0) = {any}\n", .{ expected_loss_rate_p10(0) }); + if (!(expected_loss_rate_p10(10) > 0x10)) __t27_assert_fail("\n expected_loss_rate_p10 10 > 0x10:\n expected_loss_rate_p10(10) = {any}\n", .{ expected_loss_rate_p10(10) }); + if (!(expected_loss_rate_p10(10) <= 0x40)) __t27_assert_fail("\n expected_loss_rate_p10 10 <= 0x40:\n expected_loss_rate_p10(10) = {any}\n", .{ expected_loss_rate_p10(10) }); + if (!(expected_loss_rate_p10(36) == 0xC0)) __t27_assert_fail("\n expected_loss_rate_p10 36 == 0xC0:\n expected_loss_rate_p10(36) = {any}\n", .{ expected_loss_rate_p10(36) }); } test "signal_quality_classification" { - if (!(signal_quality(5) == 0)) @panic("signal_quality 5 == 0"); - if (!(signal_quality(10) == 1)) @panic("signal_quality 10 == 1"); - if (!(signal_quality(15) == 2)) @panic("signal_quality 15 == 2"); - if (!(signal_quality(25) == 4)) @panic("signal_quality 25 == 4"); - if (!(signal_quality(30) == 5)) @panic("signal_quality 30 == 5"); + if (!(signal_quality(5) == 0)) __t27_assert_fail("\n signal_quality 5 == 0:\n signal_quality(5) = {any}\n", .{ signal_quality(5) }); + if (!(signal_quality(10) == 1)) __t27_assert_fail("\n signal_quality 10 == 1:\n signal_quality(10) = {any}\n", .{ signal_quality(10) }); + if (!(signal_quality(15) == 2)) __t27_assert_fail("\n signal_quality 15 == 2:\n signal_quality(15) = {any}\n", .{ signal_quality(15) }); + if (!(signal_quality(25) == 4)) __t27_assert_fail("\n signal_quality 25 == 4:\n signal_quality(25) = {any}\n", .{ signal_quality(25) }); + if (!(signal_quality(30) == 5)) __t27_assert_fail("\n signal_quality 30 == 5:\n signal_quality(30) = {any}\n", .{ signal_quality(30) }); } test "throughput_factor_calculation" { const factor0: u8 = throughput_factor_p8(0); - if (!(factor0 > 0xF0)) @panic("factor0 > 0xF0"); + if (!(factor0 > 0xF0)) __t27_assert_fail("\n factor0 > 0xF0:\n factor0 = {any}\n", .{ factor0 }); const factor10: u8 = throughput_factor_p8(10); - if (!(factor10 > 0xF0)) @panic("factor10 > 0xF0"); - if (!(factor10 < 0x100)) @panic("factor10 < 0x100"); + if (!(factor10 > 0xF0)) __t27_assert_fail("\n factor10 > 0xF0:\n factor10 = {any}\n", .{ factor10 }); + if (!(factor10 < 0x100)) __t27_assert_fail("\n factor10 < 0x100:\n factor10 = {any}\n", .{ factor10 }); const factor30: u8 = throughput_factor_p8(30); - if (!(factor30 > 0xD0)) @panic("factor30 > 0xD0"); - if (!(factor30 < 0xF0)) @panic("factor30 < 0xF0"); + if (!(factor30 > 0xD0)) __t27_assert_fail("\n factor30 > 0xD0:\n factor30 = {any}\n", .{ factor30 }); + if (!(factor30 < 0xF0)) __t27_assert_fail("\n factor30 < 0xF0:\n factor30 = {any}\n", .{ factor30 }); } test "total_attenuation_calculation" { - if (!(total_attenuation(10, 10) == 20)) @panic("total_attenuation 10 10 == 20"); - if (!(total_attenuation(15, 15) == 30)) @panic("total_attenuation 15 15 == 30"); - if (!(total_attenuation(20, 20) == 30)) @panic("total_attenuation 20 20 == 30"); + if (!(total_attenuation(10, 10) == 20)) __t27_assert_fail("\n total_attenuation 10 10 == 20:\n total_attenuation(10, 10) = {any}\n", .{ total_attenuation(10, 10) }); + if (!(total_attenuation(15, 15) == 30)) __t27_assert_fail("\n total_attenuation 15 15 == 30:\n total_attenuation(15, 15) = {any}\n", .{ total_attenuation(15, 15) }); + if (!(total_attenuation(20, 20) == 30)) __t27_assert_fail("\n total_attenuation 20 20 == 30:\n total_attenuation(20, 20) = {any}\n", .{ total_attenuation(20, 20) }); } test "delivery_rate_calculation" { const rate0: u8 = delivery_rate_p8(0, 0); - if (!(rate0 > 0xF0)) @panic("rate0 > 0xF0"); + if (!(rate0 > 0xF0)) __t27_assert_fail("\n rate0 > 0xF0:\n rate0 = {any}\n", .{ rate0 }); const rate10: u8 = delivery_rate_p8(10, 10); - if (!(rate10 > 0xF0)) @panic("rate10 > 0xF0"); - if (!(rate10 < 0x100)) @panic("rate10 < 0x100"); + if (!(rate10 > 0xF0)) __t27_assert_fail("\n rate10 > 0xF0:\n rate10 = {any}\n", .{ rate10 }); + if (!(rate10 < 0x100)) __t27_assert_fail("\n rate10 < 0x100:\n rate10 = {any}\n", .{ rate10 }); } test "tcp_packet_generation" { const seq: u32 = 0x12345678; - if (!(tcp_packet_byte(seq, 0, 0) == 0x12)) @panic("tcp_packet_byte seq 0 0 == 0x12"); - if (!(tcp_packet_byte(seq, 1, 0) == 0x34)) @panic("tcp_packet_byte seq 1 0 == 0x34"); - if (!(tcp_packet_byte(seq, 2, 0) == 0x56)) @panic("tcp_packet_byte seq 2 0 == 0x56"); - if (!(tcp_packet_byte(seq, 3, 0) == 0x78)) @panic("tcp_packet_byte seq 3 0 == 0x78"); - if (!(tcp_packet_byte(seq, 10, 0) == 0xAA)) @panic("tcp_packet_byte seq 10 0 == 0xAA"); + if (!(tcp_packet_byte(seq, 0, 0) == 0x12)) __t27_assert_fail("\n tcp_packet_byte seq 0 0 == 0x12:\n tcp_packet_byte(seq, 0, 0) = {any}\n", .{ tcp_packet_byte(seq, 0, 0) }); + if (!(tcp_packet_byte(seq, 1, 0) == 0x34)) __t27_assert_fail("\n tcp_packet_byte seq 1 0 == 0x34:\n tcp_packet_byte(seq, 1, 0) = {any}\n", .{ tcp_packet_byte(seq, 1, 0) }); + if (!(tcp_packet_byte(seq, 2, 0) == 0x56)) __t27_assert_fail("\n tcp_packet_byte seq 2 0 == 0x56:\n tcp_packet_byte(seq, 2, 0) = {any}\n", .{ tcp_packet_byte(seq, 2, 0) }); + if (!(tcp_packet_byte(seq, 3, 0) == 0x78)) __t27_assert_fail("\n tcp_packet_byte seq 3 0 == 0x78:\n tcp_packet_byte(seq, 3, 0) = {any}\n", .{ tcp_packet_byte(seq, 3, 0) }); + if (!(tcp_packet_byte(seq, 10, 0) == 0xAA)) __t27_assert_fail("\n tcp_packet_byte seq 10 0 == 0xAA:\n tcp_packet_byte(seq, 10, 0) = {any}\n", .{ tcp_packet_byte(seq, 10, 0) }); } test "udp_packet_generation" { const seq: u16 = 0x1234; - if (!(udp_packet_byte(seq, 0, 0) == 0x12)) @panic("udp_packet_byte seq 0 0 == 0x12"); - if (!(udp_packet_byte(seq, 1, 0) == 0x34)) @panic("udp_packet_byte seq 1 0 == 0x34"); - if (!(udp_packet_byte(seq, 10, 0) == 0xBB)) @panic("udp_packet_byte seq 10 0 == 0xBB"); + if (!(udp_packet_byte(seq, 0, 0) == 0x12)) __t27_assert_fail("\n udp_packet_byte seq 0 0 == 0x12:\n udp_packet_byte(seq, 0, 0) = {any}\n", .{ udp_packet_byte(seq, 0, 0) }); + if (!(udp_packet_byte(seq, 1, 0) == 0x34)) __t27_assert_fail("\n udp_packet_byte seq 1 0 == 0x34:\n udp_packet_byte(seq, 1, 0) = {any}\n", .{ udp_packet_byte(seq, 1, 0) }); + if (!(udp_packet_byte(seq, 10, 0) == 0xBB)) __t27_assert_fail("\n udp_packet_byte seq 10 0 == 0xBB:\n udp_packet_byte(seq, 10, 0) = {any}\n", .{ udp_packet_byte(seq, 10, 0) }); } test "hop_simulation" { var success_count: u8 = 0; _ = &success_count; - for (0..10) |i| { + for (0 .. 10) |i| { if (simulate_hop(0, @as(u8, @intCast(i * 11)))) { success_count = success_count + 1; } } - if (!(success_count > 8)) @panic("success_count > 8"); + if (!(success_count > 8)) __t27_assert_fail("\n success_count > 8:\n success_count = {any}\n", .{ success_count }); var success_count_high: u8 = 0; _ = &success_count_high; - for (0..10) |i| { + for (0 .. 10) |i| { if (simulate_hop(20, @as(u8, @intCast(i * 11)))) { success_count_high = success_count_high + 1; } } - if (!(success_count_high < success_count)) @panic("attenuated link loses at least one packet"); + if (!(success_count_high < success_count)) __t27_assert_fail("\n attenuated link loses at least one packet:\n success_count_high = {any}\n success_count = {any}\n", .{ success_count_high, success_count }); } test "two_hop_forwarding" { var success_count: u8 = 0; _ = &success_count; - for (0..10) |i| { + for (0 .. 10) |i| { if (forward_packet(0, 0, @as(u8, @intCast(i * 11)))) { success_count = success_count + 1; } } - if (!(success_count > 7)) @panic("success_count > 7"); + if (!(success_count > 7)) __t27_assert_fail("\n success_count > 7:\n success_count = {any}\n", .{ success_count }); var success_count_high: u8 = 0; _ = &success_count_high; - for (0..10) |i| { + for (0 .. 10) |i| { if (forward_packet(15, 15, @as(u8, @intCast(i * 11)))) { success_count_high = success_count_high + 1; } } - if (!(success_count_high <= success_count)) @panic("attenuated path does not beat the clean one"); + if (!(success_count_high <= success_count)) __t27_assert_fail("\n attenuated path does not beat the clean one:\n success_count_high = {any}\n success_count = {any}\n", .{ success_count_high, success_count }); +} +const ST_IDLE: u8 = 0; +const ST_RUNNING: u8 = 1; +const ST_COMPLETE: u8 = 2; +const PerfCounters = struct { + packets_sent: u32, + packets_delivered: u32, + packets_lost: u32, + bytes_sent: u32, + test_duration_ms: u32, +}; +fn calculate_throughput_mbps(counters: PerfCounters) u32 { + const bits: u64 = @as(u64, @intCast(counters.bytes_sent)) << 3; + const duration_sec: u64 = @as(u64, @intCast(counters.test_duration_ms)) / 1000; + if (duration_sec == 0) { + 0; + } else { + @as(u32, @intCast((bits / duration_sec) / 1_000_000)); + } +} +fn calculate_loss_pct(counters: PerfCounters) u8 { + if (counters.packets_sent == 0) { + 0; + } else { + const lost: u32 = counters.packets_sent - counters.packets_delivered; + const loss_p10: u32 = (lost * 1000) / counters.packets_sent; + @as(u8, @intCast(loss_p10 / 10)); + } +} +fn meets_targets(counters: PerfCounters, hop_count: u8) bool { + const throughput: u32 = calculate_throughput_mbps(counters); + const target_throughput: u32 = TARGET_THROUGHPUT_MBPS * @as(u32, @intCast(hop_count)); + const loss_pct: u8 = calculate_loss_pct(counters); + (throughput >= target_throughput) and (loss_pct < TARGET_PACKET_LOSS_PCT); +} +fn test_next_state(current_state: u8, test_complete: bool) u8 { + _ = current_state; // unused by the spec body + _ = test_complete; // unused by the spec body + ; } diff --git a/gen/zig/mesh_node_sim.zig b/gen/zig/mesh_node_sim.zig index 6cead8b4..49f590d5 100644 --- a/gen/zig/mesh_node_sim.zig +++ b/gen/zig/mesh_node_sim.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const NODE_1: u32 = 1; @@ -60,60 +68,60 @@ fn calculate_hops(from: u32, to: u32, topology: u8) u8 { } test "create_link_quality_correct" { const link = create_link_quality(NODE_1, NODE_2, 200); - if (!(link_from(link) == NODE_1)) @panic("from node"); - if (!(link_to(link) == NODE_2)) @panic("to node"); - if (!(link_quality(link) == 200)) @panic("quality"); + if (!(link_from(link) == NODE_1)) __t27_assert_fail("\n from node:\n link_from(link) = {any}\n NODE_1 = {any}\n", .{ link_from(link), NODE_1 }); + if (!(link_to(link) == NODE_2)) __t27_assert_fail("\n to node:\n link_to(link) = {any}\n NODE_2 = {any}\n", .{ link_to(link), NODE_2 }); + if (!(link_quality(link) == 200)) __t27_assert_fail("\n quality:\n link_quality(link) = {any}\n", .{ link_quality(link) }); } test "is_link_good_threshold" { const link = create_link_quality(NODE_1, NODE_2, 150); - if (!(is_link_good(link, 100) == true)) @panic("above threshold"); - if (!(is_link_good(link, 200) == false)) @panic("below threshold"); + if (!(is_link_good(link, 100) == true)) __t27_assert_fail("\n above threshold:\n is_link_good(link, 100) = {any}\n", .{ is_link_good(link, 100) }); + if (!(is_link_good(link, 200) == false)) __t27_assert_fail("\n below threshold:\n is_link_good(link, 200) = {any}\n", .{ is_link_good(link, 200) }); } test "create_2node_mesh" { const link1, const link2 = create_2node_mesh(180); - if (!(link_from(link1) == NODE_1)) @panic("1→2"); - if (!(link_from(link2) == NODE_2)) @panic("2→1"); - if (!(link_quality(link1) == 180)) @panic("quality same"); + if (!(link_from(link1) == NODE_1)) __t27_assert_fail("\n 1→2:\n link_from(link1) = {any}\n NODE_1 = {any}\n", .{ link_from(link1), NODE_1 }); + if (!(link_from(link2) == NODE_2)) __t27_assert_fail("\n 2→1:\n link_from(link2) = {any}\n NODE_2 = {any}\n", .{ link_from(link2), NODE_2 }); + if (!(link_quality(link1) == 180)) __t27_assert_fail("\n quality same:\n link_quality(link1) = {any}\n", .{ link_quality(link1) }); } test "create_3node_mesh" { const link1, const link2, const link3 = create_3node_mesh(100, 150, 200); - if (!(link_to(link1) == NODE_2)) @panic("1→2"); - if (!(link_to(link2) == NODE_3)) @panic("2→3"); - if (!(link_to(link3) == NODE_1)) @panic("3→1"); + if (!(link_to(link1) == NODE_2)) __t27_assert_fail("\n 1→2:\n link_to(link1) = {any}\n NODE_2 = {any}\n", .{ link_to(link1), NODE_2 }); + if (!(link_to(link2) == NODE_3)) __t27_assert_fail("\n 2→3:\n link_to(link2) = {any}\n NODE_3 = {any}\n", .{ link_to(link2), NODE_3 }); + if (!(link_to(link3) == NODE_1)) __t27_assert_fail("\n 3→1:\n link_to(link3) = {any}\n NODE_1 = {any}\n", .{ link_to(link3), NODE_1 }); } test "create_4node_line" { const link1, const link2, const link3 = create_4node_line(120, 130, 140); - if (!(link_from(link1) == NODE_1)) @panic("1→2"); - if (!(link_from(link2) == NODE_2)) @panic("2→3"); - if (!(link_from(link3) == NODE_3)) @panic("3→4"); + if (!(link_from(link1) == NODE_1)) __t27_assert_fail("\n 1→2:\n link_from(link1) = {any}\n NODE_1 = {any}\n", .{ link_from(link1), NODE_1 }); + if (!(link_from(link2) == NODE_2)) __t27_assert_fail("\n 2→3:\n link_from(link2) = {any}\n NODE_2 = {any}\n", .{ link_from(link2), NODE_2 }); + if (!(link_from(link3) == NODE_3)) __t27_assert_fail("\n 3→4:\n link_from(link3) = {any}\n NODE_3 = {any}\n", .{ link_from(link3), NODE_3 }); } test "calculate_hops_same_node" { const hops = calculate_hops(NODE_1, NODE_1, 2); - if (!(hops == 0)) @panic("same node = 0 hops"); + if (!(hops == 0)) __t27_assert_fail("\n same node = 0 hops:\n hops = {any}\n", .{ hops }); } test "calculate_hops_2node" { const hops = calculate_hops(NODE_1, NODE_2, 2); - if (!(hops == 1)) @panic("2-node = 1 hop"); + if (!(hops == 1)) __t27_assert_fail("\n 2-node = 1 hop:\n hops = {any}\n", .{ hops }); } test "calculate_hops_3node_direct" { const hops = calculate_hops(NODE_1, NODE_2, 3); - if (!(hops == 1)) @panic("3-node direct = 1 hop"); + if (!(hops == 1)) __t27_assert_fail("\n 3-node direct = 1 hop:\n hops = {any}\n", .{ hops }); } test "calculate_hops_4node_adjacent" { const hops = calculate_hops(NODE_1, NODE_2, 4); - if (!(hops == 1)) @panic("4-node adjacent = 1 hop"); + if (!(hops == 1)) __t27_assert_fail("\n 4-node adjacent = 1 hop:\n hops = {any}\n", .{ hops }); } test "calculate_hops_4node_2hops" { const hops = calculate_hops(NODE_1, NODE_3, 4); - if (!(hops == 2)) @panic("4-node 1→3 = 2 hops"); + if (!(hops == 2)) __t27_assert_fail("\n 4-node 1→3 = 2 hops:\n hops = {any}\n", .{ hops }); } test "calculate_hops_4node_3hops" { const hops = calculate_hops(NODE_1, NODE_4, 4); - if (!(hops == 3)) @panic("4-node 1→4 = 3 hops"); + if (!(hops == 3)) __t27_assert_fail("\n 4-node 1→4 = 3 hops:\n hops = {any}\n", .{ hops }); } test "link_quality_threshold_check" { const link1, _ = create_2node_mesh(50); - if (!(is_link_good(link1, 75) == false)) @panic("poor link"); + if (!(is_link_good(link1, 75) == false)) __t27_assert_fail("\n poor link:\n is_link_good(link1, 75) = {any}\n", .{ is_link_good(link1, 75) }); const link2, _ = create_2node_mesh(100); - if (!(is_link_good(link2, 75) == true)) @panic("good link"); + if (!(is_link_good(link2, 75) == true)) __t27_assert_fail("\n good link:\n is_link_good(link2, 75) = {any}\n", .{ is_link_good(link2, 75) }); } diff --git a/gen/zig/mesh_protocol_stack.zig b/gen/zig/mesh_protocol_stack.zig index eed564af..3c13d203 100644 --- a/gen/zig/mesh_protocol_stack.zig +++ b/gen/zig/mesh_protocol_stack.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_NODES: u32 = 3; @@ -68,97 +76,97 @@ fn forward_packet(packet: u32, current_node: u32) struct { u32, bool, u32 } { } test "build_packet_correct_layout" { const pkt = build_packet(NODE_A, NODE_B, 3, 5); - if (!(extract_src(pkt) == NODE_A)) @panic("src preserved"); - if (!(extract_dst(pkt) == NODE_B)) @panic("dst preserved"); - if (!(extract_ttl(pkt) == 3)) @panic("ttl preserved"); - if (!(extract_payload(pkt) == 5)) @panic("payload preserved"); + if (!(extract_src(pkt) == NODE_A)) __t27_assert_fail("\n src preserved:\n extract_src(pkt) = {any}\n NODE_A = {any}\n", .{ extract_src(pkt), NODE_A }); + if (!(extract_dst(pkt) == NODE_B)) __t27_assert_fail("\n dst preserved:\n extract_dst(pkt) = {any}\n NODE_B = {any}\n", .{ extract_dst(pkt), NODE_B }); + if (!(extract_ttl(pkt) == 3)) __t27_assert_fail("\n ttl preserved:\n extract_ttl(pkt) = {any}\n", .{ extract_ttl(pkt) }); + if (!(extract_payload(pkt) == 5)) __t27_assert_fail("\n payload preserved:\n extract_payload(pkt) = {any}\n", .{ extract_payload(pkt) }); } test "tx_path_produces_valid_packet" { const pkt = tx_path(NODE_A, NODE_B, 7); - if (!(extract_src(pkt) == NODE_A)) @panic("tx src"); - if (!(extract_dst(pkt) == NODE_B)) @panic("tx dst"); - if (!(extract_payload(pkt) == 7)) @panic("tx payload"); + if (!(extract_src(pkt) == NODE_A)) __t27_assert_fail("\n tx src:\n extract_src(pkt) = {any}\n NODE_A = {any}\n", .{ extract_src(pkt), NODE_A }); + if (!(extract_dst(pkt) == NODE_B)) __t27_assert_fail("\n tx dst:\n extract_dst(pkt) = {any}\n NODE_B = {any}\n", .{ extract_dst(pkt), NODE_B }); + if (!(extract_payload(pkt) == 7)) __t27_assert_fail("\n tx payload:\n extract_payload(pkt) = {any}\n", .{ extract_payload(pkt) }); } test "rx_path_extracts_payload" { const pkt = build_packet(NODE_A, NODE_B, 3, 9); const payload = rx_path(pkt); - if (!(payload == 9)) @panic("rx payload"); + if (!(payload == 9)) __t27_assert_fail("\n rx payload:\n payload = {any}\n", .{ payload }); } test "decrement_ttl_reduces" { const pkt = build_packet(NODE_A, NODE_B, 3, 5); const new_pkt, const expired = decrement_ttl(pkt); - if (!(extract_ttl(new_pkt) == 2)) @panic("ttl decremented"); - if (!(expired == false)) @panic("not expired"); + if (!(extract_ttl(new_pkt) == 2)) __t27_assert_fail("\n ttl decremented:\n extract_ttl(new_pkt) = {any}\n", .{ extract_ttl(new_pkt) }); + if (!(expired == false)) __t27_assert_fail("\n not expired:\n expired = {any}\n", .{ expired }); } test "decrement_ttl_zero_expires" { const pkt = build_packet(NODE_A, NODE_B, 1, 5); const new_pkt, const expired = decrement_ttl(pkt); - if (!(extract_ttl(new_pkt) == 0)) @panic("ttl zero"); - if (!(expired == true)) @panic("expired"); + if (!(extract_ttl(new_pkt) == 0)) __t27_assert_fail("\n ttl zero:\n extract_ttl(new_pkt) = {any}\n", .{ extract_ttl(new_pkt) }); + if (!(expired == true)) __t27_assert_fail("\n expired:\n expired = {any}\n", .{ expired }); } test "decrement_ttl_already_expired" { const pkt = build_packet(NODE_A, NODE_B, 0, 5); const new_pkt, const expired = decrement_ttl(pkt); - if (!(extract_ttl(new_pkt) == 0)) @panic("ttl zero"); - if (!(expired == true)) @panic("expired"); + if (!(extract_ttl(new_pkt) == 0)) __t27_assert_fail("\n ttl zero:\n extract_ttl(new_pkt) = {any}\n", .{ extract_ttl(new_pkt) }); + if (!(expired == true)) __t27_assert_fail("\n expired:\n expired = {any}\n", .{ expired }); } test "route_packet_direct_a_to_b" { const next_hop = route_packet(NODE_A, NODE_B, 0); - if (!(next_hop == NODE_B)) @panic("direct route A→B"); + if (!(next_hop == NODE_B)) __t27_assert_fail("\n direct route A→B:\n next_hop = {any}\n NODE_B = {any}\n", .{ next_hop, NODE_B }); } test "route_packet_via_b_a_to_c" { const next_hop = route_packet(NODE_A, NODE_C, 0); - if (!(next_hop == NODE_B)) @panic("route A→C via B"); + if (!(next_hop == NODE_B)) __t27_assert_fail("\n route A→C via B:\n next_hop = {any}\n NODE_B = {any}\n", .{ next_hop, NODE_B }); } test "route_packet_direct_b_to_c" { const next_hop = route_packet(NODE_B, NODE_C, 0); - if (!(next_hop == NODE_C)) @panic("direct route B→C"); + if (!(next_hop == NODE_C)) __t27_assert_fail("\n direct route B→C:\n next_hop = {any}\n NODE_C = {any}\n", .{ next_hop, NODE_C }); } test "forward_packet_decrements_ttl" { const pkt = build_packet(NODE_A, NODE_B, 3, 5); const new_pkt, const expired, const next_hop = forward_packet(pkt, NODE_A); - if (!(extract_ttl(new_pkt) == 2)) @panic("ttl decreased"); - if (!(expired == false)) @panic("not expired"); - if (!(next_hop == NODE_B)) @panic("next hop B"); + if (!(extract_ttl(new_pkt) == 2)) __t27_assert_fail("\n ttl decreased:\n extract_ttl(new_pkt) = {any}\n", .{ extract_ttl(new_pkt) }); + if (!(expired == false)) __t27_assert_fail("\n not expired:\n expired = {any}\n", .{ expired }); + if (!(next_hop == NODE_B)) __t27_assert_fail("\n next hop B:\n next_hop = {any}\n NODE_B = {any}\n", .{ next_hop, NODE_B }); } test "forward_packet_preserves_payload" { const pkt = build_packet(NODE_A, NODE_B, 3, 5); const fwd, _, _ = forward_packet(pkt, NODE_A); - if (!(extract_ttl(fwd) == 2)) @panic("only the TTL changes (3 -> 2)"); - if (!(extract_src(fwd) == NODE_A)) @panic("src preserved across the hop"); - if (!(extract_dst(fwd) == NODE_B)) @panic("dst preserved across the hop"); - if (!(extract_payload(fwd) == 5)) @panic("payload preserved across the hop"); + if (!(extract_ttl(fwd) == 2)) __t27_assert_fail("\n only the TTL changes (3 -> 2):\n extract_ttl(fwd) = {any}\n", .{ extract_ttl(fwd) }); + if (!(extract_src(fwd) == NODE_A)) __t27_assert_fail("\n src preserved across the hop:\n extract_src(fwd) = {any}\n NODE_A = {any}\n", .{ extract_src(fwd), NODE_A }); + if (!(extract_dst(fwd) == NODE_B)) __t27_assert_fail("\n dst preserved across the hop:\n extract_dst(fwd) = {any}\n NODE_B = {any}\n", .{ extract_dst(fwd), NODE_B }); + if (!(extract_payload(fwd) == 5)) __t27_assert_fail("\n payload preserved across the hop:\n extract_payload(fwd) = {any}\n", .{ extract_payload(fwd) }); const fwd2, _, _ = forward_packet(fwd, NODE_A); - if (!(extract_payload(fwd2) == 5)) @panic("payload preserved after a second hop"); - if (!(extract_src(fwd2) == NODE_A)) @panic("src still preserved"); - if (!(extract_dst(fwd2) == NODE_B)) @panic("dst still preserved"); - if (!(extract_ttl(fwd2) == 1)) @panic("TTL 2 -> 1 on the second hop"); + if (!(extract_payload(fwd2) == 5)) __t27_assert_fail("\n payload preserved after a second hop:\n extract_payload(fwd2) = {any}\n", .{ extract_payload(fwd2) }); + if (!(extract_src(fwd2) == NODE_A)) __t27_assert_fail("\n src still preserved:\n extract_src(fwd2) = {any}\n NODE_A = {any}\n", .{ extract_src(fwd2), NODE_A }); + if (!(extract_dst(fwd2) == NODE_B)) __t27_assert_fail("\n dst still preserved:\n extract_dst(fwd2) = {any}\n NODE_B = {any}\n", .{ extract_dst(fwd2), NODE_B }); + if (!(extract_ttl(fwd2) == 1)) __t27_assert_fail("\n TTL 2 -> 1 on the second hop:\n extract_ttl(fwd2) = {any}\n", .{ extract_ttl(fwd2) }); } test "forward_packet_ttl_expired" { const pkt = build_packet(NODE_A, NODE_B, 1, 5); const pkt1, _, _ = forward_packet(pkt, NODE_A); _, const exp2, _ = forward_packet(pkt1, NODE_B); - if (!(exp2 == true)) @panic("expired after 2 hops"); + if (!(exp2 == true)) __t27_assert_fail("\n expired after 2 hops:\n exp2 = {any}\n", .{ exp2 }); } test "forward_packet_no_route" { const pkt = build_packet(NODE_A, 99, 3, 5); _, const expired, const next_hop = forward_packet(pkt, NODE_A); - if (!(next_hop == 0)) @panic("no route"); - if (!(expired == false)) @panic("ttl not expired yet"); + if (!(next_hop == 0)) __t27_assert_fail("\n no route:\n next_hop = {any}\n", .{ next_hop }); + if (!(expired == false)) __t27_assert_fail("\n ttl not expired yet:\n expired = {any}\n", .{ expired }); } test "end_to_end_tx_rx" { const pkt = tx_path(NODE_A, NODE_B, 42); const payload = rx_path(pkt); - if (!(payload == 42)) @panic("end-to-end payload"); + if (!(payload == 42)) __t27_assert_fail("\n end-to-end payload:\n payload = {any}\n", .{ payload }); } test "multi_hop_routing" { const pkt = tx_path(NODE_A, NODE_C, 7); const pkt1, const exp1, const hop1 = forward_packet(pkt, NODE_A); - if (!(hop1 == NODE_B)) @panic("first hop to B"); - if (!(exp1 == false)) @panic("not expired"); + if (!(hop1 == NODE_B)) __t27_assert_fail("\n first hop to B:\n hop1 = {any}\n NODE_B = {any}\n", .{ hop1, NODE_B }); + if (!(exp1 == false)) __t27_assert_fail("\n not expired:\n exp1 = {any}\n", .{ exp1 }); const pkt2, const exp2, const hop2 = forward_packet(pkt1, NODE_B); - if (!(hop2 == NODE_C)) @panic("second hop to C"); - if (!(exp2 == false)) @panic("not expired"); + if (!(hop2 == NODE_C)) __t27_assert_fail("\n second hop to C:\n hop2 = {any}\n NODE_C = {any}\n", .{ hop2, NODE_C }); + if (!(exp2 == false)) __t27_assert_fail("\n not expired:\n exp2 = {any}\n", .{ exp2 }); const payload = rx_path(pkt2); - if (!(payload == 7)) @panic("multi-hop payload"); + if (!(payload == 7)) __t27_assert_fail("\n multi-hop payload:\n payload = {any}\n", .{ payload }); } diff --git a/gen/zig/mesh_routing.zig b/gen/zig/mesh_routing.zig index 8414f14c..842dffa3 100644 --- a/gen/zig/mesh_routing.zig +++ b/gen/zig/mesh_routing.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const DEFAULT_TTL: u8 = 8; @@ -101,14 +109,14 @@ fn delivery_decision(is_local: bool, ttl_expired: bool, route_exists: bool, dest } test "mesh_ip_converts_correctly" { const a, const b, const c, const d = mesh_ip(1); - if (!(a == 10)) @panic("network A should be 10"); - if (!(b == 42)) @panic("network B should be 42"); - if (!(c == 0)) @panic("network C should be 0"); - if (!(d == 1)) @panic("node D should be 1"); + if (!(a == 10)) __t27_assert_fail("\n network A should be 10:\n a = {any}\n", .{ a }); + if (!(b == 42)) __t27_assert_fail("\n network B should be 42:\n b = {any}\n", .{ b }); + if (!(c == 0)) __t27_assert_fail("\n network C should be 0:\n c = {any}\n", .{ c }); + if (!(d == 1)) __t27_assert_fail("\n node D should be 1:\n d = {any}\n", .{ d }); } test "mesh_ip_max_node_id" { _, _, _, const d = mesh_ip(254); - if (!(d == 254)) @panic("max node ID should be 254"); + if (!(d == 254)) __t27_assert_fail("\n max node ID should be 254:\n d = {any}\n", .{ d }); } test "is_mesh_subnet_valid" { const valid = is_mesh_subnet(10, 42, 0); @@ -116,103 +124,103 @@ test "is_mesh_subnet_valid" { } test "is_mesh_subnet_invalid_network" { const valid = is_mesh_subnet(192, 168, 1); - if (!(valid == false)) @panic("192.168.1.0 should not be mesh subnet"); + if (!(valid == false)) __t27_assert_fail("\n 192.168.1.0 should not be mesh subnet:\n valid = {any}\n", .{ valid }); } test "node_of_ip_valid" { const node_id, const valid = node_of_ip(10, 42, 0, 100); - if (!(node_id == 100)) @panic("node ID should be 100"); + if (!(node_id == 100)) __t27_assert_fail("\n node ID should be 100:\n node_id = {any}\n", .{ node_id }); if (!(valid)) @panic("should be valid"); } test "node_of_ip_invalid_subnet" { _, const valid = node_of_ip(192, 168, 1, 100); - if (!(valid == false)) @panic("wrong subnet should be invalid"); + if (!(valid == false)) __t27_assert_fail("\n wrong subnet should be invalid:\n valid = {any}\n", .{ valid }); } test "node_of_ip_invalid_range" { _, const valid = node_of_ip(10, 42, 0, 255); - if (!(valid == false)) @panic("node ID 255 should be invalid"); + if (!(valid == false)) __t27_assert_fail("\n node ID 255 should be invalid:\n valid = {any}\n", .{ valid }); } test "node_of_ip_min_boundary" { const node_id, const valid = node_of_ip(10, 42, 0, 1); - if (!(node_id == 1)) @panic("min node ID should be 1"); + if (!(node_id == 1)) __t27_assert_fail("\n min node ID should be 1:\n node_id = {any}\n", .{ node_id }); if (!(valid)) @panic("min node ID should be valid"); } test "decrement_ttl_normal" { const new_ttl, const expired = decrement_ttl(8); - if (!(new_ttl == 7)) @panic("TTL should decrement to 7"); - if (!(expired == false)) @panic("should not be expired"); + if (!(new_ttl == 7)) __t27_assert_fail("\n TTL should decrement to 7:\n new_ttl = {any}\n", .{ new_ttl }); + if (!(expired == false)) __t27_assert_fail("\n should not be expired:\n expired = {any}\n", .{ expired }); } test "decrement_ttl_at_one" { const new_ttl, const expired = decrement_ttl(1); - if (!(new_ttl == 0)) @panic("TTL should go to 0"); - if (!(expired == true)) @panic("should be expired"); + if (!(new_ttl == 0)) __t27_assert_fail("\n TTL should go to 0:\n new_ttl = {any}\n", .{ new_ttl }); + if (!(expired == true)) __t27_assert_fail("\n should be expired:\n expired = {any}\n", .{ expired }); } test "decrement_ttl_at_zero" { const new_ttl, const expired = decrement_ttl(0); - if (!(new_ttl == 0)) @panic("TTL should stay 0"); - if (!(expired == true)) @panic("should be expired"); + if (!(new_ttl == 0)) __t27_assert_fail("\n TTL should stay 0:\n new_ttl = {any}\n", .{ new_ttl }); + if (!(expired == true)) __t27_assert_fail("\n should be expired:\n expired = {any}\n", .{ expired }); } test "is_ttl_expired_check" { const expired = is_ttl_expired(0); if (!(expired)) @panic("TTL 0 should be expired"); const not_expired = is_ttl_expired(5); - if (!(not_expired == false)) @panic("TTL 5 should not be expired"); + if (!(not_expired == false)) __t27_assert_fail("\n TTL 5 should not be expired:\n not_expired = {any}\n", .{ not_expired }); } test "choose_next_hop_all_finite" { const next_hop, const found = choose_next_hop(256, 512, 1024, true, true, true); - if (!(next_hop == 1)) @panic("should choose n1 (lowest ETX)"); + if (!(next_hop == 1)) __t27_assert_fail("\n should choose n1 (lowest ETX):\n next_hop = {any}\n", .{ next_hop }); if (!(found)) @panic("should find next hop"); } test "choose_next_hop_two_finite" { const next_hop, const found = choose_next_hop(512, 256, 0xFFFF, true, true, false); - if (!(next_hop == 2)) @panic("should choose n2 (lowest finite)"); + if (!(next_hop == 2)) __t27_assert_fail("\n should choose n2 (lowest finite):\n next_hop = {any}\n", .{ next_hop }); if (!(found)) @panic("should find next hop"); } test "choose_next_hop_one_finite" { const next_hop, const found = choose_next_hop(0xFFFF, 512, 0xFFFF, false, true, false); - if (!(next_hop == 2)) @panic("should choose only finite n2"); + if (!(next_hop == 2)) __t27_assert_fail("\n should choose only finite n2:\n next_hop = {any}\n", .{ next_hop }); if (!(found)) @panic("should find next hop"); } test "choose_next_hop_none_finite" { _, const found = choose_next_hop(0xFFFF, 0xFFFF, 0xFFFF, true, true, true); - if (!(found == false)) @panic("should not find next hop"); + if (!(found == false)) __t27_assert_fail("\n should not find next hop:\n found = {any}\n", .{ found }); } test "choose_next_hop_tie_breaker" { const next_hop, const found = choose_next_hop(512, 512, 1024, true, true, false); - if (!(next_hop == 1)) @panic("should prefer n1 in tie"); + if (!(next_hop == 1)) __t27_assert_fail("\n should prefer n1 in tie:\n next_hop = {any}\n", .{ next_hop }); if (!(found)) @panic("should find next hop"); } test "delivery_decision_local" { const action, const next_hop = delivery_decision(true, false, true, 5); - if (!(action == 0)) @panic("should deliver locally"); - if (!(next_hop == 0)) @panic("next hop irrelevant for local"); + if (!(action == 0)) __t27_assert_fail("\n should deliver locally:\n action = {any}\n", .{ action }); + if (!(next_hop == 0)) __t27_assert_fail("\n next hop irrelevant for local:\n next_hop = {any}\n", .{ next_hop }); } test "delivery_decision_ttl_expired" { const action, const next_hop = delivery_decision(false, true, true, 5); - if (!(action == 2)) @panic("should drop (TTL expired)"); - if (!(next_hop == 0)) @panic("next hop irrelevant for drop"); + if (!(action == 2)) __t27_assert_fail("\n should drop (TTL expired):\n action = {any}\n", .{ action }); + if (!(next_hop == 0)) __t27_assert_fail("\n next hop irrelevant for drop:\n next_hop = {any}\n", .{ next_hop }); } test "delivery_decision_no_route" { const action, const next_hop = delivery_decision(false, false, false, 5); - if (!(action == 2)) @panic("should drop (no route)"); - if (!(next_hop == 0)) @panic("next hop irrelevant for drop"); + if (!(action == 2)) __t27_assert_fail("\n should drop (no route):\n action = {any}\n", .{ action }); + if (!(next_hop == 0)) __t27_assert_fail("\n next hop irrelevant for drop:\n next_hop = {any}\n", .{ next_hop }); } test "delivery_decision_forward" { const action, const next_hop = delivery_decision(false, false, true, 7); - if (!(action == 1)) @panic("should forward"); - if (!(next_hop == 7)) @panic("should forward to destination"); + if (!(action == 1)) __t27_assert_fail("\n should forward:\n action = {any}\n", .{ action }); + if (!(next_hop == 7)) __t27_assert_fail("\n should forward to destination:\n next_hop = {any}\n", .{ next_hop }); } test "full_routing_flow" { const dest_node, const valid_dest = node_of_ip(10, 42, 0, 100); - if (!(dest_node == 100)) @panic("destination should be node 100"); + if (!(dest_node == 100)) __t27_assert_fail("\n destination should be node 100:\n dest_node = {any}\n", .{ dest_node }); if (!(valid_dest)) @panic("destination should be valid"); const is_local = dest_node == 2; - if (!(is_local == false)) @panic("not for us, need to forward"); + if (!(is_local == false)) __t27_assert_fail("\n not for us, need to forward:\n is_local = {any}\n", .{ is_local }); _, const ttl_expired = decrement_ttl(7); - if (!(ttl_expired == false)) @panic("TTL still valid"); + if (!(ttl_expired == false)) __t27_assert_fail("\n TTL still valid:\n ttl_expired = {any}\n", .{ ttl_expired }); const next_hop, const route_exists = choose_next_hop(512, 1024, 256, true, true, true); - if (!(next_hop == 3)) @panic("should forward via node 3"); + if (!(next_hop == 3)) __t27_assert_fail("\n should forward via node 3:\n next_hop = {any}\n", .{ next_hop }); if (!(route_exists)) @panic("route exists"); const action, const final_hop = delivery_decision(is_local, ttl_expired, route_exists, next_hop); - if (!(action == 1)) @panic("should forward"); - if (!(final_hop == 3)) @panic("forward to node 3"); + if (!(action == 1)) __t27_assert_fail("\n should forward:\n action = {any}\n", .{ action }); + if (!(final_hop == 3)) __t27_assert_fail("\n forward to node 3:\n final_hop = {any}\n", .{ final_hop }); } diff --git a/gen/zig/modem_frame.zig b/gen/zig/modem_frame.zig index dadca0f2..34d34ae6 100644 --- a/gen/zig/modem_frame.zig +++ b/gen/zig/modem_frame.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const PREAMBLE_LEN: usize = 13; @@ -32,32 +40,60 @@ fn sync_margin_pct() usize { return (SYNC_THRESHOLD * 100) / PEAK; } test "empty_frame_is_21_symbols" { + const s = frame_symbols(0); + if (!(s == 21)) __t27_assert_fail("\n assertion failed:\n s = {any}\n", .{ s }); } test "one_byte_payload_is_29_symbols" { + const s = frame_symbols(1); + if (!(s == 29)) __t27_assert_fail("\n assertion failed:\n s = {any}\n", .{ s }); } test "max_frame_symbols" { + const s = frame_symbols(255); + if (!(s == 2061)) __t27_assert_fail("\n assertion failed:\n s = {any}\n", .{ s }); } test "min_parse_len_is_preamble_plus_length_byte" { + const m = min_parse_len(); + if (!(m == 21)) __t27_assert_fail("\n assertion failed:\n m = {any}\n", .{ m }); } test "can_parse_gate" { + const ok = can_parse(21); + const short = can_parse(20); + if (!(ok == true)) __t27_assert_fail("\n assertion failed:\n ok = {any}\n", .{ ok }); + if (!(short == false)) __t27_assert_fail("\n assertion failed:\n short = {any}\n", .{ short }); } test "payload_cap" { + const fits = payload_fits(255); + const over = payload_fits(256); + if (!(fits == true)) __t27_assert_fail("\n assertion failed:\n fits = {any}\n", .{ fits }); + if (!(over == false)) __t27_assert_fail("\n assertion failed:\n over = {any}\n", .{ over }); } test "decode_bounds" { + const inside = decode_fits(13, 2, 29); + const past = decode_fits(13, 2, 28); + if (!(inside == true)) __t27_assert_fail("\n assertion failed:\n inside = {any}\n", .{ inside }); + if (!(past == false)) __t27_assert_fail("\n assertion failed:\n past = {any}\n", .{ past }); } test "sync_gate" { + const locked = is_synced(13); + const edge = is_synced(8); + const noise = is_synced(7); + if (!(locked == true)) __t27_assert_fail("\n assertion failed:\n locked = {any}\n", .{ locked }); + if (!(edge == true)) __t27_assert_fail("\n assertion failed:\n edge = {any}\n", .{ edge }); + if (!(noise == false)) __t27_assert_fail("\n assertion failed:\n noise = {any}\n", .{ noise }); } test "sync_margin_is_61_percent" { + const p = sync_margin_pct(); + if (!(p == 61)) __t27_assert_fail("\n assertion failed:\n p = {any}\n", .{ p }); } comptime { // invariant: preamble_is_barker13 - // invariant: preamble_is_barker13 verified (no statements) + if (!(PREAMBLE_LEN == 13)) __t27_assert_fail("\n assertion failed:\n PREAMBLE_LEN = {any}\n", .{ PREAMBLE_LEN }); } comptime { // invariant: payload_cap_is_one_byte - // invariant: payload_cap_is_one_byte verified (no statements) + if (!(MAX_PAYLOAD == 255)) __t27_assert_fail("\n assertion failed:\n MAX_PAYLOAD = {any}\n", .{ MAX_PAYLOAD }); } comptime { // invariant: threshold_below_peak - // invariant: threshold_below_peak verified (no statements) + if (!(SYNC_THRESHOLD == 8)) __t27_assert_fail("\n assertion failed:\n SYNC_THRESHOLD = {any}\n", .{ SYNC_THRESHOLD }); } diff --git a/gen/zig/multipath_router.zig b/gen/zig/multipath_router.zig index 0d8725ac..0dbce6b6 100644 --- a/gen/zig/multipath_router.zig +++ b/gen/zig/multipath_router.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} const MAX_PATHS: u8 = 3; const ETX_THRESHOLD_GOOD: u8 = 0x30; @@ -51,29 +59,29 @@ fn path_reliability(etx: u8, loss_rate: u8) u8 { test "path_selection_logic" { const etx_values: [3]u8 = .{ 0x25, 0x30, 0x20 }; const best_idx: u8 = select_path_index(etx_values); - if (!(best_idx == 2)) @panic("best_idx == 2"); + if (!(best_idx == 2)) __t27_assert_fail("\n best_idx == 2:\n best_idx = {any}\n", .{ best_idx }); } test "quality_score_calculation" { const etx: u8 = 0x30; const latency: u16 = 50; const loss: u8 = 0x0A; const score: u8 = path_quality_score(etx, latency, loss); - if (!(score > 0)) @panic("score > 0"); - if (!(score < 200)) @panic("score < 200"); + if (!(score > 0)) __t27_assert_fail("\n score > 0:\n score = {any}\n", .{ score }); + if (!(score < 200)) __t27_assert_fail("\n score < 200:\n score = {any}\n", .{ score }); } test "failover_decision" { - if (!(needs_failover(0x25, 0, 3) == false)) @panic("needs_failover 0x25 0 3 == false"); - if (!(needs_failover(0x70, 0, 3) == true)) @panic("needs_failover 0x70 0 3 == true"); - if (!(needs_failover(0x70, 3, 3) == false)) @panic("needs_failover 0x70 3 3 == false"); + if (!(needs_failover(0x25, 0, 3) == false)) __t27_assert_fail("\n needs_failover 0x25 0 3 == false:\n needs_failover(0x25, 0, 3) = {any}\n", .{ needs_failover(0x25, 0, 3) }); + if (!(needs_failover(0x70, 0, 3) == true)) __t27_assert_fail("\n needs_failover 0x70 0 3 == true:\n needs_failover(0x70, 0, 3) = {any}\n", .{ needs_failover(0x70, 0, 3) }); + if (!(needs_failover(0x70, 3, 3) == false)) __t27_assert_fail("\n needs_failover 0x70 3 3 == false:\n needs_failover(0x70, 3, 3) = {any}\n", .{ needs_failover(0x70, 3, 3) }); } test "path_index_progression" { - if (!(next_path_index(0, 3) == 1)) @panic("next_path_index 0 3 == 1"); - if (!(next_path_index(1, 3) == 2)) @panic("next_path_index 1 3 == 2"); - if (!(next_path_index(2, 3) == 0)) @panic("next_path_index 2 3 == 0"); + if (!(next_path_index(0, 3) == 1)) __t27_assert_fail("\n next_path_index 0 3 == 1:\n next_path_index(0, 3) = {any}\n", .{ next_path_index(0, 3) }); + if (!(next_path_index(1, 3) == 2)) __t27_assert_fail("\n next_path_index 1 3 == 2:\n next_path_index(1, 3) = {any}\n", .{ next_path_index(1, 3) }); + if (!(next_path_index(2, 3) == 0)) __t27_assert_fail("\n next_path_index 2 3 == 0:\n next_path_index(2, 3) = {any}\n", .{ next_path_index(2, 3) }); } test "reliability_estimation" { const high_reliability: u8 = path_reliability(0x25, 0x05); const low_reliability: u8 = path_reliability(0xF0, 0x80); - if (!(high_reliability > 200)) @panic("high_reliability > 200"); - if (!(low_reliability < 150)) @panic("low_reliability < 150"); + if (!(high_reliability > 200)) __t27_assert_fail("\n high_reliability > 200:\n high_reliability = {any}\n", .{ high_reliability }); + if (!(low_reliability < 150)) __t27_assert_fail("\n low_reliability < 150:\n low_reliability = {any}\n", .{ low_reliability }); } diff --git a/gen/zig/multipath_routing.zig b/gen/zig/multipath_routing.zig index 588fe2a4..5054ef2c 100644 --- a/gen/zig/multipath_routing.zig +++ b/gen/zig/multipath_routing.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_PATHS: u32 = 4; @@ -182,82 +190,82 @@ fn calculate_multipath_gain(path_array: [4]u32) u32 { } test "create_multipath_basic" { const path = create_multipath(PATH_VALID, 10, 20, 30); - if (!(get_path_valid(path) == PATH_VALID)) @panic("valid"); - if (!(get_multipath_hop1(path) == 10)) @panic("hop1"); - if (!(get_multipath_hop2(path) == 20)) @panic("hop2"); - if (!(get_multipath_hop3(path) == 30)) @panic("hop3"); + if (!(get_path_valid(path) == PATH_VALID)) __t27_assert_fail("\n valid:\n get_path_valid(path) = {any}\n PATH_VALID = {any}\n", .{ get_path_valid(path), PATH_VALID }); + if (!(get_multipath_hop1(path) == 10)) __t27_assert_fail("\n hop1:\n get_multipath_hop1(path) = {any}\n", .{ get_multipath_hop1(path) }); + if (!(get_multipath_hop2(path) == 20)) __t27_assert_fail("\n hop2:\n get_multipath_hop2(path) = {any}\n", .{ get_multipath_hop2(path) }); + if (!(get_multipath_hop3(path) == 30)) __t27_assert_fail("\n hop3:\n get_multipath_hop3(path) = {any}\n", .{ get_multipath_hop3(path) }); } test "create_multipath_state_basic" { const state = create_multipath_state(3, 1, 100, 50); - if (!(get_active_paths(state) == 3)) @panic("active paths"); - if (!(get_current_path(state) == 1)) @panic("current path"); - if (!(get_flow_id(state) == 100)) @panic("flow ID"); - if (!(get_multipath_last_update(state) == 50)) @panic("last update"); + if (!(get_active_paths(state) == 3)) __t27_assert_fail("\n active paths:\n get_active_paths(state) = {any}\n", .{ get_active_paths(state) }); + if (!(get_current_path(state) == 1)) __t27_assert_fail("\n current path:\n get_current_path(state) = {any}\n", .{ get_current_path(state) }); + if (!(get_flow_id(state) == 100)) __t27_assert_fail("\n flow ID:\n get_flow_id(state) = {any}\n", .{ get_flow_id(state) }); + if (!(get_multipath_last_update(state) == 50)) __t27_assert_fail("\n last update:\n get_multipath_last_update(state) = {any}\n", .{ get_multipath_last_update(state) }); } test "count_valid_paths_all" { const array = create_path_array(create_multipath(PATH_VALID, 10, 20, 30), create_multipath(PATH_VALID, 40, 50, 60), create_multipath(PATH_VALID, 70, 80, 90), create_multipath(PATH_INVALID, 0, 0, 0)); - if (!(count_valid_paths(array) == 3)) @panic("3 valid paths"); + if (!(count_valid_paths(array) == 3)) __t27_assert_fail("\n 3 valid paths:\n count_valid_paths(array) = {any}\n", .{ count_valid_paths(array) }); } test "count_valid_paths_some" { const array = create_path_array(create_multipath(PATH_VALID, 10, 20, 30), create_multipath(PATH_INVALID, 0, 0, 0), create_multipath(PATH_VALID, 70, 80, 90), create_multipath(PATH_INVALID, 0, 0, 0)); - if (!(count_valid_paths(array) == 2)) @panic("2 valid paths"); + if (!(count_valid_paths(array) == 2)) __t27_assert_fail("\n 2 valid paths:\n count_valid_paths(array) = {any}\n", .{ count_valid_paths(array) }); } test "is_multipath_viable_true" { const array = create_path_array(create_multipath(PATH_VALID, 10, 20, 30), create_multipath(PATH_VALID, 40, 50, 60), create_multipath(PATH_INVALID, 0, 0, 0), create_multipath(PATH_INVALID, 0, 0, 0)); - if (!(is_multipath_viable(array) == true)) @panic("viable"); + if (!(is_multipath_viable(array) == true)) __t27_assert_fail("\n viable:\n is_multipath_viable(array) = {any}\n", .{ is_multipath_viable(array) }); } test "is_multipath_viable_false" { const array = create_path_array(create_multipath(PATH_VALID, 10, 20, 30), create_multipath(PATH_INVALID, 0, 0, 0), create_multipath(PATH_INVALID, 0, 0, 0), create_multipath(PATH_INVALID, 0, 0, 0)); - if (!(is_multipath_viable(array) == false)) @panic("not viable"); + if (!(is_multipath_viable(array) == false)) __t27_assert_fail("\n not viable:\n is_multipath_viable(array) = {any}\n", .{ is_multipath_viable(array) }); } test "select_primary_path_first" { const array = create_path_array(create_multipath(PATH_VALID, 10, 20, 30), create_multipath(PATH_VALID, 40, 50, 60), create_multipath(PATH_VALID, 70, 80, 90), create_multipath(PATH_INVALID, 0, 0, 0)); - if (!(select_primary_path(array, create_path_array(0, 0, 0, 0)) == 0)) @panic("first path selected"); + if (!(select_primary_path(array, create_path_array(0, 0, 0, 0)) == 0)) __t27_assert_fail("\n first path selected:\n select_primary_path(array, create_path_array(0, 0, 0, 0)) = {any}\n", .{ select_primary_path(array, create_path_array(0, 0, 0, 0)) }); } test "select_primary_path_skip_invalid" { const array = create_path_array(create_multipath(PATH_INVALID, 0, 0, 0), create_multipath(PATH_VALID, 40, 50, 60), create_multipath(PATH_VALID, 70, 80, 90), create_multipath(PATH_INVALID, 0, 0, 0)); - if (!(select_primary_path(array, create_path_array(0, 0, 0, 0)) == 1)) @panic("second path selected"); + if (!(select_primary_path(array, create_path_array(0, 0, 0, 0)) == 1)) __t27_assert_fail("\n second path selected:\n select_primary_path(array, create_path_array(0, 0, 0, 0)) = {any}\n", .{ select_primary_path(array, create_path_array(0, 0, 0, 0)) }); } test "calculate_path_diversity_high" { const array = create_path_array(create_multipath(PATH_VALID, 1, 20, 30), create_multipath(PATH_VALID, 2, 21, 31), create_multipath(PATH_VALID, 3, 22, 32), create_multipath(PATH_VALID, 4, 23, 33)); const diversity = calculate_path_diversity(array); - if (!(diversity == 4)) @panic("4 different first hops"); + if (!(diversity == 4)) __t27_assert_fail("\n 4 different first hops:\n diversity = {any}\n", .{ diversity }); } test "calculate_path_diversity_low" { const array = create_path_array(create_multipath(PATH_VALID, 1, 20, 30), create_multipath(PATH_VALID, 1, 21, 31), create_multipath(PATH_INVALID, 0, 0, 0), create_multipath(PATH_INVALID, 0, 0, 0)); const diversity = calculate_path_diversity(array); - if (!(diversity == 1)) @panic("1 unique first hop"); + if (!(diversity == 1)) __t27_assert_fail("\n 1 unique first hop:\n diversity = {any}\n", .{ diversity }); } test "distribute_load_round_robin" { const array = create_path_array(create_multipath(PATH_VALID, 10, 20, 30), create_multipath(PATH_VALID, 40, 50, 60), create_multipath(PATH_VALID, 70, 80, 90), create_multipath(PATH_INVALID, 0, 0, 0)); const next = distribute_load(array, 0, 0); - if (!(next == 1)) @panic("distribute to path 1"); + if (!(next == 1)) __t27_assert_fail("\n distribute to path 1:\n next = {any}\n", .{ next }); } test "distribute_load_wraps" { const array = create_path_array(create_multipath(PATH_VALID, 10, 20, 30), create_multipath(PATH_VALID, 40, 50, 60), create_multipath(PATH_VALID, 70, 80, 90), create_multipath(PATH_INVALID, 0, 0, 0)); const next1 = distribute_load(array, 1, 0); - if (!(next1 == 2)) @panic("distribute to path 2"); + if (!(next1 == 2)) __t27_assert_fail("\n distribute to path 2:\n next1 = {any}\n", .{ next1 }); const next2 = distribute_load(array, 2, 0); - if (!(next2 == 0)) @panic("skips invalid path 3, wraps to path 0"); + if (!(next2 == 0)) __t27_assert_fail("\n skips invalid path 3, wraps to path 0:\n next2 = {any}\n", .{ next2 }); const next3 = distribute_load(array, 3, 0); - if (!(next3 == 1)) @panic("wraps to path 1"); + if (!(next3 == 1)) __t27_assert_fail("\n wraps to path 1:\n next3 = {any}\n", .{ next3 }); } test "needs_failover_true" { const array = create_path_array(create_multipath(PATH_VALID, 10, 20, 30), create_multipath(PATH_INVALID, 0, 0, 0), create_multipath(PATH_VALID, 70, 80, 90), create_multipath(PATH_VALID, 40, 50, 60)); - if (!(needs_failover(array, 1) == true)) @panic("needs failover"); + if (!(needs_failover(array, 1) == true)) __t27_assert_fail("\n needs failover:\n needs_failover(array, 1) = {any}\n", .{ needs_failover(array, 1) }); } test "needs_failover_false" { const array = create_path_array(create_multipath(PATH_VALID, 10, 20, 30), create_multipath(PATH_VALID, 40, 50, 60), create_multipath(PATH_VALID, 70, 80, 90), create_multipath(PATH_VALID, 15, 25, 35)); - if (!(needs_failover(array, 1) == false)) @panic("no failover needed"); + if (!(needs_failover(array, 1) == false)) __t27_assert_fail("\n no failover needed:\n needs_failover(array, 1) = {any}\n", .{ needs_failover(array, 1) }); } test "perform_failover_updates_state" { const state = create_multipath_state(3, 1, 100, 50); const array = create_path_array(create_multipath(PATH_VALID, 10, 20, 30), create_multipath(PATH_INVALID, 0, 0, 0), create_multipath(PATH_VALID, 70, 80, 90), create_multipath(PATH_VALID, 40, 50, 60)); const new_state = perform_failover(state, array, 1); - if (!(get_current_path(new_state) != 1)) @panic("path changed"); + if (!(get_current_path(new_state) != 1)) __t27_assert_fail("\n path changed:\n get_current_path(new_state) = {any}\n", .{ get_current_path(new_state) }); } test "calculate_multipath_gain" { const array = create_path_array(create_multipath(PATH_VALID, 10, 20, 30), create_multipath(PATH_VALID, 40, 50, 60), create_multipath(PATH_VALID, 70, 80, 90), create_multipath(PATH_INVALID, 0, 0, 0)); const gain = calculate_multipath_gain(array); - if (!(gain > 0)) @panic("multipath provides gain"); + if (!(gain > 0)) __t27_assert_fail("\n multipath provides gain:\n gain = {any}\n", .{ gain }); } diff --git a/gen/zig/network_analytics.zig b/gen/zig/network_analytics.zig index f737e7a5..4c8fd4b0 100644 --- a/gen/zig/network_analytics.zig +++ b/gen/zig/network_analytics.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_NODES: u32 = 8; @@ -108,84 +116,84 @@ fn is_congested(stats: u32, max_capacity: u32) bool { } test "create_traffic_stats_basic" { const stats = create_traffic_stats(100, 200, 50, 5); - if (!(get_bytes_sent(stats) == 100)) @panic("sent"); - if (!(get_bytes_recv(stats) == 200)) @panic("received"); - if (!(get_packet_count(stats) == 50)) @panic("packets"); - if (!(get_error_count(stats) == 5)) @panic("errors"); + if (!(get_bytes_sent(stats) == 100)) __t27_assert_fail("\n sent:\n get_bytes_sent(stats) = {any}\n", .{ get_bytes_sent(stats) }); + if (!(get_bytes_recv(stats) == 200)) __t27_assert_fail("\n received:\n get_bytes_recv(stats) = {any}\n", .{ get_bytes_recv(stats) }); + if (!(get_packet_count(stats) == 50)) __t27_assert_fail("\n packets:\n get_packet_count(stats) = {any}\n", .{ get_packet_count(stats) }); + if (!(get_error_count(stats) == 5)) __t27_assert_fail("\n errors:\n get_error_count(stats) = {any}\n", .{ get_error_count(stats) }); } test "calculate_total_traffic" { const stats = create_traffic_stats(100, 200, 50, 5); - if (!(calculate_total_traffic(stats) == 300)) @panic("total traffic"); + if (!(calculate_total_traffic(stats) == 300)) __t27_assert_fail("\n total traffic:\n calculate_total_traffic(stats) = {any}\n", .{ calculate_total_traffic(stats) }); } test "is_traffic_low_true" { const stats = create_traffic_stats(30, 40, 10, 0); - if (!(is_traffic_low(stats) == true)) @panic("low traffic"); + if (!(is_traffic_low(stats) == true)) __t27_assert_fail("\n low traffic:\n is_traffic_low(stats) = {any}\n", .{ is_traffic_low(stats) }); } test "is_traffic_high_true" { const stats = create_traffic_stats(250, 200, 100, 5); - if (!(is_traffic_high(stats) == true)) @panic("high traffic"); + if (!(is_traffic_high(stats) == true)) __t27_assert_fail("\n high traffic:\n is_traffic_high(stats) = {any}\n", .{ is_traffic_high(stats) }); } test "is_traffic_normal" { const stats = create_traffic_stats(200, 300, 50, 2); - if (!(is_traffic_normal(stats) == true)) @panic("normal traffic"); + if (!(is_traffic_normal(stats) == true)) __t27_assert_fail("\n normal traffic:\n is_traffic_normal(stats) = {any}\n", .{ is_traffic_normal(stats) }); } test "calculate_error_rate" { const stats = create_traffic_stats(100, 200, 50, 5); - if (!(calculate_error_rate(stats) == 10)) @panic("10% error rate"); + if (!(calculate_error_rate(stats) == 10)) __t27_assert_fail("\n 10% error rate:\n calculate_error_rate(stats) = {any}\n", .{ calculate_error_rate(stats) }); } test "calculate_error_rate_no_traffic" { const stats = create_traffic_stats(0, 0, 0, 0); - if (!(calculate_error_rate(stats) == 0)) @panic("no error rate"); + if (!(calculate_error_rate(stats) == 0)) __t27_assert_fail("\n no error rate:\n calculate_error_rate(stats) = {any}\n", .{ calculate_error_rate(stats) }); } test "is_high_error_rate_true" { const stats = create_traffic_stats(100, 200, 40, 5); - if (!(is_high_error_rate(stats) == true)) @panic("high error rate"); + if (!(is_high_error_rate(stats) == true)) __t27_assert_fail("\n high error rate:\n is_high_error_rate(stats) = {any}\n", .{ is_high_error_rate(stats) }); } test "is_high_error_rate_false" { const stats = create_traffic_stats(100, 200, 60, 3); - if (!(is_high_error_rate(stats) == false)) @panic("normal error rate"); + if (!(is_high_error_rate(stats) == false)) __t27_assert_fail("\n normal error rate:\n is_high_error_rate(stats) = {any}\n", .{ is_high_error_rate(stats) }); } test "detect_pattern_spike" { const current = create_traffic_stats(250, 240, 100, 2); const previous = create_traffic_stats(100, 100, 20, 0); - if (!(detect_pattern(current, previous) == PATTERN_SPIKE)) @panic("spike detected"); + if (!(detect_pattern(current, previous) == PATTERN_SPIKE)) __t27_assert_fail("\n spike detected:\n detect_pattern(current, previous) = {any}\n PATTERN_SPIKE = {any}\n", .{ detect_pattern(current, previous), PATTERN_SPIKE }); } test "detect_pattern_dropout" { const current = create_traffic_stats(50, 50, 10, 0); const previous = create_traffic_stats(250, 250, 80, 2); - if (!(detect_pattern(current, previous) == PATTERN_DROPOUT)) @panic("dropout detected"); + if (!(detect_pattern(current, previous) == PATTERN_DROPOUT)) __t27_assert_fail("\n dropout detected:\n detect_pattern(current, previous) = {any}\n PATTERN_DROPOUT = {any}\n", .{ detect_pattern(current, previous), PATTERN_DROPOUT }); } test "detect_pattern_congestion" { const current = create_traffic_stats(200, 200, 40, 5); const previous = create_traffic_stats(200, 200, 40, 2); - if (!(detect_pattern(current, previous) == PATTERN_CONGESTION)) @panic("congestion detected"); + if (!(detect_pattern(current, previous) == PATTERN_CONGESTION)) __t27_assert_fail("\n congestion detected:\n detect_pattern(current, previous) = {any}\n PATTERN_CONGESTION = {any}\n", .{ detect_pattern(current, previous), PATTERN_CONGESTION }); } test "detect_pattern_normal" { const current = create_traffic_stats(200, 250, 50, 2); const previous = create_traffic_stats(180, 230, 45, 1); - if (!(detect_pattern(current, previous) == PATTERN_NORMAL)) @panic("normal pattern"); + if (!(detect_pattern(current, previous) == PATTERN_NORMAL)) __t27_assert_fail("\n normal pattern:\n detect_pattern(current, previous) = {any}\n PATTERN_NORMAL = {any}\n", .{ detect_pattern(current, previous), PATTERN_NORMAL }); } test "update_traffic_works" { const stats = create_traffic_stats(100, 200, 50, 5); const new_stats = update_traffic(stats, 50, 30, 10, 1); - if (!(get_bytes_sent(new_stats) == 150)) @panic("sent updated"); - if (!(get_bytes_recv(new_stats) == 230)) @panic("received updated"); - if (!(get_packet_count(new_stats) == 60)) @panic("packets updated"); - if (!(get_error_count(new_stats) == 6)) @panic("errors updated"); + if (!(get_bytes_sent(new_stats) == 150)) __t27_assert_fail("\n sent updated:\n get_bytes_sent(new_stats) = {any}\n", .{ get_bytes_sent(new_stats) }); + if (!(get_bytes_recv(new_stats) == 230)) __t27_assert_fail("\n received updated:\n get_bytes_recv(new_stats) = {any}\n", .{ get_bytes_recv(new_stats) }); + if (!(get_packet_count(new_stats) == 60)) __t27_assert_fail("\n packets updated:\n get_packet_count(new_stats) = {any}\n", .{ get_packet_count(new_stats) }); + if (!(get_error_count(new_stats) == 6)) __t27_assert_fail("\n errors updated:\n get_error_count(new_stats) = {any}\n", .{ get_error_count(new_stats) }); } test "calculate_utilization" { const stats = create_traffic_stats(200, 200, 100, 5); - if (!(calculate_utilization(stats, 800) == 50)) @panic("50% utilization"); + if (!(calculate_utilization(stats, 800) == 50)) __t27_assert_fail("\n 50% utilization:\n calculate_utilization(stats, 800) = {any}\n", .{ calculate_utilization(stats, 800) }); } test "calculate_utilization_zero_capacity" { const stats = create_traffic_stats(400, 600, 100, 5); - if (!(calculate_utilization(stats, 0) == 0)) @panic("no capacity"); + if (!(calculate_utilization(stats, 0) == 0)) __t27_assert_fail("\n no capacity:\n calculate_utilization(stats, 0) = {any}\n", .{ calculate_utilization(stats, 0) }); } test "is_congested_true" { const stats = create_traffic_stats(250, 250, 200, 10); - if (!(is_congested(stats, 500) == true)) @panic("network congested"); + if (!(is_congested(stats, 500) == true)) __t27_assert_fail("\n network congested:\n is_congested(stats, 500) = {any}\n", .{ is_congested(stats, 500) }); } test "is_congested_false" { const stats = create_traffic_stats(400, 500, 100, 5); - if (!(is_congested(stats, 2000) == false)) @panic("network not congested"); + if (!(is_congested(stats, 2000) == false)) __t27_assert_fail("\n network not congested:\n is_congested(stats, 2000) = {any}\n", .{ is_congested(stats, 2000) }); } diff --git a/gen/zig/network_coding.zig b/gen/zig/network_coding.zig index 2005bb7e..6df70bb7 100644 --- a/gen/zig/network_coding.zig +++ b/gen/zig/network_coding.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_PACKETS: u32 = 4; @@ -120,95 +128,95 @@ fn calculate_coding_gain(original: u32, coded: u32) u32 { } test "create_packet_basic" { const pkt = create_packet(5, 10, 0xAB, 100); - if (!(get_packet_src(pkt) == 5)) @panic("source"); - if (!(get_packet_dst(pkt) == 10)) @panic("destination"); - if (!(get_packet_payload(pkt) == 0xAB)) @panic("payload"); - if (!(get_packet_seq(pkt) == 100)) @panic("sequence"); + if (!(get_packet_src(pkt) == 5)) __t27_assert_fail("\n source:\n get_packet_src(pkt) = {any}\n", .{ get_packet_src(pkt) }); + if (!(get_packet_dst(pkt) == 10)) __t27_assert_fail("\n destination:\n get_packet_dst(pkt) = {any}\n", .{ get_packet_dst(pkt) }); + if (!(get_packet_payload(pkt) == 0xAB)) __t27_assert_fail("\n payload:\n get_packet_payload(pkt) = {any}\n", .{ get_packet_payload(pkt) }); + if (!(get_packet_seq(pkt) == 100)) __t27_assert_fail("\n sequence:\n get_packet_seq(pkt) = {any}\n", .{ get_packet_seq(pkt) }); } test "create_coded_packet_basic" { const coded = create_coded_packet(0b1010, 0xCD, 5, 1000); - if (!(get_coeff_vector(coded) == 0b1010)) @panic("coefficient"); - if (!(get_coded_payload(coded) == 0xCD)) @panic("coded payload"); - if (!(get_generation(coded) == 5)) @panic("generation"); + if (!(get_coeff_vector(coded) == 0b1010)) __t27_assert_fail("\n coefficient:\n get_coeff_vector(coded) = {any}\n", .{ get_coeff_vector(coded) }); + if (!(get_coded_payload(coded) == 0xCD)) __t27_assert_fail("\n coded payload:\n get_coded_payload(coded) = {any}\n", .{ get_coded_payload(coded) }); + if (!(get_generation(coded) == 5)) __t27_assert_fail("\n generation:\n get_generation(coded) = {any}\n", .{ get_generation(coded) }); } test "xor_packets_basic" { const pkt1 = create_packet(1, 2, 0xAA, 100); const pkt2 = create_packet(3, 4, 0x55, 101); const xored = xor_packets(pkt1, pkt2); - if (!(get_packet_payload(xored) == 0xFF)) @panic("XOR payload"); + if (!(get_packet_payload(xored) == 0xFF)) __t27_assert_fail("\n XOR payload:\n get_packet_payload(xored) = {any}\n", .{ get_packet_payload(xored) }); } test "create_xoded_native" { const pkt1 = create_packet(1, 2, 0xAA, 100); const pkt2 = create_packet(3, 4, 0x55, 100); const coded = create_xoded_native(pkt1, pkt2, 5, 1000); - if (!(get_coded_payload(coded) == 0xFF)) @panic("coded payload"); - if (!(get_coeff_vector(coded) == 0b11)) @panic("both packets"); + if (!(get_coded_payload(coded) == 0xFF)) __t27_assert_fail("\n coded payload:\n get_coded_payload(coded) = {any}\n", .{ get_coded_payload(coded) }); + if (!(get_coeff_vector(coded) == 0b11)) __t27_assert_fail("\n both packets:\n get_coeff_vector(coded) = {any}\n", .{ get_coeff_vector(coded) }); } test "decode_xoded_packet" { const pkt1 = create_packet(1, 2, 0xAA, 100); const pkt2 = create_packet(3, 4, 0x55, 100); const coded = create_xoded_native(pkt1, pkt2, 5, 1000); const decoded = decode_xoded_packet(coded, pkt1); - if (!(get_packet_payload(decoded) == 0x55)) @panic("decoded payload"); + if (!(get_packet_payload(decoded) == 0x55)) __t27_assert_fail("\n decoded payload:\n get_packet_payload(decoded) = {any}\n", .{ get_packet_payload(decoded) }); } test "same_generation_true" { const pkt1 = create_packet(1, 2, 0xAA, 8); const pkt2 = create_packet(3, 4, 0x55, 10); - if (!(same_generation(pkt1, pkt2) == true)) @panic("same generation"); + if (!(same_generation(pkt1, pkt2) == true)) __t27_assert_fail("\n same generation:\n same_generation(pkt1, pkt2) = {any}\n", .{ same_generation(pkt1, pkt2) }); } test "same_generation_false" { const pkt1 = create_packet(1, 2, 0xAA, 3); const pkt2 = create_packet(3, 4, 0x55, 8); - if (!(same_generation(pkt1, pkt2) == false)) @panic("different generation"); + if (!(same_generation(pkt1, pkt2) == false)) __t27_assert_fail("\n different generation:\n same_generation(pkt1, pkt2) = {any}\n", .{ same_generation(pkt1, pkt2) }); } test "get_generation_id" { const pkt1 = create_packet(1, 2, 0xAA, 8); const pkt2 = create_packet(3, 4, 0x55, 10); - if (!(get_generation_id(pkt1) == get_generation_id(pkt2))) @panic("same generation ID"); + if (!(get_generation_id(pkt1) == get_generation_id(pkt2))) __t27_assert_fail("\n same generation ID:\n get_generation_id(pkt1) = {any}\n get_generation_id(pkt2) = {any}\n", .{ get_generation_id(pkt1), get_generation_id(pkt2) }); } test "is_coding_beneficial_different_hops" { const pkt1 = create_packet(1, 2, 0xAA, 100); const pkt2 = create_packet(3, 4, 0x55, 101); - if (!(is_coding_beneficial(pkt1, pkt2, 10, 20) == true)) @panic("beneficial"); + if (!(is_coding_beneficial(pkt1, pkt2, 10, 20) == true)) __t27_assert_fail("\n beneficial:\n is_coding_beneficial(pkt1, pkt2, 10, 20) = {any}\n", .{ is_coding_beneficial(pkt1, pkt2, 10, 20) }); } test "is_coding_beneficial_same_hop" { const pkt1 = create_packet(1, 2, 0xAA, 100); const pkt2 = create_packet(3, 4, 0x55, 101); - if (!(is_coding_beneficial(pkt1, pkt2, 10, 10) == false)) @panic("not beneficial"); + if (!(is_coding_beneficial(pkt1, pkt2, 10, 10) == false)) __t27_assert_fail("\n not beneficial:\n is_coding_beneficial(pkt1, pkt2, 10, 10) = {any}\n", .{ is_coding_beneficial(pkt1, pkt2, 10, 10) }); } test "linear_code_packets_both_odd" { const pkt1 = create_packet(1, 2, 0xAA, 100); const pkt2 = create_packet(3, 4, 0x55, 101); const coded = linear_code_packets(pkt1, pkt2, 3, 5); - if (!(get_packet_payload(coded) == 0xFF)) @panic("linear coded payload"); + if (!(get_packet_payload(coded) == 0xFF)) __t27_assert_fail("\n linear coded payload:\n get_packet_payload(coded) = {any}\n", .{ get_packet_payload(coded) }); } test "linear_code_packets_one_even" { const pkt1 = create_packet(1, 2, 0xAA, 100); const pkt2 = create_packet(3, 4, 0x55, 101); const coded = linear_code_packets(pkt1, pkt2, 2, 5); - if (!(get_packet_payload(coded) == 0x55)) @panic("only pkt2 coded"); + if (!(get_packet_payload(coded) == 0x55)) __t27_assert_fail("\n only pkt2 coded:\n get_packet_payload(coded) = {any}\n", .{ get_packet_payload(coded) }); } test "create_coded_generation" { const gen = create_coded_generation(create_packet(1, 2, 0xAA, 100), create_packet(3, 4, 0x55, 101), 0, 0); - if (!(count_generation_packets(gen) == 2)) @panic("2 packets"); + if (!(count_generation_packets(gen) == 2)) __t27_assert_fail("\n 2 packets:\n count_generation_packets(gen) = {any}\n", .{ count_generation_packets(gen) }); } test "count_generation_packets_full" { const gen = create_coded_generation(create_packet(1, 2, 0xAA, 100), create_packet(3, 4, 0x55, 101), create_packet(5, 6, 0x33, 102), create_packet(7, 8, 0x11, 103)); - if (!(count_generation_packets(gen) == 4)) @panic("4 packets"); + if (!(count_generation_packets(gen) == 4)) __t27_assert_fail("\n 4 packets:\n count_generation_packets(gen) = {any}\n", .{ count_generation_packets(gen) }); } test "is_generation_decodable_true" { const gen = create_coded_generation(create_packet(1, 2, 0xAA, 100), create_packet(3, 4, 0x55, 101), 0, 0); - if (!(is_generation_decodable(gen, 2) == 1)) @panic("decodable"); + if (!(is_generation_decodable(gen, 2) == 1)) __t27_assert_fail("\n decodable:\n is_generation_decodable(gen, 2) = {any}\n", .{ is_generation_decodable(gen, 2) }); } test "is_generation_decodable_false" { const gen = create_coded_generation(create_packet(1, 2, 0xAA, 100), 0, 0, 0); - if (!(is_generation_decodable(gen, 2) == 0)) @panic("not decodable"); + if (!(is_generation_decodable(gen, 2) == 0)) __t27_assert_fail("\n not decodable:\n is_generation_decodable(gen, 2) = {any}\n", .{ is_generation_decodable(gen, 2) }); } test "calculate_coding_gain" { const gain = calculate_coding_gain(4, 2); - if (!(gain == 2)) @panic("2 packets saved"); + if (!(gain == 2)) __t27_assert_fail("\n 2 packets saved:\n gain = {any}\n", .{ gain }); } test "calculate_coding_gain_zero" { const gain = calculate_coding_gain(4, 4); - if (!(gain == 0)) @panic("no gain"); + if (!(gain == 0)) __t27_assert_fail("\n no gain:\n gain = {any}\n", .{ gain }); } diff --git a/gen/zig/network_metrics.zig b/gen/zig/network_metrics.zig index da25f0b9..745e398c 100644 --- a/gen/zig/network_metrics.zig +++ b/gen/zig/network_metrics.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module fn get_sent(metrics: u32) u32 { @@ -34,29 +42,29 @@ fn success_rate(sent: u32, success: u32) u8 { } } test "initial_zero" { - if (!(get_sent(0) == 0)) @panic("initial"); + if (!(get_sent(0) == 0)) __t27_assert_fail("\n initial:\n get_sent(0) = {any}\n", .{ get_sent(0) }); } test "inc_sent_works" { const m1 = inc_sent(0); - if (!(get_sent(m1) == 1)) @panic("inc works"); + if (!(get_sent(m1) == 1)) __t27_assert_fail("\n inc works:\n get_sent(m1) = {any}\n", .{ get_sent(m1) }); } test "inc_recv_works" { const m1 = inc_recv(0); - if (!(get_recv(m1) == 1)) @panic("inc works"); + if (!(get_recv(m1) == 1)) __t27_assert_fail("\n inc works:\n get_recv(m1) = {any}\n", .{ get_recv(m1) }); } test "inc_success_works" { const m1 = inc_success(0); - if (!(get_success(m1) == 1)) @panic("inc success"); + if (!(get_success(m1) == 1)) __t27_assert_fail("\n inc success:\n get_success(m1) = {any}\n", .{ get_success(m1) }); } test "success_rate_perfect" { - if (!(success_rate(1, 1) == 100)) @panic("100%"); + if (!(success_rate(1, 1) == 100)) __t27_assert_fail("\n 100%:\n success_rate(1, 1) = {any}\n", .{ success_rate(1, 1) }); } test "success_rate_zero_sent" { - if (!(success_rate(0, 0) == 100)) @panic("none sent = 100%"); + if (!(success_rate(0, 0) == 100)) __t27_assert_fail("\n none sent = 100%:\n success_rate(0, 0) = {any}\n", .{ success_rate(0, 0) }); } test "success_rate_half" { - if (!(success_rate(10, 5) == 50)) @panic("50%"); + if (!(success_rate(10, 5) == 50)) __t27_assert_fail("\n 50%:\n success_rate(10, 5) = {any}\n", .{ success_rate(10, 5) }); } test "success_rate_zero_success" { - if (!(success_rate(10, 0) == 0)) @panic("0%"); + if (!(success_rate(10, 0) == 0)) __t27_assert_fail("\n 0%:\n success_rate(10, 0) = {any}\n", .{ success_rate(10, 0) }); } diff --git a/gen/zig/network_orchestrator.zig b/gen/zig/network_orchestrator.zig index 60d8c1d3..26746062 100644 --- a/gen/zig/network_orchestrator.zig +++ b/gen/zig/network_orchestrator.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_NODES: u32 = 8; @@ -263,19 +271,19 @@ fn monitor_network_health(node_states: [MAX_NODES]u32, node_count: u32) u32 { } test "policy_roundtrip" { const p = create_network_policy(7, 200, 3, 3000); - if (!(get_policy_id(p) == 7)) @panic("policy id"); - if (!(get_policy_priority(p) == 200)) @panic("priority"); - if (!(get_policy_scope(p) == 3)) @panic("scope"); - if (!(get_policy_parameter(p) == 3000)) @panic("parameter"); + if (!(get_policy_id(p) == 7)) __t27_assert_fail("\n policy id:\n get_policy_id(p) = {any}\n", .{ get_policy_id(p) }); + if (!(get_policy_priority(p) == 200)) __t27_assert_fail("\n priority:\n get_policy_priority(p) = {any}\n", .{ get_policy_priority(p) }); + if (!(get_policy_scope(p) == 3)) __t27_assert_fail("\n scope:\n get_policy_scope(p) = {any}\n", .{ get_policy_scope(p) }); + if (!(get_policy_parameter(p) == 3000)) __t27_assert_fail("\n parameter:\n get_policy_parameter(p) = {any}\n", .{ get_policy_parameter(p) }); } test "coordination_roundtrip" { const st = create_coordination_state(9, STATE_NEGOTIATING, 3, 50000); - if (!(get_coordinator_id(st) == 9)) @panic("coordinator"); - if (!(get_coordination_state(st) == STATE_NEGOTIATING)) @panic("state"); - if (!(get_coordination_phase(st) == 3)) @panic("phase"); - if (!(get_coordination_timeout(st) == 50000)) @panic("timeout"); + if (!(get_coordinator_id(st) == 9)) __t27_assert_fail("\n coordinator:\n get_coordinator_id(st) = {any}\n", .{ get_coordinator_id(st) }); + if (!(get_coordination_state(st) == STATE_NEGOTIATING)) __t27_assert_fail("\n state:\n get_coordination_state(st) = {any}\n STATE_NEGOTIATING = {any}\n", .{ get_coordination_state(st), STATE_NEGOTIATING }); + if (!(get_coordination_phase(st) == 3)) __t27_assert_fail("\n phase:\n get_coordination_phase(st) = {any}\n", .{ get_coordination_phase(st) }); + if (!(get_coordination_timeout(st) == 50000)) __t27_assert_fail("\n timeout:\n get_coordination_timeout(st) = {any}\n", .{ get_coordination_timeout(st) }); } test "highest_priority_policy_selection" { - const ps: [4]u32 = .{ create_network_policy(1,10,1,0), create_network_policy(2,90,1,0), create_network_policy(3,200,2,0), create_network_policy(4,50,1,0) }; - if (!(find_highest_priority_policy(ps, 1) == 1)) @panic("highest in scope wins"); + const ps: [4]u32 = .{ create_network_policy(1, 10, 1, 0), create_network_policy(2, 90, 1, 0), create_network_policy(3, 200, 2, 0), create_network_policy(4, 50, 1, 0) }; + if (!(find_highest_priority_policy(ps, 1) == 1)) __t27_assert_fail("\n highest in scope wins:\n find_highest_priority_policy(ps, 1) = {any}\n", .{ find_highest_priority_policy(ps, 1) }); } diff --git a/gen/zig/network_simulator.zig b/gen/zig/network_simulator.zig index a28a0a05..5cd2c4d4 100644 --- a/gen/zig/network_simulator.zig +++ b/gen/zig/network_simulator.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_NODES: u32 = 32; @@ -244,17 +252,17 @@ fn generate_simulation_report(stats: u32, duration: u32, node_count: u32) u32 { } test "sim_event_roundtrip" { const e = create_sim_event(5, 40000, 9, 12); - if (!(get_event_id(e) == 5)) @panic("event id"); - if (!(get_event_timestamp(e) == 40000)) @panic("timestamp"); - if (!(get_event_type(e) == 9)) @panic("event type"); - if (!(get_event_node_id(e) == 12)) @panic("node id"); + if (!(get_event_id(e) == 5)) __t27_assert_fail("\n event id:\n get_event_id(e) = {any}\n", .{ get_event_id(e) }); + if (!(get_event_timestamp(e) == 40000)) __t27_assert_fail("\n timestamp:\n get_event_timestamp(e) = {any}\n", .{ get_event_timestamp(e) }); + if (!(get_event_type(e) == 9)) __t27_assert_fail("\n event type:\n get_event_type(e) = {any}\n", .{ get_event_type(e) }); + if (!(get_event_node_id(e) == 12)) __t27_assert_fail("\n node id:\n get_event_node_id(e) = {any}\n", .{ get_event_node_id(e) }); } test "energy_drain_fails_node" { var st = create_node_state(3, NODE_ACTIVE, 10, 7); st = update_node_energy(st, 4); - if (!(get_node_energy(st) == 6)) @panic("energy drained"); - if (!(get_node_status(st) == NODE_ACTIVE)) @panic("still active"); + if (!(get_node_energy(st) == 6)) __t27_assert_fail("\n energy drained:\n get_node_energy(st) = {any}\n", .{ get_node_energy(st) }); + if (!(get_node_status(st) == NODE_ACTIVE)) __t27_assert_fail("\n still active:\n get_node_status(st) = {any}\n NODE_ACTIVE = {any}\n", .{ get_node_status(st), NODE_ACTIVE }); st = update_node_energy(st, 100); - if (!(get_node_energy(st) == 0)) @panic("clamps at zero"); - if (!(get_node_status(st) == NODE_FAILED)) @panic("empty battery fails the node"); + if (!(get_node_energy(st) == 0)) __t27_assert_fail("\n clamps at zero:\n get_node_energy(st) = {any}\n", .{ get_node_energy(st) }); + if (!(get_node_status(st) == NODE_FAILED)) __t27_assert_fail("\n empty battery fails the node:\n get_node_status(st) = {any}\n NODE_FAILED = {any}\n", .{ get_node_status(st), NODE_FAILED }); } diff --git a/gen/zig/olsr_routing.zig b/gen/zig/olsr_routing.zig index 82e66a0f..25e6de14 100644 --- a/gen/zig/olsr_routing.zig +++ b/gen/zig/olsr_routing.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_NEIGHBORS: u32 = 4; @@ -97,36 +105,36 @@ fn count_neighbors(table: [4]u32) u32 { } test "create_neighbor_basic" { const n = create_neighbor(1, 100, 5000); - if (!(get_id(n) == 1)) @panic("id"); - if (!(get_quality(n) == 100)) @panic("quality"); - if (!(get_last_seen(n) == 5000)) @panic("timestamp"); + if (!(get_id(n) == 1)) __t27_assert_fail("\n id:\n get_id(n) = {any}\n", .{ get_id(n) }); + if (!(get_quality(n) == 100)) __t27_assert_fail("\n quality:\n get_quality(n) = {any}\n", .{ get_quality(n) }); + if (!(get_last_seen(n) == 5000)) __t27_assert_fail("\n timestamp:\n get_last_seen(n) = {any}\n", .{ get_last_seen(n) }); } test "is_valid_within_timeout" { const n = create_neighbor(5, 200, 1000); - if (!(is_valid(n, 5000) == true)) @panic("within timeout"); + if (!(is_valid(n, 5000) == true)) __t27_assert_fail("\n within timeout:\n is_valid(n, 5000) = {any}\n", .{ is_valid(n, 5000) }); } test "is_valid_timeout" { const n = create_neighbor(5, 200, 1000); - if (!(is_valid(n, 8000) == false)) @panic("timeout"); + if (!(is_valid(n, 8000) == false)) __t27_assert_fail("\n timeout:\n is_valid(n, 8000) = {any}\n", .{ is_valid(n, 8000) }); } test "table_reads_and_find" { - const table: [4]u32 = .{ create_neighbor(1,100,1000), create_neighbor(2,200,2000), create_neighbor(3,150,3000), create_neighbor(4,50,4000) }; - if (!(get_id_at(table, 0) == 1)) @panic("entry 0"); - if (!(get_id_at(table, 3) == 4)) @panic("entry 3"); - if (!(find_index(table, 3) == 2)) @panic("find id 3"); - if (!(find_index(table, 9) == NO_SLOT)) @panic("unknown id"); - if (!(count_neighbors(table) == 4)) @panic("all four present"); + const table: [4]u32 = .{ create_neighbor(1, 100, 1000), create_neighbor(2, 200, 2000), create_neighbor(3, 150, 3000), create_neighbor(4, 50, 4000) }; + if (!(get_id_at(table, 0) == 1)) __t27_assert_fail("\n entry 0:\n get_id_at(table, 0) = {any}\n", .{ get_id_at(table, 0) }); + if (!(get_id_at(table, 3) == 4)) __t27_assert_fail("\n entry 3:\n get_id_at(table, 3) = {any}\n", .{ get_id_at(table, 3) }); + if (!(find_index(table, 3) == 2)) __t27_assert_fail("\n find id 3:\n find_index(table, 3) = {any}\n", .{ find_index(table, 3) }); + if (!(find_index(table, 9) == NO_SLOT)) __t27_assert_fail("\n unknown id:\n find_index(table, 9) = {any}\n NO_SLOT = {any}\n", .{ find_index(table, 9), NO_SLOT }); + if (!(count_neighbors(table) == 4)) __t27_assert_fail("\n all four present:\n count_neighbors(table) = {any}\n", .{ count_neighbors(table) }); } test "slot_decisions" { - const table: [4]u32 = .{ create_neighbor(1,100,1000), create_neighbor(NO_NEIGHBOR,0,0), create_neighbor(3,150,3000), create_neighbor(4,50,4000) }; - if (!(slot_for_update(table, 3) == 2)) @panic("known id updates in place"); - if (!(slot_for_update(table, 9) == 1)) @panic("unknown id takes the first empty slot"); - const full: [4]u32 = .{ create_neighbor(1,100,1000), create_neighbor(2,200,2000), create_neighbor(3,150,3000), create_neighbor(4,50,4000) }; - if (!(slot_for_update(full, 9) == NO_SLOT)) @panic("full table admits nothing new"); + const table: [4]u32 = .{ create_neighbor(1, 100, 1000), create_neighbor(NO_NEIGHBOR, 0, 0), create_neighbor(3, 150, 3000), create_neighbor(4, 50, 4000) }; + if (!(slot_for_update(table, 3) == 2)) __t27_assert_fail("\n known id updates in place:\n slot_for_update(table, 3) = {any}\n", .{ slot_for_update(table, 3) }); + if (!(slot_for_update(table, 9) == 1)) __t27_assert_fail("\n unknown id takes the first empty slot:\n slot_for_update(table, 9) = {any}\n", .{ slot_for_update(table, 9) }); + const full: [4]u32 = .{ create_neighbor(1, 100, 1000), create_neighbor(2, 200, 2000), create_neighbor(3, 150, 3000), create_neighbor(4, 50, 4000) }; + if (!(slot_for_update(full, 9) == NO_SLOT)) __t27_assert_fail("\n full table admits nothing new:\n slot_for_update(full, 9) = {any}\n NO_SLOT = {any}\n", .{ slot_for_update(full, 9), NO_SLOT }); } test "mpr_selection" { - const table: [4]u32 = .{ create_neighbor(1,100,1000), create_neighbor(2,200,2000), create_neighbor(3,150,3000), create_neighbor(4,50,4000) }; - if (!(get_best_neighbor(table) == 2)) @panic("best by quality"); - if (!(get_second_best(table, 2) == 3)) @panic("second best excludes the best"); - if (!(select_mprs(table) == ((2 << 8) | 3))) @panic("mpr pack [best][second]"); + const table: [4]u32 = .{ create_neighbor(1, 100, 1000), create_neighbor(2, 200, 2000), create_neighbor(3, 150, 3000), create_neighbor(4, 50, 4000) }; + if (!(get_best_neighbor(table) == 2)) __t27_assert_fail("\n best by quality:\n get_best_neighbor(table) = {any}\n", .{ get_best_neighbor(table) }); + if (!(get_second_best(table, 2) == 3)) __t27_assert_fail("\n second best excludes the best:\n get_second_best(table, 2) = {any}\n", .{ get_second_best(table, 2) }); + if (!(select_mprs(table) == ((2 << 8) | 3))) __t27_assert_fail("\n mpr pack [best][second]:\n select_mprs(table) = {any}\n (2 << 8) | 3 = {any}\n", .{ select_mprs(table), (2 << 8) | 3 }); } diff --git a/gen/zig/packet_loss_injection.zig b/gen/zig/packet_loss_injection.zig index 91251009..fbe62547 100644 --- a/gen/zig/packet_loss_injection.zig +++ b/gen/zig/packet_loss_injection.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const ERROR_NONE: u8 = 0; @@ -45,30 +53,30 @@ fn extract_sequence(packet: u32) u32 { test "inject_bit_flip_flips_bit" { const pkt = 0x00000000; const corrupted = inject_bit_flip(pkt, 5); - if (!(corrupted == 0x00000020)) @panic("bit 5 flipped"); + if (!(corrupted == 0x00000020)) __t27_assert_fail("\n bit 5 flipped:\n corrupted = {any}\n", .{ corrupted }); } test "inject_bit_flip_multiple" { const pkt = 0xFFFFFFFF; const corrupted = inject_bit_flip(pkt, 10); - if (!(corrupted == 0xFFFFFBFF)) @panic("bit 10 flipped"); + if (!(corrupted == 0xFFFFFBFF)) __t27_assert_fail("\n bit 10 flipped:\n corrupted = {any}\n", .{ corrupted }); } test "inject_bit_flip_invalid_pos" { const pkt = 0x12345678; const result = inject_bit_flip(pkt, 35); - if (!(result == pkt)) @panic("no change for invalid pos"); + if (!(result == pkt)) __t27_assert_fail("\n no change for invalid pos:\n result = {any}\n pkt = {any}\n", .{ result, pkt }); } test "calculate_crc_reproducible" { const pkt = 0x12345678; const crc1 = calculate_crc(pkt); const crc2 = calculate_crc(pkt); - if (!(crc1 == crc2)) @panic("reproducible"); + if (!(crc1 == crc2)) __t27_assert_fail("\n reproducible:\n crc1 = {any}\n crc2 = {any}\n", .{ crc1, crc2 }); } test "calculate_crc_different" { const pkt1 = 0x12345678; const pkt2 = 0x12345679; const crc1 = calculate_crc(pkt1); const crc2 = calculate_crc(pkt2); - if (!(crc1 != crc2)) @panic("different for different data"); + if (!(crc1 != crc2)) __t27_assert_fail("\n different for different data:\n crc1 = {any}\n crc2 = {any}\n", .{ crc1, crc2 }); } test "verify_crc_valid" { const pkt = 0x01020304; @@ -81,48 +89,48 @@ test "verify_crc_invalid" { const crc = calculate_crc(pkt); const corrupted = inject_crc_error(pkt); const valid = verify_crc(corrupted, crc); - if (!(valid == false)) @panic("invalid CRC"); + if (!(valid == false)) __t27_assert_fail("\n invalid CRC:\n valid = {any}\n", .{ valid }); } test "duplicate_packet_creates_copy" { const pkt = 0xABCDEF00; const dup1, const dup2 = duplicate_packet(pkt); - if (!(dup1 == pkt)) @panic("first copy"); - if (!(dup2 == pkt)) @panic("second copy"); + if (!(dup1 == pkt)) __t27_assert_fail("\n first copy:\n dup1 = {any}\n pkt = {any}\n", .{ dup1, pkt }); + if (!(dup2 == pkt)) __t27_assert_fail("\n second copy:\n dup2 = {any}\n pkt = {any}\n", .{ dup2, pkt }); } test "is_duplicate_detects_same" { const pkt1 = 0x12345678; const pkt2 = 0x12345678; - if (!(is_duplicate(pkt1, pkt2) == true)) @panic("same packet"); + if (!(is_duplicate(pkt1, pkt2) == true)) __t27_assert_fail("\n same packet:\n is_duplicate(pkt1, pkt2) = {any}\n", .{ is_duplicate(pkt1, pkt2) }); } test "is_duplicate_different" { const pkt1 = 0x12345678; const pkt2 = 0x12345679; - if (!(is_duplicate(pkt1, pkt2) == false)) @panic("different packet"); + if (!(is_duplicate(pkt1, pkt2) == false)) __t27_assert_fail("\n different packet:\n is_duplicate(pkt1, pkt2) = {any}\n", .{ is_duplicate(pkt1, pkt2) }); } test "inject_out_of_order_swaps" { const pkt1 = 0x11111111; const pkt2 = 0x22222222; const out1, const out2 = inject_out_of_order(pkt1, pkt2); - if (!(out1 == pkt2)) @panic("swapped to pkt2"); - if (!(out2 == pkt1)) @panic("swapped to pkt1"); + if (!(out1 == pkt2)) __t27_assert_fail("\n swapped to pkt2:\n out1 = {any}\n pkt2 = {any}\n", .{ out1, pkt2 }); + if (!(out2 == pkt1)) __t27_assert_fail("\n swapped to pkt1:\n out2 = {any}\n pkt1 = {any}\n", .{ out2, pkt1 }); } test "extract_sequence_low_bits" { const pkt = 0x1234ABCD; const seq = extract_sequence(pkt); - if (!(seq == 0xABCD)) @panic("extracted low 16 bits"); + if (!(seq == 0xABCD)) __t27_assert_fail("\n extracted low 16 bits:\n seq = {any}\n", .{ seq }); } test "check_replay_newer" { const pkt = 0x00000005; const last = 0x00000003; - if (!(check_replay(pkt, last) == true)) @panic("newer packet"); + if (!(check_replay(pkt, last) == true)) __t27_assert_fail("\n newer packet:\n check_replay(pkt, last) = {any}\n", .{ check_replay(pkt, last) }); } test "check_replay_older" { const pkt = 0x00000002; const last = 0x00000005; - if (!(check_replay(pkt, last) == false)) @panic("replay detected"); + if (!(check_replay(pkt, last) == false)) __t27_assert_fail("\n replay detected:\n check_replay(pkt, last) = {any}\n", .{ check_replay(pkt, last) }); } test "check_replay_same" { const pkt = 0x00000005; const last = 0x00000005; - if (!(check_replay(pkt, last) == false)) @panic("same seq = replay"); + if (!(check_replay(pkt, last) == false)) __t27_assert_fail("\n same seq = replay:\n check_replay(pkt, last) = {any}\n", .{ check_replay(pkt, last) }); } diff --git a/gen/zig/packet_queue.zig b/gen/zig/packet_queue.zig index df4f190f..5783c55f 100644 --- a/gen/zig/packet_queue.zig +++ b/gen/zig/packet_queue.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const QUEUE_SIZE: u8 = 8; @@ -52,22 +60,22 @@ test "queue_initially_empty" { } test "enqueue_increases_count" { const new_state = enqueue(clear(), 0xABCD); - if (!(get_count(new_state) == 1)) @panic("count should be 1"); + if (!(get_count(new_state) == 1)) __t27_assert_fail("\n count should be 1:\n get_count(new_state) = {any}\n", .{ get_count(new_state) }); } test "dequeue_from_empty" { const new_state = dequeue(clear()); - if (!(get_count(new_state) == 0)) @panic("should stay empty"); + if (!(get_count(new_state) == 0)) __t27_assert_fail("\n should stay empty:\n get_count(new_state) = {any}\n", .{ get_count(new_state) }); } test "enqueue_dequeue_roundtrip" { const state2 = enqueue(clear(), 0x1234); const state3 = dequeue(state2); - if (!(get_count(state3) == 0)) @panic("back to empty"); + if (!(get_count(state3) == 0)) __t27_assert_fail("\n back to empty:\n get_count(state3) = {any}\n", .{ get_count(state3) }); } test "multiple_enqueues" { const s1 = enqueue(clear(), 1); const s2 = enqueue(s1, 2); const s3 = enqueue(s2, 3); - if (!(get_count(s3) == 3)) @panic("count is 3"); + if (!(get_count(s3) == 3)) __t27_assert_fail("\n count is 3:\n get_count(s3) = {any}\n", .{ get_count(s3) }); } test "queue_fills_up" { const s1 = enqueue(clear(), 1); @@ -78,7 +86,7 @@ test "queue_fills_up" { const s6 = enqueue(s5, 6); const s7 = enqueue(s6, 7); const s8 = enqueue(s7, 8); - if (!(get_count(s8) == 8)) @panic("full queue"); + if (!(get_count(s8) == 8)) __t27_assert_fail("\n full queue:\n get_count(s8) = {any}\n", .{ get_count(s8) }); } test "enqueue_full_idempotent" { const s1 = enqueue(clear(), 1); @@ -90,13 +98,13 @@ test "enqueue_full_idempotent" { const s7 = enqueue(s6, 7); const s8 = enqueue(s7, 8); const s9 = enqueue(s8, 9); - if (!(get_count(s8) == get_count(s9))) @panic("full queue no-op"); + if (!(get_count(s8) == get_count(s9))) __t27_assert_fail("\n full queue no-op:\n get_count(s8) = {any}\n get_count(s9) = {any}\n", .{ get_count(s8), get_count(s9) }); } test "increment_wrap" { - if (!(increment_index(0) == 1)) @panic("0→1"); - if (!(increment_index(7) == 0)) @panic("7→0"); + if (!(increment_index(0) == 1)) __t27_assert_fail("\n 0→1:\n increment_index(0) = {any}\n", .{ increment_index(0) }); + if (!(increment_index(7) == 0)) __t27_assert_fail("\n 7→0:\n increment_index(7) = {any}\n", .{ increment_index(7) }); } test "size_check" { - if (!(size(clear()) == 0)) @panic("initial size"); - if (!(size(enqueue(clear(), 1)) == 1)) @panic("size after enqueue"); + if (!(size(clear()) == 0)) __t27_assert_fail("\n initial size:\n size(clear()) = {any}\n", .{ size(clear()) }); + if (!(size(enqueue(clear(), 1)) == 1)) __t27_assert_fail("\n size after enqueue:\n size(enqueue(clear(), 1)) = {any}\n", .{ size(enqueue(clear(), 1)) }); } diff --git a/gen/zig/pattern_predictor.zig b/gen/zig/pattern_predictor.zig index fdfe80a5..9844f016 100644 --- a/gen/zig/pattern_predictor.zig +++ b/gen/zig/pattern_predictor.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_SAMPLES: u32 = 16; @@ -192,79 +200,79 @@ fn calculate_variance(array: [16]u32, samples: u32) u32 { } test "create_sample_basic" { const sample = create_sample(50, 100, 1, 1); - if (!(get_sample_value(sample) == 50)) @panic("value"); - if (!(get_sample_timestamp(sample) == 100)) @panic("timestamp"); - if (!(get_sample_sequence(sample) == 1)) @panic("sequence"); - if (!(get_sample_valid(sample) == 1)) @panic("valid"); + if (!(get_sample_value(sample) == 50)) __t27_assert_fail("\n value:\n get_sample_value(sample) = {any}\n", .{ get_sample_value(sample) }); + if (!(get_sample_timestamp(sample) == 100)) __t27_assert_fail("\n timestamp:\n get_sample_timestamp(sample) = {any}\n", .{ get_sample_timestamp(sample) }); + if (!(get_sample_sequence(sample) == 1)) __t27_assert_fail("\n sequence:\n get_sample_sequence(sample) = {any}\n", .{ get_sample_sequence(sample) }); + if (!(get_sample_valid(sample) == 1)) __t27_assert_fail("\n valid:\n get_sample_valid(sample) = {any}\n", .{ get_sample_valid(sample) }); } test "create_pattern_storage_basic" { const storage = create_pattern_storage(0x1234, 8, 1, 1); - if (!(get_pattern_samples(storage) == 0x1234)) @panic("samples"); - if (!(get_pattern_count(storage) == 8)) @panic("count"); - if (!(get_trend_direction(storage) == 1)) @panic("trend"); + if (!(get_pattern_samples(storage) == 0x1234)) __t27_assert_fail("\n samples:\n get_pattern_samples(storage) = {any}\n", .{ get_pattern_samples(storage) }); + if (!(get_pattern_count(storage) == 8)) __t27_assert_fail("\n count:\n get_pattern_count(storage) = {any}\n", .{ get_pattern_count(storage) }); + if (!(get_trend_direction(storage) == 1)) __t27_assert_fail("\n trend:\n get_trend_direction(storage) = {any}\n", .{ get_trend_direction(storage) }); } test "calculate_moving_average_4_samples" { const array = create_sample_array(create_sample(50, 1, 1, 1), create_sample(60, 2, 2, 1), create_sample(70, 3, 3, 1), create_sample(80, 4, 4, 1), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); const avg = calculate_moving_average(array, 4); - if (!(avg == 65)) @panic("average of 50,60,70,80"); + if (!(avg == 65)) __t27_assert_fail("\n average of 50,60,70,80:\n avg = {any}\n", .{ avg }); } test "calculate_moving_average_all_samples" { const array = create_sample_array(create_sample(100, 1, 1, 1), create_sample(100, 2, 2, 1), create_sample(100, 3, 3, 1), create_sample(100, 4, 4, 1), create_sample(100, 5, 5, 1), create_sample(100, 6, 6, 1), create_sample(100, 7, 7, 1), create_sample(100, 8, 8, 1), 0, 0, 0, 0, 0, 0, 0, 0); const avg = calculate_moving_average(array, 8); - if (!(avg == 100)) @panic("all samples = 100"); + if (!(avg == 100)) __t27_assert_fail("\n all samples = 100:\n avg = {any}\n", .{ avg }); } test "detect_trend_increasing" { const array = create_sample_array(create_sample(10, 1, 1, 1), create_sample(20, 2, 2, 1), create_sample(30, 3, 3, 1), create_sample(40, 4, 4, 1), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - if (!(detect_trend(array, 4) == 1)) @panic("increasing trend"); + if (!(detect_trend(array, 4) == 1)) __t27_assert_fail("\n increasing trend:\n detect_trend(array, 4) = {any}\n", .{ detect_trend(array, 4) }); } test "detect_trend_decreasing" { const array = create_sample_array(create_sample(80, 1, 1, 1), create_sample(60, 2, 2, 1), create_sample(40, 3, 3, 1), create_sample(20, 4, 4, 1), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - if (!(detect_trend(array, 4) == 2)) @panic("decreasing trend"); + if (!(detect_trend(array, 4) == 2)) __t27_assert_fail("\n decreasing trend:\n detect_trend(array, 4) = {any}\n", .{ detect_trend(array, 4) }); } test "detect_trend_stable" { const array = create_sample_array(create_sample(50, 1, 1, 1), create_sample(52, 2, 2, 1), create_sample(48, 3, 3, 1), create_sample(51, 4, 4, 1), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - if (!(detect_trend(array, 4) == 0)) @panic("stable trend"); + if (!(detect_trend(array, 4) == 0)) __t27_assert_fail("\n stable trend:\n detect_trend(array, 4) = {any}\n", .{ detect_trend(array, 4) }); } test "predict_next_value_increasing" { const array = create_sample_array(create_sample(50, 1, 1, 1), create_sample(60, 2, 2, 1), create_sample(70, 3, 3, 1), create_sample(80, 4, 4, 1), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); const predicted = predict_next_value(array, 4); - if (!(predicted == 90)) @panic("predict 90 (80 + 10)"); + if (!(predicted == 90)) __t27_assert_fail("\n predict 90 (80 + 10):\n predicted = {any}\n", .{ predicted }); } test "predict_next_value_decreasing" { const array = create_sample_array(create_sample(80, 1, 1, 1), create_sample(60, 2, 2, 1), create_sample(40, 3, 3, 1), create_sample(20, 4, 4, 1), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); const predicted = predict_next_value(array, 4); - if (!(predicted == 10)) @panic("predict 10 (20 - 10)"); + if (!(predicted == 10)) __t27_assert_fail("\n predict 10 (20 - 10):\n predicted = {any}\n", .{ predicted }); } test "predict_next_value_stable" { const array = create_sample_array(create_sample(50, 1, 1, 1), create_sample(52, 2, 2, 1), create_sample(48, 3, 3, 1), create_sample(51, 4, 4, 1), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); const predicted = predict_next_value(array, 4); - if (!(predicted == 51)) @panic("predict 51 (stable)"); + if (!(predicted == 51)) __t27_assert_fail("\n predict 51 (stable):\n predicted = {any}\n", .{ predicted }); } test "is_anomalous_large_deviation" { const array = create_sample_array(create_sample(50, 1, 1, 1), create_sample(60, 2, 2, 1), create_sample(70, 3, 3, 1), create_sample(80, 4, 4, 1), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); const anomaly = is_anomalous(array, 4, 120); - if (!(anomaly > 20)) @panic("large deviation"); + if (!(anomaly > 20)) __t27_assert_fail("\n large deviation:\n anomaly = {any}\n", .{ anomaly }); } test "is_anomalous_normal" { const array = create_sample_array(create_sample(50, 1, 1, 1), create_sample(60, 2, 2, 1), create_sample(70, 3, 3, 1), create_sample(80, 4, 4, 1), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); const anomaly = is_anomalous(array, 4, 85); - if (!(anomaly <= 5)) @panic("normal deviation"); + if (!(anomaly <= 5)) __t27_assert_fail("\n normal deviation:\n anomaly = {any}\n", .{ anomaly }); } test "detect_repeating_pattern_found" { const array = create_sample_array(create_sample(10, 1, 1, 1), create_sample(20, 2, 2, 1), create_sample(10, 3, 3, 1), create_sample(20, 4, 4, 1), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - if (!(detect_repeating_pattern(array, 4) == 1)) @panic("pattern found"); + if (!(detect_repeating_pattern(array, 4) == 1)) __t27_assert_fail("\n pattern found:\n detect_repeating_pattern(array, 4) = {any}\n", .{ detect_repeating_pattern(array, 4) }); } test "detect_repeating_pattern_not_found" { const array = create_sample_array(create_sample(10, 1, 1, 1), create_sample(20, 2, 2, 1), create_sample(30, 3, 3, 1), create_sample(40, 4, 4, 1), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - if (!(detect_repeating_pattern(array, 4) == 0)) @panic("no pattern"); + if (!(detect_repeating_pattern(array, 4) == 0)) __t27_assert_fail("\n no pattern:\n detect_repeating_pattern(array, 4) = {any}\n", .{ detect_repeating_pattern(array, 4) }); } test "calculate_variance_low" { const array = create_sample_array(create_sample(50, 1, 1, 1), create_sample(52, 2, 2, 1), create_sample(48, 3, 3, 1), create_sample(51, 4, 4, 1), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); const variance = calculate_variance(array, 4); - if (!(variance < 10)) @panic("low variance"); + if (!(variance < 10)) __t27_assert_fail("\n low variance:\n variance = {any}\n", .{ variance }); } test "calculate_variance_high" { const array = create_sample_array(create_sample(10, 1, 1, 1), create_sample(100, 2, 2, 1), create_sample(20, 3, 3, 1), create_sample(90, 4, 4, 1), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); const variance = calculate_variance(array, 4); - if (!(variance > 1000)) @panic("high variance"); + if (!(variance > 1000)) __t27_assert_fail("\n high variance:\n variance = {any}\n", .{ variance }); } diff --git a/gen/zig/performance_benchmarks.zig b/gen/zig/performance_benchmarks.zig index 05cbec43..ac511f37 100644 --- a/gen/zig/performance_benchmarks.zig +++ b/gen/zig/performance_benchmarks.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_QUEUE_SIZE: u32 = 16; @@ -61,39 +69,39 @@ fn ticks_to_milliseconds(ticks: u32) u32 { } test "create_queue_correct_layout" { const q = create_queue(5, 10, 15); - if (!(queue_count(q) == 5)) @panic("count"); - if (!(queue_head(q) == 10)) @panic("head"); - if (!(queue_tail(q) == 15)) @panic("tail"); + if (!(queue_count(q) == 5)) __t27_assert_fail("\n count:\n queue_count(q) = {any}\n", .{ queue_count(q) }); + if (!(queue_head(q) == 10)) __t27_assert_fail("\n head:\n queue_head(q) = {any}\n", .{ queue_head(q) }); + if (!(queue_tail(q) == 15)) __t27_assert_fail("\n tail:\n queue_tail(q) = {any}\n", .{ queue_tail(q) }); } test "queue_enqueue_increases_count" { const q = create_queue(0, 0, 0); const q2 = queue_enqueue(q); - if (!(queue_count(q2) == 1)) @panic("count increased"); - if (!(queue_tail(q2) == 1)) @panic("tail advanced"); + if (!(queue_count(q2) == 1)) __t27_assert_fail("\n count increased:\n queue_count(q2) = {any}\n", .{ queue_count(q2) }); + if (!(queue_tail(q2) == 1)) __t27_assert_fail("\n tail advanced:\n queue_tail(q2) = {any}\n", .{ queue_tail(q2) }); } test "queue_enqueue_full" { const q = create_queue(MAX_QUEUE_SIZE, 0, MAX_QUEUE_SIZE - 1); const q2 = queue_enqueue(q); - if (!(queue_count(q2) == MAX_QUEUE_SIZE)) @panic("still full"); + if (!(queue_count(q2) == MAX_QUEUE_SIZE)) __t27_assert_fail("\n still full:\n queue_count(q2) = {any}\n MAX_QUEUE_SIZE = {any}\n", .{ queue_count(q2), MAX_QUEUE_SIZE }); } test "queue_dequeue_decreases_count" { const q = create_queue(5, 0, 5); const q2 = queue_dequeue(q); - if (!(queue_count(q2) == 4)) @panic("count decreased"); - if (!(queue_head(q2) == 1)) @panic("head advanced"); + if (!(queue_count(q2) == 4)) __t27_assert_fail("\n count decreased:\n queue_count(q2) = {any}\n", .{ queue_count(q2) }); + if (!(queue_head(q2) == 1)) __t27_assert_fail("\n head advanced:\n queue_head(q2) = {any}\n", .{ queue_head(q2) }); } test "queue_dequeue_empty" { const q = create_queue(0, 0, 0); const q2 = queue_dequeue(q); - if (!(queue_count(q2) == 0)) @panic("still empty"); + if (!(queue_count(q2) == 0)) __t27_assert_fail("\n still empty:\n queue_count(q2) = {any}\n", .{ queue_count(q2) }); } test "queue_is_full_detects_full" { const q = create_queue(MAX_QUEUE_SIZE, 0, MAX_QUEUE_SIZE - 1); - if (!(queue_is_full(q) == true)) @panic("is full"); + if (!(queue_is_full(q) == true)) __t27_assert_fail("\n is full:\n queue_is_full(q) = {any}\n", .{ queue_is_full(q) }); } test "queue_is_empty_detects_empty" { const q = create_queue(0, 0, 0); - if (!(queue_is_empty(q) == true)) @panic("is empty"); + if (!(queue_is_empty(q) == true)) __t27_assert_fail("\n is empty:\n queue_is_empty(q) = {any}\n", .{ queue_is_empty(q) }); } test "queue_max_capacity" { const q = create_queue(0, 0, 0); @@ -113,38 +121,38 @@ test "queue_max_capacity" { const q15 = queue_enqueue(q14); const q16 = queue_enqueue(q15); const q17 = queue_enqueue(q16); - if (!(queue_count(q17) == MAX_QUEUE_SIZE)) @panic("max capacity"); - if (!(queue_is_full(q17) == true)) @panic("is full"); + if (!(queue_count(q17) == MAX_QUEUE_SIZE)) __t27_assert_fail("\n max capacity:\n queue_count(q17) = {any}\n MAX_QUEUE_SIZE = {any}\n", .{ queue_count(q17), MAX_QUEUE_SIZE }); + if (!(queue_is_full(q17) == true)) __t27_assert_fail("\n is full:\n queue_is_full(q17) = {any}\n", .{ queue_is_full(q17) }); } test "inc_counter_increments" { const c = inc_counter(0); - if (!(c == 1)) @panic("incremented"); + if (!(c == 1)) __t27_assert_fail("\n incremented:\n c = {any}\n", .{ c }); } test "inc_counter_overflows_at_max" { const c = inc_counter(MAX_COUNTER); - if (!(c == 0)) @panic("wrapped to zero"); + if (!(c == 0)) __t27_assert_fail("\n wrapped to zero:\n c = {any}\n", .{ c }); } test "counter_will_overflow_detects_max" { - if (!(counter_will_overflow(MAX_COUNTER) == true)) @panic("will overflow"); - if (!(counter_will_overflow(MAX_COUNTER - 1) == false)) @panic("not yet"); + if (!(counter_will_overflow(MAX_COUNTER) == true)) __t27_assert_fail("\n will overflow:\n counter_will_overflow(MAX_COUNTER) = {any}\n", .{ counter_will_overflow(MAX_COUNTER) }); + if (!(counter_will_overflow(MAX_COUNTER - 1) == false)) __t27_assert_fail("\n not yet:\n counter_will_overflow(MAX_COUNTER - 1) = {any}\n", .{ counter_will_overflow(MAX_COUNTER - 1) }); } test "ticks_to_microseconds_converts" { const us = ticks_to_microseconds(10); - if (!(us == 1000)) @panic("10 ticks = 1000us"); + if (!(us == 1000)) __t27_assert_fail("\n 10 ticks = 1000us:\n us = {any}\n", .{ us }); } test "microseconds_to_ticks_converts" { const ticks = microseconds_to_ticks(1000); - if (!(ticks == 10)) @panic("1000us = 10 ticks"); + if (!(ticks == 10)) __t27_assert_fail("\n 1000us = 10 ticks:\n ticks = {any}\n", .{ ticks }); } test "ticks_to_milliseconds_converts" { const ms = ticks_to_milliseconds(100); - if (!(ms == 10)) @panic("100 ticks = 10ms"); + if (!(ms == 10)) __t27_assert_fail("\n 100 ticks = 10ms:\n ms = {any}\n", .{ ms }); } test "timer_conversion_roundtrip" { const us = 5000; const ticks = microseconds_to_ticks(us); const us2 = ticks_to_microseconds(ticks); - if (!(us2 >= (us - TIMER_TICK_US))) @panic("roundtrip within 1 tick"); + if (!(us2 >= (us - TIMER_TICK_US))) __t27_assert_fail("\n roundtrip within 1 tick:\n us2 = {any}\n us - TIMER_TICK_US = {any}\n", .{ us2, us - TIMER_TICK_US }); } test "queue_enqueue_dequeue_balance" { const q = create_queue(0, 0, 0); @@ -152,5 +160,5 @@ test "queue_enqueue_dequeue_balance" { const q3 = queue_enqueue(q2); const q4 = queue_dequeue(q3); const q5 = queue_dequeue(q4); - if (!(queue_count(q5) == 0)) @panic("balanced enqueue/dequeue"); + if (!(queue_count(q5) == 0)) __t27_assert_fail("\n balanced enqueue/dequeue:\n queue_count(q5) = {any}\n", .{ queue_count(q5) }); } diff --git a/gen/zig/performance_profiler.zig b/gen/zig/performance_profiler.zig index ea291ca6..441fc542 100644 --- a/gen/zig/performance_profiler.zig +++ b/gen/zig/performance_profiler.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_SAMPLES: u32 = 64; @@ -269,15 +277,15 @@ fn calculate_improvement_opportunity(current_performance: u32, target_performanc } test "perf_sample_roundtrip" { const smp = create_perf_sample(6, 45, 30, 99); - if (!(get_sample_function_id(smp) == 6)) @panic("function id"); - if (!(get_sample_cpu(smp) == 45)) @panic("cpu"); - if (!(get_sample_memory(smp) == 30)) @panic("memory"); - if (!(get_sample_timestamp(smp) == 99)) @panic("timestamp"); + if (!(get_sample_function_id(smp) == 6)) __t27_assert_fail("\n function id:\n get_sample_function_id(smp) = {any}\n", .{ get_sample_function_id(smp) }); + if (!(get_sample_cpu(smp) == 45)) __t27_assert_fail("\n cpu:\n get_sample_cpu(smp) = {any}\n", .{ get_sample_cpu(smp) }); + if (!(get_sample_memory(smp) == 30)) __t27_assert_fail("\n memory:\n get_sample_memory(smp) = {any}\n", .{ get_sample_memory(smp) }); + if (!(get_sample_timestamp(smp) == 99)) __t27_assert_fail("\n timestamp:\n get_sample_timestamp(smp) = {any}\n", .{ get_sample_timestamp(smp) }); } test "hotspot_roundtrip" { const h = create_hotspot(6, 90, 1, 77); - if (!(get_hotspot_function_id(h) == 6)) @panic("function id"); - if (!(get_hotspot_score(h) == 90)) @panic("score"); - if (!(get_hotspot_rank(h) == 1)) @panic("rank"); - if (!(get_hotspot_impact(h) == 77)) @panic("impact"); + if (!(get_hotspot_function_id(h) == 6)) __t27_assert_fail("\n function id:\n get_hotspot_function_id(h) = {any}\n", .{ get_hotspot_function_id(h) }); + if (!(get_hotspot_score(h) == 90)) __t27_assert_fail("\n score:\n get_hotspot_score(h) = {any}\n", .{ get_hotspot_score(h) }); + if (!(get_hotspot_rank(h) == 1)) __t27_assert_fail("\n rank:\n get_hotspot_rank(h) = {any}\n", .{ get_hotspot_rank(h) }); + if (!(get_hotspot_impact(h) == 77)) __t27_assert_fail("\n impact:\n get_hotspot_impact(h) = {any}\n", .{ get_hotspot_impact(h) }); } diff --git a/gen/zig/power_monitoring.zig b/gen/zig/power_monitoring.zig index cc92be1c..7d1452c9 100644 --- a/gen/zig/power_monitoring.zig +++ b/gen/zig/power_monitoring.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_NODES: u32 = 8; @@ -107,92 +115,92 @@ fn should_sleep(state: u32, current_time: u32, sleep_start: u32, sleep_end: u32) } test "create_power_state_basic" { const state = create_power_state(80, POWER_NORMAL, 50, 100); - if (!(get_battery_level(state) == 80)) @panic("battery"); - if (!(get_power_mode(state) == POWER_NORMAL)) @panic("mode"); - if (!(get_consumption(state) == 50)) @panic("consumption"); - if (!(get_uptime(state) == 100)) @panic("uptime"); + if (!(get_battery_level(state) == 80)) __t27_assert_fail("\n battery:\n get_battery_level(state) = {any}\n", .{ get_battery_level(state) }); + if (!(get_power_mode(state) == POWER_NORMAL)) __t27_assert_fail("\n mode:\n get_power_mode(state) = {any}\n POWER_NORMAL = {any}\n", .{ get_power_mode(state), POWER_NORMAL }); + if (!(get_consumption(state) == 50)) __t27_assert_fail("\n consumption:\n get_consumption(state) = {any}\n", .{ get_consumption(state) }); + if (!(get_uptime(state) == 100)) __t27_assert_fail("\n uptime:\n get_uptime(state) = {any}\n", .{ get_uptime(state) }); } test "is_battery_critical_true" { const state = create_power_state(15, POWER_NORMAL, 50, 100); - if (!(is_battery_critical(state) == true)) @panic("critical"); + if (!(is_battery_critical(state) == true)) __t27_assert_fail("\n critical:\n is_battery_critical(state) = {any}\n", .{ is_battery_critical(state) }); } test "is_battery_critical_false" { const state = create_power_state(25, POWER_NORMAL, 50, 100); - if (!(is_battery_critical(state) == false)) @panic("not critical"); + if (!(is_battery_critical(state) == false)) __t27_assert_fail("\n not critical:\n is_battery_critical(state) = {any}\n", .{ is_battery_critical(state) }); } test "is_battery_low" { const state = create_power_state(30, POWER_NORMAL, 50, 100); - if (!(is_battery_low(state) == true)) @panic("low"); + if (!(is_battery_low(state) == true)) __t27_assert_fail("\n low:\n is_battery_low(state) = {any}\n", .{ is_battery_low(state) }); } test "is_battery_healthy" { const state = create_power_state(70, POWER_NORMAL, 50, 100); - if (!(is_battery_healthy(state) == true)) @panic("healthy"); + if (!(is_battery_healthy(state) == true)) __t27_assert_fail("\n healthy:\n is_battery_healthy(state) = {any}\n", .{ is_battery_healthy(state) }); } test "estimate_remaining_time_calculates" { const state = create_power_state(60, POWER_NORMAL, 10, 100); const time = estimate_remaining_time(state); - if (!((time >= 59) and (time <= 61))) @panic("estimated time"); + if (!((time >= 59) and (time <= 61))) __t27_assert_fail("\n estimated time:\n time = {any}\n", .{ time }); } test "estimate_remaining_time_zero_consumption" { const state = create_power_state(60, POWER_NORMAL, 0, 100); - if (!(estimate_remaining_time(state) == 0xFF)) @panic("infinite time"); + if (!(estimate_remaining_time(state) == 0xFF)) __t27_assert_fail("\n infinite time:\n estimate_remaining_time(state) = {any}\n", .{ estimate_remaining_time(state) }); } test "update_power_mode_emergency" { const state = create_power_state(15, POWER_NORMAL, 50, 100); const new_state = update_power_mode(state); - if (!(get_power_mode(new_state) == POWER_EMERGENCY)) @panic("emergency mode"); + if (!(get_power_mode(new_state) == POWER_EMERGENCY)) __t27_assert_fail("\n emergency mode:\n get_power_mode(new_state) = {any}\n POWER_EMERGENCY = {any}\n", .{ get_power_mode(new_state), POWER_EMERGENCY }); } test "update_power_mode_eco" { const state = create_power_state(30, POWER_NORMAL, 50, 100); const new_state = update_power_mode(state); - if (!(get_power_mode(new_state) == POWER_ECO)) @panic("eco mode"); + if (!(get_power_mode(new_state) == POWER_ECO)) __t27_assert_fail("\n eco mode:\n get_power_mode(new_state) = {any}\n POWER_ECO = {any}\n", .{ get_power_mode(new_state), POWER_ECO }); } test "update_power_mode_normal" { const state = create_power_state(80, POWER_NORMAL, 50, 100); const new_state = update_power_mode(state); - if (!(get_power_mode(new_state) == POWER_NORMAL)) @panic("normal mode"); + if (!(get_power_mode(new_state) == POWER_NORMAL)) __t27_assert_fail("\n normal mode:\n get_power_mode(new_state) = {any}\n POWER_NORMAL = {any}\n", .{ get_power_mode(new_state), POWER_NORMAL }); } test "reduce_consumption_works" { const state = create_power_state(80, POWER_NORMAL, 50, 100); const new_state = reduce_consumption(state, 10); - if (!(get_consumption(new_state) == 40)) @panic("consumption reduced"); + if (!(get_consumption(new_state) == 40)) __t27_assert_fail("\n consumption reduced:\n get_consumption(new_state) = {any}\n", .{ get_consumption(new_state) }); } test "reduce_consumption_minimum" { const state = create_power_state(80, POWER_NORMAL, 2, 100); const new_state = reduce_consumption(state, 5); - if (!(get_consumption(new_state) == 1)) @panic("minimum consumption"); + if (!(get_consumption(new_state) == 1)) __t27_assert_fail("\n minimum consumption:\n get_consumption(new_state) = {any}\n", .{ get_consumption(new_state) }); } test "drain_battery_works" { const state = create_power_state(80, POWER_NORMAL, 50, 100); const new_state = drain_battery(state, 20); - if (!(get_battery_level(new_state) == 60)) @panic("battery drained"); + if (!(get_battery_level(new_state) == 60)) __t27_assert_fail("\n battery drained:\n get_battery_level(new_state) = {any}\n", .{ get_battery_level(new_state) }); } test "drain_battery_empty" { const state = create_power_state(10, POWER_NORMAL, 50, 100); const new_state = drain_battery(state, 20); - if (!(get_battery_level(new_state) == 0)) @panic("battery empty"); + if (!(get_battery_level(new_state) == 0)) __t27_assert_fail("\n battery empty:\n get_battery_level(new_state) = {any}\n", .{ get_battery_level(new_state) }); } test "get_power_priority_critical" { const state = create_power_state(15, POWER_NORMAL, 50, 100); - if (!(get_power_priority(state) == 3)) @panic("highest priority"); + if (!(get_power_priority(state) == 3)) __t27_assert_fail("\n highest priority:\n get_power_priority(state) = {any}\n", .{ get_power_priority(state) }); } test "get_power_priority_low" { const state = create_power_state(30, POWER_NORMAL, 50, 100); - if (!(get_power_priority(state) == 2)) @panic("medium priority"); + if (!(get_power_priority(state) == 2)) __t27_assert_fail("\n medium priority:\n get_power_priority(state) = {any}\n", .{ get_power_priority(state) }); } test "get_power_priority_normal" { const state = create_power_state(70, POWER_NORMAL, 50, 100); - if (!(get_power_priority(state) == 1)) @panic("normal priority"); + if (!(get_power_priority(state) == 1)) __t27_assert_fail("\n normal priority:\n get_power_priority(state) = {any}\n", .{ get_power_priority(state) }); } test "should_sleep_critical_in_window" { const state = create_power_state(15, POWER_NORMAL, 50, 100); - if (!(should_sleep(state, 5000, 4000, 6000) == true)) @panic("should sleep"); + if (!(should_sleep(state, 5000, 4000, 6000) == true)) __t27_assert_fail("\n should sleep:\n should_sleep(state, 5000, 4000, 6000) = {any}\n", .{ should_sleep(state, 5000, 4000, 6000) }); } test "should_sleep_critical_outside_window" { const state = create_power_state(15, POWER_NORMAL, 50, 100); - if (!(should_sleep(state, 7000, 4000, 6000) == false)) @panic("no sleep"); + if (!(should_sleep(state, 7000, 4000, 6000) == false)) __t27_assert_fail("\n no sleep:\n should_sleep(state, 7000, 4000, 6000) = {any}\n", .{ should_sleep(state, 7000, 4000, 6000) }); } test "should_sleep_healthy_battery" { const state = create_power_state(70, POWER_NORMAL, 50, 100); - if (!(should_sleep(state, 5000, 4000, 6000) == false)) @panic("no sleep with healthy battery"); + if (!(should_sleep(state, 5000, 4000, 6000) == false)) __t27_assert_fail("\n no sleep with healthy battery:\n should_sleep(state, 5000, 4000, 6000) = {any}\n", .{ should_sleep(state, 5000, 4000, 6000) }); } diff --git a/gen/zig/production_deployment.zig b/gen/zig/production_deployment.zig index 5898475f..7290818f 100644 --- a/gen/zig/production_deployment.zig +++ b/gen/zig/production_deployment.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const DEPLOY_PENDING: u32 = 0; @@ -90,64 +98,64 @@ fn checklist_complete(checklist: u32) bool { } test "create_deployment_correct" { const deploy = create_deployment(DEPLOY_PROGRAMMING, STEP_FLASH, 15, 12345); - if (!(extract_deploy_state(deploy) == DEPLOY_PROGRAMMING)) @panic("state"); - if (!(extract_deploy_step(deploy) == STEP_FLASH)) @panic("step"); - if (!(extract_deploy_progress(deploy) == 15)) @panic("progress"); - if (!(extract_device_id(deploy) == 12345)) @panic("device"); + if (!(extract_deploy_state(deploy) == DEPLOY_PROGRAMMING)) __t27_assert_fail("\n state:\n extract_deploy_state(deploy) = {any}\n DEPLOY_PROGRAMMING = {any}\n", .{ extract_deploy_state(deploy), DEPLOY_PROGRAMMING }); + if (!(extract_deploy_step(deploy) == STEP_FLASH)) __t27_assert_fail("\n step:\n extract_deploy_step(deploy) = {any}\n STEP_FLASH = {any}\n", .{ extract_deploy_step(deploy), STEP_FLASH }); + if (!(extract_deploy_progress(deploy) == 15)) __t27_assert_fail("\n progress:\n extract_deploy_progress(deploy) = {any}\n", .{ extract_deploy_progress(deploy) }); + if (!(extract_device_id(deploy) == 12345)) __t27_assert_fail("\n device:\n extract_device_id(deploy) = {any}\n", .{ extract_device_id(deploy) }); } test "deployment_complete_yes" { const deploy = create_deployment(DEPLOY_ACTIVE, STEP_MONITOR, 31, 12345); - if (!(deployment_complete(deploy) == true)) @panic("complete"); + if (!(deployment_complete(deploy) == true)) __t27_assert_fail("\n complete:\n deployment_complete(deploy) = {any}\n", .{ deployment_complete(deploy) }); } test "deployment_complete_no_state" { const deploy = create_deployment(DEPLOY_VERIFIED, STEP_MONITOR, 31, 12345); - if (!(deployment_complete(deploy) == false)) @panic("not active"); + if (!(deployment_complete(deploy) == false)) __t27_assert_fail("\n not active:\n deployment_complete(deploy) = {any}\n", .{ deployment_complete(deploy) }); } test "deployment_complete_no_progress" { const deploy = create_deployment(DEPLOY_ACTIVE, STEP_MONITOR, 15, 12345); - if (!(deployment_complete(deploy) == false)) @panic("not 100%"); + if (!(deployment_complete(deploy) == false)) __t27_assert_fail("\n not 100%:\n deployment_complete(deploy) = {any}\n", .{ deployment_complete(deploy) }); } test "create_bitstream_info_correct" { const info = create_bitstream_info(0x1234, 0xAB, 5); - if (!(extract_bitstream_size(info) == 0x1234)) @panic("size"); - if (!(extract_bitstream_checksum(info) == 0xAB)) @panic("checksum"); - if (!(extract_bitstream_version(info) == 5)) @panic("version"); + if (!(extract_bitstream_size(info) == 0x1234)) __t27_assert_fail("\n size:\n extract_bitstream_size(info) = {any}\n", .{ extract_bitstream_size(info) }); + if (!(extract_bitstream_checksum(info) == 0xAB)) __t27_assert_fail("\n checksum:\n extract_bitstream_checksum(info) = {any}\n", .{ extract_bitstream_checksum(info) }); + if (!(extract_bitstream_version(info) == 5)) __t27_assert_fail("\n version:\n extract_bitstream_version(info) = {any}\n", .{ extract_bitstream_version(info) }); } test "flash_programming_success_yes" { - if (!(flash_programming_success(1000, 1000) == true)) @panic("exact match"); + if (!(flash_programming_success(1000, 1000) == true)) __t27_assert_fail("\n exact match:\n flash_programming_success(1000, 1000) = {any}\n", .{ flash_programming_success(1000, 1000) }); } test "flash_programming_success_no" { - if (!(flash_programming_success(999, 1000) == false)) @panic("mismatch"); + if (!(flash_programming_success(999, 1000) == false)) __t27_assert_fail("\n mismatch:\n flash_programming_success(999, 1000) = {any}\n", .{ flash_programming_success(999, 1000) }); } test "flash_programming_success_zero" { - if (!(flash_programming_success(0, 0) == false)) @panic("zero bytes"); + if (!(flash_programming_success(0, 0) == false)) __t27_assert_fail("\n zero bytes:\n flash_programming_success(0, 0) = {any}\n", .{ flash_programming_success(0, 0) }); } test "create_monitor_config_correct" { const config = create_monitor_config(1000, 0xFF); - if (!(extract_sample_rate(config) == 1000)) @panic("sample rate"); - if (!(extract_metrics_enabled(config) == 0xFF)) @panic("metrics"); + if (!(extract_sample_rate(config) == 1000)) __t27_assert_fail("\n sample rate:\n extract_sample_rate(config) = {any}\n", .{ extract_sample_rate(config) }); + if (!(extract_metrics_enabled(config) == 0xFF)) __t27_assert_fail("\n metrics:\n extract_metrics_enabled(config) = {any}\n", .{ extract_metrics_enabled(config) }); } test "create_checklist_all_true" { const checklist = create_checklist(true, true, true, true); - if (!(checklist_complete(checklist) == true)) @panic("all items"); + if (!(checklist_complete(checklist) == true)) __t27_assert_fail("\n all items:\n checklist_complete(checklist) = {any}\n", .{ checklist_complete(checklist) }); } test "checklist_power_true" { const checklist = create_checklist(true, false, false, false); - if (!(checklist_power(checklist) == true)) @panic("power OK"); + if (!(checklist_power(checklist) == true)) __t27_assert_fail("\n power OK:\n checklist_power(checklist) = {any}\n", .{ checklist_power(checklist) }); } test "checklist_cooling_false" { const checklist = create_checklist(true, false, true, true); - if (!(checklist_cooling(checklist) == false)) @panic("cooling missing"); + if (!(checklist_cooling(checklist) == false)) __t27_assert_fail("\n cooling missing:\n checklist_cooling(checklist) = {any}\n", .{ checklist_cooling(checklist) }); } test "checklist_network_true" { const checklist = create_checklist(false, true, true, false); - if (!(checklist_network(checklist) == true)) @panic("network OK"); + if (!(checklist_network(checklist) == true)) __t27_assert_fail("\n network OK:\n checklist_network(checklist) = {any}\n", .{ checklist_network(checklist) }); } test "checklist_monitoring_false" { const checklist = create_checklist(true, true, true, false); - if (!(checklist_monitoring(checklist) == false)) @panic("monitoring missing"); + if (!(checklist_monitoring(checklist) == false)) __t27_assert_fail("\n monitoring missing:\n checklist_monitoring(checklist) = {any}\n", .{ checklist_monitoring(checklist) }); } test "checklist_complete_incomplete" { const checklist = create_checklist(true, true, false, true); - if (!(checklist_complete(checklist) == false)) @panic("missing network"); + if (!(checklist_complete(checklist) == false)) __t27_assert_fail("\n missing network:\n checklist_complete(checklist) = {any}\n", .{ checklist_complete(checklist) }); } diff --git a/gen/zig/production_scenarios.zig b/gen/zig/production_scenarios.zig index 48387d6f..5696ae90 100644 --- a/gen/zig/production_scenarios.zig +++ b/gen/zig/production_scenarios.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const STATE_COLD_START: u8 = 0; @@ -77,83 +85,83 @@ fn check_max_hops(ttl: u8, max_hops: u8) bool { } test "cold_start_initial_state" { const node = cold_start(); - if (!(node_state_of(node) == STATE_COLD_START)) @panic("cold start state"); - if (!(node_neighbors(node) == 0)) @panic("no neighbors"); - if (!(node_uptime(node) == 0)) @panic("zero uptime"); + if (!(node_state_of(node) == STATE_COLD_START)) __t27_assert_fail("\n cold start state:\n node_state_of(node) = {any}\n STATE_COLD_START = {any}\n", .{ node_state_of(node), STATE_COLD_START }); + if (!(node_neighbors(node) == 0)) __t27_assert_fail("\n no neighbors:\n node_neighbors(node) = {any}\n", .{ node_neighbors(node) }); + if (!(node_uptime(node) == 0)) __t27_assert_fail("\n zero uptime:\n node_uptime(node) = {any}\n", .{ node_uptime(node) }); } test "discover_neighbor_transitions" { const node = cold_start(); const node2 = discover_neighbor(node); - if (!(node_state_of(node2) == STATE_DISCOVERING)) @panic("discovering"); + if (!(node_state_of(node2) == STATE_DISCOVERING)) __t27_assert_fail("\n discovering:\n node_state_of(node2) = {any}\n STATE_DISCOVERING = {any}\n", .{ node_state_of(node2), STATE_DISCOVERING }); const node3 = discover_neighbor(node2); - if (!(node_state_of(node3) == STATE_CONNECTED)) @panic("connected"); - if (!(node_neighbors(node3) == 1)) @panic("1 neighbor"); + if (!(node_state_of(node3) == STATE_CONNECTED)) __t27_assert_fail("\n connected:\n node_state_of(node3) = {any}\n STATE_CONNECTED = {any}\n", .{ node_state_of(node3), STATE_CONNECTED }); + if (!(node_neighbors(node3) == 1)) __t27_assert_fail("\n 1 neighbor:\n node_neighbors(node3) = {any}\n", .{ node_neighbors(node3) }); } test "simulate_partition_removes_neighbors" { const node = create_node_state(STATE_CONNECTED, 3, 1000); const node2 = simulate_partition(node); - if (!(node_state_of(node2) == STATE_PARTITIONED)) @panic("partitioned"); - if (!(node_neighbors(node2) == 0)) @panic("neighbors cleared"); + if (!(node_state_of(node2) == STATE_PARTITIONED)) __t27_assert_fail("\n partitioned:\n node_state_of(node2) = {any}\n STATE_PARTITIONED = {any}\n", .{ node_state_of(node2), STATE_PARTITIONED }); + if (!(node_neighbors(node2) == 0)) __t27_assert_fail("\n neighbors cleared:\n node_neighbors(node2) = {any}\n", .{ node_neighbors(node2) }); } test "recover_from_partition_transitions" { const node = create_node_state(STATE_PARTITIONED, 0, 1000); const node2 = recover_from_partition(node); - if (!(node_state_of(node2) == STATE_RECOVERING)) @panic("recovering"); + if (!(node_state_of(node2) == STATE_RECOVERING)) __t27_assert_fail("\n recovering:\n node_state_of(node2) = {any}\n STATE_RECOVERING = {any}\n", .{ node_state_of(node2), STATE_RECOVERING }); } test "node_join_increases_neighbors" { const node = create_node_state(STATE_CONNECTED, 2, 1000); const node2 = node_join(node); - if (!(node_neighbors(node2) == 3)) @panic("3 neighbors"); + if (!(node_neighbors(node2) == 3)) __t27_assert_fail("\n 3 neighbors:\n node_neighbors(node2) = {any}\n", .{ node_neighbors(node2) }); } test "node_leave_decreases_neighbors" { const node = create_node_state(STATE_CONNECTED, 3, 1000); const node2 = node_leave(node); - if (!(node_neighbors(node2) == 2)) @panic("2 neighbors"); + if (!(node_neighbors(node2) == 2)) __t27_assert_fail("\n 2 neighbors:\n node_neighbors(node2) = {any}\n", .{ node_neighbors(node2) }); } test "node_leave_no_neighbors" { const node = create_node_state(STATE_CONNECTED, 0, 1000); const node2 = node_leave(node); - if (!(node_neighbors(node2) == 0)) @panic("still 0"); + if (!(node_neighbors(node2) == 0)) __t27_assert_fail("\n still 0:\n node_neighbors(node2) = {any}\n", .{ node_neighbors(node2) }); } test "simulate_interference_high_clears" { const node = create_node_state(STATE_CONNECTED, 3, 1000); const node2 = simulate_interference(node, 200); - if (!(node_neighbors(node2) == 0)) @panic("high interference clears"); + if (!(node_neighbors(node2) == 0)) __t27_assert_fail("\n high interference clears:\n node_neighbors(node2) = {any}\n", .{ node_neighbors(node2) }); } test "simulate_interference_low_ok" { const node = create_node_state(STATE_CONNECTED, 3, 1000); const node2 = simulate_interference(node, 50); - if (!(node_neighbors(node2) == 3)) @panic("low interference ok"); + if (!(node_neighbors(node2) == 3)) __t27_assert_fail("\n low interference ok:\n node_neighbors(node2) = {any}\n", .{ node_neighbors(node2) }); } test "battery_drain_kills_node" { const uptime = 5000; const drain = 4; const uptime2 = battery_drain(uptime, drain); - if (!(uptime2 == 0)) @panic("battery dead"); + if (!(uptime2 == 0)) __t27_assert_fail("\n battery dead:\n uptime2 = {any}\n", .{ uptime2 }); } test "battery_drain_survives" { const uptime = 100; const drain = 1; const uptime2 = battery_drain(uptime, drain); - if (!(uptime2 > 0)) @panic("battery ok"); + if (!(uptime2 > 0)) __t27_assert_fail("\n battery ok:\n uptime2 = {any}\n", .{ uptime2 }); } test "check_max_hops_valid" { - if (!(check_max_hops(3, 5) == true)) @panic("valid hops"); - if (!(check_max_hops(1, 5) == true)) @panic("min hops"); - if (!(check_max_hops(5, 5) == true)) @panic("max hops"); + if (!(check_max_hops(3, 5) == true)) __t27_assert_fail("\n valid hops:\n check_max_hops(3, 5) = {any}\n", .{ check_max_hops(3, 5) }); + if (!(check_max_hops(1, 5) == true)) __t27_assert_fail("\n min hops:\n check_max_hops(1, 5) = {any}\n", .{ check_max_hops(1, 5) }); + if (!(check_max_hops(5, 5) == true)) __t27_assert_fail("\n max hops:\n check_max_hops(5, 5) = {any}\n", .{ check_max_hops(5, 5) }); } test "check_max_hops_invalid" { - if (!(check_max_hops(0, 5) == false)) @panic("zero ttl"); - if (!(check_max_hops(6, 5) == false)) @panic("exceeds max"); + if (!(check_max_hops(0, 5) == false)) __t27_assert_fail("\n zero ttl:\n check_max_hops(0, 5) = {any}\n", .{ check_max_hops(0, 5) }); + if (!(check_max_hops(6, 5) == false)) __t27_assert_fail("\n exceeds max:\n check_max_hops(6, 5) = {any}\n", .{ check_max_hops(6, 5) }); } test "complete_scenario_cold_to_connected" { var node = cold_start(); node = discover_neighbor(node); node = discover_neighbor(node); - if (!(node_state_of(node) == STATE_CONNECTED)) @panic("connected"); - if (!(node_neighbors(node) == 1)) @panic("1 neighbor"); + if (!(node_state_of(node) == STATE_CONNECTED)) __t27_assert_fail("\n connected:\n node_state_of(node) = {any}\n STATE_CONNECTED = {any}\n", .{ node_state_of(node), STATE_CONNECTED }); + if (!(node_neighbors(node) == 1)) __t27_assert_fail("\n 1 neighbor:\n node_neighbors(node) = {any}\n", .{ node_neighbors(node) }); node = simulate_partition(node); - if (!(node_state_of(node) == STATE_PARTITIONED)) @panic("partitioned"); + if (!(node_state_of(node) == STATE_PARTITIONED)) __t27_assert_fail("\n partitioned:\n node_state_of(node) = {any}\n STATE_PARTITIONED = {any}\n", .{ node_state_of(node), STATE_PARTITIONED }); node = recover_from_partition(node); - if (!(node_state_of(node) == STATE_RECOVERING)) @panic("recovering"); + if (!(node_state_of(node) == STATE_RECOVERING)) __t27_assert_fail("\n recovering:\n node_state_of(node) = {any}\n STATE_RECOVERING = {any}\n", .{ node_state_of(node), STATE_RECOVERING }); } diff --git a/gen/zig/quarantine_manager.zig b/gen/zig/quarantine_manager.zig index 7994a609..7e4a11f9 100644 --- a/gen/zig/quarantine_manager.zig +++ b/gen/zig/quarantine_manager.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_NODES: u32 = 8; @@ -230,25 +238,25 @@ fn get_notification_duration(notification: u32) u32 { } test "quarantine_state_roundtrip" { const st = create_quarantine_state(9, STATUS_SUSPENDED, 200, 12345); - if (!(get_quarantine_node_id(st) == 9)) @panic("node id"); - if (!(get_quarantine_status(st) == STATUS_SUSPENDED)) @panic("status"); - if (!(get_start_time(st) == 200)) @panic("start time"); - if (!(get_violation_count(st) == 12345)) @panic("violations"); + if (!(get_quarantine_node_id(st) == 9)) __t27_assert_fail("\n node id:\n get_quarantine_node_id(st) = {any}\n", .{ get_quarantine_node_id(st) }); + if (!(get_quarantine_status(st) == STATUS_SUSPENDED)) __t27_assert_fail("\n status:\n get_quarantine_status(st) = {any}\n STATUS_SUSPENDED = {any}\n", .{ get_quarantine_status(st), STATUS_SUSPENDED }); + if (!(get_start_time(st) == 200)) __t27_assert_fail("\n start time:\n get_start_time(st) = {any}\n", .{ get_start_time(st) }); + if (!(get_violation_count(st) == 12345)) __t27_assert_fail("\n violations:\n get_violation_count(st) = {any}\n", .{ get_violation_count(st) }); } test "quarantine_lifecycle" { var st = create_quarantine_state(5, STATUS_NORMAL, 0, 0); st = quarantine_node(st, 100); - if (!(get_quarantine_status(st) == STATUS_QUARANTINED)) @panic("quarantined"); - if (!(get_violation_count(st) == 1)) @panic("violation recorded"); - if (!(should_release_quarantine(st, 100 + QUARANTINE_DURATION) == 1)) @panic("released after the duration"); - if (!(should_release_quarantine(st, 100) == 0)) @panic("held before the duration"); + if (!(get_quarantine_status(st) == STATUS_QUARANTINED)) __t27_assert_fail("\n quarantined:\n get_quarantine_status(st) = {any}\n STATUS_QUARANTINED = {any}\n", .{ get_quarantine_status(st), STATUS_QUARANTINED }); + if (!(get_violation_count(st) == 1)) __t27_assert_fail("\n violation recorded:\n get_violation_count(st) = {any}\n", .{ get_violation_count(st) }); + if (!(should_release_quarantine(st, 100 + QUARANTINE_DURATION) == 1)) __t27_assert_fail("\n released after the duration:\n should_release_quarantine(st, 100 + QUARANTINE_DURATION) = {any}\n", .{ should_release_quarantine(st, 100 + QUARANTINE_DURATION) }); + if (!(should_release_quarantine(st, 100) == 0)) __t27_assert_fail("\n held before the duration:\n should_release_quarantine(st, 100) = {any}\n", .{ should_release_quarantine(st, 100) }); st = release_quarantine(st); - if (!(get_quarantine_status(st) == STATUS_NORMAL)) @panic("released"); - if (!(get_violation_count(st) == 1)) @panic("violations persist"); + if (!(get_quarantine_status(st) == STATUS_NORMAL)) __t27_assert_fail("\n released:\n get_quarantine_status(st) = {any}\n STATUS_NORMAL = {any}\n", .{ get_quarantine_status(st), STATUS_NORMAL }); + if (!(get_violation_count(st) == 1)) __t27_assert_fail("\n violations persist:\n get_violation_count(st) = {any}\n", .{ get_violation_count(st) }); } test "ban_pins_violation_ceiling" { var st = create_quarantine_state(5, STATUS_NORMAL, 0, 3); st = ban_node(st); - if (!(get_quarantine_status(st) == STATUS_BANNED)) @panic("banned"); - if (!(get_violation_count(st) == 0x3FFF)) @panic("ceiling fits the 14-bit field"); + if (!(get_quarantine_status(st) == STATUS_BANNED)) __t27_assert_fail("\n banned:\n get_quarantine_status(st) = {any}\n STATUS_BANNED = {any}\n", .{ get_quarantine_status(st), STATUS_BANNED }); + if (!(get_violation_count(st) == 0x3FFF)) __t27_assert_fail("\n ceiling fits the 14-bit field:\n get_violation_count(st) = {any}\n", .{ get_violation_count(st) }); } diff --git a/gen/zig/redundancy_management.zig b/gen/zig/redundancy_management.zig index 191b7e56..7d05e59a 100644 --- a/gen/zig/redundancy_management.zig +++ b/gen/zig/redundancy_management.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_PATHS: u32 = 4; @@ -161,73 +169,73 @@ fn failover(path_set: [4]u32, failed_path: u32) [4]u32 { } test "create_path_basic" { const path = create_path(1, 10, 20, 30); - if (!(get_path_valid(path) == 1)) @panic("valid"); - if (!(get_hop1(path) == 10)) @panic("hop1"); - if (!(get_hop2(path) == 20)) @panic("hop2"); - if (!(get_hop3(path) == 30)) @panic("hop3"); + if (!(get_path_valid(path) == 1)) __t27_assert_fail("\n valid:\n get_path_valid(path) = {any}\n", .{ get_path_valid(path) }); + if (!(get_hop1(path) == 10)) __t27_assert_fail("\n hop1:\n get_hop1(path) = {any}\n", .{ get_hop1(path) }); + if (!(get_hop2(path) == 20)) __t27_assert_fail("\n hop2:\n get_hop2(path) = {any}\n", .{ get_hop2(path) }); + if (!(get_hop3(path) == 30)) __t27_assert_fail("\n hop3:\n get_hop3(path) = {any}\n", .{ get_hop3(path) }); } test "create_path_set" { const path_set = create_path_set(create_path(1, 10, 20, 30), create_path(0, 40, 50, 60), create_path(1, 70, 80, 90), create_path(1, 15, 25, 35)); - if (!(get_path_valid(get_path(path_set, 0)) == 1)) @panic("path 0 valid"); - if (!(get_path_valid(get_path(path_set, 1)) == 0)) @panic("path 1 invalid"); + if (!(get_path_valid(get_path(path_set, 0)) == 1)) __t27_assert_fail("\n path 0 valid:\n get_path_valid(get_path(path_set, 0)) = {any}\n", .{ get_path_valid(get_path(path_set, 0)) }); + if (!(get_path_valid(get_path(path_set, 1)) == 0)) __t27_assert_fail("\n path 1 invalid:\n get_path_valid(get_path(path_set, 1)) = {any}\n", .{ get_path_valid(get_path(path_set, 1)) }); } test "find_primary_path_first" { const path_set = create_path_set(create_path(1, 10, 20, 30), create_path(1, 40, 50, 60), create_path(1, 70, 80, 90), create_path(1, 15, 25, 35)); - if (!(find_primary_path(path_set) == 0)) @panic("first path is primary"); + if (!(find_primary_path(path_set) == 0)) __t27_assert_fail("\n first path is primary:\n find_primary_path(path_set) = {any}\n", .{ find_primary_path(path_set) }); } test "find_primary_path_skip_invalid" { const path_set = create_path_set(create_path(0, 10, 20, 30), create_path(1, 40, 50, 60), create_path(1, 70, 80, 90), create_path(1, 15, 25, 35)); - if (!(find_primary_path(path_set) == 1)) @panic("second path is primary"); + if (!(find_primary_path(path_set) == 1)) __t27_assert_fail("\n second path is primary:\n find_primary_path(path_set) = {any}\n", .{ find_primary_path(path_set) }); } test "find_backup_path" { const path_set = create_path_set(create_path(1, 10, 20, 30), create_path(1, 40, 50, 60), create_path(1, 70, 80, 90), create_path(0, 15, 25, 35)); - if (!(find_backup_path(path_set, 0) == 1)) @panic("backup is path 1"); + if (!(find_backup_path(path_set, 0) == 1)) __t27_assert_fail("\n backup is path 1:\n find_backup_path(path_set, 0) = {any}\n", .{ find_backup_path(path_set, 0) }); } test "invalidate_path_works" { const path_set = create_path_set(create_path(1, 10, 20, 30), create_path(1, 40, 50, 60), create_path(1, 70, 80, 90), create_path(0, 15, 25, 35)); const new_set = invalidate_path(path_set, 0); - if (!(get_path_valid(get_path(new_set, 0)) == 0)) @panic("path invalidated"); + if (!(get_path_valid(get_path(new_set, 0)) == 0)) __t27_assert_fail("\n path invalidated:\n get_path_valid(get_path(new_set, 0)) = {any}\n", .{ get_path_valid(get_path(new_set, 0)) }); } test "validate_path_works" { const path_set = create_path_set(create_path(0, 10, 20, 30), create_path(1, 40, 50, 60), create_path(1, 70, 80, 90), create_path(1, 15, 25, 35)); const new_set = validate_path(path_set, 0); - if (!(get_path_valid(get_path(new_set, 0)) == 1)) @panic("path validated"); + if (!(get_path_valid(get_path(new_set, 0)) == 1)) __t27_assert_fail("\n path validated:\n get_path_valid(get_path(new_set, 0)) = {any}\n", .{ get_path_valid(get_path(new_set, 0)) }); } test "count_valid_paths_all" { const path_set = create_path_set(create_path(1, 10, 20, 30), create_path(1, 40, 50, 60), create_path(1, 70, 80, 90), create_path(1, 15, 25, 35)); - if (!(count_valid_paths(path_set) == 4)) @panic("4 valid paths"); + if (!(count_valid_paths(path_set) == 4)) __t27_assert_fail("\n 4 valid paths:\n count_valid_paths(path_set) = {any}\n", .{ count_valid_paths(path_set) }); } test "count_valid_paths_some" { const path_set = create_path_set(create_path(1, 10, 20, 30), create_path(0, 40, 50, 60), create_path(1, 70, 80, 90), create_path(0, 15, 25, 35)); - if (!(count_valid_paths(path_set) == 2)) @panic("2 valid paths"); + if (!(count_valid_paths(path_set) == 2)) __t27_assert_fail("\n 2 valid paths:\n count_valid_paths(path_set) = {any}\n", .{ count_valid_paths(path_set) }); } test "has_redundancy_true" { const path_set = create_path_set(create_path(1, 10, 20, 30), create_path(1, 40, 50, 60), create_path(1, 70, 80, 90), create_path(0, 15, 25, 35)); - if (!(has_redundancy(path_set) == true)) @panic("has redundancy"); + if (!(has_redundancy(path_set) == true)) __t27_assert_fail("\n has redundancy:\n has_redundancy(path_set) = {any}\n", .{ has_redundancy(path_set) }); } test "has_redundancy_false" { const path_set = create_path_set(create_path(1, 10, 20, 30), create_path(0, 40, 50, 60), create_path(0, 70, 80, 90), create_path(0, 15, 25, 35)); - if (!(has_redundancy(path_set) == false)) @panic("no redundancy"); + if (!(has_redundancy(path_set) == false)) __t27_assert_fail("\n no redundancy:\n has_redundancy(path_set) = {any}\n", .{ has_redundancy(path_set) }); } test "get_hop_count_three" { const path = create_path(1, 10, 20, 30); - if (!(get_hop_count(path) == 3)) @panic("3 hops"); + if (!(get_hop_count(path) == 3)) __t27_assert_fail("\n 3 hops:\n get_hop_count(path) = {any}\n", .{ get_hop_count(path) }); } test "get_hop_count_one" { const path = create_path(1, 10, 0, 0); - if (!(get_hop_count(path) == 1)) @panic("1 hop"); + if (!(get_hop_count(path) == 1)) __t27_assert_fail("\n 1 hop:\n get_hop_count(path) = {any}\n", .{ get_hop_count(path) }); } test "find_shortest_path" { const path_set = create_path_set(create_path(1, 10, 0, 0), create_path(1, 40, 50, 0), create_path(1, 70, 80, 90), create_path(0, 15, 25, 35)); - if (!(find_shortest_path(path_set) == 0)) @panic("shortest is path 0"); + if (!(find_shortest_path(path_set) == 0)) __t27_assert_fail("\n shortest is path 0:\n find_shortest_path(path_set) = {any}\n", .{ find_shortest_path(path_set) }); } test "failover_invalidates_failed" { const path_set = create_path_set(create_path(1, 10, 20, 30), create_path(1, 40, 50, 60), create_path(1, 70, 80, 90), create_path(0, 15, 25, 35)); const new_set = failover(path_set, 0); - if (!(get_path_valid(get_path(new_set, 0)) == 0)) @panic("failed path invalidated"); + if (!(get_path_valid(get_path(new_set, 0)) == 0)) __t27_assert_fail("\n failed path invalidated:\n get_path_valid(get_path(new_set, 0)) = {any}\n", .{ get_path_valid(get_path(new_set, 0)) }); } test "failover_no_backup" { const path_set = create_path_set(create_path(1, 10, 20, 30), create_path(0, 40, 50, 60), create_path(0, 70, 80, 90), create_path(0, 15, 25, 35)); const new_set = failover(path_set, 0); - if (!(get_path_valid(get_path(new_set, 0)) == 1)) @panic("no change when no backup"); + if (!(get_path_valid(get_path(new_set, 0)) == 1)) __t27_assert_fail("\n no change when no backup:\n get_path_valid(get_path(new_set, 0)) = {any}\n", .{ get_path_valid(get_path(new_set, 0)) }); } diff --git a/gen/zig/resource_scheduler.zig b/gen/zig/resource_scheduler.zig index 60f08291..c942de6e 100644 --- a/gen/zig/resource_scheduler.zig +++ b/gen/zig/resource_scheduler.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_TASKS: u32 = 8; @@ -210,93 +218,93 @@ fn count_tasks_by_priority(task_array: [8]u32, priority: u32) u32 { } test "create_task_resource_basic" { const task = create_task_resource(30, 64, PRIORITY_HIGH, 5); - if (!(get_cpu_req(task) == 30)) @panic("CPU requirement"); - if (!(get_mem_req(task) == 64)) @panic("memory requirement"); - if (!(get_priority(task) == PRIORITY_HIGH)) @panic("priority"); - if (!(get_task_id(task) == 5)) @panic("task ID"); + if (!(get_cpu_req(task) == 30)) __t27_assert_fail("\n CPU requirement:\n get_cpu_req(task) = {any}\n", .{ get_cpu_req(task) }); + if (!(get_mem_req(task) == 64)) __t27_assert_fail("\n memory requirement:\n get_mem_req(task) = {any}\n", .{ get_mem_req(task) }); + if (!(get_priority(task) == PRIORITY_HIGH)) __t27_assert_fail("\n priority:\n get_priority(task) = {any}\n PRIORITY_HIGH = {any}\n", .{ get_priority(task), PRIORITY_HIGH }); + if (!(get_task_id(task) == 5)) __t27_assert_fail("\n task ID:\n get_task_id(task) = {any}\n", .{ get_task_id(task) }); } test "create_system_state_basic" { const state = create_system_state(60, 128, 4, 100); - if (!(get_used_cpu(state) == 60)) @panic("used CPU"); - if (!(get_used_mem(state) == 128)) @panic("used memory"); - if (!(get_active_tasks(state) == 4)) @panic("active tasks"); - if (!(get_sched_tick(state) == 100)) @panic("scheduler tick"); + if (!(get_used_cpu(state) == 60)) __t27_assert_fail("\n used CPU:\n get_used_cpu(state) = {any}\n", .{ get_used_cpu(state) }); + if (!(get_used_mem(state) == 128)) __t27_assert_fail("\n used memory:\n get_used_mem(state) = {any}\n", .{ get_used_mem(state) }); + if (!(get_active_tasks(state) == 4)) __t27_assert_fail("\n active tasks:\n get_active_tasks(state) = {any}\n", .{ get_active_tasks(state) }); + if (!(get_sched_tick(state) == 100)) __t27_assert_fail("\n scheduler tick:\n get_sched_tick(state) = {any}\n", .{ get_sched_tick(state) }); } test "can_admit_task_true" { const state = create_system_state(30, 100, 2, 0); const task = create_task_resource(20, 50, PRIORITY_MEDIUM, 5); - if (!(can_admit_task(state, task) == true)) @panic("can admit"); + if (!(can_admit_task(state, task) == true)) __t27_assert_fail("\n can admit:\n can_admit_task(state, task) = {any}\n", .{ can_admit_task(state, task) }); } test "can_admit_task_false_cpu" { const state = create_system_state(95, 100, 2, 0); const task = create_task_resource(20, 50, PRIORITY_MEDIUM, 5); - if (!(can_admit_task(state, task) == false)) @panic("insufficient CPU"); + if (!(can_admit_task(state, task) == false)) __t27_assert_fail("\n insufficient CPU:\n can_admit_task(state, task) = {any}\n", .{ can_admit_task(state, task) }); } test "can_admit_task_false_memory" { const state = create_system_state(30, 230, 2, 0); const task = create_task_resource(20, 50, PRIORITY_MEDIUM, 5); - if (!(can_admit_task(state, task) == false)) @panic("insufficient memory"); + if (!(can_admit_task(state, task) == false)) __t27_assert_fail("\n insufficient memory:\n can_admit_task(state, task) = {any}\n", .{ can_admit_task(state, task) }); } test "has_cpu_capacity_true" { const state = create_system_state(30, 100, 2, 0); - if (!(has_cpu_capacity(state, 50) == true)) @panic("has CPU capacity"); + if (!(has_cpu_capacity(state, 50) == true)) __t27_assert_fail("\n has CPU capacity:\n has_cpu_capacity(state, 50) = {any}\n", .{ has_cpu_capacity(state, 50) }); } test "has_cpu_capacity_false" { const state = create_system_state(80, 100, 2, 0); - if (!(has_cpu_capacity(state, 50) == false)) @panic("no CPU capacity"); + if (!(has_cpu_capacity(state, 50) == false)) __t27_assert_fail("\n no CPU capacity:\n has_cpu_capacity(state, 50) = {any}\n", .{ has_cpu_capacity(state, 50) }); } test "allocate_resources_works" { const state = create_system_state(30, 100, 2, 0); const task = create_task_resource(20, 50, PRIORITY_MEDIUM, 5); const new_state = allocate_resources(state, task); - if (!(get_used_cpu(new_state) == 50)) @panic("CPU allocated"); - if (!(get_used_mem(new_state) == 150)) @panic("memory allocated"); - if (!(get_active_tasks(new_state) == 3)) @panic("task count increased"); + if (!(get_used_cpu(new_state) == 50)) __t27_assert_fail("\n CPU allocated:\n get_used_cpu(new_state) = {any}\n", .{ get_used_cpu(new_state) }); + if (!(get_used_mem(new_state) == 150)) __t27_assert_fail("\n memory allocated:\n get_used_mem(new_state) = {any}\n", .{ get_used_mem(new_state) }); + if (!(get_active_tasks(new_state) == 3)) __t27_assert_fail("\n task count increased:\n get_active_tasks(new_state) = {any}\n", .{ get_active_tasks(new_state) }); } test "release_resources_works" { const state = create_system_state(60, 150, 4, 0); const task = create_task_resource(20, 50, PRIORITY_MEDIUM, 5); const new_state = release_resources(state, task); - if (!(get_used_cpu(new_state) == 40)) @panic("CPU released"); - if (!(get_used_mem(new_state) == 100)) @panic("memory released"); - if (!(get_active_tasks(new_state) == 3)) @panic("task count decreased"); + if (!(get_used_cpu(new_state) == 40)) __t27_assert_fail("\n CPU released:\n get_used_cpu(new_state) = {any}\n", .{ get_used_cpu(new_state) }); + if (!(get_used_mem(new_state) == 100)) __t27_assert_fail("\n memory released:\n get_used_mem(new_state) = {any}\n", .{ get_used_mem(new_state) }); + if (!(get_active_tasks(new_state) == 3)) __t27_assert_fail("\n task count decreased:\n get_active_tasks(new_state) = {any}\n", .{ get_active_tasks(new_state) }); } test "find_admittable_task_high_priority" { const state = create_system_state(30, 100, 2, 0); const task_array = create_task_array(create_task_resource(20, 30, PRIORITY_LOW, 1), create_task_resource(15, 40, PRIORITY_HIGH, 2), create_task_resource(25, 35, PRIORITY_MEDIUM, 3), 0, 0, 0, 0, 0); - if (!(find_admittable_task(state, task_array) == 1)) @panic("high priority task"); + if (!(find_admittable_task(state, task_array) == 1)) __t27_assert_fail("\n high priority task:\n find_admittable_task(state, task_array) = {any}\n", .{ find_admittable_task(state, task_array) }); } test "calculate_cpu_utilization" { const state = create_system_state(60, 128, 4, 0); - if (!(calculate_cpu_utilization(state) == 60)) @panic("60% CPU utilization"); + if (!(calculate_cpu_utilization(state) == 60)) __t27_assert_fail("\n 60% CPU utilization:\n calculate_cpu_utilization(state) = {any}\n", .{ calculate_cpu_utilization(state) }); } test "calculate_memory_utilization" { const state = create_system_state(60, 128, 4, 0); - if (!(calculate_memory_utilization(state) == 50)) @panic("50% memory utilization"); + if (!(calculate_memory_utilization(state) == 50)) __t27_assert_fail("\n 50% memory utilization:\n calculate_memory_utilization(state) = {any}\n", .{ calculate_memory_utilization(state) }); } test "is_overloaded_true" { const state = create_system_state(95, 128, 4, 0); - if (!(is_overloaded(state) == true)) @panic("system overloaded"); + if (!(is_overloaded(state) == true)) __t27_assert_fail("\n system overloaded:\n is_overloaded(state) = {any}\n", .{ is_overloaded(state) }); } test "is_overloaded_false" { const state = create_system_state(60, 128, 4, 0); - if (!(is_overloaded(state) == false)) @panic("system not overloaded"); + if (!(is_overloaded(state) == false)) __t27_assert_fail("\n system not overloaded:\n is_overloaded(state) = {any}\n", .{ is_overloaded(state) }); } test "increment_tick_works" { const state = create_system_state(60, 128, 4, 100); const new_state = increment_tick(state); - if (!(get_sched_tick(new_state) == 101)) @panic("tick incremented"); + if (!(get_sched_tick(new_state) == 101)) __t27_assert_fail("\n tick incremented:\n get_sched_tick(new_state) = {any}\n", .{ get_sched_tick(new_state) }); } test "increment_tick_wraps" { const state = create_system_state(60, 128, 4, 255); const new_state = increment_tick(state); - if (!(get_sched_tick(new_state) == 0)) @panic("tick wrapped"); + if (!(get_sched_tick(new_state) == 0)) __t27_assert_fail("\n tick wrapped:\n get_sched_tick(new_state) = {any}\n", .{ get_sched_tick(new_state) }); } test "count_tasks_by_priority_high" { const task_array = create_task_array(create_task_resource(20, 30, PRIORITY_HIGH, 1), create_task_resource(15, 40, PRIORITY_HIGH, 2), create_task_resource(25, 35, PRIORITY_LOW, 3), create_task_resource(10, 20, PRIORITY_HIGH, 4), 0, 0, 0, 0); - if (!(count_tasks_by_priority(task_array, PRIORITY_HIGH) == 3)) @panic("3 high priority tasks"); + if (!(count_tasks_by_priority(task_array, PRIORITY_HIGH) == 3)) __t27_assert_fail("\n 3 high priority tasks:\n count_tasks_by_priority(task_array, PRIORITY_HIGH) = {any}\n", .{ count_tasks_by_priority(task_array, PRIORITY_HIGH) }); } test "count_tasks_by_priority_mixed" { const task_array = create_task_array(create_task_resource(20, 30, PRIORITY_HIGH, 1), create_task_resource(15, 40, PRIORITY_MEDIUM, 2), create_task_resource(25, 35, PRIORITY_LOW, 3), create_task_resource(10, 20, PRIORITY_MEDIUM, 4), 0, 0, 0, 0); - if (!(count_tasks_by_priority(task_array, PRIORITY_MEDIUM) == 2)) @panic("2 medium priority tasks"); + if (!(count_tasks_by_priority(task_array, PRIORITY_MEDIUM) == 2)) __t27_assert_fail("\n 2 medium priority tasks:\n count_tasks_by_priority(task_array, PRIORITY_MEDIUM) = {any}\n", .{ count_tasks_by_priority(task_array, PRIORITY_MEDIUM) }); } diff --git a/gen/zig/routing_etx.zig b/gen/zig/routing_etx.zig index bda0b444..28748ad6 100644 --- a/gen/zig/routing_etx.zig +++ b/gen/zig/routing_etx.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MILLI: u32 = 1000; @@ -54,38 +62,82 @@ fn learn_ok(is_self_route: u32, feasible: bool) bool { return feasible; } test "perfect_link_is_exactly_one_transmission" { + const e = etx_milli(1000, 1000, 1000); + if (!(e == 1000)) __t27_assert_fail("\n assertion failed:\n e = {any}\n", .{ e }); } test "optimistic_prior_link" { + const e = etx_milli(900, 900, 1000); + if (!(e == 1234)) __t27_assert_fail("\n assertion failed:\n e = {any}\n", .{ e }); } test "dead_forward_direction_is_dead" { + const e = etx_milli(149, 1000, 1000); + if (!(e == 0)) __t27_assert_fail("\n assertion failed:\n e = {any}\n", .{ e }); } test "dead_reverse_direction_is_dead" { + const e = etx_milli(1000, 100, 1000); + if (!(e == 0)) __t27_assert_fail("\n assertion failed:\n e = {any}\n", .{ e }); } test "rti_penalty_scales_cost" { + const clear = etx_milli(1000, 1000, 1000); + const blocked = etx_milli(1000, 1000, 10000); + if (!(clear == 1000)) __t27_assert_fail("\n assertion failed:\n clear = {any}\n", .{ clear }); + if (!(blocked == 10000)) __t27_assert_fail("\n assertion failed:\n blocked = {any}\n", .{ blocked }); } test "runaway_penalty_is_clamped_not_wrapped" { + const huge = etx_milli(1000, 1000, 500000); + const at_cap = etx_milli(1000, 1000, 32000); + if (!(huge == 32000)) __t27_assert_fail("\n assertion failed:\n huge = {any}\n", .{ huge }); + if (!(at_cap == 32000)) __t27_assert_fail("\n assertion failed:\n at_cap = {any}\n", .{ at_cap }); } test "strictly_better_wins_ties_do_not" { + const win = better_route(1200, 1300); + const tie = better_route(1300, 1300); + if (!(win == true)) __t27_assert_fail("\n assertion failed:\n win = {any}\n", .{ win }); + if (!(tie == false)) __t27_assert_fail("\n assertion failed:\n tie = {any}\n", .{ tie }); } test "dead_candidate_never_wins" { + const w = better_route(0, 5000); + if (!(w == false)) __t27_assert_fail("\n assertion failed:\n w = {any}\n", .{ w }); } test "anything_beats_dead_incumbent" { + const w = better_route(9000, 0); + if (!(w == true)) __t27_assert_fail("\n assertion failed:\n w = {any}\n", .{ w }); } test "path_adds_and_dead_propagates" { + const p = path_etx(2000, 1500); + const d = path_etx(2000, 0); + if (!(p == 3500)) __t27_assert_fail("\n assertion failed:\n p = {any}\n", .{ p }); + if (!(d == 0)) __t27_assert_fail("\n assertion failed:\n d = {any}\n", .{ d }); } test "no_incumbent_is_always_feasible" { + const f = is_feasible(9999, 0, 0); + if (!(f == true)) __t27_assert_fail("\n assertion failed:\n f = {any}\n", .{ f }); } test "strictly_better_is_feasible_ties_are_not" { + const better = is_feasible(1200, 1500, 1); + const tie = is_feasible(1500, 1500, 1); + const worse = is_feasible(1800, 1500, 1); + if (!(better == true)) __t27_assert_fail("\n assertion failed:\n better = {any}\n", .{ better }); + if (!(tie == false)) __t27_assert_fail("\n assertion failed:\n tie = {any}\n", .{ tie }); + if (!(worse == false)) __t27_assert_fail("\n assertion failed:\n worse = {any}\n", .{ worse }); } test "dead_candidate_not_feasible" { + const f = is_feasible(0, 1500, 1); + if (!(f == false)) __t27_assert_fail("\n assertion failed:\n f = {any}\n", .{ f }); } test "self_route_never_learned" { + const selfroute = learn_ok(1, true); + const normal = learn_ok(0, true); + const infeasible = learn_ok(0, false); + if (!(selfroute == false)) __t27_assert_fail("\n assertion failed:\n selfroute = {any}\n", .{ selfroute }); + if (!(normal == true)) __t27_assert_fail("\n assertion failed:\n normal = {any}\n", .{ normal }); + if (!(infeasible == false)) __t27_assert_fail("\n assertion failed:\n infeasible = {any}\n", .{ infeasible }); } comptime { // invariant: dead_epsilon_is_150_milli - // invariant: dead_epsilon_is_150_milli verified (no statements) + if (!(DEAD_EPS_MILLI == 150)) __t27_assert_fail("\n assertion failed:\n DEAD_EPS_MILLI = {any}\n", .{ DEAD_EPS_MILLI }); } comptime { // invariant: optimistic_prior_is_900_milli - // invariant: optimistic_prior_is_900_milli verified (no statements) + if (!(OPTIMISTIC_MILLI == 900)) __t27_assert_fail("\n assertion failed:\n OPTIMISTIC_MILLI = {any}\n", .{ OPTIMISTIC_MILLI }); } diff --git a/gen/zig/rti_alert.zig b/gen/zig/rti_alert.zig index 7d8026da..c3332985 100644 --- a/gen/zig/rti_alert.zig +++ b/gen/zig/rti_alert.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const SEV_CATASTROPHIC: u8 = 4; @@ -21,18 +29,34 @@ fn alert_severity(anom_sev: u32) u8 { } } test "catastrophic_at_and_above_80" { + const hi = alert_severity(85); + const ed = alert_severity(80); + if (!(hi == 4)) __t27_assert_fail("\n assertion failed:\n hi = {any}\n", .{ hi }); + if (!(ed == 4)) __t27_assert_fail("\n assertion failed:\n ed = {any}\n", .{ ed }); } test "critical_band_60_to_79" { + const hi = alert_severity(79); + const ed = alert_severity(60); + if (!(hi == 3)) __t27_assert_fail("\n assertion failed:\n hi = {any}\n", .{ hi }); + if (!(ed == 3)) __t27_assert_fail("\n assertion failed:\n ed = {any}\n", .{ ed }); } test "urgent_band_40_to_59" { + const hi = alert_severity(59); + const ed = alert_severity(40); + if (!(hi == 2)) __t27_assert_fail("\n assertion failed:\n hi = {any}\n", .{ hi }); + if (!(ed == 2)) __t27_assert_fail("\n assertion failed:\n ed = {any}\n", .{ ed }); } test "warning_below_40" { + const hi = alert_severity(39); + const lo = alert_severity(0); + if (!(hi == 1)) __t27_assert_fail("\n assertion failed:\n hi = {any}\n", .{ hi }); + if (!(lo == 1)) __t27_assert_fail("\n assertion failed:\n lo = {any}\n", .{ lo }); } comptime { // invariant: severities_ordered - // invariant: severities_ordered verified (no statements) + if (!(SEV_CATASTROPHIC > SEV_CRITICAL)) __t27_assert_fail("\n assertion failed:\n SEV_CATASTROPHIC = {any}\n SEV_CRITICAL = {any}\n", .{ SEV_CATASTROPHIC, SEV_CRITICAL }); } comptime { // invariant: warning_is_min - // invariant: warning_is_min verified (no statements) + if (!(SEV_WARNING < SEV_URGENT)) __t27_assert_fail("\n assertion failed:\n SEV_WARNING = {any}\n SEV_URGENT = {any}\n", .{ SEV_WARNING, SEV_URGENT }); } diff --git a/gen/zig/rti_security.zig b/gen/zig/rti_security.zig index ca6125e0..b02ae6ce 100644 --- a/gen/zig/rti_security.zig +++ b/gen/zig/rti_security.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_ZONES: u8 = 16; @@ -120,96 +128,96 @@ fn notification_priority(level: u8) u8 { return 1; } test "classify_none" { - if (!(classify_alert(30, 3, SENSITIVITY_MEDIUM, false) == ALERT_NONE)) @panic("low brightness"); + if (!(classify_alert(30, 3, SENSITIVITY_MEDIUM, false) == ALERT_NONE)) __t27_assert_fail("\n low brightness:\n classify_alert(30, 3, SENSITIVITY_MEDIUM, false) = {any}\n ALERT_NONE = {any}\n", .{ classify_alert(30, 3, SENSITIVITY_MEDIUM, false), ALERT_NONE }); } test "classify_info" { - if (!(classify_alert(70, 2, SENSITIVITY_MEDIUM, false) == ALERT_INFO)) @panic("small movement"); + if (!(classify_alert(70, 2, SENSITIVITY_MEDIUM, false) == ALERT_INFO)) __t27_assert_fail("\n small movement:\n classify_alert(70, 2, SENSITIVITY_MEDIUM, false) = {any}\n ALERT_INFO = {any}\n", .{ classify_alert(70, 2, SENSITIVITY_MEDIUM, false), ALERT_INFO }); } test "classify_warning" { - if (!(classify_alert(80, 5, SENSITIVITY_MEDIUM, false) == ALERT_WARNING)) @panic("medium object"); + if (!(classify_alert(80, 5, SENSITIVITY_MEDIUM, false) == ALERT_WARNING)) __t27_assert_fail("\n medium object:\n classify_alert(80, 5, SENSITIVITY_MEDIUM, false) = {any}\n ALERT_WARNING = {any}\n", .{ classify_alert(80, 5, SENSITIVITY_MEDIUM, false), ALERT_WARNING }); } test "classify_critical" { - if (!(classify_alert(100, 10, SENSITIVITY_MEDIUM, false) == ALERT_CRITICAL)) @panic("large object"); + if (!(classify_alert(100, 10, SENSITIVITY_MEDIUM, false) == ALERT_CRITICAL)) __t27_assert_fail("\n large object:\n classify_alert(100, 10, SENSITIVITY_MEDIUM, false) = {any}\n ALERT_CRITICAL = {any}\n", .{ classify_alert(100, 10, SENSITIVITY_MEDIUM, false), ALERT_CRITICAL }); } test "classify_night_sensitive" { - if (!(classify_alert(35, 2, SENSITIVITY_MEDIUM, true) == ALERT_INFO)) @panic("night = more sensitive"); + if (!(classify_alert(35, 2, SENSITIVITY_MEDIUM, true) == ALERT_INFO)) __t27_assert_fail("\n night = more sensitive:\n classify_alert(35, 2, SENSITIVITY_MEDIUM, true) = {any}\n ALERT_INFO = {any}\n", .{ classify_alert(35, 2, SENSITIVITY_MEDIUM, true), ALERT_INFO }); } test "classify_high_sensitivity" { - if (!(classify_alert(45, 2, SENSITIVITY_HIGH, false) == ALERT_INFO)) @panic("high sens = lower threshold"); + if (!(classify_alert(45, 2, SENSITIVITY_HIGH, false) == ALERT_INFO)) __t27_assert_fail("\n high sens = lower threshold:\n classify_alert(45, 2, SENSITIVITY_HIGH, false) = {any}\n ALERT_INFO = {any}\n", .{ classify_alert(45, 2, SENSITIVITY_HIGH, false), ALERT_INFO }); } test "in_cooldown_active" { - if (!(in_cooldown(3000) == true)) @panic("3s < 5s cooldown"); + if (!(in_cooldown(3000) == true)) __t27_assert_fail("\n 3s < 5s cooldown:\n in_cooldown(3000) = {any}\n", .{ in_cooldown(3000) }); } test "in_cooldown_expired" { - if (!(in_cooldown(6000) == false)) @panic("6s > 5s cooldown"); + if (!(in_cooldown(6000) == false)) __t27_assert_fail("\n 6s > 5s cooldown:\n in_cooldown(6000) = {any}\n", .{ in_cooldown(6000) }); } test "should_suppress_none" { - if (!(should_suppress(ALERT_NONE, ALERT_NONE, 0) == true)) @panic("no alert = suppress"); + if (!(should_suppress(ALERT_NONE, ALERT_NONE, 0) == true)) __t27_assert_fail("\n no alert = suppress:\n should_suppress(ALERT_NONE, ALERT_NONE, 0) = {any}\n", .{ should_suppress(ALERT_NONE, ALERT_NONE, 0) }); } test "should_suppress_cooldown" { - if (!(should_suppress(ALERT_INFO, ALERT_WARNING, 2000) == true)) @panic("lower during cooldown"); + if (!(should_suppress(ALERT_INFO, ALERT_WARNING, 2000) == true)) __t27_assert_fail("\n lower during cooldown:\n should_suppress(ALERT_INFO, ALERT_WARNING, 2000) = {any}\n", .{ should_suppress(ALERT_INFO, ALERT_WARNING, 2000) }); } test "should_not_suppress_higher" { - if (!(should_suppress(ALERT_CRITICAL, ALERT_INFO, 2000) == false)) @panic("higher level passes"); + if (!(should_suppress(ALERT_CRITICAL, ALERT_INFO, 2000) == false)) __t27_assert_fail("\n higher level passes:\n should_suppress(ALERT_CRITICAL, ALERT_INFO, 2000) = {any}\n", .{ should_suppress(ALERT_CRITICAL, ALERT_INFO, 2000) }); } test "zone_from_coord_basic" { - if (!(zone_from_coord(5, 5, 10) == 0)) @panic("top-left zone"); + if (!(zone_from_coord(5, 5, 10) == 0)) __t27_assert_fail("\n top-left zone:\n zone_from_coord(5, 5, 10) = {any}\n", .{ zone_from_coord(5, 5, 10) }); } test "zone_from_coord_second" { - if (!(zone_from_coord(15, 5, 10) == 1)) @panic("second zone right"); + if (!(zone_from_coord(15, 5, 10) == 1)) __t27_assert_fail("\n second zone right:\n zone_from_coord(15, 5, 10) = {any}\n", .{ zone_from_coord(15, 5, 10) }); } test "in_zone_inside" { - if (!(in_zone(5, 5, 0, 0, 10, 10) == true)) @panic("inside"); + if (!(in_zone(5, 5, 0, 0, 10, 10) == true)) __t27_assert_fail("\n inside:\n in_zone(5, 5, 0, 0, 10, 10) = {any}\n", .{ in_zone(5, 5, 0, 0, 10, 10) }); } test "in_zone_outside_x" { - if (!(in_zone(15, 5, 0, 0, 10, 10) == false)) @panic("outside X"); + if (!(in_zone(15, 5, 0, 0, 10, 10) == false)) __t27_assert_fail("\n outside X:\n in_zone(15, 5, 0, 0, 10, 10) = {any}\n", .{ in_zone(15, 5, 0, 0, 10, 10) }); } test "in_zone_outside_y" { - if (!(in_zone(5, 15, 0, 0, 10, 10) == false)) @panic("outside Y"); + if (!(in_zone(5, 15, 0, 0, 10, 10) == false)) __t27_assert_fail("\n outside Y:\n in_zone(5, 15, 0, 0, 10, 10) = {any}\n", .{ in_zone(5, 15, 0, 0, 10, 10) }); } test "threat_score_none" { - if (!(threat_score(ALERT_NONE, 5, 100) == 0)) @panic("no alert = 0"); + if (!(threat_score(ALERT_NONE, 5, 100) == 0)) __t27_assert_fail("\n no alert = 0:\n threat_score(ALERT_NONE, 5, 100) = {any}\n", .{ threat_score(ALERT_NONE, 5, 100) }); } test "threat_score_critical" { - if (!(threat_score(ALERT_CRITICAL, 10, 200) == 600)) @panic("3*100 + 10*10 + 200"); + if (!(threat_score(ALERT_CRITICAL, 10, 200) == 600)) __t27_assert_fail("\n 3*100 + 10*10 + 200:\n threat_score(ALERT_CRITICAL, 10, 200) = {any}\n", .{ threat_score(ALERT_CRITICAL, 10, 200) }); } test "should_escalate_yes" { - if (!(should_escalate(ALERT_INFO, 500) == true)) @panic("high threat"); + if (!(should_escalate(ALERT_INFO, 500) == true)) __t27_assert_fail("\n high threat:\n should_escalate(ALERT_INFO, 500) = {any}\n", .{ should_escalate(ALERT_INFO, 500) }); } test "should_escalate_no" { - if (!(should_escalate(ALERT_INFO, 100) == false)) @panic("low threat"); + if (!(should_escalate(ALERT_INFO, 100) == false)) __t27_assert_fail("\n low threat:\n should_escalate(ALERT_INFO, 100) = {any}\n", .{ should_escalate(ALERT_INFO, 100) }); } test "is_night_late" { - if (!(is_night_time(23) == true)) @panic("23:00 = night"); + if (!(is_night_time(23) == true)) __t27_assert_fail("\n 23:00 = night:\n is_night_time(23) = {any}\n", .{ is_night_time(23) }); } test "is_night_early" { - if (!(is_night_time(3) == true)) @panic("03:00 = night"); + if (!(is_night_time(3) == true)) __t27_assert_fail("\n 03:00 = night:\n is_night_time(3) = {any}\n", .{ is_night_time(3) }); } test "is_day" { - if (!(is_night_time(14) == false)) @panic("14:00 = day"); + if (!(is_night_time(14) == false)) __t27_assert_fail("\n 14:00 = day:\n is_night_time(14) = {any}\n", .{ is_night_time(14) }); } test "notification_critical" { - if (!(notification_priority(ALERT_CRITICAL) == 10)) @panic("immediate"); + if (!(notification_priority(ALERT_CRITICAL) == 10)) __t27_assert_fail("\n immediate:\n notification_priority(ALERT_CRITICAL) = {any}\n", .{ notification_priority(ALERT_CRITICAL) }); } test "notification_warning" { - if (!(notification_priority(ALERT_WARNING) == 5)) @panic("batch"); + if (!(notification_priority(ALERT_WARNING) == 5)) __t27_assert_fail("\n batch:\n notification_priority(ALERT_WARNING) = {any}\n", .{ notification_priority(ALERT_WARNING) }); } test "notification_info" { - if (!(notification_priority(ALERT_INFO) == 1)) @panic("log only"); + if (!(notification_priority(ALERT_INFO) == 1)) __t27_assert_fail("\n log only:\n notification_priority(ALERT_INFO) = {any}\n", .{ notification_priority(ALERT_INFO) }); } comptime { // invariant: max_zones_16 - // invariant: max_zones_16 verified (no statements) + if (!(MAX_ZONES == 16)) __t27_assert_fail("\n assertion failed:\n MAX_ZONES = {any}\n", .{ MAX_ZONES }); } comptime { // invariant: zone_grid_40 - // invariant: zone_grid_40 verified (no statements) + if (!(ZONE_GRID == 40)) __t27_assert_fail("\n assertion failed:\n ZONE_GRID = {any}\n", .{ ZONE_GRID }); } comptime { // invariant: alert_cooldown_5000 - // invariant: alert_cooldown_5000 verified (no statements) + if (!(ALERT_COOLDOWN_MS == 5000)) __t27_assert_fail("\n assertion failed:\n ALERT_COOLDOWN_MS = {any}\n", .{ ALERT_COOLDOWN_MS }); } comptime { // invariant: alert_entry_8 - // invariant: alert_entry_8 verified (no statements) + if (!(ALERT_ENTRY_SIZE == 8)) __t27_assert_fail("\n assertion failed:\n ALERT_ENTRY_SIZE = {any}\n", .{ ALERT_ENTRY_SIZE }); } diff --git a/gen/zig/self_healing.zig b/gen/zig/self_healing.zig index 1ba425d4..ff3353c4 100644 --- a/gen/zig/self_healing.zig +++ b/gen/zig/self_healing.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const RECOVERY_COOLDOWN: u32 = 5000; @@ -112,108 +120,108 @@ fn update_network_after_recovery(network_state: u32, nodes_recovered: u32, links } test "create_recovery_state_basic" { const state = create_recovery_state(2, 1000, 1, 5); - if (!(get_attempts(state) == 2)) @panic("attempts"); - if (!(get_last_attempt(state) == 1000)) @panic("last attempt"); - if (!(get_in_progress(state) == 1)) @panic("in progress"); - if (!(get_success_count(state) == 5)) @panic("success count"); + if (!(get_attempts(state) == 2)) __t27_assert_fail("\n attempts:\n get_attempts(state) = {any}\n", .{ get_attempts(state) }); + if (!(get_last_attempt(state) == 1000)) __t27_assert_fail("\n last attempt:\n get_last_attempt(state) = {any}\n", .{ get_last_attempt(state) }); + if (!(get_in_progress(state) == 1)) __t27_assert_fail("\n in progress:\n get_in_progress(state) = {any}\n", .{ get_in_progress(state) }); + if (!(get_success_count(state) == 5)) __t27_assert_fail("\n success count:\n get_success_count(state) = {any}\n", .{ get_success_count(state) }); } test "can_recover_true" { const state = create_recovery_state(1, 1000, 0, 2); - if (!(can_recover(state, 8000) == true)) @panic("can recover"); + if (!(can_recover(state, 8000) == true)) __t27_assert_fail("\n can recover:\n can_recover(state, 8000) = {any}\n", .{ can_recover(state, 8000) }); } test "can_recover_max_attempts" { const state = create_recovery_state(3, 1000, 0, 0); - if (!(can_recover(state, 8000) == false)) @panic("max attempts reached"); + if (!(can_recover(state, 8000) == false)) __t27_assert_fail("\n max attempts reached:\n can_recover(state, 8000) = {any}\n", .{ can_recover(state, 8000) }); } test "can_recover_in_progress" { const state = create_recovery_state(1, 1000, 1, 0); - if (!(can_recover(state, 8000) == false)) @panic("already in progress"); + if (!(can_recover(state, 8000) == false)) __t27_assert_fail("\n already in progress:\n can_recover(state, 8000) = {any}\n", .{ can_recover(state, 8000) }); } test "can_recover_cooldown" { const state = create_recovery_state(1, 7000, 0, 0); - if (!(can_recover(state, 8000) == false)) @panic("cooldown not met"); + if (!(can_recover(state, 8000) == false)) __t27_assert_fail("\n cooldown not met:\n can_recover(state, 8000) = {any}\n", .{ can_recover(state, 8000) }); } test "start_recovery_sets_flag" { const state = create_recovery_state(1, 1000, 0, 0); const new_state = start_recovery(state, 5000); - if (!(get_in_progress(new_state) == 1)) @panic("in progress set"); - if (!(get_last_attempt(new_state) == 5000)) @panic("time updated"); + if (!(get_in_progress(new_state) == 1)) __t27_assert_fail("\n in progress set:\n get_in_progress(new_state) = {any}\n", .{ get_in_progress(new_state) }); + if (!(get_last_attempt(new_state) == 5000)) __t27_assert_fail("\n time updated:\n get_last_attempt(new_state) = {any}\n", .{ get_last_attempt(new_state) }); } test "complete_recovery_success" { const state = create_recovery_state(2, 5000, 1, 3); const new_state = complete_recovery_success(state); - if (!(get_in_progress(new_state) == 0)) @panic("in progress cleared"); - if (!(get_success_count(new_state) == 4)) @panic("success incremented"); + if (!(get_in_progress(new_state) == 0)) __t27_assert_fail("\n in progress cleared:\n get_in_progress(new_state) = {any}\n", .{ get_in_progress(new_state) }); + if (!(get_success_count(new_state) == 4)) __t27_assert_fail("\n success incremented:\n get_success_count(new_state) = {any}\n", .{ get_success_count(new_state) }); } test "complete_recovery_failure" { const state = create_recovery_state(2, 5000, 1, 3); const new_state = complete_recovery_failure(state); - if (!(get_in_progress(new_state) == 0)) @panic("in progress cleared"); - if (!(get_attempts(new_state) == 3)) @panic("attempts incremented"); + if (!(get_in_progress(new_state) == 0)) __t27_assert_fail("\n in progress cleared:\n get_in_progress(new_state) = {any}\n", .{ get_in_progress(new_state) }); + if (!(get_attempts(new_state) == 3)) __t27_assert_fail("\n attempts incremented:\n get_attempts(new_state) = {any}\n", .{ get_attempts(new_state) }); } test "reset_recovery_clears" { const state = create_recovery_state(3, 5000, 1, 0); const new_state = reset_recovery(state); - if (!(get_attempts(new_state) == 0)) @panic("attempts cleared"); - if (!(get_in_progress(new_state) == 0)) @panic("in progress cleared"); + if (!(get_attempts(new_state) == 0)) __t27_assert_fail("\n attempts cleared:\n get_attempts(new_state) = {any}\n", .{ get_attempts(new_state) }); + if (!(get_in_progress(new_state) == 0)) __t27_assert_fail("\n in progress cleared:\n get_in_progress(new_state) = {any}\n", .{ get_in_progress(new_state) }); } test "is_recovery_failed_max" { const state = create_recovery_state(3, 5000, 0, 0); - if (!(is_recovery_failed(state) == true)) @panic("recovery failed"); + if (!(is_recovery_failed(state) == true)) __t27_assert_fail("\n recovery failed:\n is_recovery_failed(state) = {any}\n", .{ is_recovery_failed(state) }); } test "is_recovery_failed_below_max" { const state = create_recovery_state(2, 5000, 0, 0); - if (!(is_recovery_failed(state) == false)) @panic("recovery not failed"); + if (!(is_recovery_failed(state) == false)) __t27_assert_fail("\n recovery not failed:\n is_recovery_failed(state) = {any}\n", .{ is_recovery_failed(state) }); } test "create_network_state_basic" { const state = create_network_state(7, 8, 2, 12); - if (!(get_healthy_nodes(state) == 7)) @panic("healthy nodes"); - if (!(get_total_nodes(state) == 8)) @panic("total nodes"); - if (!(get_degraded_links(state) == 2)) @panic("degraded links"); - if (!(get_total_links(state) == 12)) @panic("total links"); + if (!(get_healthy_nodes(state) == 7)) __t27_assert_fail("\n healthy nodes:\n get_healthy_nodes(state) = {any}\n", .{ get_healthy_nodes(state) }); + if (!(get_total_nodes(state) == 8)) __t27_assert_fail("\n total nodes:\n get_total_nodes(state) = {any}\n", .{ get_total_nodes(state) }); + if (!(get_degraded_links(state) == 2)) __t27_assert_fail("\n degraded links:\n get_degraded_links(state) = {any}\n", .{ get_degraded_links(state) }); + if (!(get_total_links(state) == 12)) __t27_assert_fail("\n total links:\n get_total_links(state) = {any}\n", .{ get_total_links(state) }); } test "network_health_percent_calculates" { const state = create_network_state(6, 8, 2, 12); - if (!(network_health_percent(state) == 75)) @panic("75% healthy"); + if (!(network_health_percent(state) == 75)) __t27_assert_fail("\n 75% healthy:\n network_health_percent(state) = {any}\n", .{ network_health_percent(state) }); } test "network_health_percent_zero_nodes" { const state = create_network_state(0, 0, 0, 0); - if (!(network_health_percent(state) == 100)) @panic("100% when no nodes"); + if (!(network_health_percent(state) == 100)) __t27_assert_fail("\n 100% when no nodes:\n network_health_percent(state) = {any}\n", .{ network_health_percent(state) }); } test "is_network_healthy_true" { const state = create_network_state(7, 8, 1, 12); - if (!(is_network_healthy(state) == true)) @panic("network healthy"); + if (!(is_network_healthy(state) == true)) __t27_assert_fail("\n network healthy:\n is_network_healthy(state) = {any}\n", .{ is_network_healthy(state) }); } test "is_network_healthy_false" { const state = create_network_state(4, 8, 4, 12); - if (!(is_network_healthy(state) == false)) @panic("network not healthy"); + if (!(is_network_healthy(state) == false)) __t27_assert_fail("\n network not healthy:\n is_network_healthy(state) = {any}\n", .{ is_network_healthy(state) }); } test "is_network_degraded" { const state = create_network_state(5, 8, 3, 12); - if (!(is_network_degraded(state) == true)) @panic("network degraded"); + if (!(is_network_degraded(state) == true)) __t27_assert_fail("\n network degraded:\n is_network_degraded(state) = {any}\n", .{ is_network_degraded(state) }); } test "is_network_critical" { const state = create_network_state(3, 8, 5, 12); - if (!(is_network_critical(state) == true)) @panic("network critical"); + if (!(is_network_critical(state) == true)) __t27_assert_fail("\n network critical:\n is_network_critical(state) = {any}\n", .{ is_network_critical(state) }); } test "should_initiate_healing_needed" { const rec_state = create_recovery_state(1, 1000, 0, 2); const net_state = create_network_state(5, 8, 3, 12); - if (!(should_initiate_healing(rec_state, net_state, 8000) == 1)) @panic("start healing"); + if (!(should_initiate_healing(rec_state, net_state, 8000) == 1)) __t27_assert_fail("\n start healing:\n should_initiate_healing(rec_state, net_state, 8000) = {any}\n", .{ should_initiate_healing(rec_state, net_state, 8000) }); } test "should_initiate_healing_not_needed" { const rec_state = create_recovery_state(1, 1000, 0, 2); const net_state = create_network_state(7, 8, 1, 12); - if (!(should_initiate_healing(rec_state, net_state, 8000) == 0)) @panic("no healing"); + if (!(should_initiate_healing(rec_state, net_state, 8000) == 0)) __t27_assert_fail("\n no healing:\n should_initiate_healing(rec_state, net_state, 8000) = {any}\n", .{ should_initiate_healing(rec_state, net_state, 8000) }); } test "should_initiate_healing_wait" { const rec_state = create_recovery_state(1, 7000, 0, 2); const net_state = create_network_state(5, 8, 3, 12); - if (!(should_initiate_healing(rec_state, net_state, 8000) == 2)) @panic("wait cooldown"); + if (!(should_initiate_healing(rec_state, net_state, 8000) == 2)) __t27_assert_fail("\n wait cooldown:\n should_initiate_healing(rec_state, net_state, 8000) = {any}\n", .{ should_initiate_healing(rec_state, net_state, 8000) }); } test "update_network_after_recovery_improves" { const state = create_network_state(5, 8, 4, 12); const new_state = update_network_after_recovery(state, 2, 1); - if (!(get_healthy_nodes(new_state) == 7)) @panic("nodes recovered"); - if (!(get_degraded_links(new_state) == 3)) @panic("links restored"); + if (!(get_healthy_nodes(new_state) == 7)) __t27_assert_fail("\n nodes recovered:\n get_healthy_nodes(new_state) = {any}\n", .{ get_healthy_nodes(new_state) }); + if (!(get_degraded_links(new_state) == 3)) __t27_assert_fail("\n links restored:\n get_degraded_links(new_state) = {any}\n", .{ get_degraded_links(new_state) }); } diff --git a/gen/zig/swarm_coordinator.zig b/gen/zig/swarm_coordinator.zig index 5b974e53..1fe22a9e 100644 --- a/gen/zig/swarm_coordinator.zig +++ b/gen/zig/swarm_coordinator.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_NODES: u32 = 8; @@ -189,81 +197,81 @@ fn cooperative_decision(neighbor_values: u32, my_value: u32, weight_neighbors: u } test "create_proposal_basic" { const proposal = create_proposal(5, 10, 100, 1000); - if (!(get_proposal_id(proposal) == 5)) @panic("proposal id"); - if (!(get_proposal_node(proposal) == 10)) @panic("node id"); - if (!(get_proposal_value(proposal) == 100)) @panic("value"); - if (!(get_proposal_timestamp(proposal) == 1000)) @panic("timestamp"); + if (!(get_proposal_id(proposal) == 5)) __t27_assert_fail("\n proposal id:\n get_proposal_id(proposal) = {any}\n", .{ get_proposal_id(proposal) }); + if (!(get_proposal_node(proposal) == 10)) __t27_assert_fail("\n node id:\n get_proposal_node(proposal) = {any}\n", .{ get_proposal_node(proposal) }); + if (!(get_proposal_value(proposal) == 100)) __t27_assert_fail("\n value:\n get_proposal_value(proposal) = {any}\n", .{ get_proposal_value(proposal) }); + if (!(get_proposal_timestamp(proposal) == 1000)) __t27_assert_fail("\n timestamp:\n get_proposal_timestamp(proposal) = {any}\n", .{ get_proposal_timestamp(proposal) }); } test "create_vote_yes" { const vote = create_vote(5, VOTE_YES, 10, 1000); - if (!(get_vote_node(vote) == 5)) @panic("node"); - if (!(get_vote_value(vote) == VOTE_YES)) @panic("yes vote"); - if (!(get_vote_proposal_id(vote) == 10)) @panic("proposal id"); + if (!(get_vote_node(vote) == 5)) __t27_assert_fail("\n node:\n get_vote_node(vote) = {any}\n", .{ get_vote_node(vote) }); + if (!(get_vote_value(vote) == VOTE_YES)) __t27_assert_fail("\n yes vote:\n get_vote_value(vote) = {any}\n VOTE_YES = {any}\n", .{ get_vote_value(vote), VOTE_YES }); + if (!(get_vote_proposal_id(vote) == 10)) __t27_assert_fail("\n proposal id:\n get_vote_proposal_id(vote) = {any}\n", .{ get_vote_proposal_id(vote) }); } test "create_vote_no" { const vote = create_vote(5, VOTE_NO, 10, 1000); - if (!(get_vote_value(vote) == VOTE_NO)) @panic("no vote"); + if (!(get_vote_value(vote) == VOTE_NO)) __t27_assert_fail("\n no vote:\n get_vote_value(vote) = {any}\n VOTE_NO = {any}\n", .{ get_vote_value(vote), VOTE_NO }); } test "create_vote_abstain" { const vote = create_vote(5, VOTE_ABSTAIN, 10, 1000); - if (!(get_vote_value(vote) == VOTE_ABSTAIN)) @panic("abstain vote"); + if (!(get_vote_value(vote) == VOTE_ABSTAIN)) __t27_assert_fail("\n abstain vote:\n get_vote_value(vote) = {any}\n VOTE_ABSTAIN = {any}\n", .{ get_vote_value(vote), VOTE_ABSTAIN }); } test "count_votes_unanimous_yes" { const vote_array = create_vote_array(create_vote(1, VOTE_YES, 10, 1000), create_vote(2, VOTE_YES, 10, 1000), create_vote(3, VOTE_YES, 10, 1000), create_vote(4, VOTE_YES, 10, 1000), create_vote(5, VOTE_YES, 10, 1000), create_vote(6, VOTE_YES, 10, 1000), create_vote(7, VOTE_YES, 10, 1000), create_vote(8, VOTE_YES, 10, 1000)); const yes, const no, const abstain = count_votes(vote_array, 10); - if (!(yes == 8)) @panic("8 yes votes"); - if (!(no == 0)) @panic("0 no votes"); - if (!(abstain == 0)) @panic("0 abstain"); + if (!(yes == 8)) __t27_assert_fail("\n 8 yes votes:\n yes = {any}\n", .{ yes }); + if (!(no == 0)) __t27_assert_fail("\n 0 no votes:\n no = {any}\n", .{ no }); + if (!(abstain == 0)) __t27_assert_fail("\n 0 abstain:\n abstain = {any}\n", .{ abstain }); } test "count_votes_mixed" { const vote_array = create_vote_array(create_vote(1, VOTE_YES, 10, 1000), create_vote(2, VOTE_NO, 10, 1000), create_vote(3, VOTE_YES, 10, 1000), create_vote(4, VOTE_ABSTAIN, 10, 1000), create_vote(5, VOTE_YES, 10, 1000), create_vote(6, VOTE_NO, 10, 1000), create_vote(7, VOTE_YES, 10, 1000), create_vote(8, VOTE_ABSTAIN, 10, 1000)); const yes, const no, const abstain = count_votes(vote_array, 10); - if (!(yes == 4)) @panic("4 yes votes"); - if (!(no == 2)) @panic("2 no votes"); - if (!(abstain == 2)) @panic("2 abstain"); + if (!(yes == 4)) __t27_assert_fail("\n 4 yes votes:\n yes = {any}\n", .{ yes }); + if (!(no == 2)) __t27_assert_fail("\n 2 no votes:\n no = {any}\n", .{ no }); + if (!(abstain == 2)) __t27_assert_fail("\n 2 abstain:\n abstain = {any}\n", .{ abstain }); } test "has_quorum_true" { const yes, const no, const abstain = .{ 4, 3, 1 }; - if (!(has_quorum(yes, no, abstain) == true)) @panic("quorum reached"); + if (!(has_quorum(yes, no, abstain) == true)) __t27_assert_fail("\n quorum reached:\n has_quorum(yes, no, abstain) = {any}\n", .{ has_quorum(yes, no, abstain) }); } test "has_quorum_false" { const yes, const no, const abstain = .{ 2, 2, 0 }; - if (!(has_quorum(yes, no, abstain) == false)) @panic("no quorum"); + if (!(has_quorum(yes, no, abstain) == false)) __t27_assert_fail("\n no quorum:\n has_quorum(yes, no, abstain) = {any}\n", .{ has_quorum(yes, no, abstain) }); } test "proposal_passes_yes" { const yes, const no, const abstain = .{ 5, 3, 1 }; _ = abstain; // dead after const-inlining - if (!(proposal_passes(yes, no) == true)) @panic("proposal passes"); + if (!(proposal_passes(yes, no) == true)) __t27_assert_fail("\n proposal passes:\n proposal_passes(yes, no) = {any}\n", .{ proposal_passes(yes, no) }); } test "proposal_passes_no" { const yes, const no, const abstain = .{ 3, 5, 1 }; _ = abstain; // dead after const-inlining - if (!(proposal_passes(yes, no) == false)) @panic("proposal fails"); + if (!(proposal_passes(yes, no) == false)) __t27_assert_fail("\n proposal fails:\n proposal_passes(yes, no) = {any}\n", .{ proposal_passes(yes, no) }); } test "proposal_passes_tie" { const yes, const no, const abstain = .{ 4, 4, 1 }; _ = abstain; // dead after const-inlining - if (!(proposal_passes(yes, no) == false)) @panic("proposal fails on tie"); + if (!(proposal_passes(yes, no) == false)) __t27_assert_fail("\n proposal fails on tie:\n proposal_passes(yes, no) = {any}\n", .{ proposal_passes(yes, no) }); } test "calculate_consensus_value_average" { const vote_array = create_vote_array(create_proposal(1, 10, 100, 1000), create_proposal(2, 10, 200, 1000), create_proposal(3, 10, 150, 1000), create_proposal(4, 10, 250, 1000), create_proposal(5, 10, 0, 0), create_proposal(6, 10, 0, 0), create_proposal(7, 10, 0, 0), create_proposal(8, 10, 0, 0)); const consensus = calculate_consensus_value(vote_array, 10); - if (!(consensus == 175)) @panic("average of 100,200,150,250 = 175"); + if (!(consensus == 175)) __t27_assert_fail("\n average of 100,200,150,250 = 175:\n consensus = {any}\n", .{ consensus }); } test "calculate_consensus_value_empty" { const vote_array = create_vote_array(create_proposal(1, 99, 100, 1000), create_proposal(2, 99, 200, 1000), create_proposal(3, 10, 0, 0), create_proposal(4, 10, 0, 0), create_proposal(5, 10, 0, 0), create_proposal(6, 10, 0, 0), create_proposal(7, 10, 0, 0), create_proposal(8, 10, 0, 0)); const consensus = calculate_consensus_value(vote_array, 10); - if (!(consensus == 0)) @panic("no votes for proposal"); + if (!(consensus == 0)) __t27_assert_fail("\n no votes for proposal:\n consensus = {any}\n", .{ consensus }); } test "cooperative_decision_equal_weight" { const result = cooperative_decision(80, 60, 50); - if (!(result == 70)) @panic("equal weighted average"); + if (!(result == 70)) __t27_assert_fail("\n equal weighted average:\n result = {any}\n", .{ result }); } test "cooperative_decision_neighbor_heavy" { const result = cooperative_decision(100, 50, 80); - if (!(result == 90)) @panic("neighbor-weighted"); + if (!(result == 90)) __t27_assert_fail("\n neighbor-weighted:\n result = {any}\n", .{ result }); } test "cooperative_decision_self_heavy" { const result = cooperative_decision(50, 100, 20); - if (!(result == 90)) @panic("self-weighted"); + if (!(result == 90)) __t27_assert_fail("\n self-weighted:\n result = {any}\n", .{ result }); } diff --git a/gen/zig/test_framework.zig b/gen/zig/test_framework.zig index 2cce072c..0bfd9d1f 100644 --- a/gen/zig/test_framework.zig +++ b/gen/zig/test_framework.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_TESTS: u32 = 32; @@ -300,15 +308,15 @@ fn generate_test_report(summary: u32, coverage: u32, duration_ms: u32) u32 { } test "test_result_roundtrip" { const r = create_test_result(8, 2, 40, 3); - if (!(get_test_id(r) == 8)) @panic("test id"); - if (!(get_test_status(r) == 2)) @panic("status"); - if (!(get_assertion_count(r) == 40)) @panic("assertions"); - if (!(get_failure_count(r) == 3)) @panic("failures"); + if (!(get_test_id(r) == 8)) __t27_assert_fail("\n test id:\n get_test_id(r) = {any}\n", .{ get_test_id(r) }); + if (!(get_test_status(r) == 2)) __t27_assert_fail("\n status:\n get_test_status(r) = {any}\n", .{ get_test_status(r) }); + if (!(get_assertion_count(r) == 40)) __t27_assert_fail("\n assertions:\n get_assertion_count(r) = {any}\n", .{ get_assertion_count(r) }); + if (!(get_failure_count(r) == 3)) __t27_assert_fail("\n failures:\n get_failure_count(r) = {any}\n", .{ get_failure_count(r) }); } test "test_case_roundtrip" { const tc = create_test_case(4, 9, 55, 110); - if (!(get_test_case_id(tc) == 4)) @panic("case id"); - if (!(get_function_id(tc) == 9)) @panic("function id"); - if (!(get_test_input(tc) == 55)) @panic("input"); - if (!(get_expected_output(tc) == 110)) @panic("expected"); + if (!(get_test_case_id(tc) == 4)) __t27_assert_fail("\n case id:\n get_test_case_id(tc) = {any}\n", .{ get_test_case_id(tc) }); + if (!(get_function_id(tc) == 9)) __t27_assert_fail("\n function id:\n get_function_id(tc) = {any}\n", .{ get_function_id(tc) }); + if (!(get_test_input(tc) == 55)) __t27_assert_fail("\n input:\n get_test_input(tc) = {any}\n", .{ get_test_input(tc) }); + if (!(get_expected_output(tc) == 110)) __t27_assert_fail("\n expected:\n get_expected_output(tc) = {any}\n", .{ get_expected_output(tc) }); } diff --git a/gen/zig/test_validator.zig b/gen/zig/test_validator.zig index 0441dc48..0f10cb8f 100644 --- a/gen/zig/test_validator.zig +++ b/gen/zig/test_validator.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_ERRORS: u32 = 16; @@ -257,18 +265,18 @@ fn generate_validation_report(summary: u32, metrics: u32, filename_id: u32) u32 } test "validation_error_roundtrip" { const e = create_validation_error(7, ERROR_TYPE_MISMATCH, 199, 3000); - if (!(get_error_id(e) == 7)) @panic("error id"); - if (!(get_error_type(e) == ERROR_TYPE_MISMATCH)) @panic("error type"); - if (!(get_error_line(e) == 199)) @panic("line"); - if (!(get_error_severity(e) == 3000)) @panic("severity"); + if (!(get_error_id(e) == 7)) __t27_assert_fail("\n error id:\n get_error_id(e) = {any}\n", .{ get_error_id(e) }); + if (!(get_error_type(e) == ERROR_TYPE_MISMATCH)) __t27_assert_fail("\n error type:\n get_error_type(e) = {any}\n ERROR_TYPE_MISMATCH = {any}\n", .{ get_error_type(e), ERROR_TYPE_MISMATCH }); + if (!(get_error_line(e) == 199)) __t27_assert_fail("\n line:\n get_error_line(e) = {any}\n", .{ get_error_line(e) }); + if (!(get_error_severity(e) == 3000)) __t27_assert_fail("\n severity:\n get_error_severity(e) = {any}\n", .{ get_error_severity(e) }); } test "signature_validation_paths" { const ok_sig = create_function_signature(5, 4, 2, 1); - if (!(validate_function_signature(ok_sig) == 0)) @panic("4 params bool return is valid"); + if (!(validate_function_signature(ok_sig) == 0)) __t27_assert_fail("\n 4 params bool return is valid:\n validate_function_signature(ok_sig) = {any}\n", .{ validate_function_signature(ok_sig) }); const many = create_function_signature(5, 12, 2, 1); const e1 = validate_function_signature(many); - if (!(get_error_type(e1) == ERROR_CONSTRAINT_VIOLATION)) @panic("12 params violates the constraint"); + if (!(get_error_type(e1) == ERROR_CONSTRAINT_VIOLATION)) __t27_assert_fail("\n 12 params violates the constraint:\n get_error_type(e1) = {any}\n ERROR_CONSTRAINT_VIOLATION = {any}\n", .{ get_error_type(e1), ERROR_CONSTRAINT_VIOLATION }); const badret = create_function_signature(5, 4, 9, 1); const e2 = validate_function_signature(badret); - if (!(get_error_type(e2) == ERROR_TYPE_MISMATCH)) @panic("return type 9 is invalid"); + if (!(get_error_type(e2) == ERROR_TYPE_MISMATCH)) __t27_assert_fail("\n return type 9 is invalid:\n get_error_type(e2) = {any}\n ERROR_TYPE_MISMATCH = {any}\n", .{ get_error_type(e2), ERROR_TYPE_MISMATCH }); } diff --git a/gen/zig/timer.zig b/gen/zig/timer.zig index 17b81f29..defd2eec 100644 --- a/gen/zig/timer.zig +++ b/gen/zig/timer.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const BASE_MS: u16 = 10; @@ -29,29 +37,29 @@ fn is_expired(counter: u16) bool { } test "calc_timeout_zero" { const t0 = calc_timeout(0); - if (!(t0 == BASE_MS)) @panic("retry 0 → base"); + if (!(t0 == BASE_MS)) __t27_assert_fail("\n retry 0 → base:\n t0 = {any}\n BASE_MS = {any}\n", .{ t0, BASE_MS }); } test "calc_timeout_doubles" { const t0 = calc_timeout(0); const t1 = calc_timeout(1); const t2 = calc_timeout(2); - if (!(t0 == 10)) @panic("0→10"); - if (!(t1 == 20)) @panic("1→20"); - if (!(t2 == 40)) @panic("2→40"); + if (!(t0 == 10)) __t27_assert_fail("\n 0→10:\n t0 = {any}\n", .{ t0 }); + if (!(t1 == 20)) __t27_assert_fail("\n 1→20:\n t1 = {any}\n", .{ t1 }); + if (!(t2 == 40)) __t27_assert_fail("\n 2→40:\n t2 = {any}\n", .{ t2 }); } test "calc_timeout_capped" { const t3 = calc_timeout(3); - if (!(t3 == 80)) @panic("3→80 (capped)"); + if (!(t3 == 80)) __t27_assert_fail("\n 3→80 (capped):\n t3 = {any}\n", .{ t3 }); } test "tick_counter_decrements" { const c1 = tick_counter(10); const c2 = tick_counter(c1); - if (!(c1 == 9)) @panic("first tick"); - if (!(c2 == 8)) @panic("second tick"); + if (!(c1 == 9)) __t27_assert_fail("\n first tick:\n c1 = {any}\n", .{ c1 }); + if (!(c2 == 8)) __t27_assert_fail("\n second tick:\n c2 = {any}\n", .{ c2 }); } test "tick_counter_stops_at_zero" { const c0 = tick_counter(0); - if (!(c0 == 0)) @panic("stays at zero"); + if (!(c0 == 0)) __t27_assert_fail("\n stays at zero:\n c0 = {any}\n", .{ c0 }); } test "tick_counter_reaches_zero" { const c1 = tick_counter(5); @@ -59,19 +67,19 @@ test "tick_counter_reaches_zero" { const c3 = tick_counter(c2); const c4 = tick_counter(c3); const c5 = tick_counter(c4); - if (!(c5 == 0)) @panic("reaches zero"); + if (!(c5 == 0)) __t27_assert_fail("\n reaches zero:\n c5 = {any}\n", .{ c5 }); } test "is_expired_check" { - if (!(is_expired(0) == true)) @panic("zero is expired"); - if (!(is_expired(1) == false)) @panic("non-zero not expired"); + if (!(is_expired(0) == true)) __t27_assert_fail("\n zero is expired:\n is_expired(0) = {any}\n", .{ is_expired(0) }); + if (!(is_expired(1) == false)) __t27_assert_fail("\n non-zero not expired:\n is_expired(1) = {any}\n", .{ is_expired(1) }); } test "full_backoff_sequence" { const r0 = calc_timeout(0); const r1 = calc_timeout(1); const r2 = calc_timeout(2); const r3 = calc_timeout(3); - if (!(r0 == 10)) @panic("0→10"); - if (!(r1 == 20)) @panic("1→20"); - if (!(r2 == 40)) @panic("2→40"); - if (!(r3 == 80)) @panic("3→80"); + if (!(r0 == 10)) __t27_assert_fail("\n 0→10:\n r0 = {any}\n", .{ r0 }); + if (!(r1 == 20)) __t27_assert_fail("\n 1→20:\n r1 = {any}\n", .{ r1 }); + if (!(r2 == 40)) __t27_assert_fail("\n 2→40:\n r2 = {any}\n", .{ r2 }); + if (!(r3 == 80)) __t27_assert_fail("\n 3→80:\n r3 = {any}\n", .{ r3 }); } diff --git a/gen/zig/timing_closure.zig b/gen/zig/timing_closure.zig index 9c21e129..09c27b77 100644 --- a/gen/zig/timing_closure.zig +++ b/gen/zig/timing_closure.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const TIMING_PASS: u32 = 0; @@ -79,78 +87,78 @@ fn timing_closure_achieved(report: u32, target_freq: u32) bool { } test "create_critical_path_correct" { const path = create_critical_path(500, 3, 100); - if (!(extract_delay(path) == 500)) @panic("delay"); - if (!(extract_stages(path) == 3)) @panic("stages"); - if (!(extract_slack(path) == 100)) @panic("slack"); + if (!(extract_delay(path) == 500)) __t27_assert_fail("\n delay:\n extract_delay(path) = {any}\n", .{ extract_delay(path) }); + if (!(extract_stages(path) == 3)) __t27_assert_fail("\n stages:\n extract_stages(path) = {any}\n", .{ extract_stages(path) }); + if (!(extract_slack(path) == 100)) __t27_assert_fail("\n slack:\n extract_slack(path) = {any}\n", .{ extract_slack(path) }); } test "grade_timing_pass" { const grade = grade_timing(150); - if (!(grade == TIMING_PASS)) @panic("positive slack = pass"); + if (!(grade == TIMING_PASS)) __t27_assert_fail("\n positive slack = pass:\n grade = {any}\n TIMING_PASS = {any}\n", .{ grade, TIMING_PASS }); } test "grade_timing_marginal" { const grade = grade_timing(50); - if (!(grade == TIMING_MARGINAL)) @panic("low slack = marginal"); + if (!(grade == TIMING_MARGINAL)) __t27_assert_fail("\n low slack = marginal:\n grade = {any}\n TIMING_MARGINAL = {any}\n", .{ grade, TIMING_MARGINAL }); } test "grade_timing_fail" { const grade = grade_timing(0xFFFFFFFF - 50); - if (!(grade == TIMING_FAIL)) @panic("negative = fail"); + if (!(grade == TIMING_FAIL)) __t27_assert_fail("\n negative = fail:\n grade = {any}\n TIMING_FAIL = {any}\n", .{ grade, TIMING_FAIL }); } test "calculate_pipeline_stages_needed" { const stages = calculate_pipeline_stages(500, 50); - if (!(stages == MAX_PIPELINE)) @panic("capped at max"); + if (!(stages == MAX_PIPELINE)) __t27_assert_fail("\n capped at max:\n stages = {any}\n MAX_PIPELINE = {any}\n", .{ stages, MAX_PIPELINE }); } test "calculate_pipeline_stages_few" { const stages = calculate_pipeline_stages(40, 50); - if (!(stages == 2)) @panic("2 stages needed"); + if (!(stages == 2)) __t27_assert_fail("\n 2 stages needed:\n stages = {any}\n", .{ stages }); } test "calculate_pipeline_stages_zero_freq" { const stages = calculate_pipeline_stages(100, 0); - if (!(stages == MAX_PIPELINE)) @panic("zero freq = max stages"); + if (!(stages == MAX_PIPELINE)) __t27_assert_fail("\n zero freq = max stages:\n stages = {any}\n MAX_PIPELINE = {any}\n", .{ stages, MAX_PIPELINE }); } test "retiming_needed_yes" { - if (!(retiming_needed(10, 100) == true)) @panic("slack < threshold"); + if (!(retiming_needed(10, 100) == true)) __t27_assert_fail("\n slack < threshold:\n retiming_needed(10, 100) = {any}\n", .{ retiming_needed(10, 100) }); } test "retiming_needed_no" { - if (!(retiming_needed(150, 100) == false)) @panic("slack >= threshold"); + if (!(retiming_needed(150, 100) == false)) __t27_assert_fail("\n slack >= threshold:\n retiming_needed(150, 100) = {any}\n", .{ retiming_needed(150, 100) }); } test "balance_registers_yes" { - if (!(balance_registers(50, 20) == true)) @panic("delay > 2x period"); + if (!(balance_registers(50, 20) == true)) __t27_assert_fail("\n delay > 2x period:\n balance_registers(50, 20) = {any}\n", .{ balance_registers(50, 20) }); } test "balance_registers_no" { - if (!(balance_registers(15, 20) == false)) @panic("delay <= 2x period"); + if (!(balance_registers(15, 20) == false)) __t27_assert_fail("\n delay <= 2x period:\n balance_registers(15, 20) = {any}\n", .{ balance_registers(15, 20) }); } test "compare_critical_paths_first" { const path1 = create_critical_path(500, 3, 50); const path2 = create_critical_path(300, 2, 100); const result = compare_critical_paths(path1, path2); - if (!(extract_delay(result) == 500)) @panic("first is longer"); + if (!(extract_delay(result) == 500)) __t27_assert_fail("\n first is longer:\n extract_delay(result) = {any}\n", .{ extract_delay(result) }); } test "compare_critical_paths_second" { const path1 = create_critical_path(300, 2, 100); const path2 = create_critical_path(500, 3, 50); const result = compare_critical_paths(path1, path2); - if (!(extract_delay(result) == 500)) @panic("second is longer"); + if (!(extract_delay(result) == 500)) __t27_assert_fail("\n second is longer:\n extract_delay(result) = {any}\n", .{ extract_delay(result) }); } test "create_timing_report_correct" { const report = create_timing_report(0, 100, 5); - if (!(extract_grade(report) == 0)) @panic("grade"); - if (!(extract_max_freq(report) == 100)) @panic("frequency"); - if (!(extract_critical_paths(report) == 5)) @panic("paths"); + if (!(extract_grade(report) == 0)) __t27_assert_fail("\n grade:\n extract_grade(report) = {any}\n", .{ extract_grade(report) }); + if (!(extract_max_freq(report) == 100)) __t27_assert_fail("\n frequency:\n extract_max_freq(report) = {any}\n", .{ extract_max_freq(report) }); + if (!(extract_critical_paths(report) == 5)) __t27_assert_fail("\n paths:\n extract_critical_paths(report) = {any}\n", .{ extract_critical_paths(report) }); } test "timing_closure_achieved_yes" { const report = create_timing_report(TIMING_PASS, 75, 3); - if (!(timing_closure_achieved(report, 50) == true)) @panic("pass + freq met"); + if (!(timing_closure_achieved(report, 50) == true)) __t27_assert_fail("\n pass + freq met:\n timing_closure_achieved(report, 50) = {any}\n", .{ timing_closure_achieved(report, 50) }); } test "timing_closure_achieved_no_grade" { const report = create_timing_report(TIMING_FAIL, 75, 3); - if (!(timing_closure_achieved(report, 50) == false)) @panic("grade fail"); + if (!(timing_closure_achieved(report, 50) == false)) __t27_assert_fail("\n grade fail:\n timing_closure_achieved(report, 50) = {any}\n", .{ timing_closure_achieved(report, 50) }); } test "timing_closure_achieved_no_freq" { const report = create_timing_report(TIMING_PASS, 40, 3); - if (!(timing_closure_achieved(report, 50) == false)) @panic("freq not met"); + if (!(timing_closure_achieved(report, 50) == false)) __t27_assert_fail("\n freq not met:\n timing_closure_achieved(report, 50) = {any}\n", .{ timing_closure_achieved(report, 50) }); } test "extract_slack_negative_handling" { const path = create_critical_path(500, 3, 0xFF); const slack = extract_slack(path); - if (!(slack == 0xFF)) @panic("extracted large slack"); + if (!(slack == 0xFF)) __t27_assert_fail("\n extracted large slack:\n slack = {any}\n", .{ slack }); } diff --git a/gen/zig/topology_visualizer.zig b/gen/zig/topology_visualizer.zig index 7c4a8ef6..0216dfec 100644 --- a/gen/zig/topology_visualizer.zig +++ b/gen/zig/topology_visualizer.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_NODES: u32 = 32; @@ -311,14 +319,14 @@ fn generate_topology_visualization(nodes: [MAX_NODES]u32, edges: [MAX_EDGES]u32, } test "visual_node_roundtrip" { const n = create_visual_node(6, 120, 200, 3); - if (!(get_viz_node_id(n) == 6)) @panic("node id"); - if (!(get_node_x_position(n) == 120)) @panic("x"); - if (!(get_node_y_position(n) == 200)) @panic("y"); + if (!(get_viz_node_id(n) == 6)) __t27_assert_fail("\n node id:\n get_viz_node_id(n) = {any}\n", .{ get_viz_node_id(n) }); + if (!(get_node_x_position(n) == 120)) __t27_assert_fail("\n x:\n get_node_x_position(n) = {any}\n", .{ get_node_x_position(n) }); + if (!(get_node_y_position(n) == 200)) __t27_assert_fail("\n y:\n get_node_y_position(n) = {any}\n", .{ get_node_y_position(n) }); } test "visual_edge_roundtrip" { const e = create_visual_edge(2, 5, 80, 1); - if (!(get_viz_edge_source(e) == 2)) @panic("source"); - if (!(get_viz_edge_dest(e) == 5)) @panic("dest"); - if (!(get_viz_edge_quality(e) == 80)) @panic("quality"); - if (!(get_viz_edge_type(e) == 1)) @panic("type"); + if (!(get_viz_edge_source(e) == 2)) __t27_assert_fail("\n source:\n get_viz_edge_source(e) = {any}\n", .{ get_viz_edge_source(e) }); + if (!(get_viz_edge_dest(e) == 5)) __t27_assert_fail("\n dest:\n get_viz_edge_dest(e) = {any}\n", .{ get_viz_edge_dest(e) }); + if (!(get_viz_edge_quality(e) == 80)) __t27_assert_fail("\n quality:\n get_viz_edge_quality(e) = {any}\n", .{ get_viz_edge_quality(e) }); + if (!(get_viz_edge_type(e) == 1)) __t27_assert_fail("\n type:\n get_viz_edge_type(e) = {any}\n", .{ get_viz_edge_type(e) }); } diff --git a/gen/zig/traffic_animator.zig b/gen/zig/traffic_animator.zig index bf77d46f..eb81e7c4 100644 --- a/gen/zig/traffic_animator.zig +++ b/gen/zig/traffic_animator.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_PACKETS: u32 = 64; @@ -341,17 +349,17 @@ fn calculate_animation_stats(frames: [MAX_FRAMES]u32, frame_count: u32) u32 { } test "anim_packet_roundtrip_and_progress" { var p = create_anim_packet(5, 1, 2, 40); - if (!(get_anim_packet_id(p) == 5)) @panic("packet id"); - if (!(get_anim_packet_progress(p) == 40)) @panic("progress"); + if (!(get_anim_packet_id(p) == 5)) __t27_assert_fail("\n packet id:\n get_anim_packet_id(p) = {any}\n", .{ get_anim_packet_id(p) }); + if (!(get_anim_packet_progress(p) == 40)) __t27_assert_fail("\n progress:\n get_anim_packet_progress(p) = {any}\n", .{ get_anim_packet_progress(p) }); p = update_packet_progress(p, 30); - if (!(get_anim_packet_progress(p) == 70)) @panic("advanced"); + if (!(get_anim_packet_progress(p) == 70)) __t27_assert_fail("\n advanced:\n get_anim_packet_progress(p) = {any}\n", .{ get_anim_packet_progress(p) }); p = update_packet_progress(p, 90); - if (!(get_anim_packet_progress(p) == 100)) @panic("caps at 100"); + if (!(get_anim_packet_progress(p) == 100)) __t27_assert_fail("\n caps at 100:\n get_anim_packet_progress(p) = {any}\n", .{ get_anim_packet_progress(p) }); } test "packet_position_interpolates_both_directions" { var pos = calculate_packet_position(10, 20, 90, 20, 50); - if (!(((pos >> 24) & 0xFF) == 50)) @panic("x midpoint rightward"); + if (!(((pos >> 24) & 0xFF) == 50)) __t27_assert_fail("\n x midpoint rightward:\n (pos >> 24) & 0xFF = {any}\n", .{ (pos >> 24) & 0xFF }); pos = calculate_packet_position(90, 20, 10, 20, 50); - if (!(((pos >> 24) & 0xFF) == 50)) @panic("x midpoint leftward"); - if (!(((pos >> 16) & 0xFF) == 20)) @panic("y unchanged"); + if (!(((pos >> 24) & 0xFF) == 50)) __t27_assert_fail("\n x midpoint leftward:\n (pos >> 24) & 0xFF = {any}\n", .{ (pos >> 24) & 0xFF }); + if (!(((pos >> 16) & 0xFF) == 20)) __t27_assert_fail("\n y unchanged:\n (pos >> 16) & 0xFF = {any}\n", .{ (pos >> 16) & 0xFF }); } diff --git a/gen/zig/transport_tx_fsm.zig b/gen/zig/transport_tx_fsm.zig index 68aded8e..dd9d6e7b 100644 --- a/gen/zig/transport_tx_fsm.zig +++ b/gen/zig/transport_tx_fsm.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const ST_IDLE: u8 = 0; @@ -96,39 +104,39 @@ fn header_byte(kind: u8, src: u32, dst: u32, ttl: u8, idx: usize) u8 { } test "idle_to_enqueue_on_frame" { const next = next_state(ST_IDLE, true, false, false); - if (!(next == ST_ENQUEUE)) @panic("should transition to ENQUEUE"); + if (!(next == ST_ENQUEUE)) __t27_assert_fail("\n should transition to ENQUEUE:\n next = {any}\n ST_ENQUEUE = {any}\n", .{ next, ST_ENQUEUE }); } test "idle_stays_idle_when_no_frame" { const next = next_state(ST_IDLE, false, false, false); - if (!(next == ST_IDLE)) @panic("should stay IDLE"); + if (!(next == ST_IDLE)) __t27_assert_fail("\n should stay IDLE:\n next = {any}\n ST_IDLE = {any}\n", .{ next, ST_IDLE }); } test "enqueue_to_build_hdr" { const next = next_state(ST_ENQUEUE, false, false, false); - if (!(next == ST_BUILD_HDR)) @panic("should transition to BUILD_HDR"); + if (!(next == ST_BUILD_HDR)) __t27_assert_fail("\n should transition to BUILD_HDR:\n next = {any}\n ST_BUILD_HDR = {any}\n", .{ next, ST_BUILD_HDR }); } test "build_hdr_to_tx_wait" { const next = next_state(ST_BUILD_HDR, false, false, false); - if (!(next == ST_TX_WAIT)) @panic("should transition to TX_WAIT"); + if (!(next == ST_TX_WAIT)) __t27_assert_fail("\n should transition to TX_WAIT:\n next = {any}\n ST_TX_WAIT = {any}\n", .{ next, ST_TX_WAIT }); } test "tx_wait_to_acked_on_success" { const next = next_state(ST_TX_WAIT, false, true, false); - if (!(next == ST_ACKED)) @panic("should transition to ACKED"); + if (!(next == ST_ACKED)) __t27_assert_fail("\n should transition to ACKED:\n next = {any}\n ST_ACKED = {any}\n", .{ next, ST_ACKED }); } test "tx_wait_stays_waiting_when_no_ack" { const next = next_state(ST_TX_WAIT, false, false, false); - if (!(next == ST_TX_WAIT)) @panic("should stay in TX_WAIT"); + if (!(next == ST_TX_WAIT)) __t27_assert_fail("\n should stay in TX_WAIT:\n next = {any}\n ST_TX_WAIT = {any}\n", .{ next, ST_TX_WAIT }); } test "tx_wait_to_failed_on_retry_exceeded" { const next = next_state(ST_TX_WAIT, false, false, true); - if (!(next == ST_FAILED)) @panic("should transition to FAILED"); + if (!(next == ST_FAILED)) __t27_assert_fail("\n should transition to FAILED:\n next = {any}\n ST_FAILED = {any}\n", .{ next, ST_FAILED }); } test "acked_returns_to_idle" { const next = next_state(ST_ACKED, false, false, false); - if (!(next == ST_IDLE)) @panic("should return to IDLE"); + if (!(next == ST_IDLE)) __t27_assert_fail("\n should return to IDLE:\n next = {any}\n ST_IDLE = {any}\n", .{ next, ST_IDLE }); } test "failed_returns_to_idle" { const next = next_state(ST_FAILED, false, false, false); - if (!(next == ST_IDLE)) @panic("should return to IDLE"); + if (!(next == ST_IDLE)) __t27_assert_fail("\n should return to IDLE:\n next = {any}\n ST_IDLE = {any}\n", .{ next, ST_IDLE }); } test "retry_exponential_backoff" { const delay0 = retry_delay_ms(0, 10); @@ -136,49 +144,49 @@ test "retry_exponential_backoff" { const delay2 = retry_delay_ms(2, 10); const delay3 = retry_delay_ms(3, 10); const delay4 = retry_delay_ms(4, 10); - if (!(delay0 == 10)) @panic("retry 0 should be 10ms"); - if (!(delay1 == 20)) @panic("retry 1 should be 20ms"); - if (!(delay2 == 40)) @panic("retry 2 should be 40ms"); - if (!(delay3 == 80)) @panic("retry 3 should be 80ms"); - if (!(delay4 == 160)) @panic("retry 4 should be 160ms"); + if (!(delay0 == 10)) __t27_assert_fail("\n retry 0 should be 10ms:\n delay0 = {any}\n", .{ delay0 }); + if (!(delay1 == 20)) __t27_assert_fail("\n retry 1 should be 20ms:\n delay1 = {any}\n", .{ delay1 }); + if (!(delay2 == 40)) __t27_assert_fail("\n retry 2 should be 40ms:\n delay2 = {any}\n", .{ delay2 }); + if (!(delay3 == 80)) __t27_assert_fail("\n retry 3 should be 80ms:\n delay3 = {any}\n", .{ delay3 }); + if (!(delay4 == 160)) __t27_assert_fail("\n retry 4 should be 160ms:\n delay4 = {any}\n", .{ delay4 }); } test "is_retries_exceeded_check" { const exceeded = is_retries_exceeded(5); const not_exceeded = is_retries_exceeded(4); if (!(exceeded)) @panic("5 retries should be exceeded"); - if (!(not_exceeded == false)) @panic("4 retries should not be exceeded"); + if (!(not_exceeded == false)) __t27_assert_fail("\n 4 retries should not be exceeded:\n not_exceeded = {any}\n", .{ not_exceeded }); } test "increment_retry_saturates" { const r0 = increment_retry(0); const r1 = increment_retry(1); const r4 = increment_retry(4); const r5 = increment_retry(5); - if (!(r0 == 1)) @panic("0→1"); - if (!(r1 == 2)) @panic("1→2"); - if (!(r4 == 5)) @panic("4→5"); - if (!(r5 == 5)) @panic("5 should saturate at 5"); + if (!(r0 == 1)) __t27_assert_fail("\n 0→1:\n r0 = {any}\n", .{ r0 }); + if (!(r1 == 2)) __t27_assert_fail("\n 1→2:\n r1 = {any}\n", .{ r1 }); + if (!(r4 == 5)) __t27_assert_fail("\n 4→5:\n r4 = {any}\n", .{ r4 }); + if (!(r5 == 5)) __t27_assert_fail("\n 5 should saturate at 5:\n r5 = {any}\n", .{ r5 }); } test "header_byte_correctness_version" { const b0 = header_byte(KIND_DATA, 0x01020304, 0x05060708, 8, 0); - if (!(b0 == VERSION)) @panic("byte 0 should be VERSION"); + if (!(b0 == VERSION)) __t27_assert_fail("\n byte 0 should be VERSION:\n b0 = {any}\n VERSION = {any}\n", .{ b0, VERSION }); } test "header_byte_correctness_kind" { const b1 = header_byte(KIND_DATA, 0x01020304, 0x05060708, 8, 1); - if (!(b1 == KIND_DATA)) @panic("byte 1 should be KIND_DATA"); + if (!(b1 == KIND_DATA)) __t27_assert_fail("\n byte 1 should be KIND_DATA:\n b1 = {any}\n KIND_DATA = {any}\n", .{ b1, KIND_DATA }); } test "header_byte_correctness_src" { const b2 = header_byte(KIND_DATA, 0x01020304, 0x05060708, 8, 2); const b5 = header_byte(KIND_DATA, 0x01020304, 0x05060708, 8, 5); - if (!(b2 == 1)) @panic("src byte 0 should be 0x01"); - if (!(b5 == 4)) @panic("src byte 3 should be 0x04"); + if (!(b2 == 1)) __t27_assert_fail("\n src byte 0 should be 0x01:\n b2 = {any}\n", .{ b2 }); + if (!(b5 == 4)) __t27_assert_fail("\n src byte 3 should be 0x04:\n b5 = {any}\n", .{ b5 }); } test "header_byte_correctness_dst" { const b6 = header_byte(KIND_DATA, 0x01020304, 0x05060708, 8, 6); const b9 = header_byte(KIND_DATA, 0x01020304, 0x05060708, 8, 9); - if (!(b6 == 5)) @panic("dst byte 0 should be 0x05"); - if (!(b9 == 8)) @panic("dst byte 3 should be 0x08"); + if (!(b6 == 5)) __t27_assert_fail("\n dst byte 0 should be 0x05:\n b6 = {any}\n", .{ b6 }); + if (!(b9 == 8)) __t27_assert_fail("\n dst byte 3 should be 0x08:\n b9 = {any}\n", .{ b9 }); } test "header_byte_correctness_ttl" { const b10 = header_byte(KIND_DATA, 0x01020304, 0x05060708, 8, 10); - if (!(b10 == 8)) @panic("byte 10 should be TTL"); + if (!(b10 == 8)) __t27_assert_fail("\n byte 10 should be TTL:\n b10 = {any}\n", .{ b10 }); } diff --git a/gen/zig/tri_a2a.zig b/gen/zig/tri_a2a.zig index 2460712e..b45d0ecf 100644 --- a/gen/zig/tri_a2a.zig +++ b/gen/zig/tri_a2a.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const KIND_DATA: u32 = 1; @@ -380,171 +388,171 @@ fn admit_result_signed_sized(assign_task_id: u32, result_task_id: u32, receipt_t } } test "demux_by_port_not_payload" { - if (!(is_a2a(KIND_DATA, A2A_PORT) == true)) @panic("DATA on the A2A port is A2A"); - if (!(is_a2a(0, A2A_PORT) == false)) @panic("HELLO is not A2A even on the port"); - if (!(is_a2a(KIND_DATA, 0x1234) == false)) @panic("DATA on another port is not A2A"); + if (!(is_a2a(KIND_DATA, A2A_PORT) == true)) __t27_assert_fail("\n DATA on the A2A port is A2A:\n is_a2a(KIND_DATA, A2A_PORT) = {any}\n", .{ is_a2a(KIND_DATA, A2A_PORT) }); + if (!(is_a2a(0, A2A_PORT) == false)) __t27_assert_fail("\n HELLO is not A2A even on the port:\n is_a2a(0, A2A_PORT) = {any}\n", .{ is_a2a(0, A2A_PORT) }); + if (!(is_a2a(KIND_DATA, 0x1234) == false)) __t27_assert_fail("\n DATA on another port is not A2A:\n is_a2a(KIND_DATA, 0x1234) = {any}\n", .{ is_a2a(KIND_DATA, 0x1234) }); } test "skill_et_is_the_ratified_rung" { - if (!(skill_et(SKILL_GFT16_MUL) == 4)) @panic("GF-T16 skill -> Et 4"); - if (!(skill_et(SKILL_GFT16_ADD) == 4)) @panic("GF-T16 add skill -> Et 4"); - if (!(skill_et(SKILL_GFT8_MUL) == 3)) @panic("GF-T8 skill -> Et 3"); - if (!(skill_et(SKILL_GF16_MUL) == 0)) @panic("binary GF16 skill has no ternary Et"); - if (!(skill_et(0xDEADBEEF) == 0)) @panic("an unknown skill is fail-closed at Et 0"); + if (!(skill_et(SKILL_GFT16_MUL) == 4)) __t27_assert_fail("\n GF-T16 skill -> Et 4:\n skill_et(SKILL_GFT16_MUL) = {any}\n", .{ skill_et(SKILL_GFT16_MUL) }); + if (!(skill_et(SKILL_GFT16_ADD) == 4)) __t27_assert_fail("\n GF-T16 add skill -> Et 4:\n skill_et(SKILL_GFT16_ADD) = {any}\n", .{ skill_et(SKILL_GFT16_ADD) }); + if (!(skill_et(SKILL_GFT8_MUL) == 3)) __t27_assert_fail("\n GF-T8 skill -> Et 3:\n skill_et(SKILL_GFT8_MUL) = {any}\n", .{ skill_et(SKILL_GFT8_MUL) }); + if (!(skill_et(SKILL_GF16_MUL) == 0)) __t27_assert_fail("\n binary GF16 skill has no ternary Et:\n skill_et(SKILL_GF16_MUL) = {any}\n", .{ skill_et(SKILL_GF16_MUL) }); + if (!(skill_et(0xDEADBEEF) == 0)) __t27_assert_fail("\n an unknown skill is fail-closed at Et 0:\n skill_et(0xDEADBEEF) = {any}\n", .{ skill_et(0xDEADBEEF) }); } test "assignment_binds_the_exact_rung" { - if (!(result_binds_assign_rung(7, 7, 7, SKILL_GFT16_MUL, FMT_GFT, 0x11, 16, 4) == true)) @panic("GF-T16 assignment + Et4/width16/GFT receipt binds"); - if (!(result_binds_assign_rung(7, 7, 7, SKILL_GFT16_MUL, FMT_GFT, 0x11, 16, 6) == false)) @panic("a GF-T32-rung (Et6) receipt does NOT bind a GF-T16 assignment"); - if (!(result_binds_assign_rung(7, 7, 7, SKILL_GFT8_MUL, FMT_GFT, 0x11, 8, 3) == true)) @panic("GF-T8 assignment + Et3/width8 receipt binds"); - if (!(result_binds_assign_rung(7, 7, 7, SKILL_GFT8_MUL, FMT_GFT, 0x11, 8, 4) == false)) @panic("a GF-T16-rung (Et4) receipt does NOT bind a GF-T8 assignment (precision upgrade rejected)"); + if (!(result_binds_assign_rung(7, 7, 7, SKILL_GFT16_MUL, FMT_GFT, 0x11, 16, 4) == true)) __t27_assert_fail("\n GF-T16 assignment + Et4/width16/GFT receipt binds:\n result_binds_assign_rung(7, 7, 7, SKILL_GFT16_MUL, FMT_GFT, 0x11, 16, 4) = {any}\n", .{ result_binds_assign_rung(7, 7, 7, SKILL_GFT16_MUL, FMT_GFT, 0x11, 16, 4) }); + if (!(result_binds_assign_rung(7, 7, 7, SKILL_GFT16_MUL, FMT_GFT, 0x11, 16, 6) == false)) __t27_assert_fail("\n a GF-T32-rung (Et6) receipt does NOT bind a GF-T16 assignment:\n result_binds_assign_rung(7, 7, 7, SKILL_GFT16_MUL, FMT_GFT, 0x11, 16, 6) = {any}\n", .{ result_binds_assign_rung(7, 7, 7, SKILL_GFT16_MUL, FMT_GFT, 0x11, 16, 6) }); + if (!(result_binds_assign_rung(7, 7, 7, SKILL_GFT8_MUL, FMT_GFT, 0x11, 8, 3) == true)) __t27_assert_fail("\n GF-T8 assignment + Et3/width8 receipt binds:\n result_binds_assign_rung(7, 7, 7, SKILL_GFT8_MUL, FMT_GFT, 0x11, 8, 3) = {any}\n", .{ result_binds_assign_rung(7, 7, 7, SKILL_GFT8_MUL, FMT_GFT, 0x11, 8, 3) }); + if (!(result_binds_assign_rung(7, 7, 7, SKILL_GFT8_MUL, FMT_GFT, 0x11, 8, 4) == false)) __t27_assert_fail("\n a GF-T16-rung (Et4) receipt does NOT bind a GF-T8 assignment (precision upgrade rejected):\n result_binds_assign_rung(7, 7, 7, SKILL_GFT8_MUL, FMT_GFT, 0x11, 8, 4) = {any}\n", .{ result_binds_assign_rung(7, 7, 7, SKILL_GFT8_MUL, FMT_GFT, 0x11, 8, 4) }); } test "gft32_is_a_hosted_rung" { - if (!(is_hosted_skill(SKILL_GFT32_MUL) == 1)) @panic("GF-T32 mul is hosted"); - if (!(is_gft_skill(SKILL_GFT32_ADD) == true)) @panic("GF-T32 add is a GF-T (ternary) skill"); - if (!(is_gf_skill(SKILL_GFT32_MUL) == false)) @panic("GF-T32 is not a binary GF skill"); - if (!(skill_family(SKILL_GFT32_MUL) == FMT_GFT)) @panic("GF-T32 family is FMT_GFT"); - if (!(skill_width(SKILL_GFT32_MUL) == 32)) @panic("GF-T32 width 32"); - if (!(skill_op(SKILL_GFT32_MUL) == 0x11)) @panic("GF-T32 mul -> op 0x11"); - if (!(skill_op(SKILL_GFT32_ADD) == 0x10)) @panic("GF-T32 add -> op 0x10"); - if (!(skill_et(SKILL_GFT32_MUL) == 6)) @panic("GF-T32 rung Et 6 (ratified golden rule)"); - if (!(result_binds_assign_rung(9, 9, 9, SKILL_GFT32_MUL, FMT_GFT, 0x11, 32, 6) == true)) @panic("GF-T32 assignment binds a GF-T32 receipt (width32, Et6)"); - if (!(result_binds_assign_rung(9, 9, 9, SKILL_GFT32_MUL, FMT_GFT, 0x11, 16, 4) == false)) @panic("a GF-T16 receipt does NOT bind a GF-T32 assignment (precision downgrade rejected)"); + if (!(is_hosted_skill(SKILL_GFT32_MUL) == 1)) __t27_assert_fail("\n GF-T32 mul is hosted:\n is_hosted_skill(SKILL_GFT32_MUL) = {any}\n", .{ is_hosted_skill(SKILL_GFT32_MUL) }); + if (!(is_gft_skill(SKILL_GFT32_ADD) == true)) __t27_assert_fail("\n GF-T32 add is a GF-T (ternary) skill:\n is_gft_skill(SKILL_GFT32_ADD) = {any}\n", .{ is_gft_skill(SKILL_GFT32_ADD) }); + if (!(is_gf_skill(SKILL_GFT32_MUL) == false)) __t27_assert_fail("\n GF-T32 is not a binary GF skill:\n is_gf_skill(SKILL_GFT32_MUL) = {any}\n", .{ is_gf_skill(SKILL_GFT32_MUL) }); + if (!(skill_family(SKILL_GFT32_MUL) == FMT_GFT)) __t27_assert_fail("\n GF-T32 family is FMT_GFT:\n skill_family(SKILL_GFT32_MUL) = {any}\n FMT_GFT = {any}\n", .{ skill_family(SKILL_GFT32_MUL), FMT_GFT }); + if (!(skill_width(SKILL_GFT32_MUL) == 32)) __t27_assert_fail("\n GF-T32 width 32:\n skill_width(SKILL_GFT32_MUL) = {any}\n", .{ skill_width(SKILL_GFT32_MUL) }); + if (!(skill_op(SKILL_GFT32_MUL) == 0x11)) __t27_assert_fail("\n GF-T32 mul -> op 0x11:\n skill_op(SKILL_GFT32_MUL) = {any}\n", .{ skill_op(SKILL_GFT32_MUL) }); + if (!(skill_op(SKILL_GFT32_ADD) == 0x10)) __t27_assert_fail("\n GF-T32 add -> op 0x10:\n skill_op(SKILL_GFT32_ADD) = {any}\n", .{ skill_op(SKILL_GFT32_ADD) }); + if (!(skill_et(SKILL_GFT32_MUL) == 6)) __t27_assert_fail("\n GF-T32 rung Et 6 (ratified golden rule):\n skill_et(SKILL_GFT32_MUL) = {any}\n", .{ skill_et(SKILL_GFT32_MUL) }); + if (!(result_binds_assign_rung(9, 9, 9, SKILL_GFT32_MUL, FMT_GFT, 0x11, 32, 6) == true)) __t27_assert_fail("\n GF-T32 assignment binds a GF-T32 receipt (width32, Et6):\n result_binds_assign_rung(9, 9, 9, SKILL_GFT32_MUL, FMT_GFT, 0x11, 32, 6) = {any}\n", .{ result_binds_assign_rung(9, 9, 9, SKILL_GFT32_MUL, FMT_GFT, 0x11, 32, 6) }); + if (!(result_binds_assign_rung(9, 9, 9, SKILL_GFT32_MUL, FMT_GFT, 0x11, 16, 4) == false)) __t27_assert_fail("\n a GF-T16 receipt does NOT bind a GF-T32 assignment (precision downgrade rejected):\n result_binds_assign_rung(9, 9, 9, SKILL_GFT32_MUL, FMT_GFT, 0x11, 16, 4) = {any}\n", .{ result_binds_assign_rung(9, 9, 9, SKILL_GFT32_MUL, FMT_GFT, 0x11, 16, 4) }); } test "gft64_gft128_are_hosted_rungs" { - if (!(is_hosted_skill(SKILL_GFT64_MUL) == 1)) @panic("GF-T64 mul is hosted"); - if (!(is_hosted_skill(SKILL_GFT128_ADD) == 1)) @panic("GF-T128 add is hosted"); - if (!(skill_family(SKILL_GFT64_MUL) == FMT_GFT)) @panic("GF-T64 family FMT_GFT"); - if (!(skill_family(SKILL_GFT128_MUL) == FMT_GFT)) @panic("GF-T128 family FMT_GFT"); - if (!(skill_width(SKILL_GFT64_MUL) == 64)) @panic("GF-T64 width 64"); - if (!(skill_width(SKILL_GFT128_MUL) == 128)) @panic("GF-T128 width 128"); - if (!(skill_et(SKILL_GFT64_MUL) == 9)) @panic("GF-T64 Et9"); - if (!(skill_et(SKILL_GFT128_MUL) == 14)) @panic("GF-T128 Et14"); - if (!(skill_op(SKILL_GFT64_ADD) == 0x10)) @panic("GF-T64 add -> op 0x10"); - if (!(result_binds_assign_rung(11, 11, 11, SKILL_GFT64_MUL, FMT_GFT, 0x11, 64, 9) == true)) @panic("GF-T64 assignment binds a GF-T64 receipt (width64, Et9)"); - if (!(result_binds_assign_rung(11, 11, 11, SKILL_GFT64_MUL, FMT_GFT, 0x11, 32, 6) == false)) @panic("a GF-T32 receipt does NOT bind a GF-T64 assignment"); - if (!(is_hosted_skill(0xBADC0DE) == 0)) @panic("unknown skill not hosted"); - if (!(skill_et(0xBADC0DE) == 0)) @panic("unknown skill fail-closed Et 0"); + if (!(is_hosted_skill(SKILL_GFT64_MUL) == 1)) __t27_assert_fail("\n GF-T64 mul is hosted:\n is_hosted_skill(SKILL_GFT64_MUL) = {any}\n", .{ is_hosted_skill(SKILL_GFT64_MUL) }); + if (!(is_hosted_skill(SKILL_GFT128_ADD) == 1)) __t27_assert_fail("\n GF-T128 add is hosted:\n is_hosted_skill(SKILL_GFT128_ADD) = {any}\n", .{ is_hosted_skill(SKILL_GFT128_ADD) }); + if (!(skill_family(SKILL_GFT64_MUL) == FMT_GFT)) __t27_assert_fail("\n GF-T64 family FMT_GFT:\n skill_family(SKILL_GFT64_MUL) = {any}\n FMT_GFT = {any}\n", .{ skill_family(SKILL_GFT64_MUL), FMT_GFT }); + if (!(skill_family(SKILL_GFT128_MUL) == FMT_GFT)) __t27_assert_fail("\n GF-T128 family FMT_GFT:\n skill_family(SKILL_GFT128_MUL) = {any}\n FMT_GFT = {any}\n", .{ skill_family(SKILL_GFT128_MUL), FMT_GFT }); + if (!(skill_width(SKILL_GFT64_MUL) == 64)) __t27_assert_fail("\n GF-T64 width 64:\n skill_width(SKILL_GFT64_MUL) = {any}\n", .{ skill_width(SKILL_GFT64_MUL) }); + if (!(skill_width(SKILL_GFT128_MUL) == 128)) __t27_assert_fail("\n GF-T128 width 128:\n skill_width(SKILL_GFT128_MUL) = {any}\n", .{ skill_width(SKILL_GFT128_MUL) }); + if (!(skill_et(SKILL_GFT64_MUL) == 9)) __t27_assert_fail("\n GF-T64 Et9:\n skill_et(SKILL_GFT64_MUL) = {any}\n", .{ skill_et(SKILL_GFT64_MUL) }); + if (!(skill_et(SKILL_GFT128_MUL) == 14)) __t27_assert_fail("\n GF-T128 Et14:\n skill_et(SKILL_GFT128_MUL) = {any}\n", .{ skill_et(SKILL_GFT128_MUL) }); + if (!(skill_op(SKILL_GFT64_ADD) == 0x10)) __t27_assert_fail("\n GF-T64 add -> op 0x10:\n skill_op(SKILL_GFT64_ADD) = {any}\n", .{ skill_op(SKILL_GFT64_ADD) }); + if (!(result_binds_assign_rung(11, 11, 11, SKILL_GFT64_MUL, FMT_GFT, 0x11, 64, 9) == true)) __t27_assert_fail("\n GF-T64 assignment binds a GF-T64 receipt (width64, Et9):\n result_binds_assign_rung(11, 11, 11, SKILL_GFT64_MUL, FMT_GFT, 0x11, 64, 9) = {any}\n", .{ result_binds_assign_rung(11, 11, 11, SKILL_GFT64_MUL, FMT_GFT, 0x11, 64, 9) }); + if (!(result_binds_assign_rung(11, 11, 11, SKILL_GFT64_MUL, FMT_GFT, 0x11, 32, 6) == false)) __t27_assert_fail("\n a GF-T32 receipt does NOT bind a GF-T64 assignment:\n result_binds_assign_rung(11, 11, 11, SKILL_GFT64_MUL, FMT_GFT, 0x11, 32, 6) = {any}\n", .{ result_binds_assign_rung(11, 11, 11, SKILL_GFT64_MUL, FMT_GFT, 0x11, 32, 6) }); + if (!(is_hosted_skill(0xBADC0DE) == 0)) __t27_assert_fail("\n unknown skill not hosted:\n is_hosted_skill(0xBADC0DE) = {any}\n", .{ is_hosted_skill(0xBADC0DE) }); + if (!(skill_et(0xBADC0DE) == 0)) __t27_assert_fail("\n unknown skill fail-closed Et 0:\n skill_et(0xBADC0DE) = {any}\n", .{ skill_et(0xBADC0DE) }); } test "gft4_is_the_bottom_hosted_rung" { - if (!(is_hosted_skill(SKILL_GFT4_MUL) == 1)) @panic("GF-T4 mul is hosted"); - if (!(is_gft_skill(SKILL_GFT4_ADD) == true)) @panic("GF-T4 add is a GF-T (ternary) skill"); - if (!(skill_family(SKILL_GFT4_MUL) == FMT_GFT)) @panic("GF-T4 family FMT_GFT"); - if (!(skill_width(SKILL_GFT4_MUL) == 4)) @panic("GF-T4 width 4"); - if (!(skill_op(SKILL_GFT4_MUL) == 0x11)) @panic("GF-T4 mul -> op 0x11"); - if (!(skill_et(SKILL_GFT4_MUL) == 2)) @panic("GF-T4 rung Et2 (bottom of the ladder)"); - if (!(result_binds_assign_rung(3, 3, 3, SKILL_GFT4_MUL, FMT_GFT, 0x11, 4, 2) == true)) @panic("GF-T4 assignment binds a GF-T4 receipt (width4, Et2)"); - if (!(result_binds_assign_rung(3, 3, 3, SKILL_GFT4_MUL, FMT_GFT, 0x11, 8, 3) == false)) @panic("a GF-T8 receipt does NOT bind a GF-T4 assignment (precision upgrade rejected)"); + if (!(is_hosted_skill(SKILL_GFT4_MUL) == 1)) __t27_assert_fail("\n GF-T4 mul is hosted:\n is_hosted_skill(SKILL_GFT4_MUL) = {any}\n", .{ is_hosted_skill(SKILL_GFT4_MUL) }); + if (!(is_gft_skill(SKILL_GFT4_ADD) == true)) __t27_assert_fail("\n GF-T4 add is a GF-T (ternary) skill:\n is_gft_skill(SKILL_GFT4_ADD) = {any}\n", .{ is_gft_skill(SKILL_GFT4_ADD) }); + if (!(skill_family(SKILL_GFT4_MUL) == FMT_GFT)) __t27_assert_fail("\n GF-T4 family FMT_GFT:\n skill_family(SKILL_GFT4_MUL) = {any}\n FMT_GFT = {any}\n", .{ skill_family(SKILL_GFT4_MUL), FMT_GFT }); + if (!(skill_width(SKILL_GFT4_MUL) == 4)) __t27_assert_fail("\n GF-T4 width 4:\n skill_width(SKILL_GFT4_MUL) = {any}\n", .{ skill_width(SKILL_GFT4_MUL) }); + if (!(skill_op(SKILL_GFT4_MUL) == 0x11)) __t27_assert_fail("\n GF-T4 mul -> op 0x11:\n skill_op(SKILL_GFT4_MUL) = {any}\n", .{ skill_op(SKILL_GFT4_MUL) }); + if (!(skill_et(SKILL_GFT4_MUL) == 2)) __t27_assert_fail("\n GF-T4 rung Et2 (bottom of the ladder):\n skill_et(SKILL_GFT4_MUL) = {any}\n", .{ skill_et(SKILL_GFT4_MUL) }); + if (!(result_binds_assign_rung(3, 3, 3, SKILL_GFT4_MUL, FMT_GFT, 0x11, 4, 2) == true)) __t27_assert_fail("\n GF-T4 assignment binds a GF-T4 receipt (width4, Et2):\n result_binds_assign_rung(3, 3, 3, SKILL_GFT4_MUL, FMT_GFT, 0x11, 4, 2) = {any}\n", .{ result_binds_assign_rung(3, 3, 3, SKILL_GFT4_MUL, FMT_GFT, 0x11, 4, 2) }); + if (!(result_binds_assign_rung(3, 3, 3, SKILL_GFT4_MUL, FMT_GFT, 0x11, 8, 3) == false)) __t27_assert_fail("\n a GF-T8 receipt does NOT bind a GF-T4 assignment (precision upgrade rejected):\n result_binds_assign_rung(3, 3, 3, SKILL_GFT4_MUL, FMT_GFT, 0x11, 8, 3) = {any}\n", .{ result_binds_assign_rung(3, 3, 3, SKILL_GFT4_MUL, FMT_GFT, 0x11, 8, 3) }); } test "only_result_carries_receipt" { - if (!(carries_receipt(MSG_TASK_RESULT) == true)) @panic("taskResult carries a receipt"); - if (!(carries_receipt(MSG_TASK_ASSIGN) == false)) @panic("taskAssign carries no receipt"); - if (!(carries_receipt(MSG_HEARTBEAT) == false)) @panic("heartbeat carries no receipt"); + if (!(carries_receipt(MSG_TASK_RESULT) == true)) __t27_assert_fail("\n taskResult carries a receipt:\n carries_receipt(MSG_TASK_RESULT) = {any}\n", .{ carries_receipt(MSG_TASK_RESULT) }); + if (!(carries_receipt(MSG_TASK_ASSIGN) == false)) __t27_assert_fail("\n taskAssign carries no receipt:\n carries_receipt(MSG_TASK_ASSIGN) = {any}\n", .{ carries_receipt(MSG_TASK_ASSIGN) }); + if (!(carries_receipt(MSG_HEARTBEAT) == false)) __t27_assert_fail("\n heartbeat carries no receipt:\n carries_receipt(MSG_HEARTBEAT) = {any}\n", .{ carries_receipt(MSG_HEARTBEAT) }); } test "skill_is_goldenfloat" { - if (!(is_gf_skill(SKILL_GF16_MUL) == true)) @panic("GF16 mul is a hosted skill"); - if (!(is_gf_skill(SKILL_GF16_ADD) == true)) @panic("GF16 add is a hosted skill"); - if (!(is_gft_skill(SKILL_GFT16_MUL) == true)) @panic("GF-T16 mul is a hosted skill"); - if (!(is_gft_skill(SKILL_GFT8_ADD) == true)) @panic("GF-T8 add is a hosted skill"); - if (!(is_gft_skill(SKILL_GF16_MUL) == false)) @panic("binary GF16 is NOT a GF-T skill (family distinct)"); - if (!(is_gf_skill(SKILL_GFT16_MUL) == false)) @panic("GF-T16 is NOT a binary GF skill"); - if (!(skill_op(SKILL_GF16_MUL) == 0x11)) @panic("GF16 mul skill -> receipt op 0x11"); - if (!(skill_op(SKILL_GF16_ADD) == 0x10)) @panic("GF16 add skill -> receipt op 0x10"); - if (!(skill_op(SKILL_GFT16_MUL) == 0x11)) @panic("GF-T16 mul skill -> same op 0x11"); - if (!(skill_op(SKILL_GFT8_ADD) == 0x10)) @panic("GF-T8 add skill -> op 0x10"); - if (!(is_gf_skill(0xDEAD) == false)) @panic("a non-GF skill is rejected"); + if (!(is_gf_skill(SKILL_GF16_MUL) == true)) __t27_assert_fail("\n GF16 mul is a hosted skill:\n is_gf_skill(SKILL_GF16_MUL) = {any}\n", .{ is_gf_skill(SKILL_GF16_MUL) }); + if (!(is_gf_skill(SKILL_GF16_ADD) == true)) __t27_assert_fail("\n GF16 add is a hosted skill:\n is_gf_skill(SKILL_GF16_ADD) = {any}\n", .{ is_gf_skill(SKILL_GF16_ADD) }); + if (!(is_gft_skill(SKILL_GFT16_MUL) == true)) __t27_assert_fail("\n GF-T16 mul is a hosted skill:\n is_gft_skill(SKILL_GFT16_MUL) = {any}\n", .{ is_gft_skill(SKILL_GFT16_MUL) }); + if (!(is_gft_skill(SKILL_GFT8_ADD) == true)) __t27_assert_fail("\n GF-T8 add is a hosted skill:\n is_gft_skill(SKILL_GFT8_ADD) = {any}\n", .{ is_gft_skill(SKILL_GFT8_ADD) }); + if (!(is_gft_skill(SKILL_GF16_MUL) == false)) __t27_assert_fail("\n binary GF16 is NOT a GF-T skill (family distinct):\n is_gft_skill(SKILL_GF16_MUL) = {any}\n", .{ is_gft_skill(SKILL_GF16_MUL) }); + if (!(is_gf_skill(SKILL_GFT16_MUL) == false)) __t27_assert_fail("\n GF-T16 is NOT a binary GF skill:\n is_gf_skill(SKILL_GFT16_MUL) = {any}\n", .{ is_gf_skill(SKILL_GFT16_MUL) }); + if (!(skill_op(SKILL_GF16_MUL) == 0x11)) __t27_assert_fail("\n GF16 mul skill -> receipt op 0x11:\n skill_op(SKILL_GF16_MUL) = {any}\n", .{ skill_op(SKILL_GF16_MUL) }); + if (!(skill_op(SKILL_GF16_ADD) == 0x10)) __t27_assert_fail("\n GF16 add skill -> receipt op 0x10:\n skill_op(SKILL_GF16_ADD) = {any}\n", .{ skill_op(SKILL_GF16_ADD) }); + if (!(skill_op(SKILL_GFT16_MUL) == 0x11)) __t27_assert_fail("\n GF-T16 mul skill -> same op 0x11:\n skill_op(SKILL_GFT16_MUL) = {any}\n", .{ skill_op(SKILL_GFT16_MUL) }); + if (!(skill_op(SKILL_GFT8_ADD) == 0x10)) __t27_assert_fail("\n GF-T8 add skill -> op 0x10:\n skill_op(SKILL_GFT8_ADD) = {any}\n", .{ skill_op(SKILL_GFT8_ADD) }); + if (!(is_gf_skill(0xDEAD) == false)) __t27_assert_fail("\n a non-GF skill is rejected:\n is_gf_skill(0xDEAD) = {any}\n", .{ is_gf_skill(0xDEAD) }); } test "result_binds_to_assign" { - if (!(result_matches_assign(0x777, 0x777, 0x777) == true)) @panic("matching id + receipt binds"); - if (!(result_matches_assign(0x777, 0x888, 0x777) == false)) @panic("wrong result task_id rejected"); - if (!(result_matches_assign(0x777, 0x777, 0x999) == false)) @panic("receipt for another task rejected"); + if (!(result_matches_assign(0x777, 0x777, 0x777) == true)) __t27_assert_fail("\n matching id + receipt binds:\n result_matches_assign(0x777, 0x777, 0x777) = {any}\n", .{ result_matches_assign(0x777, 0x777, 0x777) }); + if (!(result_matches_assign(0x777, 0x888, 0x777) == false)) __t27_assert_fail("\n wrong result task_id rejected:\n result_matches_assign(0x777, 0x888, 0x777) = {any}\n", .{ result_matches_assign(0x777, 0x888, 0x777) }); + if (!(result_matches_assign(0x777, 0x777, 0x999) == false)) __t27_assert_fail("\n receipt for another task rejected:\n result_matches_assign(0x777, 0x777, 0x999) = {any}\n", .{ result_matches_assign(0x777, 0x777, 0x999) }); } test "op_must_match_the_skill" { - if (!(op_matches(SKILL_GF16_MUL, 0x11) == true)) @panic("mul skill + mul receipt op agree"); - if (!(op_matches(SKILL_GF16_MUL, 0x10) == false)) @panic("mul assignment must NOT accept an add receipt"); - if (!(op_matches(SKILL_GFT8_ADD, 0x10) == true)) @panic("GF-T8 add skill + add op agree"); - if (!(op_matches(SKILL_GFT8_ADD, 0x11) == false)) @panic("add assignment must NOT accept a mul receipt"); + if (!(op_matches(SKILL_GF16_MUL, 0x11) == true)) __t27_assert_fail("\n mul skill + mul receipt op agree:\n op_matches(SKILL_GF16_MUL, 0x11) = {any}\n", .{ op_matches(SKILL_GF16_MUL, 0x11) }); + if (!(op_matches(SKILL_GF16_MUL, 0x10) == false)) __t27_assert_fail("\n mul assignment must NOT accept an add receipt:\n op_matches(SKILL_GF16_MUL, 0x10) = {any}\n", .{ op_matches(SKILL_GF16_MUL, 0x10) }); + if (!(op_matches(SKILL_GFT8_ADD, 0x10) == true)) __t27_assert_fail("\n GF-T8 add skill + add op agree:\n op_matches(SKILL_GFT8_ADD, 0x10) = {any}\n", .{ op_matches(SKILL_GFT8_ADD, 0x10) }); + if (!(op_matches(SKILL_GFT8_ADD, 0x11) == false)) __t27_assert_fail("\n add assignment must NOT accept a mul receipt:\n op_matches(SKILL_GFT8_ADD, 0x11) = {any}\n", .{ op_matches(SKILL_GFT8_ADD, 0x11) }); } test "composed_binding_gate" { - if (!(result_binds_assign(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11) == true)) @panic("all four bind -> valid"); - if (!(result_binds_assign(0x777, 0x888, 0x777, SKILL_GF16_MUL, 0, 0x11) == false)) @panic("wrong result id -> reject"); - if (!(result_binds_assign(0x777, 0x777, 0x999, SKILL_GF16_MUL, 0, 0x11) == false)) @panic("receipt for another task -> reject"); - if (!(result_binds_assign(0x777, 0x777, 0x777, SKILL_GF16_MUL, 1, 0x11) == false)) @panic("GF-T receipt for a binary skill -> reject"); - if (!(result_binds_assign(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x10) == false)) @panic("add receipt for a mul assignment -> reject"); + if (!(result_binds_assign(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11) == true)) __t27_assert_fail("\n all four bind -> valid:\n result_binds_assign(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11) = {any}\n", .{ result_binds_assign(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11) }); + if (!(result_binds_assign(0x777, 0x888, 0x777, SKILL_GF16_MUL, 0, 0x11) == false)) __t27_assert_fail("\n wrong result id -> reject:\n result_binds_assign(0x777, 0x888, 0x777, SKILL_GF16_MUL, 0, 0x11) = {any}\n", .{ result_binds_assign(0x777, 0x888, 0x777, SKILL_GF16_MUL, 0, 0x11) }); + if (!(result_binds_assign(0x777, 0x777, 0x999, SKILL_GF16_MUL, 0, 0x11) == false)) __t27_assert_fail("\n receipt for another task -> reject:\n result_binds_assign(0x777, 0x777, 0x999, SKILL_GF16_MUL, 0, 0x11) = {any}\n", .{ result_binds_assign(0x777, 0x777, 0x999, SKILL_GF16_MUL, 0, 0x11) }); + if (!(result_binds_assign(0x777, 0x777, 0x777, SKILL_GF16_MUL, 1, 0x11) == false)) __t27_assert_fail("\n GF-T receipt for a binary skill -> reject:\n result_binds_assign(0x777, 0x777, 0x777, SKILL_GF16_MUL, 1, 0x11) = {any}\n", .{ result_binds_assign(0x777, 0x777, 0x777, SKILL_GF16_MUL, 1, 0x11) }); + if (!(result_binds_assign(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x10) == false)) __t27_assert_fail("\n add receipt for a mul assignment -> reject:\n result_binds_assign(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x10) = {any}\n", .{ result_binds_assign(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x10) }); } test "width_binds_the_exact_skill" { - if (!(skill_width(SKILL_GFT16_MUL) == 16)) @panic("GFT16 is width 16"); - if (!(skill_width(SKILL_GFT8_MUL) == 8)) @panic("GFT8 is width 8"); - if (!(skill_width(SKILL_GF16_MUL) == 16)) @panic("GF16 is width 16"); - if (!(result_binds_assign(0x777, 0x777, 0x777, SKILL_GFT16_MUL, 1, 0x11) == true)) @panic("GFT16 assignment + GFT-family mul receipt binds on family+op"); - if (!(result_binds_assign_sized(0x777, 0x777, 0x777, SKILL_GFT16_MUL, 1, 0x11, 8) == false)) @panic("GFT8 (width 8) receipt for a GFT16 assignment -> reject (precision downgrade closed)"); - if (!(result_binds_assign_sized(0x777, 0x777, 0x777, SKILL_GFT16_MUL, 1, 0x11, 16) == true)) @panic("matching width 16 -> binds"); - if (!(result_binds_assign_sized(0x777, 0x777, 0x777, SKILL_GFT8_MUL, 1, 0x11, 8) == true)) @panic("GFT8 assignment + width-8 receipt -> binds"); - if (!(result_binds_assign_sized(0x777, 0x777, 0x777, SKILL_GFT8_MUL, 1, 0x11, 16) == false)) @panic("a width-16 receipt for a GFT8 assignment -> reject"); + if (!(skill_width(SKILL_GFT16_MUL) == 16)) __t27_assert_fail("\n GFT16 is width 16:\n skill_width(SKILL_GFT16_MUL) = {any}\n", .{ skill_width(SKILL_GFT16_MUL) }); + if (!(skill_width(SKILL_GFT8_MUL) == 8)) __t27_assert_fail("\n GFT8 is width 8:\n skill_width(SKILL_GFT8_MUL) = {any}\n", .{ skill_width(SKILL_GFT8_MUL) }); + if (!(skill_width(SKILL_GF16_MUL) == 16)) __t27_assert_fail("\n GF16 is width 16:\n skill_width(SKILL_GF16_MUL) = {any}\n", .{ skill_width(SKILL_GF16_MUL) }); + if (!(result_binds_assign(0x777, 0x777, 0x777, SKILL_GFT16_MUL, 1, 0x11) == true)) __t27_assert_fail("\n GFT16 assignment + GFT-family mul receipt binds on family+op:\n result_binds_assign(0x777, 0x777, 0x777, SKILL_GFT16_MUL, 1, 0x11) = {any}\n", .{ result_binds_assign(0x777, 0x777, 0x777, SKILL_GFT16_MUL, 1, 0x11) }); + if (!(result_binds_assign_sized(0x777, 0x777, 0x777, SKILL_GFT16_MUL, 1, 0x11, 8) == false)) __t27_assert_fail("\n GFT8 (width 8) receipt for a GFT16 assignment -> reject (precision downgrade closed):\n result_binds_assign_sized(0x777, 0x777, 0x777, SKILL_GFT16_MUL, 1, 0x11, 8) = {any}\n", .{ result_binds_assign_sized(0x777, 0x777, 0x777, SKILL_GFT16_MUL, 1, 0x11, 8) }); + if (!(result_binds_assign_sized(0x777, 0x777, 0x777, SKILL_GFT16_MUL, 1, 0x11, 16) == true)) __t27_assert_fail("\n matching width 16 -> binds:\n result_binds_assign_sized(0x777, 0x777, 0x777, SKILL_GFT16_MUL, 1, 0x11, 16) = {any}\n", .{ result_binds_assign_sized(0x777, 0x777, 0x777, SKILL_GFT16_MUL, 1, 0x11, 16) }); + if (!(result_binds_assign_sized(0x777, 0x777, 0x777, SKILL_GFT8_MUL, 1, 0x11, 8) == true)) __t27_assert_fail("\n GFT8 assignment + width-8 receipt -> binds:\n result_binds_assign_sized(0x777, 0x777, 0x777, SKILL_GFT8_MUL, 1, 0x11, 8) = {any}\n", .{ result_binds_assign_sized(0x777, 0x777, 0x777, SKILL_GFT8_MUL, 1, 0x11, 8) }); + if (!(result_binds_assign_sized(0x777, 0x777, 0x777, SKILL_GFT8_MUL, 1, 0x11, 16) == false)) __t27_assert_fail("\n a width-16 receipt for a GFT8 assignment -> reject:\n result_binds_assign_sized(0x777, 0x777, 0x777, SKILL_GFT8_MUL, 1, 0x11, 16) = {any}\n", .{ result_binds_assign_sized(0x777, 0x777, 0x777, SKILL_GFT8_MUL, 1, 0x11, 16) }); } test "admit_result_gate" { - if (!(admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50) == true)) @panic("bound + fresh + admissible -> accept"); - if (!(admit_result(0x777, 0x100, 0x100, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50) == false)) @panic("stale (id == watermark) -> reject"); - if (!(admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 40, 50) == false)) @panic("executor below the reputation floor -> reject"); - if (!(admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x10, 0x100, 100, 50) == false)) @panic("wrong op (add receipt) -> reject"); - if (!(admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, 1, 0x11, 0x100, 100, 50) == false)) @panic("cross-family receipt -> reject"); - if (!(admit_result(0x777, 0x888, 0x888, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50) == false)) @panic("wrong task id -> reject"); + if (!(admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50) == true)) __t27_assert_fail("\n bound + fresh + admissible -> accept:\n admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50) = {any}\n", .{ admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50) }); + if (!(admit_result(0x777, 0x100, 0x100, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50) == false)) __t27_assert_fail("\n stale (id == watermark) -> reject:\n admit_result(0x777, 0x100, 0x100, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50) = {any}\n", .{ admit_result(0x777, 0x100, 0x100, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50) }); + if (!(admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 40, 50) == false)) __t27_assert_fail("\n executor below the reputation floor -> reject:\n admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 40, 50) = {any}\n", .{ admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 40, 50) }); + if (!(admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x10, 0x100, 100, 50) == false)) __t27_assert_fail("\n wrong op (add receipt) -> reject:\n admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x10, 0x100, 100, 50) = {any}\n", .{ admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x10, 0x100, 100, 50) }); + if (!(admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, 1, 0x11, 0x100, 100, 50) == false)) __t27_assert_fail("\n cross-family receipt -> reject:\n admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, 1, 0x11, 0x100, 100, 50) = {any}\n", .{ admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, 1, 0x11, 0x100, 100, 50) }); + if (!(admit_result(0x777, 0x888, 0x888, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50) == false)) __t27_assert_fail("\n wrong task id -> reject:\n admit_result(0x777, 0x888, 0x888, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50) = {any}\n", .{ admit_result(0x777, 0x888, 0x888, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50) }); } test "admit_result_bonded_gate" { - if (!(admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000) == true)) @panic("bond 2000 covers 20% of 10000 -> admitted"); - if (!(admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 1999, 10000, 2000) == false)) @panic("bond 1999 is one short of the 2000 required -> rejected"); - if (!(admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 1, 10000, 2000) == false)) @panic("a nominal bond does NOT cover 10000 outstanding -> rejected"); - if (!(admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 5000, 0, 2000) == true)) @panic("no outstanding risk needs no bond -> admitted"); - if (!(admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x10, 0x100, 100, 50, 999999, 10000, 2000) == false)) @panic("over-collateralized but wrong op -> still rejected"); - if (!(admit_result_bonded(0x777, 0x100, 0x100, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 999999, 10000, 2000) == false)) @panic("over-collateralized but stale -> still rejected"); + if (!(admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000) == true)) __t27_assert_fail("\n bond 2000 covers 20% of 10000 -> admitted:\n admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000) = {any}\n", .{ admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000) }); + if (!(admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 1999, 10000, 2000) == false)) __t27_assert_fail("\n bond 1999 is one short of the 2000 required -> rejected:\n admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 1999, 10000, 2000) = {any}\n", .{ admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 1999, 10000, 2000) }); + if (!(admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 1, 10000, 2000) == false)) __t27_assert_fail("\n a nominal bond does NOT cover 10000 outstanding -> rejected:\n admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 1, 10000, 2000) = {any}\n", .{ admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 1, 10000, 2000) }); + if (!(admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 5000, 0, 2000) == true)) __t27_assert_fail("\n no outstanding risk needs no bond -> admitted:\n admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 5000, 0, 2000) = {any}\n", .{ admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 5000, 0, 2000) }); + if (!(admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x10, 0x100, 100, 50, 999999, 10000, 2000) == false)) __t27_assert_fail("\n over-collateralized but wrong op -> still rejected:\n admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x10, 0x100, 100, 50, 999999, 10000, 2000) = {any}\n", .{ admit_result_bonded(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x10, 0x100, 100, 50, 999999, 10000, 2000) }); + if (!(admit_result_bonded(0x777, 0x100, 0x100, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 999999, 10000, 2000) == false)) __t27_assert_fail("\n over-collateralized but stale -> still rejected:\n admit_result_bonded(0x777, 0x100, 0x100, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 999999, 10000, 2000) = {any}\n", .{ admit_result_bonded(0x777, 0x100, 0x100, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 999999, 10000, 2000) }); } test "freshness_blocks_replay" { - if (!(is_fresh(0x10, 0x0F) == true)) @panic("newer task_id is fresh"); - if (!(is_fresh(0x0F, 0x0F) == false)) @panic("replayed task_id rejected"); - if (!(is_fresh(0x0E, 0x0F) == false)) @panic("older task_id rejected"); - if (!(next_watermark(0x10, 0x0F) == 0x10)) @panic("watermark advances on fresh"); - if (!(next_watermark(0x0E, 0x0F) == 0x0F)) @panic("watermark holds on stale"); + if (!(is_fresh(0x10, 0x0F) == true)) __t27_assert_fail("\n newer task_id is fresh:\n is_fresh(0x10, 0x0F) = {any}\n", .{ is_fresh(0x10, 0x0F) }); + if (!(is_fresh(0x0F, 0x0F) == false)) __t27_assert_fail("\n replayed task_id rejected:\n is_fresh(0x0F, 0x0F) = {any}\n", .{ is_fresh(0x0F, 0x0F) }); + if (!(is_fresh(0x0E, 0x0F) == false)) __t27_assert_fail("\n older task_id rejected:\n is_fresh(0x0E, 0x0F) = {any}\n", .{ is_fresh(0x0E, 0x0F) }); + if (!(next_watermark(0x10, 0x0F) == 0x10)) __t27_assert_fail("\n watermark advances on fresh:\n next_watermark(0x10, 0x0F) = {any}\n", .{ next_watermark(0x10, 0x0F) }); + if (!(next_watermark(0x0E, 0x0F) == 0x0F)) __t27_assert_fail("\n watermark holds on stale:\n next_watermark(0x0E, 0x0F) = {any}\n", .{ next_watermark(0x0E, 0x0F) }); } test "hosted_skill_set" { - if (!(is_hosted_skill(SKILL_GF16_MUL) == 1)) @panic("GF16 mul is hosted"); - if (!(is_hosted_skill(SKILL_GFT8_ADD) == 1)) @panic("GF-T8 add is hosted"); - if (!(is_hosted_skill(0xA412) == 0)) @panic("a GF-T4-looking id (0xA412) is NOT hosted"); - if (!(is_hosted_skill(0xA512) == 0)) @panic("a GF-T32-looking id with an unknown op is NOT hosted"); - if (!(is_hosted_skill(0xDEAD) == 0)) @panic("garbage skill is NOT hosted"); + if (!(is_hosted_skill(SKILL_GF16_MUL) == 1)) __t27_assert_fail("\n GF16 mul is hosted:\n is_hosted_skill(SKILL_GF16_MUL) = {any}\n", .{ is_hosted_skill(SKILL_GF16_MUL) }); + if (!(is_hosted_skill(SKILL_GFT8_ADD) == 1)) __t27_assert_fail("\n GF-T8 add is hosted:\n is_hosted_skill(SKILL_GFT8_ADD) = {any}\n", .{ is_hosted_skill(SKILL_GFT8_ADD) }); + if (!(is_hosted_skill(0xA412) == 0)) __t27_assert_fail("\n a GF-T4-looking id (0xA412) is NOT hosted:\n is_hosted_skill(0xA412) = {any}\n", .{ is_hosted_skill(0xA412) }); + if (!(is_hosted_skill(0xA512) == 0)) __t27_assert_fail("\n a GF-T32-looking id with an unknown op is NOT hosted:\n is_hosted_skill(0xA512) = {any}\n", .{ is_hosted_skill(0xA512) }); + if (!(is_hosted_skill(0xDEAD) == 0)) __t27_assert_fail("\n garbage skill is NOT hosted:\n is_hosted_skill(0xDEAD) = {any}\n", .{ is_hosted_skill(0xDEAD) }); } test "strict_family_rejects_unhosted" { - if (!(skill_family(0xA412) == FMT_GF_BINARY)) @panic("skill_family WRONGLY defaults the GF-T4-looking id to binary"); - if (!(family_matches(0xA412, FMT_GF_BINARY) == true)) @panic("the bare gate would accept a binary receipt for it (the bug)"); - if (!(family_matches_strict(0xA412, FMT_GF_BINARY) == false)) @panic("strict rejects the unhosted skill -> no wrong-family receipt"); - if (!(family_matches_strict(SKILL_GFT16_MUL, FMT_GFT) == true)) @panic("hosted GF-T skill + GF-T receipt matches"); - if (!(family_matches_strict(SKILL_GF16_MUL, FMT_GF_BINARY) == true)) @panic("hosted binary skill + binary receipt matches"); - if (!(family_matches_strict(SKILL_GFT16_MUL, FMT_GF_BINARY) == false)) @panic("hosted GF-T skill + binary receipt rejected"); + if (!(skill_family(0xA412) == FMT_GF_BINARY)) __t27_assert_fail("\n skill_family WRONGLY defaults the GF-T4-looking id to binary:\n skill_family(0xA412) = {any}\n FMT_GF_BINARY = {any}\n", .{ skill_family(0xA412), FMT_GF_BINARY }); + if (!(family_matches(0xA412, FMT_GF_BINARY) == true)) __t27_assert_fail("\n the bare gate would accept a binary receipt for it (the bug):\n family_matches(0xA412, FMT_GF_BINARY) = {any}\n", .{ family_matches(0xA412, FMT_GF_BINARY) }); + if (!(family_matches_strict(0xA412, FMT_GF_BINARY) == false)) __t27_assert_fail("\n strict rejects the unhosted skill -> no wrong-family receipt:\n family_matches_strict(0xA412, FMT_GF_BINARY) = {any}\n", .{ family_matches_strict(0xA412, FMT_GF_BINARY) }); + if (!(family_matches_strict(SKILL_GFT16_MUL, FMT_GFT) == true)) __t27_assert_fail("\n hosted GF-T skill + GF-T receipt matches:\n family_matches_strict(SKILL_GFT16_MUL, FMT_GFT) = {any}\n", .{ family_matches_strict(SKILL_GFT16_MUL, FMT_GFT) }); + if (!(family_matches_strict(SKILL_GF16_MUL, FMT_GF_BINARY) == true)) __t27_assert_fail("\n hosted binary skill + binary receipt matches:\n family_matches_strict(SKILL_GF16_MUL, FMT_GF_BINARY) = {any}\n", .{ family_matches_strict(SKILL_GF16_MUL, FMT_GF_BINARY) }); + if (!(family_matches_strict(SKILL_GFT16_MUL, FMT_GF_BINARY) == false)) __t27_assert_fail("\n hosted GF-T skill + binary receipt rejected:\n family_matches_strict(SKILL_GFT16_MUL, FMT_GF_BINARY) = {any}\n", .{ family_matches_strict(SKILL_GFT16_MUL, FMT_GF_BINARY) }); } test "ingress_rejects_unhosted_skill" { - if (!(result_binds_assign(0x777, 0x777, 0x777, 0xA412, FMT_GF_BINARY, 0x12) == false)) @panic("unhosted skill -> result does not bind"); - if (!(result_binds_assign(0x777, 0x777, 0x777, SKILL_GF16_MUL, FMT_GF_BINARY, 0x11) == true)) @panic("hosted skill still binds"); - if (!(admit_result(0x777, 0x777, 0x777, 0xA412, FMT_GF_BINARY, 0x12, 0x100, 100, 50) == false)) @panic("admit_result rejects an unhosted skill"); - if (!(admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, FMT_GF_BINARY, 0x11, 0x100, 100, 50) == true)) @panic("admit_result still admits a hosted skill"); + if (!(result_binds_assign(0x777, 0x777, 0x777, 0xA412, FMT_GF_BINARY, 0x12) == false)) __t27_assert_fail("\n unhosted skill -> result does not bind:\n result_binds_assign(0x777, 0x777, 0x777, 0xA412, FMT_GF_BINARY, 0x12) = {any}\n", .{ result_binds_assign(0x777, 0x777, 0x777, 0xA412, FMT_GF_BINARY, 0x12) }); + if (!(result_binds_assign(0x777, 0x777, 0x777, SKILL_GF16_MUL, FMT_GF_BINARY, 0x11) == true)) __t27_assert_fail("\n hosted skill still binds:\n result_binds_assign(0x777, 0x777, 0x777, SKILL_GF16_MUL, FMT_GF_BINARY, 0x11) = {any}\n", .{ result_binds_assign(0x777, 0x777, 0x777, SKILL_GF16_MUL, FMT_GF_BINARY, 0x11) }); + if (!(admit_result(0x777, 0x777, 0x777, 0xA412, FMT_GF_BINARY, 0x12, 0x100, 100, 50) == false)) __t27_assert_fail("\n admit_result rejects an unhosted skill:\n admit_result(0x777, 0x777, 0x777, 0xA412, FMT_GF_BINARY, 0x12, 0x100, 100, 50) = {any}\n", .{ admit_result(0x777, 0x777, 0x777, 0xA412, FMT_GF_BINARY, 0x12, 0x100, 100, 50) }); + if (!(admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, FMT_GF_BINARY, 0x11, 0x100, 100, 50) == true)) __t27_assert_fail("\n admit_result still admits a hosted skill:\n admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, FMT_GF_BINARY, 0x11, 0x100, 100, 50) = {any}\n", .{ admit_result(0x777, 0x777, 0x777, SKILL_GF16_MUL, FMT_GF_BINARY, 0x11, 0x100, 100, 50) }); } test "watermark_advances_only_when_settled" { - if (!(next_watermark_settled(0x20, 0x10, 1) == 0x20)) @panic("settled + fresh -> advance"); - if (!(next_watermark_settled(0x0E, 0x10, 1) == 0x10)) @panic("settled + stale -> hold"); - if (!(next_watermark_settled(0xFFFFFFFF, 0x10, 0) == 0x10)) @panic("unsettled high id does NOT jump the watermark"); + if (!(next_watermark_settled(0x20, 0x10, 1) == 0x20)) __t27_assert_fail("\n settled + fresh -> advance:\n next_watermark_settled(0x20, 0x10, 1) = {any}\n", .{ next_watermark_settled(0x20, 0x10, 1) }); + if (!(next_watermark_settled(0x0E, 0x10, 1) == 0x10)) __t27_assert_fail("\n settled + stale -> hold:\n next_watermark_settled(0x0E, 0x10, 1) = {any}\n", .{ next_watermark_settled(0x0E, 0x10, 1) }); + if (!(next_watermark_settled(0xFFFFFFFF, 0x10, 0) == 0x10)) __t27_assert_fail("\n unsettled high id does NOT jump the watermark:\n next_watermark_settled(0xFFFFFFFF, 0x10, 0) = {any}\n", .{ next_watermark_settled(0xFFFFFFFF, 0x10, 0) }); const w = next_watermark_settled(0xFFFFFFFF, 0x10, 0); - if (!(is_fresh(0x11, w) == true)) @panic("epoch 0x11 stays fresh -- the griefer could not block it"); - if (!(next_watermark_settled(0x20, 0x10, 1) == next_watermark(0x20, 0x10))) @panic("settled advance == bare watermark"); + if (!(is_fresh(0x11, w) == true)) __t27_assert_fail("\n epoch 0x11 stays fresh -- the griefer could not block it:\n is_fresh(0x11, w) = {any}\n", .{ is_fresh(0x11, w) }); + if (!(next_watermark_settled(0x20, 0x10, 1) == next_watermark(0x20, 0x10))) __t27_assert_fail("\n settled advance == bare watermark:\n next_watermark_settled(0x20, 0x10, 1) = {any}\n next_watermark(0x20, 0x10) = {any}\n", .{ next_watermark_settled(0x20, 0x10, 1), next_watermark(0x20, 0x10) }); } test "executor_binds_the_assignment" { - if (!(executor_binds_assign(0xE1, 0xE1) == true)) @panic("committed executor == assigned -> binds"); - if (!(executor_binds_assign(0xE1, 0xE2) == false)) @panic("a different executor does not bind"); - if (!(admit_result_authentic(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000, 0xE1, 0xE1) == true)) @panic("assignee's own result -> accept"); - if (!(admit_result_authentic(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000, 0xE1, 0xE2) == false)) @panic("another node's result for the assigned task -> reject (front-run closed)"); - if (!(admit_result_authentic(0x777, 0x100, 0x100, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000, 0xE1, 0xE1) == false)) @panic("correct executor but stale -> still reject"); - if (!(admit_result_authentic(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 1999, 10000, 2000, 0xE1, 0xE1) == false)) @panic("correct executor but under-collateralized -> still reject"); + if (!(executor_binds_assign(0xE1, 0xE1) == true)) __t27_assert_fail("\n committed executor == assigned -> binds:\n executor_binds_assign(0xE1, 0xE1) = {any}\n", .{ executor_binds_assign(0xE1, 0xE1) }); + if (!(executor_binds_assign(0xE1, 0xE2) == false)) __t27_assert_fail("\n a different executor does not bind:\n executor_binds_assign(0xE1, 0xE2) = {any}\n", .{ executor_binds_assign(0xE1, 0xE2) }); + if (!(admit_result_authentic(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000, 0xE1, 0xE1) == true)) __t27_assert_fail("\n assignee's own result -> accept:\n admit_result_authentic(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000, 0xE1, 0xE1) = {any}\n", .{ admit_result_authentic(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000, 0xE1, 0xE1) }); + if (!(admit_result_authentic(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000, 0xE1, 0xE2) == false)) __t27_assert_fail("\n another node's result for the assigned task -> reject (front-run closed):\n admit_result_authentic(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000, 0xE1, 0xE2) = {any}\n", .{ admit_result_authentic(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000, 0xE1, 0xE2) }); + if (!(admit_result_authentic(0x777, 0x100, 0x100, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000, 0xE1, 0xE1) == false)) __t27_assert_fail("\n correct executor but stale -> still reject:\n admit_result_authentic(0x777, 0x100, 0x100, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000, 0xE1, 0xE1) = {any}\n", .{ admit_result_authentic(0x777, 0x100, 0x100, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000, 0xE1, 0xE1) }); + if (!(admit_result_authentic(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 1999, 10000, 2000, 0xE1, 0xE1) == false)) __t27_assert_fail("\n correct executor but under-collateralized -> still reject:\n admit_result_authentic(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 1999, 10000, 2000, 0xE1, 0xE1) = {any}\n", .{ admit_result_authentic(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 1999, 10000, 2000, 0xE1, 0xE1) }); } test "signature_authenticates_the_executor" { - if (!(executor_authentic(0xE1, 0xE1, 1, 0xE1) == true)) @panic("assigned + signed + key hashes to executor -> authentic"); - if (!(executor_authentic(0xE1, 0xE1, 0, 0xE1) == false)) @panic("no valid signature (forger without the key) -> not authentic"); - if (!(executor_authentic(0xE1, 0xE1, 1, 0xBB) == false)) @panic("valid sig but signer key hashes to 0xBB != committed 0xE1 -> not authentic"); - if (!(executor_authentic(0xE1, 0xE2, 1, 0xE2) == false)) @panic("a different (even authentic) executor is not the assignee"); + if (!(executor_authentic(0xE1, 0xE1, 1, 0xE1) == true)) __t27_assert_fail("\n assigned + signed + key hashes to executor -> authentic:\n executor_authentic(0xE1, 0xE1, 1, 0xE1) = {any}\n", .{ executor_authentic(0xE1, 0xE1, 1, 0xE1) }); + if (!(executor_authentic(0xE1, 0xE1, 0, 0xE1) == false)) __t27_assert_fail("\n no valid signature (forger without the key) -> not authentic:\n executor_authentic(0xE1, 0xE1, 0, 0xE1) = {any}\n", .{ executor_authentic(0xE1, 0xE1, 0, 0xE1) }); + if (!(executor_authentic(0xE1, 0xE1, 1, 0xBB) == false)) __t27_assert_fail("\n valid sig but signer key hashes to 0xBB != committed 0xE1 -> not authentic:\n executor_authentic(0xE1, 0xE1, 1, 0xBB) = {any}\n", .{ executor_authentic(0xE1, 0xE1, 1, 0xBB) }); + if (!(executor_authentic(0xE1, 0xE2, 1, 0xE2) == false)) __t27_assert_fail("\n a different (even authentic) executor is not the assignee:\n executor_authentic(0xE1, 0xE2, 1, 0xE2) = {any}\n", .{ executor_authentic(0xE1, 0xE2, 1, 0xE2) }); if (!(admit_result_signed(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000, 0xE1, 0xE1, 1, 0xE1) == true)) @panic("authentic assignee result -> accept"); if (!(admit_result_signed(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000, 0xE1, 0xE1, 0, 0xE1) == false)) @panic("unsigned forge naming the assignee -> reject (the hole closed)"); if (!(admit_result_signed(0x777, 0x777, 0x777, SKILL_GF16_MUL, 0, 0x11, 0x100, 100, 50, 2000, 10000, 2000, 0xE1, 0xE1, 1, 0xBB) == false)) @panic("signed by a key that is not the committed executor -> reject"); diff --git a/gen/zig/tri_a2a_card.zig b/gen/zig/tri_a2a_card.zig index c3755b2e..f4af5d3f 100644 --- a/gen/zig/tri_a2a_card.zig +++ b/gen/zig/tri_a2a_card.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const FMT_GF_BINARY: u32 = 0; @@ -117,75 +125,75 @@ fn can_serve_skill_op(card: u32, skill: u32) bool { } test "gft16_host_routing" { const c = make_card(family_bit(FMT_GFT), 16); - if (!(can_serve(c, FMT_GFT, 16) == true)) @panic("GF-T16 host serves a GF-T16 task"); - if (!(can_serve(c, FMT_GF_BINARY, 16) == false)) @panic("GF-T16 host rejects a binary GF16 task (family)"); - if (!(can_serve(c, FMT_GFT, 8) == false)) @panic("GF-T16 host rejects a GF-T8 task (width)"); + if (!(can_serve(c, FMT_GFT, 16) == true)) __t27_assert_fail("\n GF-T16 host serves a GF-T16 task:\n can_serve(c, FMT_GFT, 16) = {any}\n", .{ can_serve(c, FMT_GFT, 16) }); + if (!(can_serve(c, FMT_GF_BINARY, 16) == false)) __t27_assert_fail("\n GF-T16 host rejects a binary GF16 task (family):\n can_serve(c, FMT_GF_BINARY, 16) = {any}\n", .{ can_serve(c, FMT_GF_BINARY, 16) }); + if (!(can_serve(c, FMT_GFT, 8) == false)) __t27_assert_fail("\n GF-T16 host rejects a GF-T8 task (width):\n can_serve(c, FMT_GFT, 8) = {any}\n", .{ can_serve(c, FMT_GFT, 8) }); } test "binary_multiwidth_host" { const c = make_card(family_bit(FMT_GF_BINARY), 16 | 32); - if (!(can_serve(c, FMT_GF_BINARY, 16) == true)) @panic("serves GF16"); - if (!(can_serve(c, FMT_GF_BINARY, 32) == true)) @panic("serves GF32"); - if (!(can_serve(c, FMT_GF_BINARY, 8) == false)) @panic("does not serve GF8 (not advertised)"); - if (!(can_serve(c, FMT_GFT, 16) == false)) @panic("does not serve any GF-T"); + if (!(can_serve(c, FMT_GF_BINARY, 16) == true)) __t27_assert_fail("\n serves GF16:\n can_serve(c, FMT_GF_BINARY, 16) = {any}\n", .{ can_serve(c, FMT_GF_BINARY, 16) }); + if (!(can_serve(c, FMT_GF_BINARY, 32) == true)) __t27_assert_fail("\n serves GF32:\n can_serve(c, FMT_GF_BINARY, 32) = {any}\n", .{ can_serve(c, FMT_GF_BINARY, 32) }); + if (!(can_serve(c, FMT_GF_BINARY, 8) == false)) __t27_assert_fail("\n does not serve GF8 (not advertised):\n can_serve(c, FMT_GF_BINARY, 8) = {any}\n", .{ can_serve(c, FMT_GF_BINARY, 8) }); + if (!(can_serve(c, FMT_GFT, 16) == false)) __t27_assert_fail("\n does not serve any GF-T:\n can_serve(c, FMT_GFT, 16) = {any}\n", .{ can_serve(c, FMT_GFT, 16) }); } test "dual_family_host" { const c = make_card(family_bit(FMT_GF_BINARY) | family_bit(FMT_GFT), 8 | 16); - if (!(can_serve(c, FMT_GF_BINARY, 16) == true)) @panic("GF16 ok"); - if (!(can_serve(c, FMT_GFT, 16) == true)) @panic("GF-T16 ok"); - if (!(can_serve(c, FMT_GFT, 8) == true)) @panic("GF-T8 ok"); - if (!(can_serve(c, FMT_GF_BINARY, 32) == false)) @panic("GF32 not advertised"); + if (!(can_serve(c, FMT_GF_BINARY, 16) == true)) __t27_assert_fail("\n GF16 ok:\n can_serve(c, FMT_GF_BINARY, 16) = {any}\n", .{ can_serve(c, FMT_GF_BINARY, 16) }); + if (!(can_serve(c, FMT_GFT, 16) == true)) __t27_assert_fail("\n GF-T16 ok:\n can_serve(c, FMT_GFT, 16) = {any}\n", .{ can_serve(c, FMT_GFT, 16) }); + if (!(can_serve(c, FMT_GFT, 8) == true)) __t27_assert_fail("\n GF-T8 ok:\n can_serve(c, FMT_GFT, 8) = {any}\n", .{ can_serve(c, FMT_GFT, 8) }); + if (!(can_serve(c, FMT_GF_BINARY, 32) == false)) __t27_assert_fail("\n GF32 not advertised:\n can_serve(c, FMT_GF_BINARY, 32) = {any}\n", .{ can_serve(c, FMT_GF_BINARY, 32) }); } test "route_by_skill_id" { const gft = make_card(family_bit(FMT_GFT), 8 | 16); - if (!(can_serve_skill(gft, 0xA611) == true)) @panic("GF-T16 mul routes to a GF-T host"); - if (!(can_serve_skill(gft, 0xA811) == true)) @panic("GF-T8 mul routes to a GF-T host"); - if (!(can_serve_skill(gft, 0x1611) == false)) @panic("binary GF16 mul does NOT route to a GF-T-only host"); + if (!(can_serve_skill(gft, 0xA611) == true)) __t27_assert_fail("\n GF-T16 mul routes to a GF-T host:\n can_serve_skill(gft, 0xA611) = {any}\n", .{ can_serve_skill(gft, 0xA611) }); + if (!(can_serve_skill(gft, 0xA811) == true)) __t27_assert_fail("\n GF-T8 mul routes to a GF-T host:\n can_serve_skill(gft, 0xA811) = {any}\n", .{ can_serve_skill(gft, 0xA811) }); + if (!(can_serve_skill(gft, 0x1611) == false)) __t27_assert_fail("\n binary GF16 mul does NOT route to a GF-T-only host:\n can_serve_skill(gft, 0x1611) = {any}\n", .{ can_serve_skill(gft, 0x1611) }); } test "gft_ladder_card_routing" { - if (!(skill_card_family(0xA411) == FMT_GFT)) @panic("GF-T4 is FMT_GFT"); - if (!(skill_card_width(0xA411) == 4)) @panic("GF-T4 width 4"); - if (!(skill_card_family(0xA511) == FMT_GFT)) @panic("GF-T32 is FMT_GFT (was mis-classed binary)"); - if (!(skill_card_width(0xA511) == 32)) @panic("GF-T32 width 32 (was mis-routed to 16)"); - if (!(skill_card_family(0xA311) == FMT_GFT)) @panic("GF-T64 is FMT_GFT"); - if (!(skill_card_width(0xA311) == 64)) @panic("GF-T64 width 64"); - if (!(skill_card_width(0xA211) == 128)) @panic("GF-T128 width 128"); + if (!(skill_card_family(0xA411) == FMT_GFT)) __t27_assert_fail("\n GF-T4 is FMT_GFT:\n skill_card_family(0xA411) = {any}\n FMT_GFT = {any}\n", .{ skill_card_family(0xA411), FMT_GFT }); + if (!(skill_card_width(0xA411) == 4)) __t27_assert_fail("\n GF-T4 width 4:\n skill_card_width(0xA411) = {any}\n", .{ skill_card_width(0xA411) }); + if (!(skill_card_family(0xA511) == FMT_GFT)) __t27_assert_fail("\n GF-T32 is FMT_GFT (was mis-classed binary):\n skill_card_family(0xA511) = {any}\n FMT_GFT = {any}\n", .{ skill_card_family(0xA511), FMT_GFT }); + if (!(skill_card_width(0xA511) == 32)) __t27_assert_fail("\n GF-T32 width 32 (was mis-routed to 16):\n skill_card_width(0xA511) = {any}\n", .{ skill_card_width(0xA511) }); + if (!(skill_card_family(0xA311) == FMT_GFT)) __t27_assert_fail("\n GF-T64 is FMT_GFT:\n skill_card_family(0xA311) = {any}\n FMT_GFT = {any}\n", .{ skill_card_family(0xA311), FMT_GFT }); + if (!(skill_card_width(0xA311) == 64)) __t27_assert_fail("\n GF-T64 width 64:\n skill_card_width(0xA311) = {any}\n", .{ skill_card_width(0xA311) }); + if (!(skill_card_width(0xA211) == 128)) __t27_assert_fail("\n GF-T128 width 128:\n skill_card_width(0xA211) = {any}\n", .{ skill_card_width(0xA211) }); const full = make_card(family_bit(FMT_GFT), ((((4 | 8) | 16) | 32) | 64) | 128); - if (!(can_serve_skill(full, 0xA411) == true)) @panic("full-ladder host serves GF-T4"); - if (!(can_serve_skill(full, 0xA511) == true)) @panic("full-ladder host serves GF-T32"); - if (!(can_serve_skill(full, 0xA311) == true)) @panic("full-ladder host serves GF-T64"); - if (!(can_serve_skill(full, 0xA211) == true)) @panic("full-ladder host serves GF-T128"); + if (!(can_serve_skill(full, 0xA411) == true)) __t27_assert_fail("\n full-ladder host serves GF-T4:\n can_serve_skill(full, 0xA411) = {any}\n", .{ can_serve_skill(full, 0xA411) }); + if (!(can_serve_skill(full, 0xA511) == true)) __t27_assert_fail("\n full-ladder host serves GF-T32:\n can_serve_skill(full, 0xA511) = {any}\n", .{ can_serve_skill(full, 0xA511) }); + if (!(can_serve_skill(full, 0xA311) == true)) __t27_assert_fail("\n full-ladder host serves GF-T64:\n can_serve_skill(full, 0xA311) = {any}\n", .{ can_serve_skill(full, 0xA311) }); + if (!(can_serve_skill(full, 0xA211) == true)) __t27_assert_fail("\n full-ladder host serves GF-T128:\n can_serve_skill(full, 0xA211) = {any}\n", .{ can_serve_skill(full, 0xA211) }); const gft16 = make_card(family_bit(FMT_GFT), 16); - if (!(can_serve_skill(gft16, 0xA311) == false)) @panic("a GF-T16-only host rejects a GF-T64 task"); - if (!(can_serve_skill(gft16, 0xA611) == true)) @panic("but still serves GF-T16"); + if (!(can_serve_skill(gft16, 0xA311) == false)) __t27_assert_fail("\n a GF-T16-only host rejects a GF-T64 task:\n can_serve_skill(gft16, 0xA311) = {any}\n", .{ can_serve_skill(gft16, 0xA311) }); + if (!(can_serve_skill(gft16, 0xA611) == true)) __t27_assert_fail("\n but still serves GF-T16:\n can_serve_skill(gft16, 0xA611) = {any}\n", .{ can_serve_skill(gft16, 0xA611) }); const bin16 = make_card(family_bit(FMT_GF_BINARY), 16 | 64); - if (!(can_serve_skill(bin16, 0xA311) == false)) @panic("a binary-GF host does NOT serve a GF-T64 task (bug fixed)"); - if (!(can_serve_skill(bin16, 0x1611) == true)) @panic("binary GF16 still serves its own binary skill"); + if (!(can_serve_skill(bin16, 0xA311) == false)) __t27_assert_fail("\n a binary-GF host does NOT serve a GF-T64 task (bug fixed):\n can_serve_skill(bin16, 0xA311) = {any}\n", .{ can_serve_skill(bin16, 0xA311) }); + if (!(can_serve_skill(bin16, 0x1611) == true)) __t27_assert_fail("\n binary GF16 still serves its own binary skill:\n can_serve_skill(bin16, 0x1611) = {any}\n", .{ can_serve_skill(bin16, 0x1611) }); } test "op_advertisement" { const mulonly: u32 = make_card_ops(family_bit(FMT_GFT), 16, op_bit(GF_OP_MUL)); - if (!(hosts_op(mulonly, GF_OP_MUL) == true)) @panic("hosts mul"); - if (!(hosts_op(mulonly, GF_OP_ADD) == false)) @panic("does NOT host add"); - if (!(can_serve_op(mulonly, FMT_GFT, 16, GF_OP_MUL) == true)) @panic("GF-T16 mul served"); - if (!(can_serve_op(mulonly, FMT_GFT, 16, GF_OP_ADD) == false)) @panic("GF-T16 add NOT served (op)"); - if (!(can_serve_op(mulonly, FMT_GF_BINARY, 16, GF_OP_MUL) == false)) @panic("wrong family still rejected"); + if (!(hosts_op(mulonly, GF_OP_MUL) == true)) __t27_assert_fail("\n hosts mul:\n hosts_op(mulonly, GF_OP_MUL) = {any}\n", .{ hosts_op(mulonly, GF_OP_MUL) }); + if (!(hosts_op(mulonly, GF_OP_ADD) == false)) __t27_assert_fail("\n does NOT host add:\n hosts_op(mulonly, GF_OP_ADD) = {any}\n", .{ hosts_op(mulonly, GF_OP_ADD) }); + if (!(can_serve_op(mulonly, FMT_GFT, 16, GF_OP_MUL) == true)) __t27_assert_fail("\n GF-T16 mul served:\n can_serve_op(mulonly, FMT_GFT, 16, GF_OP_MUL) = {any}\n", .{ can_serve_op(mulonly, FMT_GFT, 16, GF_OP_MUL) }); + if (!(can_serve_op(mulonly, FMT_GFT, 16, GF_OP_ADD) == false)) __t27_assert_fail("\n GF-T16 add NOT served (op):\n can_serve_op(mulonly, FMT_GFT, 16, GF_OP_ADD) = {any}\n", .{ can_serve_op(mulonly, FMT_GFT, 16, GF_OP_ADD) }); + if (!(can_serve_op(mulonly, FMT_GF_BINARY, 16, GF_OP_MUL) == false)) __t27_assert_fail("\n wrong family still rejected:\n can_serve_op(mulonly, FMT_GF_BINARY, 16, GF_OP_MUL) = {any}\n", .{ can_serve_op(mulonly, FMT_GF_BINARY, 16, GF_OP_MUL) }); } test "route_skill_with_op" { const both: u32 = make_card_ops(family_bit(FMT_GFT), 8 | 16, op_bit(GF_OP_MUL) | op_bit(GF_OP_ADD)); - if (!(can_serve_skill_op(both, 0xA611) == true)) @panic("hosts GF-T16 mul"); - if (!(can_serve_skill_op(both, 0xA610) == true)) @panic("hosts GF-T16 add"); + if (!(can_serve_skill_op(both, 0xA611) == true)) __t27_assert_fail("\n hosts GF-T16 mul:\n can_serve_skill_op(both, 0xA611) = {any}\n", .{ can_serve_skill_op(both, 0xA611) }); + if (!(can_serve_skill_op(both, 0xA610) == true)) __t27_assert_fail("\n hosts GF-T16 add:\n can_serve_skill_op(both, 0xA610) = {any}\n", .{ can_serve_skill_op(both, 0xA610) }); const mulonly: u32 = make_card_ops(family_bit(FMT_GFT), 16, op_bit(GF_OP_MUL)); - if (!(can_serve_skill_op(mulonly, 0xA611) == true)) @panic("mul-only takes the mul skill"); - if (!(can_serve_skill_op(mulonly, 0xA610) == false)) @panic("mul-only rejects the add skill"); + if (!(can_serve_skill_op(mulonly, 0xA611) == true)) __t27_assert_fail("\n mul-only takes the mul skill:\n can_serve_skill_op(mulonly, 0xA611) = {any}\n", .{ can_serve_skill_op(mulonly, 0xA611) }); + if (!(can_serve_skill_op(mulonly, 0xA610) == false)) __t27_assert_fail("\n mul-only rejects the add skill:\n can_serve_skill_op(mulonly, 0xA610) = {any}\n", .{ can_serve_skill_op(mulonly, 0xA610) }); } test "gft_ladder_op_routing" { const m64: u32 = make_card_ops(family_bit(FMT_GFT), 64, op_bit(GF_OP_MUL)); - if (!(can_serve_skill_op(m64, 0xA311) == true)) @panic("GF-T64 mul-only takes GF-T64 mul"); - if (!(can_serve_skill_op(m64, 0xA310) == false)) @panic("GF-T64 mul-only rejects GF-T64 add"); + if (!(can_serve_skill_op(m64, 0xA311) == true)) __t27_assert_fail("\n GF-T64 mul-only takes GF-T64 mul:\n can_serve_skill_op(m64, 0xA311) = {any}\n", .{ can_serve_skill_op(m64, 0xA311) }); + if (!(can_serve_skill_op(m64, 0xA310) == false)) __t27_assert_fail("\n GF-T64 mul-only rejects GF-T64 add:\n can_serve_skill_op(m64, 0xA310) = {any}\n", .{ can_serve_skill_op(m64, 0xA310) }); const full: u32 = make_card_ops(family_bit(FMT_GFT), ((((4 | 8) | 16) | 32) | 64) | 128, op_bit(GF_OP_MUL) | op_bit(GF_OP_ADD)); - if (!(can_serve_skill_op(full, 0xA411) == true)) @panic("GF-T4 mul"); - if (!(can_serve_skill_op(full, 0xA410) == true)) @panic("GF-T4 add"); - if (!(can_serve_skill_op(full, 0xA511) == true)) @panic("GF-T32 mul"); - if (!(can_serve_skill_op(full, 0xA211) == true)) @panic("GF-T128 mul"); + if (!(can_serve_skill_op(full, 0xA411) == true)) __t27_assert_fail("\n GF-T4 mul:\n can_serve_skill_op(full, 0xA411) = {any}\n", .{ can_serve_skill_op(full, 0xA411) }); + if (!(can_serve_skill_op(full, 0xA410) == true)) __t27_assert_fail("\n GF-T4 add:\n can_serve_skill_op(full, 0xA410) = {any}\n", .{ can_serve_skill_op(full, 0xA410) }); + if (!(can_serve_skill_op(full, 0xA511) == true)) __t27_assert_fail("\n GF-T32 mul:\n can_serve_skill_op(full, 0xA511) = {any}\n", .{ can_serve_skill_op(full, 0xA511) }); + if (!(can_serve_skill_op(full, 0xA211) == true)) __t27_assert_fail("\n GF-T128 mul:\n can_serve_skill_op(full, 0xA211) = {any}\n", .{ can_serve_skill_op(full, 0xA211) }); const m4: u32 = make_card_ops(family_bit(FMT_GFT), 4, op_bit(GF_OP_MUL) | op_bit(GF_OP_ADD)); - if (!(can_serve_skill_op(m4, 0xA311) == false)) @panic("GF-T4-only host rejects a GF-T64 mul (wrong rung)"); + if (!(can_serve_skill_op(m4, 0xA311) == false)) __t27_assert_fail("\n GF-T4-only host rejects a GF-T64 mul (wrong rung):\n can_serve_skill_op(m4, 0xA311) = {any}\n", .{ can_serve_skill_op(m4, 0xA311) }); } diff --git a/gen/zig/tri_a2a_wire.zig b/gen/zig/tri_a2a_wire.zig index 09fa33d5..f049406c 100644 --- a/gen/zig/tri_a2a_wire.zig +++ b/gen/zig/tri_a2a_wire.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const OFF_CLASS: u32 = 0; @@ -80,50 +88,50 @@ fn operand_pre(idx: u32, op: u32, a_off: u32, a_mant: u32, b_off: u32, b_mant: u return 0; } test "be_reassembly" { - if (!(task_id(0x12, 0x34, 0x56, 0x78) == 0x12345678)) @panic("task id from 4 BE bytes"); - if (!(skill_id(0xA6, 0x11) == 0xA611)) @panic("skill id from 2 BE bytes (GF-T16 mul)"); + if (!(task_id(0x12, 0x34, 0x56, 0x78) == 0x12345678)) __t27_assert_fail("\n task id from 4 BE bytes:\n task_id(0x12, 0x34, 0x56, 0x78) = {any}\n", .{ task_id(0x12, 0x34, 0x56, 0x78) }); + if (!(skill_id(0xA6, 0x11) == 0xA611)) __t27_assert_fail("\n skill id from 2 BE bytes (GF-T16 mul):\n skill_id(0xA6, 0x11) = {any}\n", .{ skill_id(0xA6, 0x11) }); } test "header_layout" { - if (!(HDR_LEN == 7)) @panic("msg_class(1)+task(4)+skill(2)"); - if (!(body_offset() == OFF_BODY)) @panic("body after the fixed header"); - if (!(OFF_SKILL == 5)) @panic("skill at byte 5"); + if (!(HDR_LEN == 7)) __t27_assert_fail("\n msg_class(1)+task(4)+skill(2):\n HDR_LEN = {any}\n", .{ HDR_LEN }); + if (!(body_offset() == OFF_BODY)) __t27_assert_fail("\n body after the fixed header:\n body_offset() = {any}\n OFF_BODY = {any}\n", .{ body_offset(), OFF_BODY }); + if (!(OFF_SKILL == 5)) __t27_assert_fail("\n skill at byte 5:\n OFF_SKILL = {any}\n", .{ OFF_SKILL }); } test "class_rules" { - if (!(class_valid(MSG_TASK_ASSIGN) == true)) @panic("assign is valid"); - if (!(class_valid(MSG_TASK_RESULT) == true)) @panic("result is valid"); - if (!(class_valid(0) == false)) @panic("msg_class 0 is malformed"); - if (!(class_valid(99) == false)) @panic("unknown msg_class is malformed"); - if (!(body_has_receipt(MSG_TASK_RESULT) == true)) @panic("result carries a receipt"); - if (!(body_has_receipt(MSG_TASK_ASSIGN) == false)) @panic("assign carries no receipt"); + if (!(class_valid(MSG_TASK_ASSIGN) == true)) __t27_assert_fail("\n assign is valid:\n class_valid(MSG_TASK_ASSIGN) = {any}\n", .{ class_valid(MSG_TASK_ASSIGN) }); + if (!(class_valid(MSG_TASK_RESULT) == true)) __t27_assert_fail("\n result is valid:\n class_valid(MSG_TASK_RESULT) = {any}\n", .{ class_valid(MSG_TASK_RESULT) }); + if (!(class_valid(0) == false)) __t27_assert_fail("\n msg_class 0 is malformed:\n class_valid(0) = {any}\n", .{ class_valid(0) }); + if (!(class_valid(99) == false)) __t27_assert_fail("\n unknown msg_class is malformed:\n class_valid(99) = {any}\n", .{ class_valid(99) }); + if (!(body_has_receipt(MSG_TASK_RESULT) == true)) __t27_assert_fail("\n result carries a receipt:\n body_has_receipt(MSG_TASK_RESULT) = {any}\n", .{ body_has_receipt(MSG_TASK_RESULT) }); + if (!(body_has_receipt(MSG_TASK_ASSIGN) == false)) __t27_assert_fail("\n assign carries no receipt:\n body_has_receipt(MSG_TASK_ASSIGN) = {any}\n", .{ body_has_receipt(MSG_TASK_ASSIGN) }); } test "signed_result_layout" { - if (!(SIG_LEN == 64)) @panic("Ed25519 signature is 64 bytes"); - if (!(body_has_signature(MSG_TASK_RESULT) == true)) @panic("a result carries a signature"); - if (!(body_has_signature(MSG_TASK_ASSIGN) == false)) @panic("an assign carries no signature"); - if (!(sig_offset(36) == (OFF_BODY + 36))) @panic("signature after a 36-byte receipt body"); - if (!(signed_result_len(36) == ((OFF_BODY + 36) + SIG_LEN))) @panic("total = header + body + 64B signature"); + if (!(SIG_LEN == 64)) __t27_assert_fail("\n Ed25519 signature is 64 bytes:\n SIG_LEN = {any}\n", .{ SIG_LEN }); + if (!(body_has_signature(MSG_TASK_RESULT) == true)) __t27_assert_fail("\n a result carries a signature:\n body_has_signature(MSG_TASK_RESULT) = {any}\n", .{ body_has_signature(MSG_TASK_RESULT) }); + if (!(body_has_signature(MSG_TASK_ASSIGN) == false)) __t27_assert_fail("\n an assign carries no signature:\n body_has_signature(MSG_TASK_ASSIGN) = {any}\n", .{ body_has_signature(MSG_TASK_ASSIGN) }); + if (!(sig_offset(36) == (OFF_BODY + 36))) __t27_assert_fail("\n signature after a 36-byte receipt body:\n sig_offset(36) = {any}\n OFF_BODY + 36 = {any}\n", .{ sig_offset(36), OFF_BODY + 36 }); + if (!(signed_result_len(36) == ((OFF_BODY + 36) + SIG_LEN))) __t27_assert_fail("\n total = header + body + 64B signature:\n signed_result_len(36) = {any}\n (OFF_BODY + 36) + SIG_LEN = {any}\n", .{ signed_result_len(36), (OFF_BODY + 36) + SIG_LEN }); } test "assign_operand_layout" { - if (!(ASSIGN_BODY_LEN == 7)) @panic("op(1)+a_off(1)+a_mant(2)+b_off(1)+b_mant(2)"); - if (!(OFF_ASSIGN_B_OFF == 4)) @panic("b operand after a"); - if (!(assign_mant(0x01, 0x00) == 256)) @panic("mantissa 256 from bytes 0x01 0x00"); - if (!(assign_mant(0x01, 0xFF) == 511)) @panic("mantissa 511 (max 9-bit) from 0x01 0xFF"); + if (!(ASSIGN_BODY_LEN == 7)) __t27_assert_fail("\n op(1)+a_off(1)+a_mant(2)+b_off(1)+b_mant(2):\n ASSIGN_BODY_LEN = {any}\n", .{ ASSIGN_BODY_LEN }); + if (!(OFF_ASSIGN_B_OFF == 4)) __t27_assert_fail("\n b operand after a:\n OFF_ASSIGN_B_OFF = {any}\n", .{ OFF_ASSIGN_B_OFF }); + if (!(assign_mant(0x01, 0x00) == 256)) __t27_assert_fail("\n mantissa 256 from bytes 0x01 0x00:\n assign_mant(0x01, 0x00) = {any}\n", .{ assign_mant(0x01, 0x00) }); + if (!(assign_mant(0x01, 0xFF) == 511)) __t27_assert_fail("\n mantissa 511 (max 9-bit) from 0x01 0xFF:\n assign_mant(0x01, 0xFF) = {any}\n", .{ assign_mant(0x01, 0xFF) }); } test "operand_preimage_layout" { - if (!(operand_pre(0, 0x11, 41, 0, 41, 0) == 0x11)) @panic("op at word 0"); - if (!(operand_pre(1, 0x11, 41, 0, 41, 0) == 41)) @panic("a_offset at word 1"); - if (!(operand_pre(4, 0x11, 41, 0, 41, 7) == 7)) @panic("b_mantissa at word 4"); - if (!(operand_pre(5, 0, 0, 0, 0, 0) == SHA_PAD_W)) @panic("pad marker at word 5"); - if (!(operand_pre(15, 0, 0, 0, 0, 0) == OPERAND_BITS)) @panic("160-bit length at word 15"); - if (!(operand_pre(9, 0x11, 41, 0, 41, 0) == 0)) @panic("interior pad word is zero"); + if (!(operand_pre(0, 0x11, 41, 0, 41, 0) == 0x11)) __t27_assert_fail("\n op at word 0:\n operand_pre(0, 0x11, 41, 0, 41, 0) = {any}\n", .{ operand_pre(0, 0x11, 41, 0, 41, 0) }); + if (!(operand_pre(1, 0x11, 41, 0, 41, 0) == 41)) __t27_assert_fail("\n a_offset at word 1:\n operand_pre(1, 0x11, 41, 0, 41, 0) = {any}\n", .{ operand_pre(1, 0x11, 41, 0, 41, 0) }); + if (!(operand_pre(4, 0x11, 41, 0, 41, 7) == 7)) __t27_assert_fail("\n b_mantissa at word 4:\n operand_pre(4, 0x11, 41, 0, 41, 7) = {any}\n", .{ operand_pre(4, 0x11, 41, 0, 41, 7) }); + if (!(operand_pre(5, 0, 0, 0, 0, 0) == SHA_PAD_W)) __t27_assert_fail("\n pad marker at word 5:\n operand_pre(5, 0, 0, 0, 0, 0) = {any}\n SHA_PAD_W = {any}\n", .{ operand_pre(5, 0, 0, 0, 0, 0), SHA_PAD_W }); + if (!(operand_pre(15, 0, 0, 0, 0, 0) == OPERAND_BITS)) __t27_assert_fail("\n 160-bit length at word 15:\n operand_pre(15, 0, 0, 0, 0, 0) = {any}\n OPERAND_BITS = {any}\n", .{ operand_pre(15, 0, 0, 0, 0, 0), OPERAND_BITS }); + if (!(operand_pre(9, 0x11, 41, 0, 41, 0) == 0)) __t27_assert_fail("\n interior pad word is zero:\n operand_pre(9, 0x11, 41, 0, 41, 0) = {any}\n", .{ operand_pre(9, 0x11, 41, 0, 41, 0) }); } test "operand_tamper_changes_the_preimage" { - if (!(operand_pre(0, 0x10, 41, 0, 41, 0) != operand_pre(0, 0x11, 41, 0, 41, 0))) @panic("op tamper moves word 0"); - if (!(operand_pre(1, 0x11, 42, 0, 41, 0) != operand_pre(1, 0x11, 41, 0, 41, 0))) @panic("a_off tamper moves word 1"); - if (!(operand_pre(2, 0x11, 41, 5, 41, 0) != operand_pre(2, 0x11, 41, 0, 41, 0))) @panic("a_mant tamper moves word 2"); - if (!(operand_pre(3, 0x11, 41, 0, 42, 0) != operand_pre(3, 0x11, 41, 0, 41, 0))) @panic("b_off tamper moves word 3"); - if (!(operand_pre(4, 0x11, 41, 0, 41, 9) != operand_pre(4, 0x11, 41, 0, 41, 0))) @panic("b_mant tamper moves word 4"); - if (!(operand_pre(0, 0x11, 99, 99, 99, 99) == operand_pre(0, 0x11, 41, 0, 41, 0))) @panic("word 0 depends only on op"); - if (!(operand_pre(1, 0x10, 41, 5, 42, 9) == operand_pre(1, 0x11, 41, 0, 41, 0))) @panic("word 1 depends only on a_off"); - if (!(operand_pre(4, 0x10, 99, 99, 99, 7) == operand_pre(4, 0x11, 41, 0, 41, 7))) @panic("word 4 depends only on b_mant"); + if (!(operand_pre(0, 0x10, 41, 0, 41, 0) != operand_pre(0, 0x11, 41, 0, 41, 0))) __t27_assert_fail("\n op tamper moves word 0:\n operand_pre(0, 0x10, 41, 0, 41, 0) = {any}\n operand_pre(0, 0x11, 41, 0, 41, 0) = {any}\n", .{ operand_pre(0, 0x10, 41, 0, 41, 0), operand_pre(0, 0x11, 41, 0, 41, 0) }); + if (!(operand_pre(1, 0x11, 42, 0, 41, 0) != operand_pre(1, 0x11, 41, 0, 41, 0))) __t27_assert_fail("\n a_off tamper moves word 1:\n operand_pre(1, 0x11, 42, 0, 41, 0) = {any}\n operand_pre(1, 0x11, 41, 0, 41, 0) = {any}\n", .{ operand_pre(1, 0x11, 42, 0, 41, 0), operand_pre(1, 0x11, 41, 0, 41, 0) }); + if (!(operand_pre(2, 0x11, 41, 5, 41, 0) != operand_pre(2, 0x11, 41, 0, 41, 0))) __t27_assert_fail("\n a_mant tamper moves word 2:\n operand_pre(2, 0x11, 41, 5, 41, 0) = {any}\n operand_pre(2, 0x11, 41, 0, 41, 0) = {any}\n", .{ operand_pre(2, 0x11, 41, 5, 41, 0), operand_pre(2, 0x11, 41, 0, 41, 0) }); + if (!(operand_pre(3, 0x11, 41, 0, 42, 0) != operand_pre(3, 0x11, 41, 0, 41, 0))) __t27_assert_fail("\n b_off tamper moves word 3:\n operand_pre(3, 0x11, 41, 0, 42, 0) = {any}\n operand_pre(3, 0x11, 41, 0, 41, 0) = {any}\n", .{ operand_pre(3, 0x11, 41, 0, 42, 0), operand_pre(3, 0x11, 41, 0, 41, 0) }); + if (!(operand_pre(4, 0x11, 41, 0, 41, 9) != operand_pre(4, 0x11, 41, 0, 41, 0))) __t27_assert_fail("\n b_mant tamper moves word 4:\n operand_pre(4, 0x11, 41, 0, 41, 9) = {any}\n operand_pre(4, 0x11, 41, 0, 41, 0) = {any}\n", .{ operand_pre(4, 0x11, 41, 0, 41, 9), operand_pre(4, 0x11, 41, 0, 41, 0) }); + if (!(operand_pre(0, 0x11, 99, 99, 99, 99) == operand_pre(0, 0x11, 41, 0, 41, 0))) __t27_assert_fail("\n word 0 depends only on op:\n operand_pre(0, 0x11, 99, 99, 99, 99) = {any}\n operand_pre(0, 0x11, 41, 0, 41, 0) = {any}\n", .{ operand_pre(0, 0x11, 99, 99, 99, 99), operand_pre(0, 0x11, 41, 0, 41, 0) }); + if (!(operand_pre(1, 0x10, 41, 5, 42, 9) == operand_pre(1, 0x11, 41, 0, 41, 0))) __t27_assert_fail("\n word 1 depends only on a_off:\n operand_pre(1, 0x10, 41, 5, 42, 9) = {any}\n operand_pre(1, 0x11, 41, 0, 41, 0) = {any}\n", .{ operand_pre(1, 0x10, 41, 5, 42, 9), operand_pre(1, 0x11, 41, 0, 41, 0) }); + if (!(operand_pre(4, 0x10, 99, 99, 99, 7) == operand_pre(4, 0x11, 41, 0, 41, 7))) __t27_assert_fail("\n word 4 depends only on b_mant:\n operand_pre(4, 0x10, 99, 99, 99, 7) = {any}\n operand_pre(4, 0x11, 41, 0, 41, 7) = {any}\n", .{ operand_pre(4, 0x10, 99, 99, 99, 7), operand_pre(4, 0x11, 41, 0, 41, 7) }); } diff --git a/gen/zig/tri_challenge.zig b/gen/zig/tri_challenge.zig index 391aac6b..a40dc3c0 100644 --- a/gen/zig/tri_challenge.zig +++ b/gen/zig/tri_challenge.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const DEFENDER_HONEST: u32 = 1; @@ -32,35 +40,35 @@ fn challenger_bond_after(verdict: u32, defender_bond: u32, challenger_bond: u32) } } test "challenge_needs_disagreement" { - if (!(is_valid_challenge(0x6EAC3F90, 0xDEADBEEF) == true)) @panic("different seals -> valid"); - if (!(is_valid_challenge(0x6EAC3F90, 0x6EAC3F90) == false)) @panic("same seal -> no dispute"); + if (!(is_valid_challenge(0x6EAC3F90, 0xDEADBEEF) == true)) __t27_assert_fail("\n different seals -> valid:\n is_valid_challenge(0x6EAC3F90, 0xDEADBEEF) = {any}\n", .{ is_valid_challenge(0x6EAC3F90, 0xDEADBEEF) }); + if (!(is_valid_challenge(0x6EAC3F90, 0x6EAC3F90) == false)) __t27_assert_fail("\n same seal -> no dispute:\n is_valid_challenge(0x6EAC3F90, 0x6EAC3F90) = {any}\n", .{ is_valid_challenge(0x6EAC3F90, 0x6EAC3F90) }); } test "honest_defender_wins" { const v = resolve(0x6EAC3F90, 0x6EAC3F90); - if (!(v == DEFENDER_HONEST)) @panic("defender honest"); + if (!(v == DEFENDER_HONEST)) __t27_assert_fail("\n defender honest:\n v = {any}\n DEFENDER_HONEST = {any}\n", .{ v, DEFENDER_HONEST }); } test "lying_defender_slashed" { const v = resolve(0xBADBAD00, 0x6EAC3F90); - if (!(v == DEFENDER_LIED)) @panic("defender lied"); + if (!(v == DEFENDER_LIED)) __t27_assert_fail("\n defender lied:\n v = {any}\n DEFENDER_LIED = {any}\n", .{ v, DEFENDER_LIED }); } test "bonds_honest_defender" { const da = defender_bond_after(DEFENDER_HONEST, 100, 100); const ca = challenger_bond_after(DEFENDER_HONEST, 100, 100); - if (!(da == 200)) @panic("defender gains challenger's bond"); - if (!(ca == 0)) @panic("challenger loses its bond"); - if (!((da + ca) == 200)) @panic("total bond conserved"); + if (!(da == 200)) __t27_assert_fail("\n defender gains challenger's bond:\n da = {any}\n", .{ da }); + if (!(ca == 0)) __t27_assert_fail("\n challenger loses its bond:\n ca = {any}\n", .{ ca }); + if (!((da + ca) == 200)) __t27_assert_fail("\n total bond conserved:\n da + ca = {any}\n", .{ da + ca }); } test "bonds_lying_defender" { const da = defender_bond_after(DEFENDER_LIED, 100, 100); const ca = challenger_bond_after(DEFENDER_LIED, 100, 100); - if (!(da == 0)) @panic("defender is slashed"); - if (!(ca == 200)) @panic("challenger gains defender's bond"); - if (!((da + ca) == 200)) @panic("total bond conserved"); + if (!(da == 0)) __t27_assert_fail("\n defender is slashed:\n da = {any}\n", .{ da }); + if (!(ca == 200)) __t27_assert_fail("\n challenger gains defender's bond:\n ca = {any}\n", .{ ca }); + if (!((da + ca) == 200)) __t27_assert_fail("\n total bond conserved:\n da + ca = {any}\n", .{ da + ca }); } test "griefing_unprofitable" { const v = resolve(0x11223344, 0x11223344); const ca = challenger_bond_after(v, 100, 100); - if (!(ca < 100)) @panic("frivolous challenger ends with less than it posted"); + if (!(ca < 100)) __t27_assert_fail("\n frivolous challenger ends with less than it posted:\n ca = {any}\n", .{ ca }); } const RESOLVE_TIMEOUT: u32 = 27; fn challenge_admissible(now_epoch: u32, receipt_epoch: u32, window: u32) bool { @@ -117,11 +125,11 @@ test "witness_quorum" { const v_frame = witness_verdict(0xAAAA, 0xBBBB, 0xAAAA, 0xAAAA); const v_caught = witness_verdict(0xBAD0, 0xAAAA, 0xAAAA, 0xDEAD); const v_none = witness_verdict(0xAAAA, 0x1111, 0x2222, 0x3333); - if (!(v_unanimous == DEFENDER_HONEST)) @panic("unanimous truth clears the defender"); - if (!(v_one_liar == DEFENDER_HONEST)) @panic("one lying witness cannot flip an honest majority"); - if (!(v_frame == DEFENDER_HONEST)) @panic("one framing witness cannot slash an honest defender"); - if (!(v_caught == DEFENDER_LIED)) @panic("a real lie is caught by the majority"); - if (!(v_none == VERDICT_NONE)) @panic("no quorum -> no verdict, dispute stays open"); + if (!(v_unanimous == DEFENDER_HONEST)) __t27_assert_fail("\n unanimous truth clears the defender:\n v_unanimous = {any}\n DEFENDER_HONEST = {any}\n", .{ v_unanimous, DEFENDER_HONEST }); + if (!(v_one_liar == DEFENDER_HONEST)) __t27_assert_fail("\n one lying witness cannot flip an honest majority:\n v_one_liar = {any}\n DEFENDER_HONEST = {any}\n", .{ v_one_liar, DEFENDER_HONEST }); + if (!(v_frame == DEFENDER_HONEST)) __t27_assert_fail("\n one framing witness cannot slash an honest defender:\n v_frame = {any}\n DEFENDER_HONEST = {any}\n", .{ v_frame, DEFENDER_HONEST }); + if (!(v_caught == DEFENDER_LIED)) __t27_assert_fail("\n a real lie is caught by the majority:\n v_caught = {any}\n DEFENDER_LIED = {any}\n", .{ v_caught, DEFENDER_LIED }); + if (!(v_none == VERDICT_NONE)) __t27_assert_fail("\n no quorum -> no verdict, dispute stays open:\n v_none = {any}\n VERDICT_NONE = {any}\n", .{ v_none, VERDICT_NONE }); } fn witness_is_majority(seal: u32, majority: u32) bool { return (majority != 0) and (seal == majority); @@ -158,11 +166,11 @@ test "witness_economics" { const m = witness_payout(0xAAAA, 0xAAAA, 0xAAAA, 0xDEAD, 100); const l = witness_payout(0xDEAD, 0xAAAA, 0xAAAA, 0xDEAD, 100); const n = witness_payout(0x1111, 0x1111, 0x2222, 0x3333, 100); - if (!(u == 100)) @panic("unanimous round: stake back, no free reward"); - if (!(m == 150)) @panic("majority of two splits the one forfeited stake"); - if (!(l == 0)) @panic("the dissenter forfeits"); - if (!(n == 100)) @panic("no quorum refunds everyone"); - if (!(((m + m) + l) == 300)) @panic("2-1 round conserves the three stakes"); + if (!(u == 100)) __t27_assert_fail("\n unanimous round: stake back, no free reward:\n u = {any}\n", .{ u }); + if (!(m == 150)) __t27_assert_fail("\n majority of two splits the one forfeited stake:\n m = {any}\n", .{ m }); + if (!(l == 0)) __t27_assert_fail("\n the dissenter forfeits:\n l = {any}\n", .{ l }); + if (!(n == 100)) __t27_assert_fail("\n no quorum refunds everyone:\n n = {any}\n", .{ n }); + if (!(((m + m) + l) == 300)) __t27_assert_fail("\n 2-1 round conserves the three stakes:\n (m + m) + l = {any}\n", .{ (m + m) + l }); } const MAX_OPEN_DISPUTES: u32 = 3; const CH_BPS_UNIT: u32 = 10000; @@ -208,14 +216,14 @@ fn may_open_dispute_rung(open_count: u32, risk: u32, reward: u32, bond: u32, min test "rung_aware_admission" { const p4 = dispute_rung_min_bps(2000, 4); const p9 = dispute_rung_min_bps(2000, 9); - const @"f0" = may_open_dispute_rung(0, 400, 100, 100, 2000, 4); + const f0 = may_open_dispute_rung(0, 400, 100, 100, 2000, 4); const w0 = may_open_dispute_rung(0, 400, 100, 100, 2000, 9); const w1 = may_open_dispute_rung(0, 400, 100, 225, 2000, 9); - if (!(p4 == 2000)) @panic("at the flagship the base premium applies"); - if (!(p9 == 4500)) @panic("Et9 adds 2500 bps"); - if (!(@"f0" == true)) @panic("bond 100 covers 500 at 20% on the flagship"); - if (!(w0 == false)) @panic("the SAME bond fails the SAME dispute at Et9 (needs 45%)"); - if (!(w1 == true)) @panic("225 covers 500 at 45% on the wide rung"); + if (!(p4 == 2000)) __t27_assert_fail("\n at the flagship the base premium applies:\n p4 = {any}\n", .{ p4 }); + if (!(p9 == 4500)) __t27_assert_fail("\n Et9 adds 2500 bps:\n p9 = {any}\n", .{ p9 }); + if (!(f0 == true)) __t27_assert_fail("\n bond 100 covers 500 at 20% on the flagship:\n f0 = {any}\n", .{ f0 }); + if (!(w0 == false)) __t27_assert_fail("\n the SAME bond fails the SAME dispute at Et9 (needs 45%):\n w0 = {any}\n", .{ w0 }); + if (!(w1 == true)) __t27_assert_fail("\n 225 covers 500 at 45% on the wide rung:\n w1 = {any}\n", .{ w1 }); } test "dispute_slots_and_risk_ledger" { const s0 = dispute_slots_ok(0); @@ -225,13 +233,13 @@ test "dispute_slots_and_risk_ledger" { const r0 = risk_after_close(140, 40); const ru = risk_after_close(30, 40); const rs = risk_after_open(0xFFFFFFF0, 0x100); - if (!(s0 == true)) @panic("empty ledger has slots"); - if (!(s2 == true)) @panic("slot 3 of 3 may open"); - if (!(s3 == false)) @panic("the cap is exact at MAX_OPEN_DISPUTES"); - if (!(r1 == 140)) @panic("open adds the reward at risk"); - if (!(r0 == 100)) @panic("close returns to the baseline"); - if (!(ru == 0)) @panic("close floors at zero, never wraps"); - if (!(rs == 0xFFFFFFFF)) @panic("an overflowing open saturates"); + if (!(s0 == true)) __t27_assert_fail("\n empty ledger has slots:\n s0 = {any}\n", .{ s0 }); + if (!(s2 == true)) __t27_assert_fail("\n slot 3 of 3 may open:\n s2 = {any}\n", .{ s2 }); + if (!(s3 == false)) __t27_assert_fail("\n the cap is exact at MAX_OPEN_DISPUTES:\n s3 = {any}\n", .{ s3 }); + if (!(r1 == 140)) __t27_assert_fail("\n open adds the reward at risk:\n r1 = {any}\n", .{ r1 }); + if (!(r0 == 100)) __t27_assert_fail("\n close returns to the baseline:\n r0 = {any}\n", .{ r0 }); + if (!(ru == 0)) __t27_assert_fail("\n close floors at zero, never wraps:\n ru = {any}\n", .{ ru }); + if (!(rs == 0xFFFFFFFF)) __t27_assert_fail("\n an overflowing open saturates:\n rs = {any}\n", .{ rs }); } test "dispute_admission_gate" { const a0 = may_open_dispute(0, 0, 400, 100, 2000); @@ -239,48 +247,48 @@ test "dispute_admission_gate" { const a2 = may_open_dispute(3, 0, 10, 1000000, 2000); const a3 = may_open_dispute(1, 400, 100, 100, 2000); const a4 = may_open_dispute(1, 450, 100, 100, 2000); - if (!(a0 == true)) @panic("bond 100 covers 20% of 400"); - if (!(a1 == false)) @panic("bond 100 cannot cover 20% of 600"); - if (!(a2 == false)) @panic("no slot, no dispute, whatever the bond"); - if (!(a3 == true)) @panic("risk 400 + 100 = 500 requires exactly the full bond -- exact cover admits"); - if (!(a4 == false)) @panic("risk 450 + 100 = 550 requires 110 > bond 100 -- rejected"); + if (!(a0 == true)) __t27_assert_fail("\n bond 100 covers 20% of 400:\n a0 = {any}\n", .{ a0 }); + if (!(a1 == false)) __t27_assert_fail("\n bond 100 cannot cover 20% of 600:\n a1 = {any}\n", .{ a1 }); + if (!(a2 == false)) __t27_assert_fail("\n no slot, no dispute, whatever the bond:\n a2 = {any}\n", .{ a2 }); + if (!(a3 == true)) __t27_assert_fail("\n risk 400 + 100 = 500 requires exactly the full bond -- exact cover admits:\n a3 = {any}\n", .{ a3 }); + if (!(a4 == false)) __t27_assert_fail("\n risk 450 + 100 = 550 requires 110 > bond 100 -- rejected:\n a4 = {any}\n", .{ a4 }); } test "rung_window_edges" { - const @"f0" = challenge_admissible_rung(1063, 1000, 4); - const @"f1" = challenge_admissible_rung(1064, 1000, 4); + const f0 = challenge_admissible_rung(1063, 1000, 4); + const f1 = challenge_admissible_rung(1064, 1000, 4); const w0 = challenge_admissible_rung(1064, 1000, 9); const w1 = challenge_admissible_rung(1143, 1000, 9); const w2 = challenge_admissible_rung(1144, 1000, 9); - if (!(@"f0" == true)) @panic("flagship: epoch 63 of 64 is challengeable"); - if (!(@"f1" == false)) @panic("flagship: the finalization epoch admits nothing"); - if (!(w0 == true)) @panic("GF-T64 (Et9) is still challengeable where GF-T16 finalized"); - if (!(w1 == true)) @panic("GF-T64: epoch 143 of 144 is challengeable"); - if (!(w2 == false)) @panic("GF-T64: its own finalization epoch admits nothing"); + if (!(f0 == true)) __t27_assert_fail("\n flagship: epoch 63 of 64 is challengeable:\n f0 = {any}\n", .{ f0 }); + if (!(f1 == false)) __t27_assert_fail("\n flagship: the finalization epoch admits nothing:\n f1 = {any}\n", .{ f1 }); + if (!(w0 == true)) __t27_assert_fail("\n GF-T64 (Et9) is still challengeable where GF-T16 finalized:\n w0 = {any}\n", .{ w0 }); + if (!(w1 == true)) __t27_assert_fail("\n GF-T64: epoch 143 of 144 is challengeable:\n w1 = {any}\n", .{ w1 }); + if (!(w2 == false)) __t27_assert_fail("\n GF-T64: its own finalization epoch admits nothing:\n w2 = {any}\n", .{ w2 }); } test "window_edges" { const a0 = challenge_admissible(100, 100, 8); const a1 = challenge_admissible(107, 100, 8); const a2 = challenge_admissible(108, 100, 8); const a3 = challenge_admissible(99, 100, 8); - if (!(a0 == true)) @panic("fresh receipt is challengeable"); - if (!(a1 == true)) @panic("last in-window epoch (window - 1) is challengeable"); - if (!(a2 == false)) @panic("the finalization epoch itself admits no challenge"); - if (!(a3 == false)) @panic("a backwards clock admits nothing"); + if (!(a0 == true)) __t27_assert_fail("\n fresh receipt is challengeable:\n a0 = {any}\n", .{ a0 }); + if (!(a1 == true)) __t27_assert_fail("\n last in-window epoch (window - 1) is challengeable:\n a1 = {any}\n", .{ a1 }); + if (!(a2 == false)) __t27_assert_fail("\n the finalization epoch itself admits no challenge:\n a2 = {any}\n", .{ a2 }); + if (!(a3 == false)) __t27_assert_fail("\n a backwards clock admits nothing:\n a3 = {any}\n", .{ a3 }); } test "expiry_edges" { const e0 = dispute_expired(50, 77); const e1 = dispute_expired(50, 78); const e2 = dispute_expired(50, 49); - if (!(e0 == false)) @panic("at the timeout the dispute is still live"); - if (!(e1 == true)) @panic("one epoch past the timeout it expires"); - if (!(e2 == false)) @panic("a backwards clock never expires a dispute"); + if (!(e0 == false)) __t27_assert_fail("\n at the timeout the dispute is still live:\n e0 = {any}\n", .{ e0 }); + if (!(e1 == true)) __t27_assert_fail("\n one epoch past the timeout it expires:\n e1 = {any}\n", .{ e1 }); + if (!(e2 == false)) __t27_assert_fail("\n a backwards clock never expires a dispute:\n e2 = {any}\n", .{ e2 }); } test "expired_dispute_settles_for_defender" { const v = expired_verdict(); const da = defender_bond_after(v, 150, 100); const ca = challenger_bond_after(v, 150, 100); - if (!(v == DEFENDER_HONEST)) @panic("no proof -> no slash"); - if (!(da == 250)) @panic("defender keeps both bonds"); - if (!(ca == 0)) @panic("the non-resolving challenger forfeits"); - if (!((da + ca) == 250)) @panic("total bond conserved on the expiry path"); + if (!(v == DEFENDER_HONEST)) __t27_assert_fail("\n no proof -> no slash:\n v = {any}\n DEFENDER_HONEST = {any}\n", .{ v, DEFENDER_HONEST }); + if (!(da == 250)) __t27_assert_fail("\n defender keeps both bonds:\n da = {any}\n", .{ da }); + if (!(ca == 0)) __t27_assert_fail("\n the non-resolving challenger forfeits:\n ca = {any}\n", .{ ca }); + if (!((da + ca) == 250)) __t27_assert_fail("\n total bond conserved on the expiry path:\n da + ca = {any}\n", .{ da + ca }); } diff --git a/gen/zig/tri_compute_account.zig b/gen/zig/tri_compute_account.zig index abde5a18..c90b18a0 100644 --- a/gen/zig/tri_compute_account.zig +++ b/gen/zig/tri_compute_account.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module fn total(balance: u32, locked: u32) u32 { @@ -109,132 +117,132 @@ fn bal_after_finalize_checked(balance: u32, pending: u32, settle_epoch: u32, now test "lock_conserves_total" { const ba = bal_after_lock(1000, 200); const la = locked_after_lock(1000, 0, 200); - if (!(total(ba, la) == total(1000, 0))) @panic("lock conserves total"); - if (!(ba == 800)) @panic("balance reduced by the bond"); - if (!(la == 200)) @panic("bond now locked"); + if (!(total(ba, la) == total(1000, 0))) __t27_assert_fail("\n lock conserves total:\n total(ba, la) = {any}\n total(1000, 0) = {any}\n", .{ total(ba, la), total(1000, 0) }); + if (!(ba == 800)) __t27_assert_fail("\n balance reduced by the bond:\n ba = {any}\n", .{ ba }); + if (!(la == 200)) __t27_assert_fail("\n bond now locked:\n la = {any}\n", .{ la }); } test "release_conserves_total" { const ba = bal_after_release(800, 200); - if (!(total(ba, 0) == total(800, 200))) @panic("release conserves total"); - if (!(ba == 1000)) @panic("the whole bond returns"); + if (!(total(ba, 0) == total(800, 200))) __t27_assert_fail("\n release conserves total:\n total(ba, 0) = {any}\n total(800, 200) = {any}\n", .{ total(ba, 0), total(800, 200) }); + if (!(ba == 1000)) __t27_assert_fail("\n the whole bond returns:\n ba = {any}\n", .{ ba }); } test "slash_removes_exactly_the_bond" { const ba = bal_after_slash(800); - if (!(total(ba, 0) == (total(800, 200) - 200))) @panic("slash removes exactly the bond"); - if (!(ba == 800)) @panic("spendable balance is untouched by a slash"); + if (!(total(ba, 0) == (total(800, 200) - 200))) __t27_assert_fail("\n slash removes exactly the bond:\n total(ba, 0) = {any}\n total(800, 200) - 200 = {any}\n", .{ total(ba, 0), total(800, 200) - 200 }); + if (!(ba == 800)) __t27_assert_fail("\n spendable balance is untouched by a slash:\n ba = {any}\n", .{ ba }); } test "settle_mints_exactly_the_reward" { const ba = bal_after_settle(1000, 16); - if (!(total(ba, 0) == (total(1000, 0) + 16))) @panic("settle mints exactly the reward"); + if (!(total(ba, 0) == (total(1000, 0) + 16))) __t27_assert_fail("\n settle mints exactly the reward:\n total(ba, 0) = {any}\n total(1000, 0) + 16 = {any}\n", .{ total(ba, 0), total(1000, 0) + 16 }); } test "balance_mint_saturates" { - if (!(bal_add_sat(1000, 500) == 1500)) @panic("normal add exact"); - if (!(bal_add_sat(0xFFFFFFF0, 32) == 0xFFFFFFFF)) @panic("overflowing add saturates, no wrap"); - if (!(bal_after_settle(0xFFFFFFF0, 32) == 0xFFFFFFFF)) @panic("settle into near-max balance saturates"); - if (!(bal_after_finalize(0xFFFFFFF0, 32) == 0xFFFFFFFF)) @panic("finalize into near-max balance saturates"); - if (!(bal_after_finalize_gated(0xFFFFFFF0, 32, 1, 100, 10) == 0xFFFFFFFF)) @panic("gated finalize saturates too"); - if (!(bal_after_finalize(800, 16) == 816)) @panic("finalize small values exact"); - if (!(bal_after_settle(1000, 16) == 1016)) @panic("settle small values exact"); + if (!(bal_add_sat(1000, 500) == 1500)) __t27_assert_fail("\n normal add exact:\n bal_add_sat(1000, 500) = {any}\n", .{ bal_add_sat(1000, 500) }); + if (!(bal_add_sat(0xFFFFFFF0, 32) == 0xFFFFFFFF)) __t27_assert_fail("\n overflowing add saturates, no wrap:\n bal_add_sat(0xFFFFFFF0, 32) = {any}\n", .{ bal_add_sat(0xFFFFFFF0, 32) }); + if (!(bal_after_settle(0xFFFFFFF0, 32) == 0xFFFFFFFF)) __t27_assert_fail("\n settle into near-max balance saturates:\n bal_after_settle(0xFFFFFFF0, 32) = {any}\n", .{ bal_after_settle(0xFFFFFFF0, 32) }); + if (!(bal_after_finalize(0xFFFFFFF0, 32) == 0xFFFFFFFF)) __t27_assert_fail("\n finalize into near-max balance saturates:\n bal_after_finalize(0xFFFFFFF0, 32) = {any}\n", .{ bal_after_finalize(0xFFFFFFF0, 32) }); + if (!(bal_after_finalize_gated(0xFFFFFFF0, 32, 1, 100, 10) == 0xFFFFFFFF)) __t27_assert_fail("\n gated finalize saturates too:\n bal_after_finalize_gated(0xFFFFFFF0, 32, 1, 100, 10) = {any}\n", .{ bal_after_finalize_gated(0xFFFFFFF0, 32, 1, 100, 10) }); + if (!(bal_after_finalize(800, 16) == 816)) __t27_assert_fail("\n finalize small values exact:\n bal_after_finalize(800, 16) = {any}\n", .{ bal_after_finalize(800, 16) }); + if (!(bal_after_settle(1000, 16) == 1016)) __t27_assert_fail("\n settle small values exact:\n bal_after_settle(1000, 16) = {any}\n", .{ bal_after_settle(1000, 16) }); } test "lock_release_round_trips" { const ba = bal_after_lock(1000, 200); const la = locked_after_lock(1000, 0, 200); const back = bal_after_release(ba, la); - if (!(back == 1000)) @panic("lock+release is a no-op on total and on balance"); + if (!(back == 1000)) __t27_assert_fail("\n lock+release is a no-op on total and on balance:\n back = {any}\n", .{ back }); } test "settle_escrows_not_spendable" { const pend = pending_after_settle(0, 16); - if (!(pend == 16)) @panic("reward escrowed in pending"); - if (!(total3(800, 200, pend) == (total3(800, 200, 0) + 16))) @panic("settle mints exactly the reward into escrow"); - if (!(bal_after_clawback(800) == 800)) @panic("the reward is not in spendable balance yet"); + if (!(pend == 16)) __t27_assert_fail("\n reward escrowed in pending:\n pend = {any}\n", .{ pend }); + if (!(total3(800, 200, pend) == (total3(800, 200, 0) + 16))) __t27_assert_fail("\n settle mints exactly the reward into escrow:\n total3(800, 200, pend) = {any}\n total3(800, 200, 0) + 16 = {any}\n", .{ total3(800, 200, pend), total3(800, 200, 0) + 16 }); + if (!(bal_after_clawback(800) == 800)) __t27_assert_fail("\n the reward is not in spendable balance yet:\n bal_after_clawback(800) = {any}\n", .{ bal_after_clawback(800) }); } test "finalize_conserves_total" { const b = bal_after_finalize(800, 16); - if (!(b == 816)) @panic("pending reward becomes spendable"); - if (!(total3(b, 200, 0) == total3(800, 200, 16))) @panic("finalize conserves total3"); + if (!(b == 816)) __t27_assert_fail("\n pending reward becomes spendable:\n b = {any}\n", .{ b }); + if (!(total3(b, 200, 0) == total3(800, 200, 16))) __t27_assert_fail("\n finalize conserves total3:\n total3(b, 200, 0) = {any}\n total3(800, 200, 16) = {any}\n", .{ total3(b, 200, 0), total3(800, 200, 16) }); } test "clawback_reverts_reward_to_pool" { const b = bal_after_clawback(800); - if (!(b == 800)) @panic("spendable balance untouched by clawback"); - if (!(total3(b, 200, 0) == (total3(800, 200, 16) - 16))) @panic("clawback removes exactly the escrowed reward"); + if (!(b == 800)) __t27_assert_fail("\n spendable balance untouched by clawback:\n b = {any}\n", .{ b }); + if (!(total3(b, 200, 0) == (total3(800, 200, 16) - 16))) __t27_assert_fail("\n clawback removes exactly the escrowed reward:\n total3(b, 200, 0) = {any}\n total3(800, 200, 16) - 16 = {any}\n", .{ total3(b, 200, 0), total3(800, 200, 16) - 16 }); } test "fraud_nets_reward_plus_bond_worse" { const honest = total3(bal_after_finalize(bal_after_release(800, 200), 16), 0, 0); const fraud = total3(bal_after_clawback(800), 0, 0); - if (!(honest == 1016)) @panic("honest keeps balance + reward + returned bond"); - if (!(fraud == 800)) @panic("fraud loses the escrowed reward and the slashed bond"); - if (!((honest - fraud) == (16 + 200))) @panic("cheating costs exactly reward + bond vs honesty"); + if (!(honest == 1016)) __t27_assert_fail("\n honest keeps balance + reward + returned bond:\n honest = {any}\n", .{ honest }); + if (!(fraud == 800)) __t27_assert_fail("\n fraud loses the escrowed reward and the slashed bond:\n fraud = {any}\n", .{ fraud }); + if (!((honest - fraud) == (16 + 200))) __t27_assert_fail("\n cheating costs exactly reward + bond vs honesty:\n honest - fraud = {any}\n 16 + 200 = {any}\n", .{ honest - fraud, 16 + 200 }); } test "finality_window_boundary" { - if (!(is_final(100, 105, 10) == false)) @panic("5 < 10 epochs: still in the window"); - if (!(is_final(100, 109, 10) == false)) @panic("one epoch short: not final"); - if (!(is_final(100, 110, 10) == true)) @panic("exactly a window elapsed: final"); - if (!(is_final(100, 200, 10) == true)) @panic("well past the window: final"); - if (!(is_final(100, 90, 10) == false)) @panic("clock before settle epoch: never final"); + if (!(is_final(100, 105, 10) == false)) __t27_assert_fail("\n 5 < 10 epochs: still in the window:\n is_final(100, 105, 10) = {any}\n", .{ is_final(100, 105, 10) }); + if (!(is_final(100, 109, 10) == false)) __t27_assert_fail("\n one epoch short: not final:\n is_final(100, 109, 10) = {any}\n", .{ is_final(100, 109, 10) }); + if (!(is_final(100, 110, 10) == true)) __t27_assert_fail("\n exactly a window elapsed: final:\n is_final(100, 110, 10) = {any}\n", .{ is_final(100, 110, 10) }); + if (!(is_final(100, 200, 10) == true)) __t27_assert_fail("\n well past the window: final:\n is_final(100, 200, 10) = {any}\n", .{ is_final(100, 200, 10) }); + if (!(is_final(100, 90, 10) == false)) __t27_assert_fail("\n clock before settle epoch: never final:\n is_final(100, 90, 10) = {any}\n", .{ is_final(100, 90, 10) }); } test "finalize_is_gated_by_the_window" { - if (!(bal_after_finalize_gated(800, 16, 100, 105, 10) == 800)) @panic("premature finalize leaves balance put"); - if (!(bal_after_finalize_gated(800, 16, 100, 110, 10) == 816)) @panic("post-window finalize releases the reward"); - if (!(bal_after_finalize_gated(800, 16, 100, 105, 10) == bal_after_clawback(800))) @panic("in-window: reward not yet spendable, clawback still bites"); + if (!(bal_after_finalize_gated(800, 16, 100, 105, 10) == 800)) __t27_assert_fail("\n premature finalize leaves balance put:\n bal_after_finalize_gated(800, 16, 100, 105, 10) = {any}\n", .{ bal_after_finalize_gated(800, 16, 100, 105, 10) }); + if (!(bal_after_finalize_gated(800, 16, 100, 110, 10) == 816)) __t27_assert_fail("\n post-window finalize releases the reward:\n bal_after_finalize_gated(800, 16, 100, 110, 10) = {any}\n", .{ bal_after_finalize_gated(800, 16, 100, 110, 10) }); + if (!(bal_after_finalize_gated(800, 16, 100, 105, 10) == bal_after_clawback(800))) __t27_assert_fail("\n in-window: reward not yet spendable, clawback still bites:\n bal_after_finalize_gated(800, 16, 100, 105, 10) = {any}\n bal_after_clawback(800) = {any}\n", .{ bal_after_finalize_gated(800, 16, 100, 105, 10), bal_after_clawback(800) }); } test "outstanding_tracks_concurrent_escrow" { const o1 = outstanding_after_escrow(0, 16); const o2 = outstanding_after_escrow(o1, 32); - if (!(o2 == 48)) @panic("two concurrent escrows sum to 48 at risk"); + if (!(o2 == 48)) __t27_assert_fail("\n two concurrent escrows sum to 48 at risk:\n o2 = {any}\n", .{ o2 }); const r1 = outstanding_after_release(o2, 16); - if (!(r1 == 32)) @panic("finalizing one task lowers outstanding by only its reward"); + if (!(r1 == 32)) __t27_assert_fail("\n finalizing one task lowers outstanding by only its reward:\n r1 = {any}\n", .{ r1 }); const r2 = outstanding_after_release(r1, 32); - if (!(r2 == 0)) @panic("releasing the other returns outstanding to zero"); + if (!(r2 == 0)) __t27_assert_fail("\n releasing the other returns outstanding to zero:\n r2 = {any}\n", .{ r2 }); } test "finalize_and_clawback_release_equally" { - if (!(outstanding_after_release(48, 16) == outstanding_after_release(48, 16))) @panic("same release regardless of the reason"); - if (!(outstanding_after_release(16, 32) == 0)) @panic("over-release drains to zero, no underflow"); - if (!(outstanding_after_escrow(0xFFFFFFF0, 32) == 0xFFFFFFFF)) @panic("escrow saturates, no wrap"); + if (!(outstanding_after_release(48, 16) == outstanding_after_release(48, 16))) __t27_assert_fail("\n same release regardless of the reason:\n outstanding_after_release(48, 16) = {any}\n", .{ outstanding_after_release(48, 16) }); + if (!(outstanding_after_release(16, 32) == 0)) __t27_assert_fail("\n over-release drains to zero, no underflow:\n outstanding_after_release(16, 32) = {any}\n", .{ outstanding_after_release(16, 32) }); + if (!(outstanding_after_escrow(0xFFFFFFF0, 32) == 0xFFFFFFFF)) __t27_assert_fail("\n escrow saturates, no wrap:\n outstanding_after_escrow(0xFFFFFFF0, 32) = {any}\n", .{ outstanding_after_escrow(0xFFFFFFF0, 32) }); } test "outstanding_round_trips" { const o = outstanding_after_escrow(outstanding_after_escrow(outstanding_after_escrow(100, 5), 7), 9); - if (!(o == 121)) @panic("100 + 5 + 7 + 9 in flight"); + if (!(o == 121)) __t27_assert_fail("\n 100 + 5 + 7 + 9 in flight:\n o = {any}\n", .{ o }); const back = outstanding_after_release(outstanding_after_release(outstanding_after_release(o, 5), 7), 9); - if (!(back == 100)) @panic("releasing the whole batch returns to the starting level"); + if (!(back == 100)) __t27_assert_fail("\n releasing the whole batch returns to the starting level:\n back = {any}\n", .{ back }); } test "outstanding_agrees_with_pending" { - if (!(outstanding_after_escrow(0, 16) == pending_after_settle(0, 16))) @panic("escrow raises both identically"); - if (!(outstanding_after_escrow(16, 32) == pending_after_settle(16, 32))) @panic("and accumulates identically"); - if (!(escrow_consistent(pending_after_settle(0, 16), outstanding_after_escrow(0, 16)) == true)) @panic("the two stay equal after an escrow"); - if (!(outstanding_after_release(16, 16) == 0)) @panic("releasing the one task zeroes outstanding, as finalize zeroes pending"); - if (!(escrow_consistent(48, 48) == true)) @panic("equal -> consistent"); - if (!(escrow_consistent(48, 32) == false)) @panic("a drift is flagged, never silently gated on"); + if (!(outstanding_after_escrow(0, 16) == pending_after_settle(0, 16))) __t27_assert_fail("\n escrow raises both identically:\n outstanding_after_escrow(0, 16) = {any}\n pending_after_settle(0, 16) = {any}\n", .{ outstanding_after_escrow(0, 16), pending_after_settle(0, 16) }); + if (!(outstanding_after_escrow(16, 32) == pending_after_settle(16, 32))) __t27_assert_fail("\n and accumulates identically:\n outstanding_after_escrow(16, 32) = {any}\n pending_after_settle(16, 32) = {any}\n", .{ outstanding_after_escrow(16, 32), pending_after_settle(16, 32) }); + if (!(escrow_consistent(pending_after_settle(0, 16), outstanding_after_escrow(0, 16)) == true)) __t27_assert_fail("\n the two stay equal after an escrow:\n escrow_consistent(pending_after_settle(0, 16), outstanding_after_escrow(0, 16)) = {any}\n", .{ escrow_consistent(pending_after_settle(0, 16), outstanding_after_escrow(0, 16)) }); + if (!(outstanding_after_release(16, 16) == 0)) __t27_assert_fail("\n releasing the one task zeroes outstanding, as finalize zeroes pending:\n outstanding_after_release(16, 16) = {any}\n", .{ outstanding_after_release(16, 16) }); + if (!(escrow_consistent(48, 48) == true)) __t27_assert_fail("\n equal -> consistent:\n escrow_consistent(48, 48) = {any}\n", .{ escrow_consistent(48, 48) }); + if (!(escrow_consistent(48, 32) == false)) __t27_assert_fail("\n a drift is flagged, never silently gated on:\n escrow_consistent(48, 32) = {any}\n", .{ escrow_consistent(48, 32) }); } test "pending_release_mirrors_outstanding" { - if (!(pending_after_release(48, 16) == 32)) @panic("pending drops by exactly the released reward"); - if (!(pending_after_release(48, 16) == outstanding_after_release(48, 16))) @panic("pending and outstanding release identically"); - if (!(escrow_consistent(pending_after_release(48, 16), outstanding_after_release(48, 16)) == true)) @panic("consistent after a release, not only an escrow"); - if (!(pending_after_release(10, 20) == 0)) @panic("an over-release floors at 0, never underflows to ~4e9"); + if (!(pending_after_release(48, 16) == 32)) __t27_assert_fail("\n pending drops by exactly the released reward:\n pending_after_release(48, 16) = {any}\n", .{ pending_after_release(48, 16) }); + if (!(pending_after_release(48, 16) == outstanding_after_release(48, 16))) __t27_assert_fail("\n pending and outstanding release identically:\n pending_after_release(48, 16) = {any}\n outstanding_after_release(48, 16) = {any}\n", .{ pending_after_release(48, 16), outstanding_after_release(48, 16) }); + if (!(escrow_consistent(pending_after_release(48, 16), outstanding_after_release(48, 16)) == true)) __t27_assert_fail("\n consistent after a release, not only an escrow:\n escrow_consistent(pending_after_release(48, 16), outstanding_after_release(48, 16)) = {any}\n", .{ escrow_consistent(pending_after_release(48, 16), outstanding_after_release(48, 16)) }); + if (!(pending_after_release(10, 20) == 0)) __t27_assert_fail("\n an over-release floors at 0, never underflows to ~4e9:\n pending_after_release(10, 20) = {any}\n", .{ pending_after_release(10, 20) }); } test "clawback_removes_reward_before_finalize" { const pend0 = pending_after_settle(0, 16); const pend1 = pending_after_release(pend0, 16); - if (!(pend1 == 0)) @panic("clawback empties pending (the 'pending then 0' contract, now real)"); - if (!(bal_after_finalize_gated(500, pend1, 0, 100, 10) == 500)) @panic("window elapsed but clawed-back reward cannot finalize -> balance unchanged"); - if (!(bal_after_finalize_gated(500, pend0, 0, 100, 10) == 516)) @panic("an honest un-clawed reward still finalizes to balance after the window"); + if (!(pend1 == 0)) __t27_assert_fail("\n clawback empties pending (the 'pending then 0' contract, now real):\n pend1 = {any}\n", .{ pend1 }); + if (!(bal_after_finalize_gated(500, pend1, 0, 100, 10) == 500)) __t27_assert_fail("\n window elapsed but clawed-back reward cannot finalize -> balance unchanged:\n bal_after_finalize_gated(500, pend1, 0, 100, 10) = {any}\n", .{ bal_after_finalize_gated(500, pend1, 0, 100, 10) }); + if (!(bal_after_finalize_gated(500, pend0, 0, 100, 10) == 516)) __t27_assert_fail("\n an honest un-clawed reward still finalizes to balance after the window:\n bal_after_finalize_gated(500, pend0, 0, 100, 10) = {any}\n", .{ bal_after_finalize_gated(500, pend0, 0, 100, 10) }); } test "slashed_reward_never_finalizes" { - if (!(bal_after_finalize_checked(500, 16, 0, 100, 10, 0) == 516)) @panic("not slashed + window elapsed -> finalizes"); - if (!(bal_after_finalize_checked(500, 16, 0, 100, 10, 1) == 500)) @panic("slashed -> never finalizes, even past the window (clawback bypassed)"); - if (!(bal_after_finalize_checked(500, 16, 0, 5, 10, 0) == 500)) @panic("not slashed but inside the window -> still no finalize (time gate intact)"); - if (!(bal_after_finalize_checked(500, 16, 0, 5, 10, 1) == 500)) @panic("slashed inside the window -> no finalize"); + if (!(bal_after_finalize_checked(500, 16, 0, 100, 10, 0) == 516)) __t27_assert_fail("\n not slashed + window elapsed -> finalizes:\n bal_after_finalize_checked(500, 16, 0, 100, 10, 0) = {any}\n", .{ bal_after_finalize_checked(500, 16, 0, 100, 10, 0) }); + if (!(bal_after_finalize_checked(500, 16, 0, 100, 10, 1) == 500)) __t27_assert_fail("\n slashed -> never finalizes, even past the window (clawback bypassed):\n bal_after_finalize_checked(500, 16, 0, 100, 10, 1) = {any}\n", .{ bal_after_finalize_checked(500, 16, 0, 100, 10, 1) }); + if (!(bal_after_finalize_checked(500, 16, 0, 5, 10, 0) == 500)) __t27_assert_fail("\n not slashed but inside the window -> still no finalize (time gate intact):\n bal_after_finalize_checked(500, 16, 0, 5, 10, 0) = {any}\n", .{ bal_after_finalize_checked(500, 16, 0, 5, 10, 0) }); + if (!(bal_after_finalize_checked(500, 16, 0, 5, 10, 1) == 500)) __t27_assert_fail("\n slashed inside the window -> no finalize:\n bal_after_finalize_checked(500, 16, 0, 5, 10, 1) = {any}\n", .{ bal_after_finalize_checked(500, 16, 0, 5, 10, 1) }); } test "escrow_saturation_keeps_them_equal" { - if (!(pending_after_settle(0xFFFFFFF0, 32) == 0xFFFFFFFF)) @panic("overflowing escrow saturates pending, no wrap"); - if (!(pending_after_settle(0xFFFFFFF0, 32) == outstanding_after_escrow(0xFFFFFFF0, 32))) @panic("pending == outstanding at the ceiling"); - if (!(escrow_consistent(pending_after_settle(0xFFFFFFF0, 32), outstanding_after_escrow(0xFFFFFFF0, 32)) == true)) @panic("still consistent under overflow"); - if (!(pending_after_settle(1000, 500) == 1500)) @panic("normal accumulation is exact"); + if (!(pending_after_settle(0xFFFFFFF0, 32) == 0xFFFFFFFF)) __t27_assert_fail("\n overflowing escrow saturates pending, no wrap:\n pending_after_settle(0xFFFFFFF0, 32) = {any}\n", .{ pending_after_settle(0xFFFFFFF0, 32) }); + if (!(pending_after_settle(0xFFFFFFF0, 32) == outstanding_after_escrow(0xFFFFFFF0, 32))) __t27_assert_fail("\n pending == outstanding at the ceiling:\n pending_after_settle(0xFFFFFFF0, 32) = {any}\n outstanding_after_escrow(0xFFFFFFF0, 32) = {any}\n", .{ pending_after_settle(0xFFFFFFF0, 32), outstanding_after_escrow(0xFFFFFFF0, 32) }); + if (!(escrow_consistent(pending_after_settle(0xFFFFFFF0, 32), outstanding_after_escrow(0xFFFFFFF0, 32)) == true)) __t27_assert_fail("\n still consistent under overflow:\n escrow_consistent(pending_after_settle(0xFFFFFFF0, 32), outstanding_after_escrow(0xFFFFFFF0, 32)) = {any}\n", .{ escrow_consistent(pending_after_settle(0xFFFFFFF0, 32), outstanding_after_escrow(0xFFFFFFF0, 32)) }); + if (!(pending_after_settle(1000, 500) == 1500)) __t27_assert_fail("\n normal accumulation is exact:\n pending_after_settle(1000, 500) = {any}\n", .{ pending_after_settle(1000, 500) }); } test "total_conserved_over_outstanding_cycle" { const o0 = outstanding_after_escrow(0, 16); const t_mid = total3(800, 200, o0); const o1 = outstanding_after_release(o0, 16); const t_end = total3(800 + 16, 200, o1); - if (!(t_mid == total3(800, 200, 16))) @panic("mid-flight holdings count the at-risk 16"); - if (!(t_end == t_mid)) @panic("finalize (outstanding -> balance) conserves total holdings"); + if (!(t_mid == total3(800, 200, 16))) __t27_assert_fail("\n mid-flight holdings count the at-risk 16:\n t_mid = {any}\n total3(800, 200, 16) = {any}\n", .{ t_mid, total3(800, 200, 16) }); + if (!(t_end == t_mid)) __t27_assert_fail("\n finalize (outstanding -> balance) conserves total holdings:\n t_end = {any}\n t_mid = {any}\n", .{ t_end, t_mid }); } diff --git a/gen/zig/tri_compute_bitnet.zig b/gen/zig/tri_compute_bitnet.zig index bd835cb8..6e829275 100644 --- a/gen/zig/tri_compute_bitnet.zig +++ b/gen/zig/tri_compute_bitnet.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const OP_BITNET: u32 = 0x20; @@ -114,92 +122,92 @@ fn bitnet_digest_pre(idx: u32, weight_code: u32, act_hash: u32, gf_result: u32, return 0; } test "sparsity_count" { - if (!(active_weights4(0x61) == 3)) @panic("three nonzero weights"); - if (!(active_weights4(0x00) == 0)) @panic("all-zero weights -> nothing active"); - if (!(active_weights4(0x55) == 4)) @panic("0x55 = four +1 trits -> 4 active"); + if (!(active_weights4(0x61) == 3)) __t27_assert_fail("\n three nonzero weights:\n active_weights4(0x61) = {any}\n", .{ active_weights4(0x61) }); + if (!(active_weights4(0x00) == 0)) __t27_assert_fail("\n all-zero weights -> nothing active:\n active_weights4(0x00) = {any}\n", .{ active_weights4(0x00) }); + if (!(active_weights4(0x55) == 4)) __t27_assert_fail("\n 0x55 = four +1 trits -> 4 active:\n active_weights4(0x55) = {any}\n", .{ active_weights4(0x55) }); } test "trit_11_is_a_zero" { - if (!(is_active(0) == 0)) @panic("00 -> zero -> inactive"); - if (!(is_active(1) == 1)) @panic("01 -> +1 -> active"); - if (!(is_active(2) == 1)) @panic("10 -> -1 -> active"); - if (!(is_active(3) == 0)) @panic("11 -> redundant zero -> inactive, NOT counted"); - if (!(active_weights4(0xFF) == 0)) @panic("four 11-codes all decode to zero -> 0 active"); - if (!(active_weights4(0x1B) == 2)) @panic("mixed word counts only the two canonical nonzero trits"); - if (!(active_weights4(0xF5) == 2)) @panic("0xF5 = {01,01,11,11} -> 2 active (the two 11s do not count)"); + if (!(is_active(0) == 0)) __t27_assert_fail("\n 00 -> zero -> inactive:\n is_active(0) = {any}\n", .{ is_active(0) }); + if (!(is_active(1) == 1)) __t27_assert_fail("\n 01 -> +1 -> active:\n is_active(1) = {any}\n", .{ is_active(1) }); + if (!(is_active(2) == 1)) __t27_assert_fail("\n 10 -> -1 -> active:\n is_active(2) = {any}\n", .{ is_active(2) }); + if (!(is_active(3) == 0)) __t27_assert_fail("\n 11 -> redundant zero -> inactive, NOT counted:\n is_active(3) = {any}\n", .{ is_active(3) }); + if (!(active_weights4(0xFF) == 0)) __t27_assert_fail("\n four 11-codes all decode to zero -> 0 active:\n active_weights4(0xFF) = {any}\n", .{ active_weights4(0xFF) }); + if (!(active_weights4(0x1B) == 2)) __t27_assert_fail("\n mixed word counts only the two canonical nonzero trits:\n active_weights4(0x1B) = {any}\n", .{ active_weights4(0x1B) }); + if (!(active_weights4(0xF5) == 2)) __t27_assert_fail("\n 0xF5 = {{01,01,11,11}} -> 2 active (the two 11s do not count):\n active_weights4(0xF5) = {any}\n", .{ active_weights4(0xF5) }); } test "canonical_packing_gate" { - if (!(packing_is_canonical(0x00) == true)) @panic("all-00 zeros are canonical"); - if (!(packing_is_canonical(0x55) == true)) @panic("all-+1 is canonical"); - if (!(packing_is_canonical(0x61) == true)) @panic("a mixed canonical word"); - if (!(packing_is_canonical(0xFF) == false)) @panic("all-11 is a non-canonical zero packing"); - if (!(packing_is_canonical(0x1B) == false)) @panic("a single 0b11 trit makes the word non-canonical"); - if (!(weights_canonical4(0xF5) == 2)) @panic("0xF5 has two 11-codes -> only 2 canonical trits"); + if (!(packing_is_canonical(0x00) == true)) __t27_assert_fail("\n all-00 zeros are canonical:\n packing_is_canonical(0x00) = {any}\n", .{ packing_is_canonical(0x00) }); + if (!(packing_is_canonical(0x55) == true)) __t27_assert_fail("\n all-+1 is canonical:\n packing_is_canonical(0x55) = {any}\n", .{ packing_is_canonical(0x55) }); + if (!(packing_is_canonical(0x61) == true)) __t27_assert_fail("\n a mixed canonical word:\n packing_is_canonical(0x61) = {any}\n", .{ packing_is_canonical(0x61) }); + if (!(packing_is_canonical(0xFF) == false)) __t27_assert_fail("\n all-11 is a non-canonical zero packing:\n packing_is_canonical(0xFF) = {any}\n", .{ packing_is_canonical(0xFF) }); + if (!(packing_is_canonical(0x1B) == false)) __t27_assert_fail("\n a single 0b11 trit makes the word non-canonical:\n packing_is_canonical(0x1B) = {any}\n", .{ packing_is_canonical(0x1B) }); + if (!(weights_canonical4(0xF5) == 2)) __t27_assert_fail("\n 0xF5 has two 11-codes -> only 2 canonical trits:\n weights_canonical4(0xF5) = {any}\n", .{ weights_canonical4(0xF5) }); } test "canonical_form_is_unique" { const zeros_ok = bitnet_leaf(0x00, 0xABCD, 0x4100, 0xC0FFEE01, 0xE0E0, 1); const zeros_bad = bitnet_leaf(0xFF, 0xABCD, 0x4100, 0xC0FFEE01, 0xE0E0, 1); - if (!(zeros_ok != zeros_bad)) @panic("the two zero-packings hash differently (the malleability)"); - if (!(packing_is_canonical(0x00) == true)) @panic("only the 0x00 packing is canonical..."); - if (!(packing_is_canonical(0xFF) == false)) @panic("...so the 0xFF alias is rejected -> one valid leaf"); + if (!(zeros_ok != zeros_bad)) __t27_assert_fail("\n the two zero-packings hash differently (the malleability):\n zeros_ok = {any}\n zeros_bad = {any}\n", .{ zeros_ok, zeros_bad }); + if (!(packing_is_canonical(0x00) == true)) __t27_assert_fail("\n only the 0x00 packing is canonical...:\n packing_is_canonical(0x00) = {any}\n", .{ packing_is_canonical(0x00) }); + if (!(packing_is_canonical(0xFF) == false)) __t27_assert_fail("\n ...so the 0xFF alias is rejected -> one valid leaf:\n packing_is_canonical(0xFF) = {any}\n", .{ packing_is_canonical(0xFF) }); } test "signed_decode_and_balance" { - if (!(pos_weights4(0x61) == 2)) @panic("two +1 weights"); - if (!(neg_weights4(0x61) == 1)) @panic("one -1 weight"); - if (!(sign_balance_biased(0x61) == 5)) @panic("balance +1 biased by 4 -> 5"); - if (!(pos_weights4(0x55) == 4)) @panic("0x55 = four +1"); - if (!(sign_balance_biased(0x55) == 8)) @panic("all +1 -> +4 -> biased 8"); - if (!(neg_weights4(0xAA) == 4)) @panic("0xAA = four -1"); - if (!(sign_balance_biased(0xAA) == 0)) @panic("all -1 -> -4 -> biased 0"); - if (!(sign_balance_biased(0x00) == 4)) @panic("all zero -> net 0 -> biased 4"); - if (!(pos_weights4(0xFF) == 0)) @panic("four 11-codes contribute no +1"); - if (!(neg_weights4(0xFF) == 0)) @panic("four 11-codes contribute no -1"); - if (!(sign_balance_biased(0xFF) == 4)) @panic("four 11-codes are net zero (biased 4)"); + if (!(pos_weights4(0x61) == 2)) __t27_assert_fail("\n two +1 weights:\n pos_weights4(0x61) = {any}\n", .{ pos_weights4(0x61) }); + if (!(neg_weights4(0x61) == 1)) __t27_assert_fail("\n one -1 weight:\n neg_weights4(0x61) = {any}\n", .{ neg_weights4(0x61) }); + if (!(sign_balance_biased(0x61) == 5)) __t27_assert_fail("\n balance +1 biased by 4 -> 5:\n sign_balance_biased(0x61) = {any}\n", .{ sign_balance_biased(0x61) }); + if (!(pos_weights4(0x55) == 4)) __t27_assert_fail("\n 0x55 = four +1:\n pos_weights4(0x55) = {any}\n", .{ pos_weights4(0x55) }); + if (!(sign_balance_biased(0x55) == 8)) __t27_assert_fail("\n all +1 -> +4 -> biased 8:\n sign_balance_biased(0x55) = {any}\n", .{ sign_balance_biased(0x55) }); + if (!(neg_weights4(0xAA) == 4)) __t27_assert_fail("\n 0xAA = four -1:\n neg_weights4(0xAA) = {any}\n", .{ neg_weights4(0xAA) }); + if (!(sign_balance_biased(0xAA) == 0)) __t27_assert_fail("\n all -1 -> -4 -> biased 0:\n sign_balance_biased(0xAA) = {any}\n", .{ sign_balance_biased(0xAA) }); + if (!(sign_balance_biased(0x00) == 4)) __t27_assert_fail("\n all zero -> net 0 -> biased 4:\n sign_balance_biased(0x00) = {any}\n", .{ sign_balance_biased(0x00) }); + if (!(pos_weights4(0xFF) == 0)) __t27_assert_fail("\n four 11-codes contribute no +1:\n pos_weights4(0xFF) = {any}\n", .{ pos_weights4(0xFF) }); + if (!(neg_weights4(0xFF) == 0)) __t27_assert_fail("\n four 11-codes contribute no -1:\n neg_weights4(0xFF) = {any}\n", .{ neg_weights4(0xFF) }); + if (!(sign_balance_biased(0xFF) == 4)) __t27_assert_fail("\n four 11-codes are net zero (biased 4):\n sign_balance_biased(0xFF) = {any}\n", .{ sign_balance_biased(0xFF) }); } test "pos_plus_neg_is_active" { - if (!((pos_weights4(0x61) + neg_weights4(0x61)) == active_weights4(0x61))) @panic("pos+neg == active (mixed)"); - if (!((pos_weights4(0x55) + neg_weights4(0x55)) == active_weights4(0x55))) @panic("pos+neg == active (all +1)"); - if (!((pos_weights4(0xFF) + neg_weights4(0xFF)) == active_weights4(0xFF))) @panic("pos+neg == active (all 11 zeros)"); + if (!((pos_weights4(0x61) + neg_weights4(0x61)) == active_weights4(0x61))) __t27_assert_fail("\n pos+neg == active (mixed):\n pos_weights4(0x61) + neg_weights4(0x61) = {any}\n active_weights4(0x61) = {any}\n", .{ pos_weights4(0x61) + neg_weights4(0x61), active_weights4(0x61) }); + if (!((pos_weights4(0x55) + neg_weights4(0x55)) == active_weights4(0x55))) __t27_assert_fail("\n pos+neg == active (all +1):\n pos_weights4(0x55) + neg_weights4(0x55) = {any}\n active_weights4(0x55) = {any}\n", .{ pos_weights4(0x55) + neg_weights4(0x55), active_weights4(0x55) }); + if (!((pos_weights4(0xFF) + neg_weights4(0xFF)) == active_weights4(0xFF))) __t27_assert_fail("\n pos+neg == active (all 11 zeros):\n pos_weights4(0xFF) + neg_weights4(0xFF) = {any}\n active_weights4(0xFF) = {any}\n", .{ pos_weights4(0xFF) + neg_weights4(0xFF), active_weights4(0xFF) }); } test "bitnet_balance_recompute" { - if (!(bitnet_balance_matches(0x61, 5) == true)) @panic("canonical weights + correct balance -> verified"); - if (!(bitnet_balance_matches(0x61, 8) == false)) @panic("canonical weights + WRONG claimed balance -> rejected (fraud)"); - if (!(bitnet_balance_matches(0x55, 8) == true)) @panic("all +1 -> biased 8 verified"); - if (!(bitnet_balance_matches(0xAA, 0) == true)) @panic("all -1 -> biased 0 verified"); - if (!(bitnet_balance_matches(0xFF, 4) == false)) @panic("non-canonical 0b11 packing rejected regardless of balance"); - if (!(bitnet_balance_matches(0x1B, sign_balance_biased(0x1B)) == false)) @panic("a single 0b11 trit fails the check even at its own balance"); + if (!(bitnet_balance_matches(0x61, 5) == true)) __t27_assert_fail("\n canonical weights + correct balance -> verified:\n bitnet_balance_matches(0x61, 5) = {any}\n", .{ bitnet_balance_matches(0x61, 5) }); + if (!(bitnet_balance_matches(0x61, 8) == false)) __t27_assert_fail("\n canonical weights + WRONG claimed balance -> rejected (fraud):\n bitnet_balance_matches(0x61, 8) = {any}\n", .{ bitnet_balance_matches(0x61, 8) }); + if (!(bitnet_balance_matches(0x55, 8) == true)) __t27_assert_fail("\n all +1 -> biased 8 verified:\n bitnet_balance_matches(0x55, 8) = {any}\n", .{ bitnet_balance_matches(0x55, 8) }); + if (!(bitnet_balance_matches(0xAA, 0) == true)) __t27_assert_fail("\n all -1 -> biased 0 verified:\n bitnet_balance_matches(0xAA, 0) = {any}\n", .{ bitnet_balance_matches(0xAA, 0) }); + if (!(bitnet_balance_matches(0xFF, 4) == false)) __t27_assert_fail("\n non-canonical 0b11 packing rejected regardless of balance:\n bitnet_balance_matches(0xFF, 4) = {any}\n", .{ bitnet_balance_matches(0xFF, 4) }); + if (!(bitnet_balance_matches(0x1B, sign_balance_biased(0x1B)) == false)) __t27_assert_fail("\n a single 0b11 trit fails the check even at its own balance:\n bitnet_balance_matches(0x1B, sign_balance_biased(0x1B)) = {any}\n", .{ bitnet_balance_matches(0x1B, sign_balance_biased(0x1B)) }); } test "weights_are_bound" { const base = bitnet_leaf(0x61, 0xABCD, 0x4100, 0xC0FFEE01, 0xE0E0, 1); const flip = bitnet_leaf(0x62, 0xABCD, 0x4100, 0xC0FFEE01, 0xE0E0, 1); - if (!(base != flip)) @panic("changing a ternary weight changes the receipt"); + if (!(base != flip)) __t27_assert_fail("\n changing a ternary weight changes the receipt:\n base = {any}\n flip = {any}\n", .{ base, flip }); } test "gf16_side_is_bound" { const base = bitnet_leaf(0x61, 0xABCD, 0x4100, 0xC0FFEE01, 0xE0E0, 1); const act = bitnet_leaf(0x61, 0x9999, 0x4100, 0xC0FFEE01, 0xE0E0, 1); const res = bitnet_leaf(0x61, 0xABCD, 0x4200, 0xC0FFEE01, 0xE0E0, 1); - if (!(base != act)) @panic("changing the GF16 activation changes the receipt"); - if (!(base != res)) @panic("changing the GF16 result changes the receipt"); + if (!(base != act)) __t27_assert_fail("\n changing the GF16 activation changes the receipt:\n base = {any}\n act = {any}\n", .{ base, act }); + if (!(base != res)) __t27_assert_fail("\n changing the GF16 result changes the receipt:\n base = {any}\n res = {any}\n", .{ base, res }); } test "executor_epoch_bound_distinctly" { const a = bitnet_leaf(0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3); const b = bitnet_leaf(0x61, 0xABCD, 0x4100, 0xC0FFEE01, 3, 5); - if (!(a != b)) @panic("same executor+epoch SUM, different pair -> different leaf (no collision)"); + if (!(a != b)) __t27_assert_fail("\n same executor+epoch SUM, different pair -> different leaf (no collision):\n a = {any}\n b = {any}\n", .{ a, b }); const base = bitnet_leaf(0x61, 0xABCD, 0x4100, 0xC0FFEE01, 0xE0E0, 1); const exe = bitnet_leaf(0x61, 0xABCD, 0x4100, 0xC0FFEE01, 0xE0E1, 1); const ep = bitnet_leaf(0x61, 0xABCD, 0x4100, 0xC0FFEE01, 0xE0E0, 2); - if (!(base != exe)) @panic("changing the executor changes the leaf"); - if (!(base != ep)) @panic("changing the epoch changes the leaf"); + if (!(base != exe)) __t27_assert_fail("\n changing the executor changes the leaf:\n base = {any}\n exe = {any}\n", .{ base, exe }); + if (!(base != ep)) __t27_assert_fail("\n changing the epoch changes the leaf:\n base = {any}\n ep = {any}\n", .{ base, ep }); } test "bitnet_digest_preimage" { - if (!(bitnet_digest_pre(0, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == TAG_BITNET)) @panic("word 0 is the bitnet domain tag"); - if (!(bitnet_digest_pre(1, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == 0x61)) @panic("word 1 is the weight_code"); - if (!(bitnet_digest_pre(2, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == 0xABCD)) @panic("word 2 is the activation hash"); - if (!(bitnet_digest_pre(3, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == 0x4100)) @panic("word 3 is the GF result"); - if (!(bitnet_digest_pre(4, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == 0xC0FFEE01)) @panic("word 4 is the device"); - if (!(bitnet_digest_pre(5, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == 5)) @panic("word 5 is the executor (distinct word)"); - if (!(bitnet_digest_pre(6, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == 3)) @panic("word 6 is the epoch (distinct -- no sum)"); - if (!(bitnet_digest_pre(7, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == SHA_PAD)) @panic("word 7 starts the SHA-256 padding"); - if (!(bitnet_digest_pre(10, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == 0)) @panic("middle padding words are zero"); - if (!(bitnet_digest_pre(15, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == BITNET_MSG_BITS)) @panic("word 15 is the 224-bit message length"); - if (!(bitnet_digest_pre(5, 0, 0, 0, 0, 3, 5) == 3)) @panic("exec 3 -> word 5 = 3 (a different preimage than exec 5)"); + if (!(bitnet_digest_pre(0, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == TAG_BITNET)) __t27_assert_fail("\n word 0 is the bitnet domain tag:\n bitnet_digest_pre(0, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) = {any}\n TAG_BITNET = {any}\n", .{ bitnet_digest_pre(0, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3), TAG_BITNET }); + if (!(bitnet_digest_pre(1, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == 0x61)) __t27_assert_fail("\n word 1 is the weight_code:\n bitnet_digest_pre(1, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) = {any}\n", .{ bitnet_digest_pre(1, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) }); + if (!(bitnet_digest_pre(2, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == 0xABCD)) __t27_assert_fail("\n word 2 is the activation hash:\n bitnet_digest_pre(2, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) = {any}\n", .{ bitnet_digest_pre(2, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) }); + if (!(bitnet_digest_pre(3, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == 0x4100)) __t27_assert_fail("\n word 3 is the GF result:\n bitnet_digest_pre(3, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) = {any}\n", .{ bitnet_digest_pre(3, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) }); + if (!(bitnet_digest_pre(4, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == 0xC0FFEE01)) __t27_assert_fail("\n word 4 is the device:\n bitnet_digest_pre(4, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) = {any}\n", .{ bitnet_digest_pre(4, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) }); + if (!(bitnet_digest_pre(5, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == 5)) __t27_assert_fail("\n word 5 is the executor (distinct word):\n bitnet_digest_pre(5, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) = {any}\n", .{ bitnet_digest_pre(5, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) }); + if (!(bitnet_digest_pre(6, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == 3)) __t27_assert_fail("\n word 6 is the epoch (distinct -- no sum):\n bitnet_digest_pre(6, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) = {any}\n", .{ bitnet_digest_pre(6, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) }); + if (!(bitnet_digest_pre(7, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == SHA_PAD)) __t27_assert_fail("\n word 7 starts the SHA-256 padding:\n bitnet_digest_pre(7, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) = {any}\n SHA_PAD = {any}\n", .{ bitnet_digest_pre(7, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3), SHA_PAD }); + if (!(bitnet_digest_pre(10, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == 0)) __t27_assert_fail("\n middle padding words are zero:\n bitnet_digest_pre(10, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) = {any}\n", .{ bitnet_digest_pre(10, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) }); + if (!(bitnet_digest_pre(15, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) == BITNET_MSG_BITS)) __t27_assert_fail("\n word 15 is the 224-bit message length:\n bitnet_digest_pre(15, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3) = {any}\n BITNET_MSG_BITS = {any}\n", .{ bitnet_digest_pre(15, 0x61, 0xABCD, 0x4100, 0xC0FFEE01, 5, 3), BITNET_MSG_BITS }); + if (!(bitnet_digest_pre(5, 0, 0, 0, 0, 3, 5) == 3)) __t27_assert_fail("\n exec 3 -> word 5 = 3 (a different preimage than exec 5):\n bitnet_digest_pre(5, 0, 0, 0, 0, 3, 5) = {any}\n", .{ bitnet_digest_pre(5, 0, 0, 0, 0, 3, 5) }); } diff --git a/gen/zig/tri_compute_bond.zig b/gen/zig/tri_compute_bond.zig index ffb1bb7a..5f61ce1f 100644 --- a/gen/zig/tri_compute_bond.zig +++ b/gen/zig/tri_compute_bond.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const ST_FREE: u32 = 0; @@ -71,64 +79,64 @@ fn bond_covers_rung(bond: u32, outstanding: u32, min_bps: u32, gf_et: u32) bool return bond >= required_bond_rung(outstanding, min_bps, gf_et); } test "post_is_guarded" { - if (!(can_post(1000, 200) == true)) @panic("can lock within balance"); - if (!(can_post(1000, 2000) == false)) @panic("cannot over-post"); - if (!(balance_after_post(1000, 200) == 800)) @panic("valid post reduces balance"); - if (!(balance_after_post(1000, 2000) == 1000)) @panic("over-post is a no-op (no underflow)"); - if (!(locked_amount(1000, 200) == 200)) @panic("locks the requested amount"); - if (!(locked_amount(1000, 2000) == 0)) @panic("invalid post locks nothing"); + if (!(can_post(1000, 200) == true)) __t27_assert_fail("\n can lock within balance:\n can_post(1000, 200) = {any}\n", .{ can_post(1000, 200) }); + if (!(can_post(1000, 2000) == false)) __t27_assert_fail("\n cannot over-post:\n can_post(1000, 2000) = {any}\n", .{ can_post(1000, 2000) }); + if (!(balance_after_post(1000, 200) == 800)) __t27_assert_fail("\n valid post reduces balance:\n balance_after_post(1000, 200) = {any}\n", .{ balance_after_post(1000, 200) }); + if (!(balance_after_post(1000, 2000) == 1000)) __t27_assert_fail("\n over-post is a no-op (no underflow):\n balance_after_post(1000, 2000) = {any}\n", .{ balance_after_post(1000, 2000) }); + if (!(locked_amount(1000, 200) == 200)) __t27_assert_fail("\n locks the requested amount:\n locked_amount(1000, 200) = {any}\n", .{ locked_amount(1000, 200) }); + if (!(locked_amount(1000, 2000) == 0)) __t27_assert_fail("\n invalid post locks nothing:\n locked_amount(1000, 2000) = {any}\n", .{ locked_amount(1000, 2000) }); } test "honest_round_trips_the_bond" { const after_post = balance_after_post(1000, 200); const bond = locked_amount(1000, 200); - if (!(bond_state_after(0) == ST_RELEASED)) @panic("honest -> released"); - if (!(balance_after_resolve(after_post, bond, 0) == 1000)) @panic("bond returns; balance whole"); + if (!(bond_state_after(0) == ST_RELEASED)) __t27_assert_fail("\n honest -> released:\n bond_state_after(0) = {any}\n ST_RELEASED = {any}\n", .{ bond_state_after(0), ST_RELEASED }); + if (!(balance_after_resolve(after_post, bond, 0) == 1000)) __t27_assert_fail("\n bond returns; balance whole:\n balance_after_resolve(after_post, bond, 0) = {any}\n", .{ balance_after_resolve(after_post, bond, 0) }); } test "honest_release_saturates" { - if (!(balance_after_resolve(500, 200, 0) == 700)) @panic("normal release exact (regression)"); - if (!(balance_after_resolve(0xFFFFFFF0, 200, 0) == 0xFFFFFFFF)) @panic("release that would overflow saturates to u32 max, not wrap to ~184"); - if (!(balance_after_resolve(0xFFFFFFF0, 200, 1) == 0xFFFFFFF0)) @panic("slash never adds -> no overflow, balance unchanged"); + if (!(balance_after_resolve(500, 200, 0) == 700)) __t27_assert_fail("\n normal release exact (regression):\n balance_after_resolve(500, 200, 0) = {any}\n", .{ balance_after_resolve(500, 200, 0) }); + if (!(balance_after_resolve(0xFFFFFFF0, 200, 0) == 0xFFFFFFFF)) __t27_assert_fail("\n release that would overflow saturates to u32 max, not wrap to ~184:\n balance_after_resolve(0xFFFFFFF0, 200, 0) = {any}\n", .{ balance_after_resolve(0xFFFFFFF0, 200, 0) }); + if (!(balance_after_resolve(0xFFFFFFF0, 200, 1) == 0xFFFFFFF0)) __t27_assert_fail("\n slash never adds -> no overflow, balance unchanged:\n balance_after_resolve(0xFFFFFFF0, 200, 1) = {any}\n", .{ balance_after_resolve(0xFFFFFFF0, 200, 1) }); } test "slash_forfeits_the_bond" { const after_post = balance_after_post(1000, 200); const bond = locked_amount(1000, 200); - if (!(bond_state_after(1) == ST_SLASHED)) @panic("slash -> slashed"); - if (!(balance_after_resolve(after_post, bond, 1) == 800)) @panic("bond forfeited; balance stays reduced"); + if (!(bond_state_after(1) == ST_SLASHED)) __t27_assert_fail("\n slash -> slashed:\n bond_state_after(1) = {any}\n ST_SLASHED = {any}\n", .{ bond_state_after(1), ST_SLASHED }); + if (!(balance_after_resolve(after_post, bond, 1) == 800)) __t27_assert_fail("\n bond forfeited; balance stays reduced:\n balance_after_resolve(after_post, bond, 1) = {any}\n", .{ balance_after_resolve(after_post, bond, 1) }); } test "non_terminal_outcomes_keep_the_bond_locked" { - if (!(bond_state_after(2) == ST_LOCKED)) @panic("MALFORMED -> bond stays locked, not slashed"); - if (!(bond_state_after(3) == ST_LOCKED)) @panic("STALE -> bond stays locked"); - if (!(bond_state_after(4) == ST_LOCKED)) @panic("FAMILY_MISMATCH -> bond stays locked"); - if (!(bond_state_after(5) == ST_LOCKED)) @panic("INDETERMINATE -> bond stays locked"); - if (!(bond_state_after(0) == ST_RELEASED)) @panic("HONEST -> released"); - if (!(bond_state_after(1) == ST_SLASHED)) @panic("SLASH -> slashed"); + if (!(bond_state_after(2) == ST_LOCKED)) __t27_assert_fail("\n MALFORMED -> bond stays locked, not slashed:\n bond_state_after(2) = {any}\n ST_LOCKED = {any}\n", .{ bond_state_after(2), ST_LOCKED }); + if (!(bond_state_after(3) == ST_LOCKED)) __t27_assert_fail("\n STALE -> bond stays locked:\n bond_state_after(3) = {any}\n ST_LOCKED = {any}\n", .{ bond_state_after(3), ST_LOCKED }); + if (!(bond_state_after(4) == ST_LOCKED)) __t27_assert_fail("\n FAMILY_MISMATCH -> bond stays locked:\n bond_state_after(4) = {any}\n ST_LOCKED = {any}\n", .{ bond_state_after(4), ST_LOCKED }); + if (!(bond_state_after(5) == ST_LOCKED)) __t27_assert_fail("\n INDETERMINATE -> bond stays locked:\n bond_state_after(5) = {any}\n ST_LOCKED = {any}\n", .{ bond_state_after(5), ST_LOCKED }); + if (!(bond_state_after(0) == ST_RELEASED)) __t27_assert_fail("\n HONEST -> released:\n bond_state_after(0) = {any}\n ST_RELEASED = {any}\n", .{ bond_state_after(0), ST_RELEASED }); + if (!(bond_state_after(1) == ST_SLASHED)) __t27_assert_fail("\n SLASH -> slashed:\n bond_state_after(1) = {any}\n ST_SLASHED = {any}\n", .{ bond_state_after(1), ST_SLASHED }); const after_post = balance_after_post(1000, 200); - if (!(balance_after_resolve(after_post, 200, 2) == 800)) @panic("malformed: bond neither returned nor added to balance"); - if (!(balance_after_resolve(after_post, 200, 5) == 800)) @panic("indeterminate: bond stays escrowed"); + if (!(balance_after_resolve(after_post, 200, 2) == 800)) __t27_assert_fail("\n malformed: bond neither returned nor added to balance:\n balance_after_resolve(after_post, 200, 2) = {any}\n", .{ balance_after_resolve(after_post, 200, 2) }); + if (!(balance_after_resolve(after_post, 200, 5) == 800)) __t27_assert_fail("\n indeterminate: bond stays escrowed:\n balance_after_resolve(after_post, 200, 5) = {any}\n", .{ balance_after_resolve(after_post, 200, 5) }); } test "required_bond_scales" { - if (!(required_bond(1000, 2000) == 200)) @panic("20% of 1000 outstanding = 200"); - if (!(required_bond(1000, BOND_BPS_UNIT) == 1000)) @panic("100% ratio -> bond must equal outstanding"); - if (!(required_bond(1000, 15000) == 1500)) @panic("150% ratio -> over-collateralized"); - if (!(required_bond(0, 15000) == 0)) @panic("no outstanding risk needs no bond"); - if (!(required_bond(1000000, 20000) == 2000000)) @panic("1e6 * 20000 / 10000 = 2e6 (u64, no u32 overflow)"); + if (!(required_bond(1000, 2000) == 200)) __t27_assert_fail("\n 20% of 1000 outstanding = 200:\n required_bond(1000, 2000) = {any}\n", .{ required_bond(1000, 2000) }); + if (!(required_bond(1000, BOND_BPS_UNIT) == 1000)) __t27_assert_fail("\n 100% ratio -> bond must equal outstanding:\n required_bond(1000, BOND_BPS_UNIT) = {any}\n", .{ required_bond(1000, BOND_BPS_UNIT) }); + if (!(required_bond(1000, 15000) == 1500)) __t27_assert_fail("\n 150% ratio -> over-collateralized:\n required_bond(1000, 15000) = {any}\n", .{ required_bond(1000, 15000) }); + if (!(required_bond(0, 15000) == 0)) __t27_assert_fail("\n no outstanding risk needs no bond:\n required_bond(0, 15000) = {any}\n", .{ required_bond(0, 15000) }); + if (!(required_bond(1000000, 20000) == 2000000)) __t27_assert_fail("\n 1e6 * 20000 / 10000 = 2e6 (u64, no u32 overflow):\n required_bond(1000000, 20000) = {any}\n", .{ required_bond(1000000, 20000) }); } test "required_bond_scales_with_rung" { - if (!(rung_min_bps(2000, 4) == 2000)) @panic("GF-T16 (Et4) uses the base ratio"); - if (!(rung_min_bps(2000, 6) == 3000)) @panic("GF-T32 (Et6) +2 trits -> +10%"); - if (!(rung_min_bps(2000, 9) == 4500)) @panic("GF-T64 (Et9) +5 trits -> +25%"); - if (!(rung_min_bps(2000, 14) == 7000)) @panic("GF-T128 (Et14) +10 trits -> +50%"); - if (!(rung_min_bps(2000, 3) == 2000)) @panic("sub-flagship GF-T8 uses the base (never shrinks)"); - if (!(required_bond_rung(1000, 2000, 4) == 200)) @panic("GF-T16 needs 200"); - if (!(required_bond_rung(1000, 2000, 9) == 450)) @panic("GF-T64 needs 450 -- more collateral"); - if (!(required_bond_rung(1000, 2000, 9) > required_bond_rung(1000, 2000, 4))) @panic("wider rung -> bigger bond"); - if (!(bond_covers_rung(450, 1000, 2000, 9) == true)) @panic("450 covers GF-T64"); - if (!(bond_covers_rung(200, 1000, 2000, 9) == false)) @panic("a GF-T16-sized bond underfunds GF-T64"); + if (!(rung_min_bps(2000, 4) == 2000)) __t27_assert_fail("\n GF-T16 (Et4) uses the base ratio:\n rung_min_bps(2000, 4) = {any}\n", .{ rung_min_bps(2000, 4) }); + if (!(rung_min_bps(2000, 6) == 3000)) __t27_assert_fail("\n GF-T32 (Et6) +2 trits -> +10%:\n rung_min_bps(2000, 6) = {any}\n", .{ rung_min_bps(2000, 6) }); + if (!(rung_min_bps(2000, 9) == 4500)) __t27_assert_fail("\n GF-T64 (Et9) +5 trits -> +25%:\n rung_min_bps(2000, 9) = {any}\n", .{ rung_min_bps(2000, 9) }); + if (!(rung_min_bps(2000, 14) == 7000)) __t27_assert_fail("\n GF-T128 (Et14) +10 trits -> +50%:\n rung_min_bps(2000, 14) = {any}\n", .{ rung_min_bps(2000, 14) }); + if (!(rung_min_bps(2000, 3) == 2000)) __t27_assert_fail("\n sub-flagship GF-T8 uses the base (never shrinks):\n rung_min_bps(2000, 3) = {any}\n", .{ rung_min_bps(2000, 3) }); + if (!(required_bond_rung(1000, 2000, 4) == 200)) __t27_assert_fail("\n GF-T16 needs 200:\n required_bond_rung(1000, 2000, 4) = {any}\n", .{ required_bond_rung(1000, 2000, 4) }); + if (!(required_bond_rung(1000, 2000, 9) == 450)) __t27_assert_fail("\n GF-T64 needs 450 -- more collateral:\n required_bond_rung(1000, 2000, 9) = {any}\n", .{ required_bond_rung(1000, 2000, 9) }); + if (!(required_bond_rung(1000, 2000, 9) > required_bond_rung(1000, 2000, 4))) __t27_assert_fail("\n wider rung -> bigger bond:\n required_bond_rung(1000, 2000, 9) = {any}\n required_bond_rung(1000, 2000, 4) = {any}\n", .{ required_bond_rung(1000, 2000, 9), required_bond_rung(1000, 2000, 4) }); + if (!(bond_covers_rung(450, 1000, 2000, 9) == true)) __t27_assert_fail("\n 450 covers GF-T64:\n bond_covers_rung(450, 1000, 2000, 9) = {any}\n", .{ bond_covers_rung(450, 1000, 2000, 9) }); + if (!(bond_covers_rung(200, 1000, 2000, 9) == false)) __t27_assert_fail("\n a GF-T16-sized bond underfunds GF-T64:\n bond_covers_rung(200, 1000, 2000, 9) = {any}\n", .{ bond_covers_rung(200, 1000, 2000, 9) }); } test "bond_coverage_gate" { - if (!(bond_covers(200, 1000, 2000) == true)) @panic("200 covers 20% of 1000"); - if (!(bond_covers(199, 1000, 2000) == false)) @panic("199 is one short of the 200 required"); - if (!(bond_covers(1, 1000, 2000) == false)) @panic("a nominal bond does NOT cover 1000 of outstanding risk"); - if (!(bond_covers(1000, 1000, BOND_BPS_UNIT) == true)) @panic("a full 100% bond covers"); - if (!(bond_covers(0, 0, 20000) == true)) @panic("a fresh node with no outstanding risk is covered by a zero bond"); + if (!(bond_covers(200, 1000, 2000) == true)) __t27_assert_fail("\n 200 covers 20% of 1000:\n bond_covers(200, 1000, 2000) = {any}\n", .{ bond_covers(200, 1000, 2000) }); + if (!(bond_covers(199, 1000, 2000) == false)) __t27_assert_fail("\n 199 is one short of the 200 required:\n bond_covers(199, 1000, 2000) = {any}\n", .{ bond_covers(199, 1000, 2000) }); + if (!(bond_covers(1, 1000, 2000) == false)) __t27_assert_fail("\n a nominal bond does NOT cover 1000 of outstanding risk:\n bond_covers(1, 1000, 2000) = {any}\n", .{ bond_covers(1, 1000, 2000) }); + if (!(bond_covers(1000, 1000, BOND_BPS_UNIT) == true)) __t27_assert_fail("\n a full 100% bond covers:\n bond_covers(1000, 1000, BOND_BPS_UNIT) = {any}\n", .{ bond_covers(1000, 1000, BOND_BPS_UNIT) }); + if (!(bond_covers(0, 0, 20000) == true)) __t27_assert_fail("\n a fresh node with no outstanding risk is covered by a zero bond:\n bond_covers(0, 0, 20000) = {any}\n", .{ bond_covers(0, 0, 20000) }); } diff --git a/gen/zig/tri_compute_challenge.zig b/gen/zig/tri_compute_challenge.zig index 1e5220c5..6595d4ec 100644 --- a/gen/zig/tri_compute_challenge.zig +++ b/gen/zig/tri_compute_challenge.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const RESOLVE_HONEST: u32 = 0; @@ -372,279 +380,279 @@ fn honest_share5(v0: u32, v1: u32, v2: u32, v3: u32, v4: u32, stake: u32) u32 { } test "honest_executor_survives" { const outcome = resolve(0x4100, 0x4100); - if (!(is_honest(0x4100, 0x4100) == true)) @panic("matching result is honest"); - if (!(outcome == RESOLVE_HONEST)) @panic("honest -> no slash"); - if (!(executor_bond_after(1000, outcome) == 1000)) @panic("bond retained"); - if (!(challenger_reward(1000, outcome) == 0)) @panic("frivolous challenge earns nothing"); - if (!(challenger_stake_after(50, outcome) == 0)) @panic("frivolous challenge burns stake"); + if (!(is_honest(0x4100, 0x4100) == true)) __t27_assert_fail("\n matching result is honest:\n is_honest(0x4100, 0x4100) = {any}\n", .{ is_honest(0x4100, 0x4100) }); + if (!(outcome == RESOLVE_HONEST)) __t27_assert_fail("\n honest -> no slash:\n outcome = {any}\n RESOLVE_HONEST = {any}\n", .{ outcome, RESOLVE_HONEST }); + if (!(executor_bond_after(1000, outcome) == 1000)) __t27_assert_fail("\n bond retained:\n executor_bond_after(1000, outcome) = {any}\n", .{ executor_bond_after(1000, outcome) }); + if (!(challenger_reward(1000, outcome) == 0)) __t27_assert_fail("\n frivolous challenge earns nothing:\n challenger_reward(1000, outcome) = {any}\n", .{ challenger_reward(1000, outcome) }); + if (!(challenger_stake_after(50, outcome) == 0)) __t27_assert_fail("\n frivolous challenge burns stake:\n challenger_stake_after(50, outcome) = {any}\n", .{ challenger_stake_after(50, outcome) }); } test "fraud_is_slashed" { const outcome = resolve(0x9999, 0x4100); - if (!(is_honest(0x9999, 0x4100) == false)) @panic("wrong result is dishonest"); - if (!(outcome == RESOLVE_SLASH)) @panic("wrong result -> slash"); - if (!(executor_bond_after(1000, outcome) == 0)) @panic("bond forfeited"); - if (!(challenger_reward(1000, outcome) == 1000)) @panic("challenger wins the bond"); - if (!(challenger_stake_after(50, outcome) == 50)) @panic("correct challenge keeps stake"); + if (!(is_honest(0x9999, 0x4100) == false)) __t27_assert_fail("\n wrong result is dishonest:\n is_honest(0x9999, 0x4100) = {any}\n", .{ is_honest(0x9999, 0x4100) }); + if (!(outcome == RESOLVE_SLASH)) __t27_assert_fail("\n wrong result -> slash:\n outcome = {any}\n RESOLVE_SLASH = {any}\n", .{ outcome, RESOLVE_SLASH }); + if (!(executor_bond_after(1000, outcome) == 0)) __t27_assert_fail("\n bond forfeited:\n executor_bond_after(1000, outcome) = {any}\n", .{ executor_bond_after(1000, outcome) }); + if (!(challenger_reward(1000, outcome) == 1000)) __t27_assert_fail("\n challenger wins the bond:\n challenger_reward(1000, outcome) = {any}\n", .{ challenger_reward(1000, outcome) }); + if (!(challenger_stake_after(50, outcome) == 50)) __t27_assert_fail("\n correct challenge keeps stake:\n challenger_stake_after(50, outcome) = {any}\n", .{ challenger_stake_after(50, outcome) }); } test "bound_dispute_on_committed_operands" { const outcome = resolve_bound(0x1234ABCD, 0x1234ABCD, 0x9999, 0x4100); - if (!(challenge_binds(0x1234ABCD, 0x1234ABCD) == true)) @panic("same leaf binds"); - if (!(outcome == RESOLVE_SLASH)) @panic("wrong result on committed operands -> slash"); - if (!(executor_bond_after(1000, outcome) == 0)) @panic("bond forfeited"); - if (!(challenger_reward(1000, outcome) == 1000)) @panic("challenger wins the bond"); - if (!(challenger_stake_after_bound(50, outcome) == 50)) @panic("correct challenge keeps stake"); + if (!(challenge_binds(0x1234ABCD, 0x1234ABCD) == true)) __t27_assert_fail("\n same leaf binds:\n challenge_binds(0x1234ABCD, 0x1234ABCD) = {any}\n", .{ challenge_binds(0x1234ABCD, 0x1234ABCD) }); + if (!(outcome == RESOLVE_SLASH)) __t27_assert_fail("\n wrong result on committed operands -> slash:\n outcome = {any}\n RESOLVE_SLASH = {any}\n", .{ outcome, RESOLVE_SLASH }); + if (!(executor_bond_after(1000, outcome) == 0)) __t27_assert_fail("\n bond forfeited:\n executor_bond_after(1000, outcome) = {any}\n", .{ executor_bond_after(1000, outcome) }); + if (!(challenger_reward(1000, outcome) == 1000)) __t27_assert_fail("\n challenger wins the bond:\n challenger_reward(1000, outcome) = {any}\n", .{ challenger_reward(1000, outcome) }); + if (!(challenger_stake_after_bound(50, outcome) == 50)) __t27_assert_fail("\n correct challenge keeps stake:\n challenger_stake_after_bound(50, outcome) = {any}\n", .{ challenger_stake_after_bound(50, outcome) }); } test "fabricated_operands_rejected" { const outcome = resolve_bound(0x1234ABCD, 0x1234ABCE, 0x9999, 0x4100); - if (!(challenge_binds(0x1234ABCD, 0x1234ABCE) == false)) @panic("off-leaf operands do not bind"); - if (!(outcome == RESOLVE_MALFORMED)) @panic("unbound dispute -> malformed"); - if (!(executor_bond_after(1000, outcome) == 1000)) @panic("honest executor bond safe"); - if (!(challenger_reward(1000, outcome) == 0)) @panic("griefer earns nothing"); - if (!(challenger_stake_after_bound(50, outcome) == 0)) @panic("griefer stake burned"); + if (!(challenge_binds(0x1234ABCD, 0x1234ABCE) == false)) __t27_assert_fail("\n off-leaf operands do not bind:\n challenge_binds(0x1234ABCD, 0x1234ABCE) = {any}\n", .{ challenge_binds(0x1234ABCD, 0x1234ABCE) }); + if (!(outcome == RESOLVE_MALFORMED)) __t27_assert_fail("\n unbound dispute -> malformed:\n outcome = {any}\n RESOLVE_MALFORMED = {any}\n", .{ outcome, RESOLVE_MALFORMED }); + if (!(executor_bond_after(1000, outcome) == 1000)) __t27_assert_fail("\n honest executor bond safe:\n executor_bond_after(1000, outcome) = {any}\n", .{ executor_bond_after(1000, outcome) }); + if (!(challenger_reward(1000, outcome) == 0)) __t27_assert_fail("\n griefer earns nothing:\n challenger_reward(1000, outcome) = {any}\n", .{ challenger_reward(1000, outcome) }); + if (!(challenger_stake_after_bound(50, outcome) == 0)) __t27_assert_fail("\n griefer stake burned:\n challenger_stake_after_bound(50, outcome) = {any}\n", .{ challenger_stake_after_bound(50, outcome) }); } test "replay_is_a_noop" { const outcome = resolve_full(5, 6, FMT_GF_BINARY, FMT_GF_BINARY, 0x1234ABCD, 0x1234ABCD, 0x9999, 0x4100); - if (!(dispute_is_fresh(5, 6) == true)) @panic("epoch 6 beyond watermark 5 is fresh"); - if (!(outcome == RESOLVE_SLASH)) @panic("fresh valid fraud -> slash"); - if (!(resolver_epoch_after(5, 6, outcome) == 6)) @panic("watermark advances to 6"); + if (!(dispute_is_fresh(5, 6) == true)) __t27_assert_fail("\n epoch 6 beyond watermark 5 is fresh:\n dispute_is_fresh(5, 6) = {any}\n", .{ dispute_is_fresh(5, 6) }); + if (!(outcome == RESOLVE_SLASH)) __t27_assert_fail("\n fresh valid fraud -> slash:\n outcome = {any}\n RESOLVE_SLASH = {any}\n", .{ outcome, RESOLVE_SLASH }); + if (!(resolver_epoch_after(5, 6, outcome) == 6)) __t27_assert_fail("\n watermark advances to 6:\n resolver_epoch_after(5, 6, outcome) = {any}\n", .{ resolver_epoch_after(5, 6, outcome) }); const replay = resolve_full(6, 6, FMT_GF_BINARY, FMT_GF_BINARY, 0x1234ABCD, 0x1234ABCD, 0x9999, 0x4100); - if (!(dispute_is_fresh(6, 6) == false)) @panic("epoch 6 == watermark is stale"); - if (!(replay == RESOLVE_STALE)) @panic("replay -> stale"); - if (!(executor_bond_after(1000, replay) == 1000)) @panic("replay does not re-slash bond"); - if (!(challenger_reward(1000, replay) == 0)) @panic("replay pays nothing"); - if (!(challenger_stake_after_bound(50, replay) == 50)) @panic("replay does not burn stake"); - if (!(resolver_epoch_after(6, 6, replay) == 6)) @panic("stale leaves watermark put"); + if (!(dispute_is_fresh(6, 6) == false)) __t27_assert_fail("\n epoch 6 == watermark is stale:\n dispute_is_fresh(6, 6) = {any}\n", .{ dispute_is_fresh(6, 6) }); + if (!(replay == RESOLVE_STALE)) __t27_assert_fail("\n replay -> stale:\n replay = {any}\n RESOLVE_STALE = {any}\n", .{ replay, RESOLVE_STALE }); + if (!(executor_bond_after(1000, replay) == 1000)) __t27_assert_fail("\n replay does not re-slash bond:\n executor_bond_after(1000, replay) = {any}\n", .{ executor_bond_after(1000, replay) }); + if (!(challenger_reward(1000, replay) == 0)) __t27_assert_fail("\n replay pays nothing:\n challenger_reward(1000, replay) = {any}\n", .{ challenger_reward(1000, replay) }); + if (!(challenger_stake_after_bound(50, replay) == 50)) __t27_assert_fail("\n replay does not burn stake:\n challenger_stake_after_bound(50, replay) = {any}\n", .{ challenger_stake_after_bound(50, replay) }); + if (!(resolver_epoch_after(6, 6, replay) == 6)) __t27_assert_fail("\n stale leaves watermark put:\n resolver_epoch_after(6, 6, replay) = {any}\n", .{ resolver_epoch_after(6, 6, replay) }); } test "watermark_advances_only_on_resolution" { - if (!(resolver_epoch_after(5, 9, RESOLVE_HONEST) == 9)) @panic("HONEST advances the watermark"); - if (!(resolver_epoch_after(5, 9, RESOLVE_SLASH) == 9)) @panic("SLASH advances the watermark"); - if (!(resolver_epoch_after(5, 9999, RESOLVE_MALFORMED) == 5)) @panic("a high-epoch MALFORMED does NOT jump the watermark"); - if (!(resolver_epoch_after(5, 9999, RESOLVE_FAMILY_MISMATCH) == 5)) @panic("FAMILY_MISMATCH does not advance"); - if (!(resolver_epoch_after(5, 9999, RESOLVE_INDETERMINATE) == 5)) @panic("INDETERMINATE does not advance"); - if (!(resolver_epoch_after(5, 9999, RESOLVE_STALE) == 5)) @panic("STALE does not advance"); + if (!(resolver_epoch_after(5, 9, RESOLVE_HONEST) == 9)) __t27_assert_fail("\n HONEST advances the watermark:\n resolver_epoch_after(5, 9, RESOLVE_HONEST) = {any}\n", .{ resolver_epoch_after(5, 9, RESOLVE_HONEST) }); + if (!(resolver_epoch_after(5, 9, RESOLVE_SLASH) == 9)) __t27_assert_fail("\n SLASH advances the watermark:\n resolver_epoch_after(5, 9, RESOLVE_SLASH) = {any}\n", .{ resolver_epoch_after(5, 9, RESOLVE_SLASH) }); + if (!(resolver_epoch_after(5, 9999, RESOLVE_MALFORMED) == 5)) __t27_assert_fail("\n a high-epoch MALFORMED does NOT jump the watermark:\n resolver_epoch_after(5, 9999, RESOLVE_MALFORMED) = {any}\n", .{ resolver_epoch_after(5, 9999, RESOLVE_MALFORMED) }); + if (!(resolver_epoch_after(5, 9999, RESOLVE_FAMILY_MISMATCH) == 5)) __t27_assert_fail("\n FAMILY_MISMATCH does not advance:\n resolver_epoch_after(5, 9999, RESOLVE_FAMILY_MISMATCH) = {any}\n", .{ resolver_epoch_after(5, 9999, RESOLVE_FAMILY_MISMATCH) }); + if (!(resolver_epoch_after(5, 9999, RESOLVE_INDETERMINATE) == 5)) __t27_assert_fail("\n INDETERMINATE does not advance:\n resolver_epoch_after(5, 9999, RESOLVE_INDETERMINATE) = {any}\n", .{ resolver_epoch_after(5, 9999, RESOLVE_INDETERMINATE) }); + if (!(resolver_epoch_after(5, 9999, RESOLVE_STALE) == 5)) __t27_assert_fail("\n STALE does not advance:\n resolver_epoch_after(5, 9999, RESOLVE_STALE) = {any}\n", .{ resolver_epoch_after(5, 9999, RESOLVE_STALE) }); const w = resolver_epoch_after(5, 9999, RESOLVE_MALFORMED); - if (!(dispute_is_fresh(w, 6) == true)) @panic("epoch 6 stays fresh -- the griefer could not block it"); + if (!(dispute_is_fresh(w, 6) == true)) __t27_assert_fail("\n epoch 6 stays fresh -- the griefer could not block it:\n dispute_is_fresh(w, 6) = {any}\n", .{ dispute_is_fresh(w, 6) }); } test "gft_dispute_slashes" { const outcome = resolve_full(0, 1, FMT_GFT, FMT_GFT, 0xBEEF01, 0xBEEF01, 0x0050, 0x0028); - if (!(outcome == RESOLVE_SLASH)) @panic("GF-T wrong result on committed operands -> slash"); - if (!(executor_bond_after(1000, outcome) == 0)) @panic("GF-T bond forfeited"); + if (!(outcome == RESOLVE_SLASH)) __t27_assert_fail("\n GF-T wrong result on committed operands -> slash:\n outcome = {any}\n RESOLVE_SLASH = {any}\n", .{ outcome, RESOLVE_SLASH }); + if (!(executor_bond_after(1000, outcome) == 0)) __t27_assert_fail("\n GF-T bond forfeited:\n executor_bond_after(1000, outcome) = {any}\n", .{ executor_bond_after(1000, outcome) }); } test "family_confusion_rejected" { const outcome = resolve_full(0, 1, FMT_GFT, FMT_GF_BINARY, 0xBEEF01, 0xBEEF01, 0x0050, 0x0028); - if (!(family_matches(FMT_GFT, FMT_GF_BINARY) == false)) @panic("families differ"); - if (!(outcome == RESOLVE_FAMILY_MISMATCH)) @panic("cross-family -> family mismatch"); - if (!(executor_bond_after(1000, outcome) == 1000)) @panic("executor bond safe under confusion"); - if (!(challenger_stake_after_bound(50, outcome) == 0)) @panic("family-confusion griefer stake burned"); + if (!(family_matches(FMT_GFT, FMT_GF_BINARY) == false)) __t27_assert_fail("\n families differ:\n family_matches(FMT_GFT, FMT_GF_BINARY) = {any}\n", .{ family_matches(FMT_GFT, FMT_GF_BINARY) }); + if (!(outcome == RESOLVE_FAMILY_MISMATCH)) __t27_assert_fail("\n cross-family -> family mismatch:\n outcome = {any}\n RESOLVE_FAMILY_MISMATCH = {any}\n", .{ outcome, RESOLVE_FAMILY_MISMATCH }); + if (!(executor_bond_after(1000, outcome) == 1000)) __t27_assert_fail("\n executor bond safe under confusion:\n executor_bond_after(1000, outcome) = {any}\n", .{ executor_bond_after(1000, outcome) }); + if (!(challenger_stake_after_bound(50, outcome) == 0)) __t27_assert_fail("\n family-confusion griefer stake burned:\n challenger_stake_after_bound(50, outcome) = {any}\n", .{ challenger_stake_after_bound(50, outcome) }); } test "rung_confusion_rejected" { const wrong = resolve_full_rung(5, 6, FMT_GFT, FMT_GFT, 9, 4, 0xAAAA, 0xAAAA, 0x11, 0x22); - if (!(rung_matches(9, 4) == false)) @panic("GF-T64 (Et9) != GF-T16 (Et4)"); - if (!(wrong == RESOLVE_RUNG_MISMATCH)) @panic("wrong-rung recompute -> rung mismatch, no slash"); - if (!(executor_bond_after(1000, wrong) == 1000)) @panic("executor bond safe under rung confusion"); - if (!(challenger_stake_after_bound(50, wrong) == 0)) @panic("rung-confusion griefer stake burned"); + if (!(rung_matches(9, 4) == false)) __t27_assert_fail("\n GF-T64 (Et9) != GF-T16 (Et4):\n rung_matches(9, 4) = {any}\n", .{ rung_matches(9, 4) }); + if (!(wrong == RESOLVE_RUNG_MISMATCH)) __t27_assert_fail("\n wrong-rung recompute -> rung mismatch, no slash:\n wrong = {any}\n RESOLVE_RUNG_MISMATCH = {any}\n", .{ wrong, RESOLVE_RUNG_MISMATCH }); + if (!(executor_bond_after(1000, wrong) == 1000)) __t27_assert_fail("\n executor bond safe under rung confusion:\n executor_bond_after(1000, wrong) = {any}\n", .{ executor_bond_after(1000, wrong) }); + if (!(challenger_stake_after_bound(50, wrong) == 0)) __t27_assert_fail("\n rung-confusion griefer stake burned:\n challenger_stake_after_bound(50, wrong) = {any}\n", .{ challenger_stake_after_bound(50, wrong) }); const slash = resolve_full_rung(5, 6, FMT_GFT, FMT_GFT, 9, 9, 0xAAAA, 0xAAAA, 0x11, 0x22); - if (!(slash == RESOLVE_SLASH)) @panic("same rung + anchored + wrong result -> slash"); + if (!(slash == RESOLVE_SLASH)) __t27_assert_fail("\n same rung + anchored + wrong result -> slash:\n slash = {any}\n RESOLVE_SLASH = {any}\n", .{ slash, RESOLVE_SLASH }); const honest = resolve_full_rung(5, 6, FMT_GFT, FMT_GFT, 9, 9, 0xAAAA, 0xAAAA, 0x33, 0x33); - if (!(honest == RESOLVE_HONEST)) @panic("same rung + matching result -> honest"); + if (!(honest == RESOLVE_HONEST)) __t27_assert_fail("\n same rung + matching result -> honest:\n honest = {any}\n RESOLVE_HONEST = {any}\n", .{ honest, RESOLVE_HONEST }); } test "rung_guard_precedence" { const stale = resolve_full_rung(6, 6, FMT_GFT, FMT_GFT, 9, 4, 0xAAAA, 0xAAAA, 0x11, 0x22); - if (!(stale == RESOLVE_STALE)) @panic("stale short-circuits before the rung check"); + if (!(stale == RESOLVE_STALE)) __t27_assert_fail("\n stale short-circuits before the rung check:\n stale = {any}\n RESOLVE_STALE = {any}\n", .{ stale, RESOLVE_STALE }); const fam = resolve_full_rung(5, 6, FMT_GF_BINARY, FMT_GFT, 9, 4, 0xAAAA, 0xAAAA, 0x11, 0x22); - if (!(fam == RESOLVE_FAMILY_MISMATCH)) @panic("family mismatch dominates a rung mismatch"); + if (!(fam == RESOLVE_FAMILY_MISMATCH)) __t27_assert_fail("\n family mismatch dominates a rung mismatch:\n fam = {any}\n RESOLVE_FAMILY_MISMATCH = {any}\n", .{ fam, RESOLVE_FAMILY_MISMATCH }); } test "gf_dispute_d256_anchor" { - if (!(resolve_bound_d256(1, 0x4100, 0x4100) == RESOLVE_HONEST)) @panic("matched digest + correct result -> honest"); - if (!(resolve_bound_d256(1, 0x9999, 0x4100) == RESOLVE_SLASH)) @panic("matched digest + wrong result -> slash"); - if (!(resolve_bound_d256(0, 0x9999, 0x4100) == RESOLVE_MALFORMED)) @panic("digest mismatch -> malformed"); - if (!(executor_bond_after(1000, resolve_bound_d256(0, 0x9999, 0x4100)) == 1000)) @panic("malformed keeps the bond"); - if (!(resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 1, 0x4100, 0x4100) == RESOLVE_HONEST)) @panic("fresh + same family + matched digest -> honest"); - if (!(resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 1, 0x9999, 0x4100) == RESOLVE_SLASH)) @panic("wrong GF -> slash"); - if (!(resolve_full_d256(5, 5, FMT_GF_BINARY, FMT_GF_BINARY, 1, 0x4100, 0x4100) == RESOLVE_STALE)) @panic("stale epoch -> stale"); - if (!(resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GFT, 1, 0x4100, 0x4100) == RESOLVE_FAMILY_MISMATCH)) @panic("cross-family -> mismatch"); - if (!(resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 0, 0x4100, 0x4100) == RESOLVE_MALFORMED)) @panic("digest mismatch -> malformed"); - if (!(resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 1, 0x4100, 0x4100) == resolve_full(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 0xAB, 0xAB, 0x4100, 0x4100))) @panic("d256 matches resolve_full on the honest path"); + if (!(resolve_bound_d256(1, 0x4100, 0x4100) == RESOLVE_HONEST)) __t27_assert_fail("\n matched digest + correct result -> honest:\n resolve_bound_d256(1, 0x4100, 0x4100) = {any}\n RESOLVE_HONEST = {any}\n", .{ resolve_bound_d256(1, 0x4100, 0x4100), RESOLVE_HONEST }); + if (!(resolve_bound_d256(1, 0x9999, 0x4100) == RESOLVE_SLASH)) __t27_assert_fail("\n matched digest + wrong result -> slash:\n resolve_bound_d256(1, 0x9999, 0x4100) = {any}\n RESOLVE_SLASH = {any}\n", .{ resolve_bound_d256(1, 0x9999, 0x4100), RESOLVE_SLASH }); + if (!(resolve_bound_d256(0, 0x9999, 0x4100) == RESOLVE_MALFORMED)) __t27_assert_fail("\n digest mismatch -> malformed:\n resolve_bound_d256(0, 0x9999, 0x4100) = {any}\n RESOLVE_MALFORMED = {any}\n", .{ resolve_bound_d256(0, 0x9999, 0x4100), RESOLVE_MALFORMED }); + if (!(executor_bond_after(1000, resolve_bound_d256(0, 0x9999, 0x4100)) == 1000)) __t27_assert_fail("\n malformed keeps the bond:\n executor_bond_after(1000, resolve_bound_d256(0, 0x9999, 0x4100)) = {any}\n", .{ executor_bond_after(1000, resolve_bound_d256(0, 0x9999, 0x4100)) }); + if (!(resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 1, 0x4100, 0x4100) == RESOLVE_HONEST)) __t27_assert_fail("\n fresh + same family + matched digest -> honest:\n resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 1, 0x4100, 0x4100) = {any}\n RESOLVE_HONEST = {any}\n", .{ resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 1, 0x4100, 0x4100), RESOLVE_HONEST }); + if (!(resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 1, 0x9999, 0x4100) == RESOLVE_SLASH)) __t27_assert_fail("\n wrong GF -> slash:\n resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 1, 0x9999, 0x4100) = {any}\n RESOLVE_SLASH = {any}\n", .{ resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 1, 0x9999, 0x4100), RESOLVE_SLASH }); + if (!(resolve_full_d256(5, 5, FMT_GF_BINARY, FMT_GF_BINARY, 1, 0x4100, 0x4100) == RESOLVE_STALE)) __t27_assert_fail("\n stale epoch -> stale:\n resolve_full_d256(5, 5, FMT_GF_BINARY, FMT_GF_BINARY, 1, 0x4100, 0x4100) = {any}\n RESOLVE_STALE = {any}\n", .{ resolve_full_d256(5, 5, FMT_GF_BINARY, FMT_GF_BINARY, 1, 0x4100, 0x4100), RESOLVE_STALE }); + if (!(resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GFT, 1, 0x4100, 0x4100) == RESOLVE_FAMILY_MISMATCH)) __t27_assert_fail("\n cross-family -> mismatch:\n resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GFT, 1, 0x4100, 0x4100) = {any}\n RESOLVE_FAMILY_MISMATCH = {any}\n", .{ resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GFT, 1, 0x4100, 0x4100), RESOLVE_FAMILY_MISMATCH }); + if (!(resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 0, 0x4100, 0x4100) == RESOLVE_MALFORMED)) __t27_assert_fail("\n digest mismatch -> malformed:\n resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 0, 0x4100, 0x4100) = {any}\n RESOLVE_MALFORMED = {any}\n", .{ resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 0, 0x4100, 0x4100), RESOLVE_MALFORMED }); + if (!(resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 1, 0x4100, 0x4100) == resolve_full(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 0xAB, 0xAB, 0x4100, 0x4100))) __t27_assert_fail("\n d256 matches resolve_full on the honest path:\n resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 1, 0x4100, 0x4100) = {any}\n resolve_full(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 0xAB, 0xAB, 0x4100, 0x4100) = {any}\n", .{ resolve_full_d256(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 1, 0x4100, 0x4100), resolve_full(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 0xAB, 0xAB, 0x4100, 0x4100) }); } test "verifier_quorum_basics" { - if (!(verifier_quorum3(0x4100, 0x4100, 0x4100) == 1)) @panic("unanimous -> quorum"); - if (!(verifier_quorum3(0x4100, 0x4100, 0x9999) == 1)) @panic("2-of-3 -> quorum"); - if (!(verifier_quorum3(0x4100, 0x9999, 0x4100) == 1)) @panic("2-of-3 (split positions) -> quorum"); - if (!(verifier_quorum3(0x4100, 0x9999, 0xBEEF) == 0)) @panic("all distinct -> no quorum"); - if (!(quorum_result3(0x9999, 0x4100, 0x4100) == 0x4100)) @panic("majority value wins over the odd one"); + if (!(verifier_quorum3(0x4100, 0x4100, 0x4100) == 1)) __t27_assert_fail("\n unanimous -> quorum:\n verifier_quorum3(0x4100, 0x4100, 0x4100) = {any}\n", .{ verifier_quorum3(0x4100, 0x4100, 0x4100) }); + if (!(verifier_quorum3(0x4100, 0x4100, 0x9999) == 1)) __t27_assert_fail("\n 2-of-3 -> quorum:\n verifier_quorum3(0x4100, 0x4100, 0x9999) = {any}\n", .{ verifier_quorum3(0x4100, 0x4100, 0x9999) }); + if (!(verifier_quorum3(0x4100, 0x9999, 0x4100) == 1)) __t27_assert_fail("\n 2-of-3 (split positions) -> quorum:\n verifier_quorum3(0x4100, 0x9999, 0x4100) = {any}\n", .{ verifier_quorum3(0x4100, 0x9999, 0x4100) }); + if (!(verifier_quorum3(0x4100, 0x9999, 0xBEEF) == 0)) __t27_assert_fail("\n all distinct -> no quorum:\n verifier_quorum3(0x4100, 0x9999, 0xBEEF) = {any}\n", .{ verifier_quorum3(0x4100, 0x9999, 0xBEEF) }); + if (!(quorum_result3(0x9999, 0x4100, 0x4100) == 0x4100)) __t27_assert_fail("\n majority value wins over the odd one:\n quorum_result3(0x9999, 0x4100, 0x4100) = {any}\n", .{ quorum_result3(0x9999, 0x4100, 0x4100) }); } test "dishonest_minority_outvoted" { const outcome = resolve_quorum3(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x9999); - if (!(outcome == RESOLVE_HONEST)) @panic("honest executor survives a lying minority verifier"); - if (!(executor_bond_after(1000, outcome) == 1000)) @panic("bond retained"); + if (!(outcome == RESOLVE_HONEST)) __t27_assert_fail("\n honest executor survives a lying minority verifier:\n outcome = {any}\n RESOLVE_HONEST = {any}\n", .{ outcome, RESOLVE_HONEST }); + if (!(executor_bond_after(1000, outcome) == 1000)) __t27_assert_fail("\n bond retained:\n executor_bond_after(1000, outcome) = {any}\n", .{ executor_bond_after(1000, outcome) }); } test "quorum_still_slashes_fraud" { const outcome = resolve_quorum3(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 0xAB, 0xAB, 0x9999, 0x4100, 0x9999, 0x4100); - if (!(outcome == RESOLVE_SLASH)) @panic("majority recomputation catches the wrong result"); - if (!(executor_bond_after(1000, outcome) == 0)) @panic("bond slashed"); + if (!(outcome == RESOLVE_SLASH)) __t27_assert_fail("\n majority recomputation catches the wrong result:\n outcome = {any}\n RESOLVE_SLASH = {any}\n", .{ outcome, RESOLVE_SLASH }); + if (!(executor_bond_after(1000, outcome) == 0)) __t27_assert_fail("\n bond slashed:\n executor_bond_after(1000, outcome) = {any}\n", .{ executor_bond_after(1000, outcome) }); } test "no_quorum_is_indeterminate" { const outcome = resolve_quorum3(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 0xAB, 0xAB, 0x4100, 0x1111, 0x2222, 0x3333); - if (!(outcome == RESOLVE_INDETERMINATE)) @panic("split verifiers -> indeterminate"); - if (!(executor_bond_after(1000, outcome) == 1000)) @panic("no slash on an unresolved recomputation"); - if (!(challenger_reward(1000, outcome) == 0)) @panic("no reward on an unresolved recomputation"); - if (!(challenger_stake_after_bound(50, outcome) == 50)) @panic("INDETERMINATE keeps the challenger's stake"); + if (!(outcome == RESOLVE_INDETERMINATE)) __t27_assert_fail("\n split verifiers -> indeterminate:\n outcome = {any}\n RESOLVE_INDETERMINATE = {any}\n", .{ outcome, RESOLVE_INDETERMINATE }); + if (!(executor_bond_after(1000, outcome) == 1000)) __t27_assert_fail("\n no slash on an unresolved recomputation:\n executor_bond_after(1000, outcome) = {any}\n", .{ executor_bond_after(1000, outcome) }); + if (!(challenger_reward(1000, outcome) == 0)) __t27_assert_fail("\n no reward on an unresolved recomputation:\n challenger_reward(1000, outcome) = {any}\n", .{ challenger_reward(1000, outcome) }); + if (!(challenger_stake_after_bound(50, outcome) == 50)) __t27_assert_fail("\n INDETERMINATE keeps the challenger's stake:\n challenger_stake_after_bound(50, outcome) = {any}\n", .{ challenger_stake_after_bound(50, outcome) }); } test "stake_burns_only_on_challenger_fault" { - if (!(challenger_stake_after_bound(50, RESOLVE_SLASH) == 50)) @panic("correct challenge keeps stake"); - if (!(challenger_stake_after_bound(50, RESOLVE_STALE) == 50)) @panic("replay keeps stake"); - if (!(challenger_stake_after_bound(50, RESOLVE_INDETERMINATE) == 50)) @panic("verifier split keeps stake"); - if (!(challenger_stake_after_bound(50, RESOLVE_HONEST) == 0)) @panic("frivolous challenge burns stake"); - if (!(challenger_stake_after_bound(50, RESOLVE_MALFORMED) == 0)) @panic("fabricated operands burn stake"); - if (!(challenger_stake_after_bound(50, RESOLVE_FAMILY_MISMATCH) == 0)) @panic("family confusion burns stake"); + if (!(challenger_stake_after_bound(50, RESOLVE_SLASH) == 50)) __t27_assert_fail("\n correct challenge keeps stake:\n challenger_stake_after_bound(50, RESOLVE_SLASH) = {any}\n", .{ challenger_stake_after_bound(50, RESOLVE_SLASH) }); + if (!(challenger_stake_after_bound(50, RESOLVE_STALE) == 50)) __t27_assert_fail("\n replay keeps stake:\n challenger_stake_after_bound(50, RESOLVE_STALE) = {any}\n", .{ challenger_stake_after_bound(50, RESOLVE_STALE) }); + if (!(challenger_stake_after_bound(50, RESOLVE_INDETERMINATE) == 50)) __t27_assert_fail("\n verifier split keeps stake:\n challenger_stake_after_bound(50, RESOLVE_INDETERMINATE) = {any}\n", .{ challenger_stake_after_bound(50, RESOLVE_INDETERMINATE) }); + if (!(challenger_stake_after_bound(50, RESOLVE_HONEST) == 0)) __t27_assert_fail("\n frivolous challenge burns stake:\n challenger_stake_after_bound(50, RESOLVE_HONEST) = {any}\n", .{ challenger_stake_after_bound(50, RESOLVE_HONEST) }); + if (!(challenger_stake_after_bound(50, RESOLVE_MALFORMED) == 0)) __t27_assert_fail("\n fabricated operands burn stake:\n challenger_stake_after_bound(50, RESOLVE_MALFORMED) = {any}\n", .{ challenger_stake_after_bound(50, RESOLVE_MALFORMED) }); + if (!(challenger_stake_after_bound(50, RESOLVE_FAMILY_MISMATCH) == 0)) __t27_assert_fail("\n family confusion burns stake:\n challenger_stake_after_bound(50, RESOLVE_FAMILY_MISMATCH) = {any}\n", .{ challenger_stake_after_bound(50, RESOLVE_FAMILY_MISMATCH) }); } test "dissenting_verifier_is_slashed" { - if (!(verifier_dissented(0x4100, 0x4100, 1) == 0)) @panic("agreeing verifier did not dissent"); - if (!(verifier_dissented(0x9999, 0x4100, 1) == 1)) @panic("the odd-one-out dissented from the quorum"); - if (!(verifier_stake_after(50, verifier_dissented(0x4100, 0x4100, 1)) == 50)) @panic("agreeing verifier keeps its stake"); - if (!(verifier_stake_after(50, verifier_dissented(0x9999, 0x4100, 1)) == 0)) @panic("dissenting verifier's stake is burned"); + if (!(verifier_dissented(0x4100, 0x4100, 1) == 0)) __t27_assert_fail("\n agreeing verifier did not dissent:\n verifier_dissented(0x4100, 0x4100, 1) = {any}\n", .{ verifier_dissented(0x4100, 0x4100, 1) }); + if (!(verifier_dissented(0x9999, 0x4100, 1) == 1)) __t27_assert_fail("\n the odd-one-out dissented from the quorum:\n verifier_dissented(0x9999, 0x4100, 1) = {any}\n", .{ verifier_dissented(0x9999, 0x4100, 1) }); + if (!(verifier_stake_after(50, verifier_dissented(0x4100, 0x4100, 1)) == 50)) __t27_assert_fail("\n agreeing verifier keeps its stake:\n verifier_stake_after(50, verifier_dissented(0x4100, 0x4100, 1)) = {any}\n", .{ verifier_stake_after(50, verifier_dissented(0x4100, 0x4100, 1)) }); + if (!(verifier_stake_after(50, verifier_dissented(0x9999, 0x4100, 1)) == 0)) __t27_assert_fail("\n dissenting verifier's stake is burned:\n verifier_stake_after(50, verifier_dissented(0x9999, 0x4100, 1)) = {any}\n", .{ verifier_stake_after(50, verifier_dissented(0x9999, 0x4100, 1)) }); } test "no_quorum_no_verifier_penalty" { - if (!(verifier_dissented(0x1111, 0x1111, 0) == 0)) @panic("no quorum -> no dissent recorded"); - if (!(verifier_stake_after(50, verifier_dissented(0x1111, 0x2222, 0)) == 50)) @panic("split set does not burn any verifier stake"); + if (!(verifier_dissented(0x1111, 0x1111, 0) == 0)) __t27_assert_fail("\n no quorum -> no dissent recorded:\n verifier_dissented(0x1111, 0x1111, 0) = {any}\n", .{ verifier_dissented(0x1111, 0x1111, 0) }); + if (!(verifier_stake_after(50, verifier_dissented(0x1111, 0x2222, 0)) == 50)) __t27_assert_fail("\n split set does not burn any verifier stake:\n verifier_stake_after(50, verifier_dissented(0x1111, 0x2222, 0)) = {any}\n", .{ verifier_stake_after(50, verifier_dissented(0x1111, 0x2222, 0)) }); } test "quorum_k_of_n" { - if (!(quorum_threshold(3) == 2)) @panic("3 nodes -> majority 2"); - if (!(quorum_threshold(5) == 3)) @panic("5 nodes -> majority 3"); - if (!(quorum_threshold(7) == 4)) @panic("7 nodes -> majority 4"); - if (!(quorum_threshold(1) == 1)) @panic("single node -> 1"); - if (!(has_quorum_k(3, 3) == 1)) @panic("3-of-5 clears a 3 threshold"); - if (!(has_quorum_k(2, 3) == 0)) @panic("2 agreements miss a 3 threshold"); - if (!(has_quorum_k(4, 3) == 1)) @panic("4 clears 3"); + if (!(quorum_threshold(3) == 2)) __t27_assert_fail("\n 3 nodes -> majority 2:\n quorum_threshold(3) = {any}\n", .{ quorum_threshold(3) }); + if (!(quorum_threshold(5) == 3)) __t27_assert_fail("\n 5 nodes -> majority 3:\n quorum_threshold(5) = {any}\n", .{ quorum_threshold(5) }); + if (!(quorum_threshold(7) == 4)) __t27_assert_fail("\n 7 nodes -> majority 4:\n quorum_threshold(7) = {any}\n", .{ quorum_threshold(7) }); + if (!(quorum_threshold(1) == 1)) __t27_assert_fail("\n single node -> 1:\n quorum_threshold(1) = {any}\n", .{ quorum_threshold(1) }); + if (!(has_quorum_k(3, 3) == 1)) __t27_assert_fail("\n 3-of-5 clears a 3 threshold:\n has_quorum_k(3, 3) = {any}\n", .{ has_quorum_k(3, 3) }); + if (!(has_quorum_k(2, 3) == 0)) __t27_assert_fail("\n 2 agreements miss a 3 threshold:\n has_quorum_k(2, 3) = {any}\n", .{ has_quorum_k(2, 3) }); + if (!(has_quorum_k(4, 3) == 1)) __t27_assert_fail("\n 4 clears 3:\n has_quorum_k(4, 3) = {any}\n", .{ has_quorum_k(4, 3) }); } test "quorum3_is_the_n3_instance" { - if (!(max_agree3(0x41, 0x41, 0x41) == 3)) @panic("unanimous -> 3 agree"); - if (!(max_agree3(0x41, 0x41, 0x99) == 2)) @panic("2-of-3 -> 2 agree"); - if (!(max_agree3(0x41, 0x99, 0xBE) == 1)) @panic("all distinct -> 1 agree"); - if (!(has_quorum_k(max_agree3(0x41, 0x41, 0x99), quorum_threshold(3)) == verifier_quorum3(0x41, 0x41, 0x99))) @panic("general == specific on 2-of-3"); - if (!(has_quorum_k(max_agree3(0x41, 0x99, 0xBE), quorum_threshold(3)) == verifier_quorum3(0x41, 0x99, 0xBE))) @panic("general == specific on split"); + if (!(max_agree3(0x41, 0x41, 0x41) == 3)) __t27_assert_fail("\n unanimous -> 3 agree:\n max_agree3(0x41, 0x41, 0x41) = {any}\n", .{ max_agree3(0x41, 0x41, 0x41) }); + if (!(max_agree3(0x41, 0x41, 0x99) == 2)) __t27_assert_fail("\n 2-of-3 -> 2 agree:\n max_agree3(0x41, 0x41, 0x99) = {any}\n", .{ max_agree3(0x41, 0x41, 0x99) }); + if (!(max_agree3(0x41, 0x99, 0xBE) == 1)) __t27_assert_fail("\n all distinct -> 1 agree:\n max_agree3(0x41, 0x99, 0xBE) = {any}\n", .{ max_agree3(0x41, 0x99, 0xBE) }); + if (!(has_quorum_k(max_agree3(0x41, 0x41, 0x99), quorum_threshold(3)) == verifier_quorum3(0x41, 0x41, 0x99))) __t27_assert_fail("\n general == specific on 2-of-3:\n has_quorum_k(max_agree3(0x41, 0x41, 0x99), quorum_threshold(3)) = {any}\n verifier_quorum3(0x41, 0x41, 0x99) = {any}\n", .{ has_quorum_k(max_agree3(0x41, 0x41, 0x99), quorum_threshold(3)), verifier_quorum3(0x41, 0x41, 0x99) }); + if (!(has_quorum_k(max_agree3(0x41, 0x99, 0xBE), quorum_threshold(3)) == verifier_quorum3(0x41, 0x99, 0xBE))) __t27_assert_fail("\n general == specific on split:\n has_quorum_k(max_agree3(0x41, 0x99, 0xBE), quorum_threshold(3)) = {any}\n verifier_quorum3(0x41, 0x99, 0xBE) = {any}\n", .{ has_quorum_k(max_agree3(0x41, 0x99, 0xBE), quorum_threshold(3)), verifier_quorum3(0x41, 0x99, 0xBE) }); } test "verifier_reward_splits_the_burn" { - if (!(verifier_reward(50, 2) == 25)) @panic("one 50-burn split between two honest -> 25 each"); - if (!(verifier_reward(100, 2) == 50)) @panic("two dissenters (100 burned), two honest -> 50 each"); - if (!(verifier_reward(50, 3) == 16)) @panic("50 over 3 honest -> 16 floor (2 dust unminted)"); - if (!(verifier_reward(50, 0) == 0)) @panic("no honest verifier -> nothing to pay, no divide-by-zero"); + if (!(verifier_reward(50, 2) == 25)) __t27_assert_fail("\n one 50-burn split between two honest -> 25 each:\n verifier_reward(50, 2) = {any}\n", .{ verifier_reward(50, 2) }); + if (!(verifier_reward(100, 2) == 50)) __t27_assert_fail("\n two dissenters (100 burned), two honest -> 50 each:\n verifier_reward(100, 2) = {any}\n", .{ verifier_reward(100, 2) }); + if (!(verifier_reward(50, 3) == 16)) __t27_assert_fail("\n 50 over 3 honest -> 16 floor (2 dust unminted):\n verifier_reward(50, 3) = {any}\n", .{ verifier_reward(50, 3) }); + if (!(verifier_reward(50, 0) == 0)) __t27_assert_fail("\n no honest verifier -> nothing to pay, no divide-by-zero:\n verifier_reward(50, 0) = {any}\n", .{ verifier_reward(50, 0) }); } test "verifier_reward_no_over_issuance" { - if (!((2 * verifier_reward(50, 2)) == 50)) @panic("2 * 25 == 50, exact"); - if (!((3 * verifier_reward(50, 3)) == 48)) @panic("3 * 16 == 48 <= 50 (floor keeps the dust)"); + if (!((2 * verifier_reward(50, 2)) == 50)) __t27_assert_fail("\n 2 * 25 == 50, exact:\n 2 * verifier_reward(50, 2) = {any}\n", .{ 2 * verifier_reward(50, 2) }); + if (!((3 * verifier_reward(50, 3)) == 48)) __t27_assert_fail("\n 3 * 16 == 48 <= 50 (floor keeps the dust):\n 3 * verifier_reward(50, 3) = {any}\n", .{ 3 * verifier_reward(50, 3) }); } test "honest_verification_is_profitable" { - if (!((verifier_stake_after(50, 0) + verifier_reward(50, 2)) == 75)) @panic("honest net = kept 50 + reward 25 = 75 > staked 50"); - if (!(verifier_stake_after(50, 1) == 0)) @panic("the colluder loses its whole 50 stake"); + if (!((verifier_stake_after(50, 0) + verifier_reward(50, 2)) == 75)) __t27_assert_fail("\n honest net = kept 50 + reward 25 = 75 > staked 50:\n verifier_stake_after(50, 0) + verifier_reward(50, 2) = {any}\n", .{ verifier_stake_after(50, 0) + verifier_reward(50, 2) }); + if (!(verifier_stake_after(50, 1) == 0)) __t27_assert_fail("\n the colluder loses its whole 50 stake:\n verifier_stake_after(50, 1) = {any}\n", .{ verifier_stake_after(50, 1) }); } test "max_agree5_counts" { - if (!(count5(0x41, 0x41, 0x41, 0x41, 0x41, 0x41) == 5)) @panic("unanimous -> 5 agree"); - if (!(max_agree5(0x41, 0x41, 0x41, 0x99, 0xBE) == 3)) @panic("3 of 5 agree on 0x41"); - if (!(max_agree5(0x41, 0x41, 0x99, 0x99, 0xBE) == 2)) @panic("2-2-1 -> largest group is 2"); - if (!(max_agree5(0x1, 0x2, 0x3, 0x4, 0x5) == 1)) @panic("all distinct -> 1"); - if (!(quorum_value5(0x99, 0x41, 0x41, 0x41, 0xBE, 3) == 0x41)) @panic("the value with >= 3 wins"); + if (!(count5(0x41, 0x41, 0x41, 0x41, 0x41, 0x41) == 5)) __t27_assert_fail("\n unanimous -> 5 agree:\n count5(0x41, 0x41, 0x41, 0x41, 0x41, 0x41) = {any}\n", .{ count5(0x41, 0x41, 0x41, 0x41, 0x41, 0x41) }); + if (!(max_agree5(0x41, 0x41, 0x41, 0x99, 0xBE) == 3)) __t27_assert_fail("\n 3 of 5 agree on 0x41:\n max_agree5(0x41, 0x41, 0x41, 0x99, 0xBE) = {any}\n", .{ max_agree5(0x41, 0x41, 0x41, 0x99, 0xBE) }); + if (!(max_agree5(0x41, 0x41, 0x99, 0x99, 0xBE) == 2)) __t27_assert_fail("\n 2-2-1 -> largest group is 2:\n max_agree5(0x41, 0x41, 0x99, 0x99, 0xBE) = {any}\n", .{ max_agree5(0x41, 0x41, 0x99, 0x99, 0xBE) }); + if (!(max_agree5(0x1, 0x2, 0x3, 0x4, 0x5) == 1)) __t27_assert_fail("\n all distinct -> 1:\n max_agree5(0x1, 0x2, 0x3, 0x4, 0x5) = {any}\n", .{ max_agree5(0x1, 0x2, 0x3, 0x4, 0x5) }); + if (!(quorum_value5(0x99, 0x41, 0x41, 0x41, 0xBE, 3) == 0x41)) __t27_assert_fail("\n the value with >= 3 wins:\n quorum_value5(0x99, 0x41, 0x41, 0x41, 0xBE, 3) = {any}\n", .{ quorum_value5(0x99, 0x41, 0x41, 0x41, 0xBE, 3) }); } test "quorum5_outvotes_two_liars" { var outcome = resolve_quorum5(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999); - if (!(outcome == RESOLVE_HONEST)) @panic("3 honest of 5 outvote 2 liars -> honest executor safe"); + if (!(outcome == RESOLVE_HONEST)) __t27_assert_fail("\n 3 honest of 5 outvote 2 liars -> honest executor safe:\n outcome = {any}\n RESOLVE_HONEST = {any}\n", .{ outcome, RESOLVE_HONEST }); outcome = resolve_quorum5(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999); - if (!(outcome == RESOLVE_SLASH)) @panic("the 3-of-5 majority still slashes real fraud"); + if (!(outcome == RESOLVE_SLASH)) __t27_assert_fail("\n the 3-of-5 majority still slashes real fraud:\n outcome = {any}\n RESOLVE_SLASH = {any}\n", .{ outcome, RESOLVE_SLASH }); } test "quorum5_no_majority_indeterminate" { const outcome = resolve_quorum5(0, 1, FMT_GF_BINARY, FMT_GF_BINARY, 0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999, 0xBEEF); - if (!(outcome == RESOLVE_INDETERMINATE)) @panic("2-2-1 split has no 3-of-5 majority -> indeterminate"); - if (!(executor_bond_after(1000, outcome) == 1000)) @panic("no slash without a quorum"); + if (!(outcome == RESOLVE_INDETERMINATE)) __t27_assert_fail("\n 2-2-1 split has no 3-of-5 majority -> indeterminate:\n outcome = {any}\n RESOLVE_INDETERMINATE = {any}\n", .{ outcome, RESOLVE_INDETERMINATE }); + if (!(executor_bond_after(1000, outcome) == 1000)) __t27_assert_fail("\n no slash without a quorum:\n executor_bond_after(1000, outcome) = {any}\n", .{ executor_bond_after(1000, outcome) }); } test "verifier_economics_5_two_dissenters" { - if (!(dissenter_count5(0x41, 0x41, 0x41, 0x99, 0xBE) == 2)) @panic("2 of 5 dissent from the 3-majority"); - if (!(max_agree5(0x41, 0x41, 0x41, 0x99, 0xBE) == 3)) @panic("3 honest form the quorum"); - if (!(burned_total5(0x41, 0x41, 0x41, 0x99, 0xBE, 50) == 100)) @panic("two 50-stakes burned"); - if (!(honest_share5(0x41, 0x41, 0x41, 0x99, 0xBE, 50) == 33)) @panic("100 split among 3 honest -> 33 each (floor)"); - if (!((verifier_stake_after(50, 0) + honest_share5(0x41, 0x41, 0x41, 0x99, 0xBE, 50)) == 83)) @panic("honest net 50 + 33 = 83 > 50 staked"); - if (!(verifier_stake_after(50, 1) == 0)) @panic("each dissenter's whole stake is burned"); - if (!((3 * honest_share5(0x41, 0x41, 0x41, 0x99, 0xBE, 50)) <= burned_total5(0x41, 0x41, 0x41, 0x99, 0xBE, 50))) @panic("no over-issuance: 3*33 <= 100"); + if (!(dissenter_count5(0x41, 0x41, 0x41, 0x99, 0xBE) == 2)) __t27_assert_fail("\n 2 of 5 dissent from the 3-majority:\n dissenter_count5(0x41, 0x41, 0x41, 0x99, 0xBE) = {any}\n", .{ dissenter_count5(0x41, 0x41, 0x41, 0x99, 0xBE) }); + if (!(max_agree5(0x41, 0x41, 0x41, 0x99, 0xBE) == 3)) __t27_assert_fail("\n 3 honest form the quorum:\n max_agree5(0x41, 0x41, 0x41, 0x99, 0xBE) = {any}\n", .{ max_agree5(0x41, 0x41, 0x41, 0x99, 0xBE) }); + if (!(burned_total5(0x41, 0x41, 0x41, 0x99, 0xBE, 50) == 100)) __t27_assert_fail("\n two 50-stakes burned:\n burned_total5(0x41, 0x41, 0x41, 0x99, 0xBE, 50) = {any}\n", .{ burned_total5(0x41, 0x41, 0x41, 0x99, 0xBE, 50) }); + if (!(honest_share5(0x41, 0x41, 0x41, 0x99, 0xBE, 50) == 33)) __t27_assert_fail("\n 100 split among 3 honest -> 33 each (floor):\n honest_share5(0x41, 0x41, 0x41, 0x99, 0xBE, 50) = {any}\n", .{ honest_share5(0x41, 0x41, 0x41, 0x99, 0xBE, 50) }); + if (!((verifier_stake_after(50, 0) + honest_share5(0x41, 0x41, 0x41, 0x99, 0xBE, 50)) == 83)) __t27_assert_fail("\n honest net 50 + 33 = 83 > 50 staked:\n verifier_stake_after(50, 0) + honest_share5(0x41, 0x41, 0x41, 0x99, 0xBE, 50) = {any}\n", .{ verifier_stake_after(50, 0) + honest_share5(0x41, 0x41, 0x41, 0x99, 0xBE, 50) }); + if (!(verifier_stake_after(50, 1) == 0)) __t27_assert_fail("\n each dissenter's whole stake is burned:\n verifier_stake_after(50, 1) = {any}\n", .{ verifier_stake_after(50, 1) }); + if (!((3 * honest_share5(0x41, 0x41, 0x41, 0x99, 0xBE, 50)) <= burned_total5(0x41, 0x41, 0x41, 0x99, 0xBE, 50))) __t27_assert_fail("\n no over-issuance: 3*33 <= 100:\n 3 * honest_share5(0x41, 0x41, 0x41, 0x99, 0xBE, 50) = {any}\n burned_total5(0x41, 0x41, 0x41, 0x99, 0xBE, 50) = {any}\n", .{ 3 * honest_share5(0x41, 0x41, 0x41, 0x99, 0xBE, 50), burned_total5(0x41, 0x41, 0x41, 0x99, 0xBE, 50) }); } test "verifier_economics_5_one_dissenter" { - if (!(dissenter_count5(0x41, 0x41, 0x41, 0x41, 0x99) == 1)) @panic("1 of 5 dissents from the 4-majority"); - if (!(burned_total5(0x41, 0x41, 0x41, 0x41, 0x99, 50) == 50)) @panic("one 50-stake burned"); - if (!(honest_share5(0x41, 0x41, 0x41, 0x41, 0x99, 50) == 12)) @panic("50 split among 4 -> 12 each (floor)"); - if (!((verifier_stake_after(50, 0) + honest_share5(0x41, 0x41, 0x41, 0x41, 0x99, 50)) == 62)) @panic("honest net 62 > 50"); + if (!(dissenter_count5(0x41, 0x41, 0x41, 0x41, 0x99) == 1)) __t27_assert_fail("\n 1 of 5 dissents from the 4-majority:\n dissenter_count5(0x41, 0x41, 0x41, 0x41, 0x99) = {any}\n", .{ dissenter_count5(0x41, 0x41, 0x41, 0x41, 0x99) }); + if (!(burned_total5(0x41, 0x41, 0x41, 0x41, 0x99, 50) == 50)) __t27_assert_fail("\n one 50-stake burned:\n burned_total5(0x41, 0x41, 0x41, 0x41, 0x99, 50) = {any}\n", .{ burned_total5(0x41, 0x41, 0x41, 0x41, 0x99, 50) }); + if (!(honest_share5(0x41, 0x41, 0x41, 0x41, 0x99, 50) == 12)) __t27_assert_fail("\n 50 split among 4 -> 12 each (floor):\n honest_share5(0x41, 0x41, 0x41, 0x41, 0x99, 50) = {any}\n", .{ honest_share5(0x41, 0x41, 0x41, 0x41, 0x99, 50) }); + if (!((verifier_stake_after(50, 0) + honest_share5(0x41, 0x41, 0x41, 0x41, 0x99, 50)) == 62)) __t27_assert_fail("\n honest net 62 > 50:\n verifier_stake_after(50, 0) + honest_share5(0x41, 0x41, 0x41, 0x41, 0x99, 50) = {any}\n", .{ verifier_stake_after(50, 0) + honest_share5(0x41, 0x41, 0x41, 0x41, 0x99, 50) }); } test "burned_total5_saturates" { - if (!(dissenter_count5(0x41, 0x42, 0x43, 0x44, 0x45) == 4)) @panic("5 distinct votes -> 4 dissent from a lone majority"); - if (!(burned_total5(0x41, 0x42, 0x43, 0x44, 0x45, 100) == 400)) @panic("small stake exact: 4 * 100 = 400"); - if (!(burned_total5(0x41, 0x42, 0x43, 0x44, 0x45, 1100000000) == 4294967295)) @panic("4 * 1.1e9 = 4.4e9 saturates to u32 max, not a wrap to ~1.05e8"); - if (!(honest_share5(0x41, 0x42, 0x43, 0x44, 0x45, 1100000000) == 4294967295)) @panic("lone honest verifier gets the whole capped pool, never a wrapped dust value"); + if (!(dissenter_count5(0x41, 0x42, 0x43, 0x44, 0x45) == 4)) __t27_assert_fail("\n 5 distinct votes -> 4 dissent from a lone majority:\n dissenter_count5(0x41, 0x42, 0x43, 0x44, 0x45) = {any}\n", .{ dissenter_count5(0x41, 0x42, 0x43, 0x44, 0x45) }); + if (!(burned_total5(0x41, 0x42, 0x43, 0x44, 0x45, 100) == 400)) __t27_assert_fail("\n small stake exact: 4 * 100 = 400:\n burned_total5(0x41, 0x42, 0x43, 0x44, 0x45, 100) = {any}\n", .{ burned_total5(0x41, 0x42, 0x43, 0x44, 0x45, 100) }); + if (!(burned_total5(0x41, 0x42, 0x43, 0x44, 0x45, 1100000000) == 4294967295)) __t27_assert_fail("\n 4 * 1.1e9 = 4.4e9 saturates to u32 max, not a wrap to ~1.05e8:\n burned_total5(0x41, 0x42, 0x43, 0x44, 0x45, 1100000000) = {any}\n", .{ burned_total5(0x41, 0x42, 0x43, 0x44, 0x45, 1100000000) }); + if (!(honest_share5(0x41, 0x42, 0x43, 0x44, 0x45, 1100000000) == 4294967295)) __t27_assert_fail("\n lone honest verifier gets the whole capped pool, never a wrapped dust value:\n honest_share5(0x41, 0x42, 0x43, 0x44, 0x45, 1100000000) = {any}\n", .{ honest_share5(0x41, 0x42, 0x43, 0x44, 0x45, 1100000000) }); } test "bitnet_dispute_needs_both_parts" { - if (!(resolve_bitnet(0xAB, 0xAB, 0x4100, 0x4100, 1) == RESOLVE_HONEST)) @panic("valid ternary + correct GF -> honest"); - if (!(resolve_bitnet(0xAB, 0xAB, 0x9999, 0x4100, 1) == RESOLVE_SLASH)) @panic("valid ternary but wrong GF value -> slash"); - if (!(resolve_bitnet(0xAB, 0xAB, 0x4100, 0x4100, 0) == RESOLVE_SLASH)) @panic("bad ternary recompute -> slash despite a matching GF value"); - if (!(resolve_bitnet(0xAB, 0xAC, 0x4100, 0x4100, 0) == RESOLVE_MALFORMED)) @panic("unbound dispute -> malformed, no slash"); - if (!(executor_bond_after(1000, resolve_bitnet(0xAB, 0xAC, 0x4100, 0x4100, 0)) == 1000)) @panic("malformed keeps the bond"); + if (!(resolve_bitnet(0xAB, 0xAB, 0x4100, 0x4100, 1) == RESOLVE_HONEST)) __t27_assert_fail("\n valid ternary + correct GF -> honest:\n resolve_bitnet(0xAB, 0xAB, 0x4100, 0x4100, 1) = {any}\n RESOLVE_HONEST = {any}\n", .{ resolve_bitnet(0xAB, 0xAB, 0x4100, 0x4100, 1), RESOLVE_HONEST }); + if (!(resolve_bitnet(0xAB, 0xAB, 0x9999, 0x4100, 1) == RESOLVE_SLASH)) __t27_assert_fail("\n valid ternary but wrong GF value -> slash:\n resolve_bitnet(0xAB, 0xAB, 0x9999, 0x4100, 1) = {any}\n RESOLVE_SLASH = {any}\n", .{ resolve_bitnet(0xAB, 0xAB, 0x9999, 0x4100, 1), RESOLVE_SLASH }); + if (!(resolve_bitnet(0xAB, 0xAB, 0x4100, 0x4100, 0) == RESOLVE_SLASH)) __t27_assert_fail("\n bad ternary recompute -> slash despite a matching GF value:\n resolve_bitnet(0xAB, 0xAB, 0x4100, 0x4100, 0) = {any}\n RESOLVE_SLASH = {any}\n", .{ resolve_bitnet(0xAB, 0xAB, 0x4100, 0x4100, 0), RESOLVE_SLASH }); + if (!(resolve_bitnet(0xAB, 0xAC, 0x4100, 0x4100, 0) == RESOLVE_MALFORMED)) __t27_assert_fail("\n unbound dispute -> malformed, no slash:\n resolve_bitnet(0xAB, 0xAC, 0x4100, 0x4100, 0) = {any}\n RESOLVE_MALFORMED = {any}\n", .{ resolve_bitnet(0xAB, 0xAC, 0x4100, 0x4100, 0), RESOLVE_MALFORMED }); + if (!(executor_bond_after(1000, resolve_bitnet(0xAB, 0xAC, 0x4100, 0x4100, 0)) == 1000)) __t27_assert_fail("\n malformed keeps the bond:\n executor_bond_after(1000, resolve_bitnet(0xAB, 0xAC, 0x4100, 0x4100, 0)) = {any}\n", .{ executor_bond_after(1000, resolve_bitnet(0xAB, 0xAC, 0x4100, 0x4100, 0)) }); } test "bitnet_full_closes_replay_and_family" { - if (!(resolve_bitnet_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x4100, 0x4100, 1) == RESOLVE_HONEST)) @panic("fresh + same family + valid -> honest"); - if (!(resolve_bitnet_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 1) == RESOLVE_SLASH)) @panic("fresh GF fraud -> slash"); - if (!(resolve_bitnet_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x4100, 0x4100, 0) == RESOLVE_SLASH)) @panic("fresh bad ternary -> slash"); - if (!(resolve_bitnet_full(6, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 1) == RESOLVE_STALE)) @panic("replayed BitNet fraud -> stale, no re-slash"); - if (!(resolve_bitnet(0xAB, 0xAB, 0x9999, 0x4100, 1) == RESOLVE_SLASH)) @panic("contrast: bare resolve_bitnet re-slashes the replay (no epoch)"); - if (!(resolve_bitnet_full(5, 6, FMT_GFT, FMT_GF_BINARY, 0xAB, 0xAB, 0x4100, 0x4100, 1) == RESOLVE_FAMILY_MISMATCH)) @panic("cross-family BitNet dispute -> family mismatch"); - if (!(resolve_bitnet_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAC, 0x4100, 0x4100, 1) == RESOLVE_MALFORMED)) @panic("fresh same-family but unbound leaf -> malformed"); - if (!(executor_bond_after(1000, resolve_bitnet_full(6, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 1)) == 1000)) @panic("replayed BitNet dispute keeps the bond"); + if (!(resolve_bitnet_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x4100, 0x4100, 1) == RESOLVE_HONEST)) __t27_assert_fail("\n fresh + same family + valid -> honest:\n resolve_bitnet_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x4100, 0x4100, 1) = {any}\n RESOLVE_HONEST = {any}\n", .{ resolve_bitnet_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x4100, 0x4100, 1), RESOLVE_HONEST }); + if (!(resolve_bitnet_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 1) == RESOLVE_SLASH)) __t27_assert_fail("\n fresh GF fraud -> slash:\n resolve_bitnet_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 1) = {any}\n RESOLVE_SLASH = {any}\n", .{ resolve_bitnet_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 1), RESOLVE_SLASH }); + if (!(resolve_bitnet_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x4100, 0x4100, 0) == RESOLVE_SLASH)) __t27_assert_fail("\n fresh bad ternary -> slash:\n resolve_bitnet_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x4100, 0x4100, 0) = {any}\n RESOLVE_SLASH = {any}\n", .{ resolve_bitnet_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x4100, 0x4100, 0), RESOLVE_SLASH }); + if (!(resolve_bitnet_full(6, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 1) == RESOLVE_STALE)) __t27_assert_fail("\n replayed BitNet fraud -> stale, no re-slash:\n resolve_bitnet_full(6, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 1) = {any}\n RESOLVE_STALE = {any}\n", .{ resolve_bitnet_full(6, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 1), RESOLVE_STALE }); + if (!(resolve_bitnet(0xAB, 0xAB, 0x9999, 0x4100, 1) == RESOLVE_SLASH)) __t27_assert_fail("\n contrast: bare resolve_bitnet re-slashes the replay (no epoch):\n resolve_bitnet(0xAB, 0xAB, 0x9999, 0x4100, 1) = {any}\n RESOLVE_SLASH = {any}\n", .{ resolve_bitnet(0xAB, 0xAB, 0x9999, 0x4100, 1), RESOLVE_SLASH }); + if (!(resolve_bitnet_full(5, 6, FMT_GFT, FMT_GF_BINARY, 0xAB, 0xAB, 0x4100, 0x4100, 1) == RESOLVE_FAMILY_MISMATCH)) __t27_assert_fail("\n cross-family BitNet dispute -> family mismatch:\n resolve_bitnet_full(5, 6, FMT_GFT, FMT_GF_BINARY, 0xAB, 0xAB, 0x4100, 0x4100, 1) = {any}\n RESOLVE_FAMILY_MISMATCH = {any}\n", .{ resolve_bitnet_full(5, 6, FMT_GFT, FMT_GF_BINARY, 0xAB, 0xAB, 0x4100, 0x4100, 1), RESOLVE_FAMILY_MISMATCH }); + if (!(resolve_bitnet_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAC, 0x4100, 0x4100, 1) == RESOLVE_MALFORMED)) __t27_assert_fail("\n fresh same-family but unbound leaf -> malformed:\n resolve_bitnet_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAC, 0x4100, 0x4100, 1) = {any}\n RESOLVE_MALFORMED = {any}\n", .{ resolve_bitnet_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAC, 0x4100, 0x4100, 1), RESOLVE_MALFORMED }); + if (!(executor_bond_after(1000, resolve_bitnet_full(6, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 1)) == 1000)) __t27_assert_fail("\n replayed BitNet dispute keeps the bond:\n executor_bond_after(1000, resolve_bitnet_full(6, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 1)) = {any}\n", .{ executor_bond_after(1000, resolve_bitnet_full(6, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 1)) }); } test "bitnet_dispute_d256_anchor" { - if (!(resolve_bitnet_d256(1, 0x4100, 0x4100, 1) == RESOLVE_HONEST)) @panic("matched digest + valid ternary + correct GF -> honest"); - if (!(resolve_bitnet_d256(1, 0x9999, 0x4100, 1) == RESOLVE_SLASH)) @panic("matched digest, wrong GF -> slash"); - if (!(resolve_bitnet_d256(1, 0x4100, 0x4100, 0) == RESOLVE_SLASH)) @panic("matched digest, bad ternary -> slash"); - if (!(resolve_bitnet_d256(0, 0x4100, 0x4100, 0) == RESOLVE_MALFORMED)) @panic("digest mismatch -> malformed"); - if (!(executor_bond_after(1000, resolve_bitnet_d256(0, 0x4100, 0x4100, 0)) == 1000)) @panic("malformed keeps the bond"); - if (!(resolve_bitnet_d256(1, 0x4100, 0x4100, 1) == resolve_bitnet(0xAB, 0xAB, 0x4100, 0x4100, 1))) @panic("d256 matches resolve_bitnet on the honest path"); + if (!(resolve_bitnet_d256(1, 0x4100, 0x4100, 1) == RESOLVE_HONEST)) __t27_assert_fail("\n matched digest + valid ternary + correct GF -> honest:\n resolve_bitnet_d256(1, 0x4100, 0x4100, 1) = {any}\n RESOLVE_HONEST = {any}\n", .{ resolve_bitnet_d256(1, 0x4100, 0x4100, 1), RESOLVE_HONEST }); + if (!(resolve_bitnet_d256(1, 0x9999, 0x4100, 1) == RESOLVE_SLASH)) __t27_assert_fail("\n matched digest, wrong GF -> slash:\n resolve_bitnet_d256(1, 0x9999, 0x4100, 1) = {any}\n RESOLVE_SLASH = {any}\n", .{ resolve_bitnet_d256(1, 0x9999, 0x4100, 1), RESOLVE_SLASH }); + if (!(resolve_bitnet_d256(1, 0x4100, 0x4100, 0) == RESOLVE_SLASH)) __t27_assert_fail("\n matched digest, bad ternary -> slash:\n resolve_bitnet_d256(1, 0x4100, 0x4100, 0) = {any}\n RESOLVE_SLASH = {any}\n", .{ resolve_bitnet_d256(1, 0x4100, 0x4100, 0), RESOLVE_SLASH }); + if (!(resolve_bitnet_d256(0, 0x4100, 0x4100, 0) == RESOLVE_MALFORMED)) __t27_assert_fail("\n digest mismatch -> malformed:\n resolve_bitnet_d256(0, 0x4100, 0x4100, 0) = {any}\n RESOLVE_MALFORMED = {any}\n", .{ resolve_bitnet_d256(0, 0x4100, 0x4100, 0), RESOLVE_MALFORMED }); + if (!(executor_bond_after(1000, resolve_bitnet_d256(0, 0x4100, 0x4100, 0)) == 1000)) __t27_assert_fail("\n malformed keeps the bond:\n executor_bond_after(1000, resolve_bitnet_d256(0, 0x4100, 0x4100, 0)) = {any}\n", .{ executor_bond_after(1000, resolve_bitnet_d256(0, 0x4100, 0x4100, 0)) }); + if (!(resolve_bitnet_d256(1, 0x4100, 0x4100, 1) == resolve_bitnet(0xAB, 0xAB, 0x4100, 0x4100, 1))) __t27_assert_fail("\n d256 matches resolve_bitnet on the honest path:\n resolve_bitnet_d256(1, 0x4100, 0x4100, 1) = {any}\n resolve_bitnet(0xAB, 0xAB, 0x4100, 0x4100, 1) = {any}\n", .{ resolve_bitnet_d256(1, 0x4100, 0x4100, 1), resolve_bitnet(0xAB, 0xAB, 0x4100, 0x4100, 1) }); } test "bitnet_d256_full_closes_replay" { - if (!(resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GFT, 1, 0x4100, 0x4100, 1) == RESOLVE_HONEST)) @panic("fresh matched-digest honest -> honest"); - if (!(resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GFT, 1, 0x9999, 0x4100, 1) == RESOLVE_SLASH)) @panic("fresh matched-digest GF fraud -> slash"); - if (!(resolve_bitnet_d256_full(6, 6, FMT_GFT, FMT_GFT, 1, 0x9999, 0x4100, 1) == RESOLVE_STALE)) @panic("replayed 256-bit fraud -> stale"); - if (!(resolve_bitnet_d256(1, 0x9999, 0x4100, 1) == RESOLVE_SLASH)) @panic("contrast: bare resolve_bitnet_d256 re-slashes the replay"); - if (!(resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GF_BINARY, 1, 0x4100, 0x4100, 1) == RESOLVE_FAMILY_MISMATCH)) @panic("cross-family -> family mismatch"); - if (!(resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GFT, 0, 0x4100, 0x4100, 1) == RESOLVE_MALFORMED)) @panic("fresh same-family but digest mismatch -> malformed"); - if (!(resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GFT, 1, 0x4100, 0x4100, 1) == resolve_full_d256(5, 6, FMT_GFT, FMT_GFT, 1, 0x4100, 0x4100))) @panic("honest-path parity with resolve_full_d256"); + if (!(resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GFT, 1, 0x4100, 0x4100, 1) == RESOLVE_HONEST)) __t27_assert_fail("\n fresh matched-digest honest -> honest:\n resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GFT, 1, 0x4100, 0x4100, 1) = {any}\n RESOLVE_HONEST = {any}\n", .{ resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GFT, 1, 0x4100, 0x4100, 1), RESOLVE_HONEST }); + if (!(resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GFT, 1, 0x9999, 0x4100, 1) == RESOLVE_SLASH)) __t27_assert_fail("\n fresh matched-digest GF fraud -> slash:\n resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GFT, 1, 0x9999, 0x4100, 1) = {any}\n RESOLVE_SLASH = {any}\n", .{ resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GFT, 1, 0x9999, 0x4100, 1), RESOLVE_SLASH }); + if (!(resolve_bitnet_d256_full(6, 6, FMT_GFT, FMT_GFT, 1, 0x9999, 0x4100, 1) == RESOLVE_STALE)) __t27_assert_fail("\n replayed 256-bit fraud -> stale:\n resolve_bitnet_d256_full(6, 6, FMT_GFT, FMT_GFT, 1, 0x9999, 0x4100, 1) = {any}\n RESOLVE_STALE = {any}\n", .{ resolve_bitnet_d256_full(6, 6, FMT_GFT, FMT_GFT, 1, 0x9999, 0x4100, 1), RESOLVE_STALE }); + if (!(resolve_bitnet_d256(1, 0x9999, 0x4100, 1) == RESOLVE_SLASH)) __t27_assert_fail("\n contrast: bare resolve_bitnet_d256 re-slashes the replay:\n resolve_bitnet_d256(1, 0x9999, 0x4100, 1) = {any}\n RESOLVE_SLASH = {any}\n", .{ resolve_bitnet_d256(1, 0x9999, 0x4100, 1), RESOLVE_SLASH }); + if (!(resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GF_BINARY, 1, 0x4100, 0x4100, 1) == RESOLVE_FAMILY_MISMATCH)) __t27_assert_fail("\n cross-family -> family mismatch:\n resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GF_BINARY, 1, 0x4100, 0x4100, 1) = {any}\n RESOLVE_FAMILY_MISMATCH = {any}\n", .{ resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GF_BINARY, 1, 0x4100, 0x4100, 1), RESOLVE_FAMILY_MISMATCH }); + if (!(resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GFT, 0, 0x4100, 0x4100, 1) == RESOLVE_MALFORMED)) __t27_assert_fail("\n fresh same-family but digest mismatch -> malformed:\n resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GFT, 0, 0x4100, 0x4100, 1) = {any}\n RESOLVE_MALFORMED = {any}\n", .{ resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GFT, 0, 0x4100, 0x4100, 1), RESOLVE_MALFORMED }); + if (!(resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GFT, 1, 0x4100, 0x4100, 1) == resolve_full_d256(5, 6, FMT_GFT, FMT_GFT, 1, 0x4100, 0x4100))) __t27_assert_fail("\n honest-path parity with resolve_full_d256:\n resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GFT, 1, 0x4100, 0x4100, 1) = {any}\n resolve_full_d256(5, 6, FMT_GFT, FMT_GFT, 1, 0x4100, 0x4100) = {any}\n", .{ resolve_bitnet_d256_full(5, 6, FMT_GFT, FMT_GFT, 1, 0x4100, 0x4100, 1), resolve_full_d256(5, 6, FMT_GFT, FMT_GFT, 1, 0x4100, 0x4100) }); } test "majority_flag_basics" { - if (!(majority_flag3(1, 1, 1) == 1)) @panic("unanimous yes"); - if (!(majority_flag3(1, 1, 0) == 1)) @panic("2-of-3 yes"); - if (!(majority_flag3(1, 0, 0) == 0)) @panic("only one yes -> no"); - if (!(majority_flag3(0, 0, 0) == 0)) @panic("unanimous no"); + if (!(majority_flag3(1, 1, 1) == 1)) __t27_assert_fail("\n unanimous yes:\n majority_flag3(1, 1, 1) = {any}\n", .{ majority_flag3(1, 1, 1) }); + if (!(majority_flag3(1, 1, 0) == 1)) __t27_assert_fail("\n 2-of-3 yes:\n majority_flag3(1, 1, 0) = {any}\n", .{ majority_flag3(1, 1, 0) }); + if (!(majority_flag3(1, 0, 0) == 0)) __t27_assert_fail("\n only one yes -> no:\n majority_flag3(1, 0, 0) = {any}\n", .{ majority_flag3(1, 0, 0) }); + if (!(majority_flag3(0, 0, 0) == 0)) __t27_assert_fail("\n unanimous no:\n majority_flag3(0, 0, 0) = {any}\n", .{ majority_flag3(0, 0, 0) }); } test "bitnet_quorum_outvotes_a_liar" { - if (!(resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x9999, 1, 1, 1) == RESOLVE_HONEST)) @panic("value liar outvoted -> honest executor safe"); - if (!(resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0, 1, 1) == RESOLVE_HONEST)) @panic("lone false ternary accusation is outvoted"); - if (!(resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0, 0, 1) == RESOLVE_SLASH)) @panic("ternary-bad majority slashes"); - if (!(resolve_bitnet_quorum(0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x9999, 1, 1, 1) == RESOLVE_SLASH)) @panic("GF fraud caught by the value majority"); - if (!(resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x1111, 0x2222, 0x3333, 1, 1, 1) == RESOLVE_INDETERMINATE)) @panic("split value set -> indeterminate"); - if (!(executor_bond_after(1000, resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x1111, 0x2222, 0x3333, 1, 1, 1)) == 1000)) @panic("indeterminate keeps the bond"); + if (!(resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x9999, 1, 1, 1) == RESOLVE_HONEST)) __t27_assert_fail("\n value liar outvoted -> honest executor safe:\n resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x9999, 1, 1, 1) = {any}\n RESOLVE_HONEST = {any}\n", .{ resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x9999, 1, 1, 1), RESOLVE_HONEST }); + if (!(resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0, 1, 1) == RESOLVE_HONEST)) __t27_assert_fail("\n lone false ternary accusation is outvoted:\n resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0, 1, 1) = {any}\n RESOLVE_HONEST = {any}\n", .{ resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0, 1, 1), RESOLVE_HONEST }); + if (!(resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0, 0, 1) == RESOLVE_SLASH)) __t27_assert_fail("\n ternary-bad majority slashes:\n resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0, 0, 1) = {any}\n RESOLVE_SLASH = {any}\n", .{ resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0, 0, 1), RESOLVE_SLASH }); + if (!(resolve_bitnet_quorum(0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x9999, 1, 1, 1) == RESOLVE_SLASH)) __t27_assert_fail("\n GF fraud caught by the value majority:\n resolve_bitnet_quorum(0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x9999, 1, 1, 1) = {any}\n RESOLVE_SLASH = {any}\n", .{ resolve_bitnet_quorum(0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x9999, 1, 1, 1), RESOLVE_SLASH }); + if (!(resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x1111, 0x2222, 0x3333, 1, 1, 1) == RESOLVE_INDETERMINATE)) __t27_assert_fail("\n split value set -> indeterminate:\n resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x1111, 0x2222, 0x3333, 1, 1, 1) = {any}\n RESOLVE_INDETERMINATE = {any}\n", .{ resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x1111, 0x2222, 0x3333, 1, 1, 1), RESOLVE_INDETERMINATE }); + if (!(executor_bond_after(1000, resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x1111, 0x2222, 0x3333, 1, 1, 1)) == 1000)) __t27_assert_fail("\n indeterminate keeps the bond:\n executor_bond_after(1000, resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x1111, 0x2222, 0x3333, 1, 1, 1)) = {any}\n", .{ executor_bond_after(1000, resolve_bitnet_quorum(0xAB, 0xAB, 0x4100, 0x1111, 0x2222, 0x3333, 1, 1, 1)) }); } test "majority_flag5_basics" { - if (!(majority_flag5(1, 1, 1, 0, 0) == 1)) @panic("3-of-5 yes"); - if (!(majority_flag5(1, 1, 0, 0, 0) == 0)) @panic("2-of-5 -> no"); - if (!(majority_flag5(1, 1, 1, 1, 1) == 1)) @panic("unanimous yes"); - if (!(majority_flag5(0, 0, 0, 0, 0) == 0)) @panic("unanimous no"); + if (!(majority_flag5(1, 1, 1, 0, 0) == 1)) __t27_assert_fail("\n 3-of-5 yes:\n majority_flag5(1, 1, 1, 0, 0) = {any}\n", .{ majority_flag5(1, 1, 1, 0, 0) }); + if (!(majority_flag5(1, 1, 0, 0, 0) == 0)) __t27_assert_fail("\n 2-of-5 -> no:\n majority_flag5(1, 1, 0, 0, 0) = {any}\n", .{ majority_flag5(1, 1, 0, 0, 0) }); + if (!(majority_flag5(1, 1, 1, 1, 1) == 1)) __t27_assert_fail("\n unanimous yes:\n majority_flag5(1, 1, 1, 1, 1) = {any}\n", .{ majority_flag5(1, 1, 1, 1, 1) }); + if (!(majority_flag5(0, 0, 0, 0, 0) == 0)) __t27_assert_fail("\n unanimous no:\n majority_flag5(0, 0, 0, 0, 0) = {any}\n", .{ majority_flag5(0, 0, 0, 0, 0) }); } test "bitnet_quorum5_outvotes_two_liars" { - if (!(resolve_bitnet_quorum5(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999, 1, 1, 1, 1, 1) == RESOLVE_HONEST)) @panic("2 value liars outvoted by 3-of-5"); - if (!(resolve_bitnet_quorum5(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0x4100, 0x4100, 0, 0, 1, 1, 1) == RESOLVE_HONEST)) @panic("2 false ternary accusations outvoted"); - if (!(resolve_bitnet_quorum5(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0x4100, 0x4100, 0, 0, 0, 1, 1) == RESOLVE_SLASH)) @panic("3-of-5 ternary-bad majority slashes"); - if (!(resolve_bitnet_quorum5(0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999, 1, 1, 1, 1, 1) == RESOLVE_SLASH)) @panic("GF fraud caught by the 3-of-5 value majority"); - if (!(resolve_bitnet_quorum5(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999, 0xBEEF, 1, 1, 1, 1, 1) == RESOLVE_INDETERMINATE)) @panic("2-2-1 split -> indeterminate"); + if (!(resolve_bitnet_quorum5(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999, 1, 1, 1, 1, 1) == RESOLVE_HONEST)) __t27_assert_fail("\n 2 value liars outvoted by 3-of-5:\n resolve_bitnet_quorum5(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999, 1, 1, 1, 1, 1) = {any}\n RESOLVE_HONEST = {any}\n", .{ resolve_bitnet_quorum5(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999, 1, 1, 1, 1, 1), RESOLVE_HONEST }); + if (!(resolve_bitnet_quorum5(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0x4100, 0x4100, 0, 0, 1, 1, 1) == RESOLVE_HONEST)) __t27_assert_fail("\n 2 false ternary accusations outvoted:\n resolve_bitnet_quorum5(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0x4100, 0x4100, 0, 0, 1, 1, 1) = {any}\n RESOLVE_HONEST = {any}\n", .{ resolve_bitnet_quorum5(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0x4100, 0x4100, 0, 0, 1, 1, 1), RESOLVE_HONEST }); + if (!(resolve_bitnet_quorum5(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0x4100, 0x4100, 0, 0, 0, 1, 1) == RESOLVE_SLASH)) __t27_assert_fail("\n 3-of-5 ternary-bad majority slashes:\n resolve_bitnet_quorum5(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0x4100, 0x4100, 0, 0, 0, 1, 1) = {any}\n RESOLVE_SLASH = {any}\n", .{ resolve_bitnet_quorum5(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 0x4100, 0x4100, 0, 0, 0, 1, 1), RESOLVE_SLASH }); + if (!(resolve_bitnet_quorum5(0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999, 1, 1, 1, 1, 1) == RESOLVE_SLASH)) __t27_assert_fail("\n GF fraud caught by the 3-of-5 value majority:\n resolve_bitnet_quorum5(0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999, 1, 1, 1, 1, 1) = {any}\n RESOLVE_SLASH = {any}\n", .{ resolve_bitnet_quorum5(0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999, 1, 1, 1, 1, 1), RESOLVE_SLASH }); + if (!(resolve_bitnet_quorum5(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999, 0xBEEF, 1, 1, 1, 1, 1) == RESOLVE_INDETERMINATE)) __t27_assert_fail("\n 2-2-1 split -> indeterminate:\n resolve_bitnet_quorum5(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999, 0xBEEF, 1, 1, 1, 1, 1) = {any}\n RESOLVE_INDETERMINATE = {any}\n", .{ resolve_bitnet_quorum5(0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999, 0xBEEF, 1, 1, 1, 1, 1), RESOLVE_INDETERMINATE }); } test "bitnet_quorum_full_closes_replay" { - if (!(resolve_bitnet_quorum_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x9999, 1, 1, 1) == RESOLVE_SLASH)) @panic("fresh quorum GF fraud -> slash"); - if (!(resolve_bitnet_quorum_full(6, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x9999, 1, 1, 1) == RESOLVE_STALE)) @panic("replayed quorum fraud -> stale"); - if (!(resolve_bitnet_quorum(0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x9999, 1, 1, 1) == RESOLVE_SLASH)) @panic("bare quorum re-slashes the replay"); - if (!(resolve_bitnet_quorum_full(5, 6, FMT_GFT, FMT_GF_BINARY, 0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 1, 1, 1) == RESOLVE_FAMILY_MISMATCH)) @panic("cross-family quorum dispute -> family mismatch"); - if (!(resolve_bitnet_quorum_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x4100, 0x1111, 0x2222, 0x3333, 1, 1, 1) == RESOLVE_INDETERMINATE)) @panic("split value set -> indeterminate (checked before freshness)"); - if (!(resolve_bitnet_quorum_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 1, 1, 1) == RESOLVE_HONEST)) @panic("fresh honest quorum -> honest"); - if (!(resolve_bitnet_quorum5_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999, 1, 1, 1, 1, 1) == RESOLVE_SLASH)) @panic("fresh 3-of-5 GF fraud -> slash"); - if (!(resolve_bitnet_quorum5_full(6, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999, 1, 1, 1, 1, 1) == RESOLVE_STALE)) @panic("replayed 3-of-5 fraud -> stale"); + if (!(resolve_bitnet_quorum_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x9999, 1, 1, 1) == RESOLVE_SLASH)) __t27_assert_fail("\n fresh quorum GF fraud -> slash:\n resolve_bitnet_quorum_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x9999, 1, 1, 1) = {any}\n RESOLVE_SLASH = {any}\n", .{ resolve_bitnet_quorum_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x9999, 1, 1, 1), RESOLVE_SLASH }); + if (!(resolve_bitnet_quorum_full(6, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x9999, 1, 1, 1) == RESOLVE_STALE)) __t27_assert_fail("\n replayed quorum fraud -> stale:\n resolve_bitnet_quorum_full(6, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x9999, 1, 1, 1) = {any}\n RESOLVE_STALE = {any}\n", .{ resolve_bitnet_quorum_full(6, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x9999, 1, 1, 1), RESOLVE_STALE }); + if (!(resolve_bitnet_quorum(0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x9999, 1, 1, 1) == RESOLVE_SLASH)) __t27_assert_fail("\n bare quorum re-slashes the replay:\n resolve_bitnet_quorum(0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x9999, 1, 1, 1) = {any}\n RESOLVE_SLASH = {any}\n", .{ resolve_bitnet_quorum(0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x9999, 1, 1, 1), RESOLVE_SLASH }); + if (!(resolve_bitnet_quorum_full(5, 6, FMT_GFT, FMT_GF_BINARY, 0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 1, 1, 1) == RESOLVE_FAMILY_MISMATCH)) __t27_assert_fail("\n cross-family quorum dispute -> family mismatch:\n resolve_bitnet_quorum_full(5, 6, FMT_GFT, FMT_GF_BINARY, 0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 1, 1, 1) = {any}\n RESOLVE_FAMILY_MISMATCH = {any}\n", .{ resolve_bitnet_quorum_full(5, 6, FMT_GFT, FMT_GF_BINARY, 0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 1, 1, 1), RESOLVE_FAMILY_MISMATCH }); + if (!(resolve_bitnet_quorum_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x4100, 0x1111, 0x2222, 0x3333, 1, 1, 1) == RESOLVE_INDETERMINATE)) __t27_assert_fail("\n split value set -> indeterminate (checked before freshness):\n resolve_bitnet_quorum_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x4100, 0x1111, 0x2222, 0x3333, 1, 1, 1) = {any}\n RESOLVE_INDETERMINATE = {any}\n", .{ resolve_bitnet_quorum_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x4100, 0x1111, 0x2222, 0x3333, 1, 1, 1), RESOLVE_INDETERMINATE }); + if (!(resolve_bitnet_quorum_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 1, 1, 1) == RESOLVE_HONEST)) __t27_assert_fail("\n fresh honest quorum -> honest:\n resolve_bitnet_quorum_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 1, 1, 1) = {any}\n RESOLVE_HONEST = {any}\n", .{ resolve_bitnet_quorum_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x4100, 0x4100, 0x4100, 0x4100, 1, 1, 1), RESOLVE_HONEST }); + if (!(resolve_bitnet_quorum5_full(5, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999, 1, 1, 1, 1, 1) == RESOLVE_SLASH)) __t27_assert_fail("\n fresh 3-of-5 GF fraud -> slash:\n RESOLVE_SLASH = {any}\n", .{ RESOLVE_SLASH }); + if (!(resolve_bitnet_quorum5_full(6, 6, FMT_GFT, FMT_GFT, 0xAB, 0xAB, 0x9999, 0x4100, 0x4100, 0x4100, 0x9999, 0x9999, 1, 1, 1, 1, 1) == RESOLVE_STALE)) __t27_assert_fail("\n replayed 3-of-5 fraud -> stale:\n RESOLVE_STALE = {any}\n", .{ RESOLVE_STALE }); } diff --git a/gen/zig/tri_compute_gfvalid.zig b/gen/zig/tri_compute_gfvalid.zig index 08440557..7fb1f470 100644 --- a/gen/zig/tri_compute_gfvalid.zig +++ b/gen/zig/tri_compute_gfvalid.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module fn is_finite_gf(result: u32, exp_bits: u32, mant_bits: u32) bool { @@ -108,87 +116,87 @@ fn is_finite_dispatch(fmt_family: u32, value: u32, exp_bits: u32, mant_bits: u32 } } test "gf16_specials" { - if (!(is_finite_gf(0x4200, 6, 9) == true)) @panic("GF16 4.0 finite"); - if (!(is_finite_gf(0x7E00, 6, 9) == false)) @panic("GF16 +inf (exp all-ones)"); - if (!(is_finite_gf(0x7E01, 6, 9) == false)) @panic("GF16 NaN"); - if (!(is_finite_gf(0xFE00, 6, 9) == false)) @panic("GF16 -inf"); + if (!(is_finite_gf(0x4200, 6, 9) == true)) __t27_assert_fail("\n GF16 4.0 finite:\n is_finite_gf(0x4200, 6, 9) = {any}\n", .{ is_finite_gf(0x4200, 6, 9) }); + if (!(is_finite_gf(0x7E00, 6, 9) == false)) __t27_assert_fail("\n GF16 +inf (exp all-ones):\n is_finite_gf(0x7E00, 6, 9) = {any}\n", .{ is_finite_gf(0x7E00, 6, 9) }); + if (!(is_finite_gf(0x7E01, 6, 9) == false)) __t27_assert_fail("\n GF16 NaN:\n is_finite_gf(0x7E01, 6, 9) = {any}\n", .{ is_finite_gf(0x7E01, 6, 9) }); + if (!(is_finite_gf(0xFE00, 6, 9) == false)) __t27_assert_fail("\n GF16 -inf:\n is_finite_gf(0xFE00, 6, 9) = {any}\n", .{ is_finite_gf(0xFE00, 6, 9) }); } test "gf8_specials" { - if (!(is_finite_gf(0x20, 3, 4) == true)) @panic("GF8 finite (exp=2)"); - if (!(is_finite_gf(0x70, 3, 4) == false)) @panic("GF8 +inf (exp=7, mant=0)"); - if (!(is_finite_gf(0x71, 3, 4) == false)) @panic("GF8 NaN (exp=7, mant!=0)"); + if (!(is_finite_gf(0x20, 3, 4) == true)) __t27_assert_fail("\n GF8 finite (exp=2):\n is_finite_gf(0x20, 3, 4) = {any}\n", .{ is_finite_gf(0x20, 3, 4) }); + if (!(is_finite_gf(0x70, 3, 4) == false)) __t27_assert_fail("\n GF8 +inf (exp=7, mant=0):\n is_finite_gf(0x70, 3, 4) = {any}\n", .{ is_finite_gf(0x70, 3, 4) }); + if (!(is_finite_gf(0x71, 3, 4) == false)) __t27_assert_fail("\n GF8 NaN (exp=7, mant!=0):\n is_finite_gf(0x71, 3, 4) = {any}\n", .{ is_finite_gf(0x71, 3, 4) }); } test "gf4_specials" { - if (!(is_finite_gf(0x1, 1, 2) == true)) @panic("GF4 finite (exp=0)"); - if (!(is_finite_gf(0x4, 1, 2) == false)) @panic("GF4 special (exp=1)"); + if (!(is_finite_gf(0x1, 1, 2) == true)) __t27_assert_fail("\n GF4 finite (exp=0):\n is_finite_gf(0x1, 1, 2) = {any}\n", .{ is_finite_gf(0x1, 1, 2) }); + if (!(is_finite_gf(0x4, 1, 2) == false)) __t27_assert_fail("\n GF4 special (exp=1):\n is_finite_gf(0x4, 1, 2) = {any}\n", .{ is_finite_gf(0x4, 1, 2) }); } test "gf14_specials" { - if (!(is_finite_gf(0x0100, 5, 8) == true)) @panic("GF14 finite (exp=1)"); - if (!(is_finite_gf(0x1F00, 5, 8) == false)) @panic("GF14 +inf (exp=31)"); + if (!(is_finite_gf(0x0100, 5, 8) == true)) __t27_assert_fail("\n GF14 finite (exp=1):\n is_finite_gf(0x0100, 5, 8) = {any}\n", .{ is_finite_gf(0x0100, 5, 8) }); + if (!(is_finite_gf(0x1F00, 5, 8) == false)) __t27_assert_fail("\n GF14 +inf (exp=31):\n is_finite_gf(0x1F00, 5, 8) = {any}\n", .{ is_finite_gf(0x1F00, 5, 8) }); } test "gft16_specials" { - if (!(is_finite_gft16(40) == true)) @panic("GF-T16 unity exponent finite"); - if (!(is_finite_gft16(79) == true)) @panic("GF-T16 near-top finite"); - if (!(is_finite_gft16(80) == false)) @panic("GF-T16 offset 80 is special"); + if (!(is_finite_gft16(40) == true)) __t27_assert_fail("\n GF-T16 unity exponent finite:\n is_finite_gft16(40) = {any}\n", .{ is_finite_gft16(40) }); + if (!(is_finite_gft16(79) == true)) __t27_assert_fail("\n GF-T16 near-top finite:\n is_finite_gft16(79) = {any}\n", .{ is_finite_gft16(79) }); + if (!(is_finite_gft16(80) == false)) __t27_assert_fail("\n GF-T16 offset 80 is special:\n is_finite_gft16(80) = {any}\n", .{ is_finite_gft16(80) }); } test "gft_ladder_finiteness" { - if (!(gft_offset_max(2) == 8)) @panic("GF-T4 special row = 3^2-1 = 8"); - if (!(gft_offset_max(3) == 26)) @panic("GF-T8 special row = 3^3-1 = 26"); - if (!(gft_offset_max(4) == 80)) @panic("GF-T16 special row = 3^4-1 = 80"); - if (!(gft_offset_max(6) == 728)) @panic("GF-T32 special row = 3^6-1 = 728 (Et6, golden rule)"); - if (!(gft_offset_max(9) == 19682)) @panic("GF-T64 special row = 3^9-1 = 19682"); - if (!(is_finite_gft_n(7, 2) == true)) @panic("GF-T4 offset 7 finite"); - if (!(is_finite_gft_n(8, 2) == false)) @panic("GF-T4 offset 8 is special"); - if (!(is_finite_gft_n(728, 6) == false)) @panic("GF-T32 offset 728 is special"); - if (!(is_finite_gft_n(242, 6) == true)) @panic("GF-T32 offset 242 is a NORMAL value (Et6), not special"); - if (!(is_finite_gft_n(80, 4) == is_finite_gft16(80))) @panic("the alias is the Et=4 case"); - if (!(is_finite_gft_n(40, 4) == is_finite_gft16(40))) @panic("alias agrees on finite too"); + if (!(gft_offset_max(2) == 8)) __t27_assert_fail("\n GF-T4 special row = 3^2-1 = 8:\n gft_offset_max(2) = {any}\n", .{ gft_offset_max(2) }); + if (!(gft_offset_max(3) == 26)) __t27_assert_fail("\n GF-T8 special row = 3^3-1 = 26:\n gft_offset_max(3) = {any}\n", .{ gft_offset_max(3) }); + if (!(gft_offset_max(4) == 80)) __t27_assert_fail("\n GF-T16 special row = 3^4-1 = 80:\n gft_offset_max(4) = {any}\n", .{ gft_offset_max(4) }); + if (!(gft_offset_max(6) == 728)) __t27_assert_fail("\n GF-T32 special row = 3^6-1 = 728 (Et6, golden rule):\n gft_offset_max(6) = {any}\n", .{ gft_offset_max(6) }); + if (!(gft_offset_max(9) == 19682)) __t27_assert_fail("\n GF-T64 special row = 3^9-1 = 19682:\n gft_offset_max(9) = {any}\n", .{ gft_offset_max(9) }); + if (!(is_finite_gft_n(7, 2) == true)) __t27_assert_fail("\n GF-T4 offset 7 finite:\n is_finite_gft_n(7, 2) = {any}\n", .{ is_finite_gft_n(7, 2) }); + if (!(is_finite_gft_n(8, 2) == false)) __t27_assert_fail("\n GF-T4 offset 8 is special:\n is_finite_gft_n(8, 2) = {any}\n", .{ is_finite_gft_n(8, 2) }); + if (!(is_finite_gft_n(728, 6) == false)) __t27_assert_fail("\n GF-T32 offset 728 is special:\n is_finite_gft_n(728, 6) = {any}\n", .{ is_finite_gft_n(728, 6) }); + if (!(is_finite_gft_n(242, 6) == true)) __t27_assert_fail("\n GF-T32 offset 242 is a NORMAL value (Et6), not special:\n is_finite_gft_n(242, 6) = {any}\n", .{ is_finite_gft_n(242, 6) }); + if (!(is_finite_gft_n(80, 4) == is_finite_gft16(80))) __t27_assert_fail("\n the alias is the Et=4 case:\n is_finite_gft_n(80, 4) = {any}\n is_finite_gft16(80) = {any}\n", .{ is_finite_gft_n(80, 4), is_finite_gft16(80) }); + if (!(is_finite_gft_n(40, 4) == is_finite_gft16(40))) __t27_assert_fail("\n alias agrees on finite too:\n is_finite_gft_n(40, 4) = {any}\n is_finite_gft16(40) = {any}\n", .{ is_finite_gft_n(40, 4), is_finite_gft16(40) }); } test "offset_max_from_width_is_bound_and_fail_closed" { - if (!(gft_exp_trits_for_width(8) == 3)) @panic("GF-T8 uses 3 exponent trits"); - if (!(gft_exp_trits_for_width(16) == 4)) @panic("GF-T16 uses 4 exponent trits"); - if (!(gft_offset_max_for_width(4) == 8)) @panic("GF-T4 special row via width"); - if (!(gft_offset_max_for_width(8) == 26)) @panic("GF-T8 special row via width"); - if (!(gft_offset_max_for_width(16) == 80)) @panic("GF-T16 special row via width"); - if (!(gft_offset_max_for_width(32) == 728)) @panic("GF-T32 special row via width (Et6, golden rule)"); - if (!(gft_offset_max_for_width(64) == 19682)) @panic("GF-T64 special row via width"); - if (!(gft_offset_max_for_width(128) == 4782968)) @panic("GF-T128 special row via width"); - if (!(gft_offset_max_for_width(16) == gft_offset_max(4))) @panic("width 16 -> Et 4 -> 80"); - if (!(gft_offset_max_for_width(32) == gft_offset_max(6))) @panic("width 32 -> Et 6 -> 728"); - if (!(gft_offset_max_for_width(0) == 0)) @panic("width 0 -> fail-closed offset_max 0"); - if (!(gft_offset_max_for_width(7) == 0)) @panic("an off-ladder width -> fail-closed 0"); - if (!(gft_offset_max_for_width(4294967295) == 0)) @panic("a garbage width -> fail-closed 0, no underflow"); + if (!(gft_exp_trits_for_width(8) == 3)) __t27_assert_fail("\n GF-T8 uses 3 exponent trits:\n gft_exp_trits_for_width(8) = {any}\n", .{ gft_exp_trits_for_width(8) }); + if (!(gft_exp_trits_for_width(16) == 4)) __t27_assert_fail("\n GF-T16 uses 4 exponent trits:\n gft_exp_trits_for_width(16) = {any}\n", .{ gft_exp_trits_for_width(16) }); + if (!(gft_offset_max_for_width(4) == 8)) __t27_assert_fail("\n GF-T4 special row via width:\n gft_offset_max_for_width(4) = {any}\n", .{ gft_offset_max_for_width(4) }); + if (!(gft_offset_max_for_width(8) == 26)) __t27_assert_fail("\n GF-T8 special row via width:\n gft_offset_max_for_width(8) = {any}\n", .{ gft_offset_max_for_width(8) }); + if (!(gft_offset_max_for_width(16) == 80)) __t27_assert_fail("\n GF-T16 special row via width:\n gft_offset_max_for_width(16) = {any}\n", .{ gft_offset_max_for_width(16) }); + if (!(gft_offset_max_for_width(32) == 728)) __t27_assert_fail("\n GF-T32 special row via width (Et6, golden rule):\n gft_offset_max_for_width(32) = {any}\n", .{ gft_offset_max_for_width(32) }); + if (!(gft_offset_max_for_width(64) == 19682)) __t27_assert_fail("\n GF-T64 special row via width:\n gft_offset_max_for_width(64) = {any}\n", .{ gft_offset_max_for_width(64) }); + if (!(gft_offset_max_for_width(128) == 4782968)) __t27_assert_fail("\n GF-T128 special row via width:\n gft_offset_max_for_width(128) = {any}\n", .{ gft_offset_max_for_width(128) }); + if (!(gft_offset_max_for_width(16) == gft_offset_max(4))) __t27_assert_fail("\n width 16 -> Et 4 -> 80:\n gft_offset_max_for_width(16) = {any}\n gft_offset_max(4) = {any}\n", .{ gft_offset_max_for_width(16), gft_offset_max(4) }); + if (!(gft_offset_max_for_width(32) == gft_offset_max(6))) __t27_assert_fail("\n width 32 -> Et 6 -> 728:\n gft_offset_max_for_width(32) = {any}\n gft_offset_max(6) = {any}\n", .{ gft_offset_max_for_width(32), gft_offset_max(6) }); + if (!(gft_offset_max_for_width(0) == 0)) __t27_assert_fail("\n width 0 -> fail-closed offset_max 0:\n gft_offset_max_for_width(0) = {any}\n", .{ gft_offset_max_for_width(0) }); + if (!(gft_offset_max_for_width(7) == 0)) __t27_assert_fail("\n an off-ladder width -> fail-closed 0:\n gft_offset_max_for_width(7) = {any}\n", .{ gft_offset_max_for_width(7) }); + if (!(gft_offset_max_for_width(4294967295) == 0)) __t27_assert_fail("\n a garbage width -> fail-closed 0, no underflow:\n gft_offset_max_for_width(4294967295) = {any}\n", .{ gft_offset_max_for_width(4294967295) }); } test "has_inf_gate" { - if (!(is_finite_gf_h(0x7E00, 6, 9, 1) == false)) @panic("GF16 inf rejected (has_inf)"); - if (!(is_finite_gf_h(0x4200, 6, 9, 1) == true)) @panic("GF16 finite accepted"); - if (!(is_finite_gf_h(0x70, 3, 4, 0) == true)) @panic("GF8 max-exp is normal (no inf/nan)"); - if (!(is_finite_gf_h(0x70, 3, 4, 1) == false)) @panic("with has_inf it would (wrongly) reject"); + if (!(is_finite_gf_h(0x7E00, 6, 9, 1) == false)) __t27_assert_fail("\n GF16 inf rejected (has_inf):\n is_finite_gf_h(0x7E00, 6, 9, 1) = {any}\n", .{ is_finite_gf_h(0x7E00, 6, 9, 1) }); + if (!(is_finite_gf_h(0x4200, 6, 9, 1) == true)) __t27_assert_fail("\n GF16 finite accepted:\n is_finite_gf_h(0x4200, 6, 9, 1) = {any}\n", .{ is_finite_gf_h(0x4200, 6, 9, 1) }); + if (!(is_finite_gf_h(0x70, 3, 4, 0) == true)) __t27_assert_fail("\n GF8 max-exp is normal (no inf/nan):\n is_finite_gf_h(0x70, 3, 4, 0) = {any}\n", .{ is_finite_gf_h(0x70, 3, 4, 0) }); + if (!(is_finite_gf_h(0x70, 3, 4, 1) == false)) __t27_assert_fail("\n with has_inf it would (wrongly) reject:\n is_finite_gf_h(0x70, 3, 4, 1) = {any}\n", .{ is_finite_gf_h(0x70, 3, 4, 1) }); } test "dispatch_routes_by_family" { - if (!(is_finite_dispatch(FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) == is_finite_gf_h(0x4200, 6, 9, 1))) @panic("GF16 finite via dispatch"); - if (!(is_finite_dispatch(FMT_GF_BINARY, 0x7E00, 6, 9, 1, 0) == false)) @panic("GF16 inf via dispatch -> not finite"); - if (!(is_finite_dispatch(FMT_GF_BINARY, 0x70, 3, 4, 0, 0) == true)) @panic("GF8 max-exp normal via dispatch"); - if (!(is_finite_dispatch(FMT_GFT16, 40, 0, 0, 0, 4) == is_finite_gft_n(40, 4))) @panic("GF-T16 finite via dispatch"); - if (!(is_finite_dispatch(FMT_GFT16, 80, 0, 0, 0, 4) == false)) @panic("GF-T16 reserved offset via dispatch -> not finite"); - if (!(is_finite_dispatch(FMT_GFT16, 8, 0, 0, 0, 2) == false)) @panic("GF-T4 special row 8 via dispatch"); - if (!(is_finite_dispatch(FMT_GFT16, 7, 0, 0, 0, 2) == true)) @panic("GF-T4 offset 7 finite via dispatch"); + if (!(is_finite_dispatch(FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) == is_finite_gf_h(0x4200, 6, 9, 1))) __t27_assert_fail("\n GF16 finite via dispatch:\n is_finite_dispatch(FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) = {any}\n is_finite_gf_h(0x4200, 6, 9, 1) = {any}\n", .{ is_finite_dispatch(FMT_GF_BINARY, 0x4200, 6, 9, 1, 0), is_finite_gf_h(0x4200, 6, 9, 1) }); + if (!(is_finite_dispatch(FMT_GF_BINARY, 0x7E00, 6, 9, 1, 0) == false)) __t27_assert_fail("\n GF16 inf via dispatch -> not finite:\n is_finite_dispatch(FMT_GF_BINARY, 0x7E00, 6, 9, 1, 0) = {any}\n", .{ is_finite_dispatch(FMT_GF_BINARY, 0x7E00, 6, 9, 1, 0) }); + if (!(is_finite_dispatch(FMT_GF_BINARY, 0x70, 3, 4, 0, 0) == true)) __t27_assert_fail("\n GF8 max-exp normal via dispatch:\n is_finite_dispatch(FMT_GF_BINARY, 0x70, 3, 4, 0, 0) = {any}\n", .{ is_finite_dispatch(FMT_GF_BINARY, 0x70, 3, 4, 0, 0) }); + if (!(is_finite_dispatch(FMT_GFT16, 40, 0, 0, 0, 4) == is_finite_gft_n(40, 4))) __t27_assert_fail("\n GF-T16 finite via dispatch:\n is_finite_dispatch(FMT_GFT16, 40, 0, 0, 0, 4) = {any}\n is_finite_gft_n(40, 4) = {any}\n", .{ is_finite_dispatch(FMT_GFT16, 40, 0, 0, 0, 4), is_finite_gft_n(40, 4) }); + if (!(is_finite_dispatch(FMT_GFT16, 80, 0, 0, 0, 4) == false)) __t27_assert_fail("\n GF-T16 reserved offset via dispatch -> not finite:\n is_finite_dispatch(FMT_GFT16, 80, 0, 0, 0, 4) = {any}\n", .{ is_finite_dispatch(FMT_GFT16, 80, 0, 0, 0, 4) }); + if (!(is_finite_dispatch(FMT_GFT16, 8, 0, 0, 0, 2) == false)) __t27_assert_fail("\n GF-T4 special row 8 via dispatch:\n is_finite_dispatch(FMT_GFT16, 8, 0, 0, 0, 2) = {any}\n", .{ is_finite_dispatch(FMT_GFT16, 8, 0, 0, 0, 2) }); + if (!(is_finite_dispatch(FMT_GFT16, 7, 0, 0, 0, 2) == true)) __t27_assert_fail("\n GF-T4 offset 7 finite via dispatch:\n is_finite_dispatch(FMT_GFT16, 7, 0, 0, 0, 2) = {any}\n", .{ is_finite_dispatch(FMT_GFT16, 7, 0, 0, 0, 2) }); } test "gft_offset_range" { - if (!(gft_offset_in_range(0, 4) == true)) @panic("GF-T16 offset 0 in range"); - if (!(gft_offset_in_range(80, 4) == true)) @panic("GF-T16 offset_max 80 is a valid (special) encoding"); - if (!(gft_offset_in_range(81, 4) == false)) @panic("GF-T16 offset 81 (== 3^4) is out of range"); - if (!(gft_offset_in_range(8, 2) == true)) @panic("GF-T4 offset_max 8 in range"); - if (!(gft_offset_in_range(9, 2) == false)) @panic("GF-T4 offset 9 (== 3^2) out of range"); - if (!(is_finite_gft_n(81, 4) == true)) @panic("is_finite alone WRONGLY calls out-of-range 81 finite"); - if (!(gft_offset_in_range(81, 4) == false)) @panic("...but the range gate rejects it"); + if (!(gft_offset_in_range(0, 4) == true)) __t27_assert_fail("\n GF-T16 offset 0 in range:\n gft_offset_in_range(0, 4) = {any}\n", .{ gft_offset_in_range(0, 4) }); + if (!(gft_offset_in_range(80, 4) == true)) __t27_assert_fail("\n GF-T16 offset_max 80 is a valid (special) encoding:\n gft_offset_in_range(80, 4) = {any}\n", .{ gft_offset_in_range(80, 4) }); + if (!(gft_offset_in_range(81, 4) == false)) __t27_assert_fail("\n GF-T16 offset 81 (== 3^4) is out of range:\n gft_offset_in_range(81, 4) = {any}\n", .{ gft_offset_in_range(81, 4) }); + if (!(gft_offset_in_range(8, 2) == true)) __t27_assert_fail("\n GF-T4 offset_max 8 in range:\n gft_offset_in_range(8, 2) = {any}\n", .{ gft_offset_in_range(8, 2) }); + if (!(gft_offset_in_range(9, 2) == false)) __t27_assert_fail("\n GF-T4 offset 9 (== 3^2) out of range:\n gft_offset_in_range(9, 2) = {any}\n", .{ gft_offset_in_range(9, 2) }); + if (!(is_finite_gft_n(81, 4) == true)) __t27_assert_fail("\n is_finite alone WRONGLY calls out-of-range 81 finite:\n is_finite_gft_n(81, 4) = {any}\n", .{ is_finite_gft_n(81, 4) }); + if (!(gft_offset_in_range(81, 4) == false)) __t27_assert_fail("\n ...but the range gate rejects it:\n gft_offset_in_range(81, 4) = {any}\n", .{ gft_offset_in_range(81, 4) }); } test "valid_gft_is_range_and_finite" { - if (!(is_valid_gft(0, 4) == true)) @panic("GF-T16 offset 0 is payable"); - if (!(is_valid_gft(79, 4) == true)) @panic("GF-T16 offset 79 (just below special) is payable"); - if (!(is_valid_gft(80, 4) == false)) @panic("GF-T16 special row 80 -> not payable (in range, not finite)"); - if (!(is_valid_gft(81, 4) == false)) @panic("GF-T16 offset 81 -> not payable (out of range)"); - if (!(is_valid_gft(7, 2) == true)) @panic("GF-T4 offset 7 payable"); - if (!(is_valid_gft(8, 2) == false)) @panic("GF-T4 special row 8 -> not payable"); - if (!(is_valid_gft(9, 2) == false)) @panic("GF-T4 offset 9 -> out of range, not payable"); + if (!(is_valid_gft(0, 4) == true)) __t27_assert_fail("\n GF-T16 offset 0 is payable:\n is_valid_gft(0, 4) = {any}\n", .{ is_valid_gft(0, 4) }); + if (!(is_valid_gft(79, 4) == true)) __t27_assert_fail("\n GF-T16 offset 79 (just below special) is payable:\n is_valid_gft(79, 4) = {any}\n", .{ is_valid_gft(79, 4) }); + if (!(is_valid_gft(80, 4) == false)) __t27_assert_fail("\n GF-T16 special row 80 -> not payable (in range, not finite):\n is_valid_gft(80, 4) = {any}\n", .{ is_valid_gft(80, 4) }); + if (!(is_valid_gft(81, 4) == false)) __t27_assert_fail("\n GF-T16 offset 81 -> not payable (out of range):\n is_valid_gft(81, 4) = {any}\n", .{ is_valid_gft(81, 4) }); + if (!(is_valid_gft(7, 2) == true)) __t27_assert_fail("\n GF-T4 offset 7 payable:\n is_valid_gft(7, 2) = {any}\n", .{ is_valid_gft(7, 2) }); + if (!(is_valid_gft(8, 2) == false)) __t27_assert_fail("\n GF-T4 special row 8 -> not payable:\n is_valid_gft(8, 2) = {any}\n", .{ is_valid_gft(8, 2) }); + if (!(is_valid_gft(9, 2) == false)) __t27_assert_fail("\n GF-T4 offset 9 -> out of range, not payable:\n is_valid_gft(9, 2) = {any}\n", .{ is_valid_gft(9, 2) }); } diff --git a/gen/zig/tri_compute_optimistic.zig b/gen/zig/tri_compute_optimistic.zig index fefc3ad8..a4c93b27 100644 --- a/gen/zig/tri_compute_optimistic.zig +++ b/gen/zig/tri_compute_optimistic.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const PENDING: u32 = 0; @@ -55,35 +63,35 @@ fn can_finalize(state: u32) bool { return state == FINALIZED; } test "provisional_credit" { - if (!(provisional_balance(1000, 16, 1) == 1016)) @panic("bonded result credits the reward provisionally"); - if (!(provisional_balance(1000, 16, 0) == 1000)) @panic("unbonded result is not credited"); + if (!(provisional_balance(1000, 16, 1) == 1016)) __t27_assert_fail("\n bonded result credits the reward provisionally:\n provisional_balance(1000, 16, 1) = {any}\n", .{ provisional_balance(1000, 16, 1) }); + if (!(provisional_balance(1000, 16, 0) == 1000)) __t27_assert_fail("\n unbonded result is not credited:\n provisional_balance(1000, 16, 0) = {any}\n", .{ provisional_balance(1000, 16, 0) }); } test "window_gating" { - if (!(window_open(5, 3, 10) == true)) @panic("epoch 5 within [3, 13) -> open"); - if (!(window_open(13, 3, 10) == false)) @panic("epoch 13 == settled_at+window -> closed"); - if (!(window_open(20, 3, 10) == false)) @panic("well past the window -> closed"); + if (!(window_open(5, 3, 10) == true)) __t27_assert_fail("\n epoch 5 within [3, 13) -> open:\n window_open(5, 3, 10) = {any}\n", .{ window_open(5, 3, 10) }); + if (!(window_open(13, 3, 10) == false)) __t27_assert_fail("\n epoch 13 == settled_at+window -> closed:\n window_open(13, 3, 10) = {any}\n", .{ window_open(13, 3, 10) }); + if (!(window_open(20, 3, 10) == false)) __t27_assert_fail("\n well past the window -> closed:\n window_open(20, 3, 10) = {any}\n", .{ window_open(20, 3, 10) }); } test "window_grows_with_the_rung" { - if (!(window_for_rung(4) == 64)) @panic("GF-T16 (Et4) base window 64"); - if (!(window_for_rung(6) == 96)) @panic("GF-T32 (Et6) window 96 -- longer than GF-T16"); - if (!(window_for_rung(9) == 144)) @panic("GF-T64 (Et9) window 144"); - if (!(window_for_rung(14) == 224)) @panic("GF-T128 (Et14) window 224 -- longest"); - if (!(window_for_rung(3) == 64)) @panic("sub-flagship GF-T8 (Et3) gets the base, never shrinks"); - if (!(window_for_rung(6) > window_for_rung(4))) @panic("GF-T32 window > GF-T16"); - if (!(window_for_rung(9) > window_for_rung(6))) @panic("GF-T64 window > GF-T32"); - if (!(window_open_rung(100, 0, 4) == false)) @panic("GF-T16 finalized by epoch 100 (window 64)"); - if (!(window_open_rung(100, 0, 9) == true)) @panic("GF-T64 still challengeable at epoch 100 (window 144)"); + if (!(window_for_rung(4) == 64)) __t27_assert_fail("\n GF-T16 (Et4) base window 64:\n window_for_rung(4) = {any}\n", .{ window_for_rung(4) }); + if (!(window_for_rung(6) == 96)) __t27_assert_fail("\n GF-T32 (Et6) window 96 -- longer than GF-T16:\n window_for_rung(6) = {any}\n", .{ window_for_rung(6) }); + if (!(window_for_rung(9) == 144)) __t27_assert_fail("\n GF-T64 (Et9) window 144:\n window_for_rung(9) = {any}\n", .{ window_for_rung(9) }); + if (!(window_for_rung(14) == 224)) __t27_assert_fail("\n GF-T128 (Et14) window 224 -- longest:\n window_for_rung(14) = {any}\n", .{ window_for_rung(14) }); + if (!(window_for_rung(3) == 64)) __t27_assert_fail("\n sub-flagship GF-T8 (Et3) gets the base, never shrinks:\n window_for_rung(3) = {any}\n", .{ window_for_rung(3) }); + if (!(window_for_rung(6) > window_for_rung(4))) __t27_assert_fail("\n GF-T32 window > GF-T16:\n window_for_rung(6) = {any}\n window_for_rung(4) = {any}\n", .{ window_for_rung(6), window_for_rung(4) }); + if (!(window_for_rung(9) > window_for_rung(6))) __t27_assert_fail("\n GF-T64 window > GF-T32:\n window_for_rung(9) = {any}\n window_for_rung(6) = {any}\n", .{ window_for_rung(9), window_for_rung(6) }); + if (!(window_open_rung(100, 0, 4) == false)) __t27_assert_fail("\n GF-T16 finalized by epoch 100 (window 64):\n window_open_rung(100, 0, 4) = {any}\n", .{ window_open_rung(100, 0, 4) }); + if (!(window_open_rung(100, 0, 9) == true)) __t27_assert_fail("\n GF-T64 still challengeable at epoch 100 (window 144):\n window_open_rung(100, 0, 9) = {any}\n", .{ window_open_rung(100, 0, 9) }); } test "lifecycle_states" { - if (!(settle_state(1, 0) == PENDING)) @panic("in window, no challenge -> pending"); - if (!(settle_state(0, 0) == FINALIZED)) @panic("window closed, no challenge -> finalized"); - if (!(settle_state(1, 1) == REVERSED)) @panic("slashed in window -> reversed"); - if (!(settle_state(0, 1) == REVERSED)) @panic("slashed after window -> still reversed"); + if (!(settle_state(1, 0) == PENDING)) __t27_assert_fail("\n in window, no challenge -> pending:\n settle_state(1, 0) = {any}\n PENDING = {any}\n", .{ settle_state(1, 0), PENDING }); + if (!(settle_state(0, 0) == FINALIZED)) __t27_assert_fail("\n window closed, no challenge -> finalized:\n settle_state(0, 0) = {any}\n FINALIZED = {any}\n", .{ settle_state(0, 0), FINALIZED }); + if (!(settle_state(1, 1) == REVERSED)) __t27_assert_fail("\n slashed in window -> reversed:\n settle_state(1, 1) = {any}\n REVERSED = {any}\n", .{ settle_state(1, 1), REVERSED }); + if (!(settle_state(0, 1) == REVERSED)) __t27_assert_fail("\n slashed after window -> still reversed:\n settle_state(0, 1) = {any}\n REVERSED = {any}\n", .{ settle_state(0, 1), REVERSED }); } test "balance_resolution" { - if (!(balance_after_settle(1016, 16, REVERSED) == 1000)) @panic("reversal claws back the reward"); - if (!(balance_after_settle(1016, 16, FINALIZED) == 1016)) @panic("finalize keeps the reward"); - if (!(balance_after_settle(1016, 16, PENDING) == 1016)) @panic("pending keeps the reward (not yet final)"); - if (!(can_finalize(FINALIZED) == true)) @panic("finalized can release the bond"); - if (!(can_finalize(PENDING) == false)) @panic("pending cannot finalize yet"); + if (!(balance_after_settle(1016, 16, REVERSED) == 1000)) __t27_assert_fail("\n reversal claws back the reward:\n balance_after_settle(1016, 16, REVERSED) = {any}\n", .{ balance_after_settle(1016, 16, REVERSED) }); + if (!(balance_after_settle(1016, 16, FINALIZED) == 1016)) __t27_assert_fail("\n finalize keeps the reward:\n balance_after_settle(1016, 16, FINALIZED) = {any}\n", .{ balance_after_settle(1016, 16, FINALIZED) }); + if (!(balance_after_settle(1016, 16, PENDING) == 1016)) __t27_assert_fail("\n pending keeps the reward (not yet final):\n balance_after_settle(1016, 16, PENDING) = {any}\n", .{ balance_after_settle(1016, 16, PENDING) }); + if (!(can_finalize(FINALIZED) == true)) __t27_assert_fail("\n finalized can release the bond:\n can_finalize(FINALIZED) = {any}\n", .{ can_finalize(FINALIZED) }); + if (!(can_finalize(PENDING) == false)) __t27_assert_fail("\n pending cannot finalize yet:\n can_finalize(PENDING) = {any}\n", .{ can_finalize(PENDING) }); } diff --git a/gen/zig/tri_compute_payout.zig b/gen/zig/tri_compute_payout.zig index 97830840..34caab4b 100644 --- a/gen/zig/tri_compute_payout.zig +++ b/gen/zig/tri_compute_payout.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module fn weighted(raw_work: u32, rep: u32) u32 { @@ -35,15 +43,15 @@ test "reputation_weighted_split" { const w1 = weighted(16, 500); const w2 = weighted(16, 250); const tw = total_weighted3(w0, w1, w2); - if (!(tw == 28000)) @panic("total weighted = 16000+8000+4000"); + if (!(tw == 28000)) __t27_assert_fail("\n total weighted = 16000+8000+4000:\n tw = {any}\n", .{ tw }); const s0 = payout(1000, w0, tw); const s1 = payout(1000, w1, tw); const s2 = payout(1000, w2, tw); - if (!(s0 == 571)) @panic("rep 1000 -> 571"); - if (!(s1 == 285)) @panic("rep 500 -> 285"); - if (!(s2 == 142)) @panic("rep 250 -> 142"); - if (!(s0 > s1)) @panic("higher reputation earns more for equal work"); - if (!(s1 > s2)) @panic("a slashed (low-rep) node earns less"); + if (!(s0 == 571)) __t27_assert_fail("\n rep 1000 -> 571:\n s0 = {any}\n", .{ s0 }); + if (!(s1 == 285)) __t27_assert_fail("\n rep 500 -> 285:\n s1 = {any}\n", .{ s1 }); + if (!(s2 == 142)) __t27_assert_fail("\n rep 250 -> 142:\n s2 = {any}\n", .{ s2 }); + if (!(s0 > s1)) __t27_assert_fail("\n higher reputation earns more for equal work:\n s0 = {any}\n s1 = {any}\n", .{ s0, s1 }); + if (!(s1 > s2)) __t27_assert_fail("\n a slashed (low-rep) node earns less:\n s1 = {any}\n s2 = {any}\n", .{ s1, s2 }); } test "weighted_no_over_issuance" { const w0 = weighted(16, 1000); @@ -51,28 +59,28 @@ test "weighted_no_over_issuance" { const w2 = weighted(16, 250); const tw = total_weighted3(w0, w1, w2); const sum = (payout(1000, w0, tw) + payout(1000, w1, tw)) + payout(1000, w2, tw); - if (!(sum == 998)) @panic("sum 998 <= pool 1000 (floor loses the dust)"); + if (!(sum == 998)) __t27_assert_fail("\n sum 998 <= pool 1000 (floor loses the dust):\n sum = {any}\n", .{ sum }); } test "zero_rep_and_empty_round" { - if (!(weighted(48, 0) == 0)) @panic("no reputation => zero weight"); - if (!(payout(1000, 0, 28000) == 0)) @panic("zero weight => zero payout"); - if (!(payout(1000, 16000, 0) == 0)) @panic("empty round pays nobody, no divide-by-zero"); + if (!(weighted(48, 0) == 0)) __t27_assert_fail("\n no reputation => zero weight:\n weighted(48, 0) = {any}\n", .{ weighted(48, 0) }); + if (!(payout(1000, 0, 28000) == 0)) __t27_assert_fail("\n zero weight => zero payout:\n payout(1000, 0, 28000) = {any}\n", .{ payout(1000, 0, 28000) }); + if (!(payout(1000, 16000, 0) == 0)) __t27_assert_fail("\n empty round pays nobody, no divide-by-zero:\n payout(1000, 16000, 0) = {any}\n", .{ payout(1000, 16000, 0) }); } test "large_payout_no_overflow" { - if (!(payout(1000000, 16000, 24000) == 666666)) @panic("large pool*weighted floor-divides exactly (no u32 overflow)"); - if (!(payout(1000000, 8000, 24000) == 333333)) @panic("second node's weighted share is exact too"); + if (!(payout(1000000, 16000, 24000) == 666666)) __t27_assert_fail("\n large pool*weighted floor-divides exactly (no u32 overflow):\n payout(1000000, 16000, 24000) = {any}\n", .{ payout(1000000, 16000, 24000) }); + if (!(payout(1000000, 8000, 24000) == 333333)) __t27_assert_fail("\n second node's weighted share is exact too:\n payout(1000000, 8000, 24000) = {any}\n", .{ payout(1000000, 8000, 24000) }); const s0 = payout(1000000, 16000, 24000); const s1 = payout(1000000, 8000, 24000); - if (!((s0 + s1) == 999999)) @panic("sum 999999 <= pool 1e6 at scale; no over-issuance under weighting"); + if (!((s0 + s1) == 999999)) __t27_assert_fail("\n sum 999999 <= pool 1e6 at scale; no over-issuance under weighting:\n s0 + s1 = {any}\n", .{ s0 + s1 }); } test "weighted_saturates" { - if (!(weighted(16, 1000) == 16000)) @panic("normal weight is exact"); - if (!(weighted(100000, 1000) == 100000000)) @panic("1e5 * 1e3 = 1e8 fits, exact"); - if (!(weighted(5000000, 1000) == 4294967295)) @panic("overflowing weight saturates to u32 max, no wrap"); - if (!(weighted(4294967, 1000) == 4294967000)) @panic("just under the ceiling is still exact"); + if (!(weighted(16, 1000) == 16000)) __t27_assert_fail("\n normal weight is exact:\n weighted(16, 1000) = {any}\n", .{ weighted(16, 1000) }); + if (!(weighted(100000, 1000) == 100000000)) __t27_assert_fail("\n 1e5 * 1e3 = 1e8 fits, exact:\n weighted(100000, 1000) = {any}\n", .{ weighted(100000, 1000) }); + if (!(weighted(5000000, 1000) == 4294967295)) __t27_assert_fail("\n overflowing weight saturates to u32 max, no wrap:\n weighted(5000000, 1000) = {any}\n", .{ weighted(5000000, 1000) }); + if (!(weighted(4294967, 1000) == 4294967000)) __t27_assert_fail("\n just under the ceiling is still exact:\n weighted(4294967, 1000) = {any}\n", .{ weighted(4294967, 1000) }); } test "total_weighted3_saturates" { - if (!(total_weighted3(16000, 8000, 4000) == 28000)) @panic("normal sum is exact"); - if (!(total_weighted3(4294967295, 4294967295, 4294967295) == 4294967295)) @panic("three max weights saturate, no wrap"); - if (!(total_weighted3(4000000000, 400000000, 0) == 4294967295)) @panic("sum 4.4e9 > 2^32 saturates"); + if (!(total_weighted3(16000, 8000, 4000) == 28000)) __t27_assert_fail("\n normal sum is exact:\n total_weighted3(16000, 8000, 4000) = {any}\n", .{ total_weighted3(16000, 8000, 4000) }); + if (!(total_weighted3(4294967295, 4294967295, 4294967295) == 4294967295)) __t27_assert_fail("\n three max weights saturate, no wrap:\n total_weighted3(4294967295, 4294967295, 4294967295) = {any}\n", .{ total_weighted3(4294967295, 4294967295, 4294967295) }); + if (!(total_weighted3(4000000000, 400000000, 0) == 4294967295)) __t27_assert_fail("\n sum 4.4e9 > 2^32 saturates:\n total_weighted3(4000000000, 400000000, 0) = {any}\n", .{ total_weighted3(4000000000, 400000000, 0) }); } diff --git a/gen/zig/tri_compute_pool.zig b/gen/zig/tri_compute_pool.zig index e78fc14d..b78940ff 100644 --- a/gen/zig/tri_compute_pool.zig +++ b/gen/zig/tri_compute_pool.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module fn total_work3(w0: u32, w1: u32, w2: u32) u32 { @@ -54,77 +62,77 @@ fn balance_after_pool_settle(prev_balance: u32, pool: u32, reward: u32) u32 { } } test "proportional_and_zero_work" { - if (!(pool_share(1000, 16, 96) == 166)) @panic("16/96 of 1000 (floor)"); - if (!(pool_share(1000, 32, 96) == 333)) @panic("32/96 of 1000 (floor)"); - if (!(pool_share(1000, 48, 96) == 500)) @panic("48/96 of 1000 (floor)"); - if (!(pool_share(1000, 0, 96) == 0)) @panic("a node with no work earns nothing"); + if (!(pool_share(1000, 16, 96) == 166)) __t27_assert_fail("\n 16/96 of 1000 (floor):\n pool_share(1000, 16, 96) = {any}\n", .{ pool_share(1000, 16, 96) }); + if (!(pool_share(1000, 32, 96) == 333)) __t27_assert_fail("\n 32/96 of 1000 (floor):\n pool_share(1000, 32, 96) = {any}\n", .{ pool_share(1000, 32, 96) }); + if (!(pool_share(1000, 48, 96) == 500)) __t27_assert_fail("\n 48/96 of 1000 (floor):\n pool_share(1000, 48, 96) = {any}\n", .{ pool_share(1000, 48, 96) }); + if (!(pool_share(1000, 0, 96) == 0)) __t27_assert_fail("\n a node with no work earns nothing:\n pool_share(1000, 0, 96) = {any}\n", .{ pool_share(1000, 0, 96) }); } test "pool_split_is_already_rung_proportional" { - if (!(pool_share(1000, 64, 80) == 800)) @panic("GF-T64 node earns 64/80 of the pool"); - if (!(pool_share(1000, 16, 80) == 200)) @panic("GF-T16 node earns 16/80"); - if (!(pool_share(1000, 64, 80) == (4 * pool_share(1000, 16, 80)))) @panic("GF-T64 : GF-T16 = 4 : 1 = the width/rung ratio"); - if (!(pool_share(1000, 32, 40) == 800)) @panic("GF-T32 node earns 32/40"); - if (!(pool_share(1000, 8, 40) == 200)) @panic("GF-T8 node earns 8/40"); + if (!(pool_share(1000, 64, 80) == 800)) __t27_assert_fail("\n GF-T64 node earns 64/80 of the pool:\n pool_share(1000, 64, 80) = {any}\n", .{ pool_share(1000, 64, 80) }); + if (!(pool_share(1000, 16, 80) == 200)) __t27_assert_fail("\n GF-T16 node earns 16/80:\n pool_share(1000, 16, 80) = {any}\n", .{ pool_share(1000, 16, 80) }); + if (!(pool_share(1000, 64, 80) == (4 * pool_share(1000, 16, 80)))) __t27_assert_fail("\n GF-T64 : GF-T16 = 4 : 1 = the width/rung ratio:\n pool_share(1000, 64, 80) = {any}\n 4 * pool_share(1000, 16, 80) = {any}\n", .{ pool_share(1000, 64, 80), 4 * pool_share(1000, 16, 80) }); + if (!(pool_share(1000, 32, 40) == 800)) __t27_assert_fail("\n GF-T32 node earns 32/40:\n pool_share(1000, 32, 40) = {any}\n", .{ pool_share(1000, 32, 40) }); + if (!(pool_share(1000, 8, 40) == 200)) __t27_assert_fail("\n GF-T8 node earns 8/40:\n pool_share(1000, 8, 40) = {any}\n", .{ pool_share(1000, 8, 40) }); } test "no_over_issuance" { const s0 = pool_share(1000, 16, 96); const s1 = pool_share(1000, 32, 96); const s2 = pool_share(1000, 48, 96); - if (!(((s0 + s1) + s2) == 999)) @panic("sum <= pool; floor under-issues by the remainder"); + if (!(((s0 + s1) + s2) == 999)) __t27_assert_fail("\n sum <= pool; floor under-issues by the remainder:\n (s0 + s1) + s2 = {any}\n", .{ (s0 + s1) + s2 }); } test "empty_round_pays_zero" { - if (!(pool_share(1000, 0, 0) == 0)) @panic("empty round is safe and pays nothing"); - if (!(total_work3(0, 0, 0) == 0)) @panic("no work summed"); + if (!(pool_share(1000, 0, 0) == 0)) __t27_assert_fail("\n empty round is safe and pays nothing:\n pool_share(1000, 0, 0) = {any}\n", .{ pool_share(1000, 0, 0) }); + if (!(total_work3(0, 0, 0) == 0)) __t27_assert_fail("\n no work summed:\n total_work3(0, 0, 0) = {any}\n", .{ total_work3(0, 0, 0) }); } test "total_work3_saturates" { - if (!(total_work3(16, 32, 48) == 96)) @panic("normal sum is exact"); - if (!(total_work3(4000000000, 400000000, 0) == 4294967295)) @panic("sum 4.4e9 > 2^32 saturates, no wrap"); - if (!(total_work3(4294967295, 4294967295, 4294967295) == 4294967295)) @panic("three max totals saturate"); - if (!(pool_share(1000, 3000000000, total_work3(3000000000, 3000000000, 3000000000)) <= 1000)) @panic("saturated total keeps the share within the pool"); + if (!(total_work3(16, 32, 48) == 96)) __t27_assert_fail("\n normal sum is exact:\n total_work3(16, 32, 48) = {any}\n", .{ total_work3(16, 32, 48) }); + if (!(total_work3(4000000000, 400000000, 0) == 4294967295)) __t27_assert_fail("\n sum 4.4e9 > 2^32 saturates, no wrap:\n total_work3(4000000000, 400000000, 0) = {any}\n", .{ total_work3(4000000000, 400000000, 0) }); + if (!(total_work3(4294967295, 4294967295, 4294967295) == 4294967295)) __t27_assert_fail("\n three max totals saturate:\n total_work3(4294967295, 4294967295, 4294967295) = {any}\n", .{ total_work3(4294967295, 4294967295, 4294967295) }); + if (!(pool_share(1000, 3000000000, total_work3(3000000000, 3000000000, 3000000000)) <= 1000)) __t27_assert_fail("\n saturated total keeps the share within the pool:\n pool_share(1000, 3000000000, total_work3(3000000000, 3000000000, 3000000000)) = {any}\n", .{ pool_share(1000, 3000000000, total_work3(3000000000, 3000000000, 3000000000)) }); } test "more_work_earns_more" { - if (!(pool_share(1000, 48, 96) > pool_share(1000, 16, 96))) @panic("more work, bigger share"); + if (!(pool_share(1000, 48, 96) > pool_share(1000, 16, 96))) __t27_assert_fail("\n more work, bigger share:\n pool_share(1000, 48, 96) = {any}\n pool_share(1000, 16, 96) = {any}\n", .{ pool_share(1000, 48, 96), pool_share(1000, 16, 96) }); } test "large_pool_no_overflow" { - if (!(pool_share(1000000, 16000, 24000) == 666666)) @panic("large pool*work floor-divides exactly (no u32 overflow)"); - if (!(pool_share(1000000, 8000, 24000) == 333333)) @panic("second node's share is exact too"); + if (!(pool_share(1000000, 16000, 24000) == 666666)) __t27_assert_fail("\n large pool*work floor-divides exactly (no u32 overflow):\n pool_share(1000000, 16000, 24000) = {any}\n", .{ pool_share(1000000, 16000, 24000) }); + if (!(pool_share(1000000, 8000, 24000) == 333333)) __t27_assert_fail("\n second node's share is exact too:\n pool_share(1000000, 8000, 24000) = {any}\n", .{ pool_share(1000000, 8000, 24000) }); const s0 = pool_share(1000000, 16000, 24000); const s1 = pool_share(1000000, 8000, 24000); - if (!((s0 + s1) == 999999)) @panic("sum 999999 <= pool 1e6 at scale; floor loses one dust unit"); + if (!((s0 + s1) == 999999)) __t27_assert_fail("\n sum 999999 <= pool 1e6 at scale; floor loses one dust unit:\n s0 + s1 = {any}\n", .{ s0 + s1 }); } test "deposit_funds_the_pool" { - if (!(pool_after_deposit(0, 1000) == 1000)) @panic("first deposit funds an empty pool"); - if (!(pool_after_deposit(1000, 500) == 1500)) @panic("deposits accumulate"); - if (!(pool_after_deposit(0xFFFFFFF0, 32) == 0xFFFFFFFF)) @panic("deposit saturates, no wrap"); + if (!(pool_after_deposit(0, 1000) == 1000)) __t27_assert_fail("\n first deposit funds an empty pool:\n pool_after_deposit(0, 1000) = {any}\n", .{ pool_after_deposit(0, 1000) }); + if (!(pool_after_deposit(1000, 500) == 1500)) __t27_assert_fail("\n deposits accumulate:\n pool_after_deposit(1000, 500) = {any}\n", .{ pool_after_deposit(1000, 500) }); + if (!(pool_after_deposit(0xFFFFFFF0, 32) == 0xFFFFFFFF)) __t27_assert_fail("\n deposit saturates, no wrap:\n pool_after_deposit(0xFFFFFFF0, 32) = {any}\n", .{ pool_after_deposit(0xFFFFFFF0, 32) }); } test "payout_never_exceeds_the_pool" { - if (!(payout_capped(1000, 300) == 300)) @panic("a payout within the pool is paid in full"); - if (!(pool_after_payout(1000, 300) == 700)) @panic("the pool is drawn down by the payout"); - if (!(payout_capped(100, 300) == 100)) @panic("an over-draw is capped at the pool balance"); - if (!(pool_after_payout(100, 300) == 0)) @panic("an over-draw drains the pool to zero, never negative"); + if (!(payout_capped(1000, 300) == 300)) __t27_assert_fail("\n a payout within the pool is paid in full:\n payout_capped(1000, 300) = {any}\n", .{ payout_capped(1000, 300) }); + if (!(pool_after_payout(1000, 300) == 700)) __t27_assert_fail("\n the pool is drawn down by the payout:\n pool_after_payout(1000, 300) = {any}\n", .{ pool_after_payout(1000, 300) }); + if (!(payout_capped(100, 300) == 100)) __t27_assert_fail("\n an over-draw is capped at the pool balance:\n payout_capped(100, 300) = {any}\n", .{ payout_capped(100, 300) }); + if (!(pool_after_payout(100, 300) == 0)) __t27_assert_fail("\n an over-draw drains the pool to zero, never negative:\n pool_after_payout(100, 300) = {any}\n", .{ pool_after_payout(100, 300) }); } test "payouts_never_exceed_deposits" { const p0 = pool_after_deposit(0, 1000); const p1 = pool_after_payout(p0, pool_share(1000, 16, 96)); const p2 = pool_after_payout(p1, pool_share(1000, 32, 96)); const p3 = pool_after_payout(p2, pool_share(1000, 48, 96)); - if (!(p1 == 834)) @panic("after 166 -> 834 remains"); - if (!(p2 == 501)) @panic("after 333 -> 501 remains"); - if (!(p3 == 1)) @panic("after 500 -> 1 remains (the floor dust stays funded)"); - if (!(p3 == (1000 - ((166 + 333) + 500)))) @panic("pool end == deposit minus total payouts, exactly conserved"); + if (!(p1 == 834)) __t27_assert_fail("\n after 166 -> 834 remains:\n p1 = {any}\n", .{ p1 }); + if (!(p2 == 501)) __t27_assert_fail("\n after 333 -> 501 remains:\n p2 = {any}\n", .{ p2 }); + if (!(p3 == 1)) __t27_assert_fail("\n after 500 -> 1 remains (the floor dust stays funded):\n p3 = {any}\n", .{ p3 }); + if (!(p3 == (1000 - ((166 + 333) + 500)))) __t27_assert_fail("\n pool end == deposit minus total payouts, exactly conserved:\n p3 = {any}\n 1000 - ((166 + 333) + 500) = {any}\n", .{ p3, 1000 - ((166 + 333) + 500) }); } test "pool_settle_conserves_total" { - if (!(balance_after_pool_settle(500, 1000, 300) == 800)) @panic("executor credited the reward"); - if (!(pool_after_payout(1000, 300) == 700)) @panic("pool drawn down by the same reward"); - if (!((balance_after_pool_settle(500, 1000, 300) + pool_after_payout(1000, 300)) == (500 + 1000))) @panic("balance + pool conserved across settle"); + if (!(balance_after_pool_settle(500, 1000, 300) == 800)) __t27_assert_fail("\n executor credited the reward:\n balance_after_pool_settle(500, 1000, 300) = {any}\n", .{ balance_after_pool_settle(500, 1000, 300) }); + if (!(pool_after_payout(1000, 300) == 700)) __t27_assert_fail("\n pool drawn down by the same reward:\n pool_after_payout(1000, 300) = {any}\n", .{ pool_after_payout(1000, 300) }); + if (!((balance_after_pool_settle(500, 1000, 300) + pool_after_payout(1000, 300)) == (500 + 1000))) __t27_assert_fail("\n balance + pool conserved across settle:\n balance_after_pool_settle(500, 1000, 300) + pool_after_payout(1000, 300) = {any}\n 500 + 1000 = {any}\n", .{ balance_after_pool_settle(500, 1000, 300) + pool_after_payout(1000, 300), 500 + 1000 }); } test "pool_settle_caps_underfunded" { - if (!(balance_after_pool_settle(500, 100, 300) == 600)) @panic("credit capped at the funded 100"); - if (!(pool_after_payout(100, 300) == 0)) @panic("underfunded pool drains to zero, not negative"); - if (!((balance_after_pool_settle(500, 100, 300) + pool_after_payout(100, 300)) == (500 + 100))) @panic("capped settle still conserves balance + pool"); + if (!(balance_after_pool_settle(500, 100, 300) == 600)) __t27_assert_fail("\n credit capped at the funded 100:\n balance_after_pool_settle(500, 100, 300) = {any}\n", .{ balance_after_pool_settle(500, 100, 300) }); + if (!(pool_after_payout(100, 300) == 0)) __t27_assert_fail("\n underfunded pool drains to zero, not negative:\n pool_after_payout(100, 300) = {any}\n", .{ pool_after_payout(100, 300) }); + if (!((balance_after_pool_settle(500, 100, 300) + pool_after_payout(100, 300)) == (500 + 100))) __t27_assert_fail("\n capped settle still conserves balance + pool:\n balance_after_pool_settle(500, 100, 300) + pool_after_payout(100, 300) = {any}\n 500 + 100 = {any}\n", .{ balance_after_pool_settle(500, 100, 300) + pool_after_payout(100, 300), 500 + 100 }); } test "pool_settle_credit_saturates" { - if (!(balance_after_pool_settle(500, 1000, 300) == 800)) @panic("normal credit exact (regression)"); - if (!(balance_after_pool_settle(0xFFFFFFF0, 1000, 300) == 0xFFFFFFFF)) @panic("credit that would overflow saturates to u32 max, not a wrap to 284"); - if (!(balance_after_pool_settle(0xFFFFFFFF, 1000, 300) == 0xFFFFFFFF)) @panic("already-max balance stays at max, never wraps to a small value"); + if (!(balance_after_pool_settle(500, 1000, 300) == 800)) __t27_assert_fail("\n normal credit exact (regression):\n balance_after_pool_settle(500, 1000, 300) = {any}\n", .{ balance_after_pool_settle(500, 1000, 300) }); + if (!(balance_after_pool_settle(0xFFFFFFF0, 1000, 300) == 0xFFFFFFFF)) __t27_assert_fail("\n credit that would overflow saturates to u32 max, not a wrap to 284:\n balance_after_pool_settle(0xFFFFFFF0, 1000, 300) = {any}\n", .{ balance_after_pool_settle(0xFFFFFFF0, 1000, 300) }); + if (!(balance_after_pool_settle(0xFFFFFFFF, 1000, 300) == 0xFFFFFFFF)) __t27_assert_fail("\n already-max balance stays at max, never wraps to a small value:\n balance_after_pool_settle(0xFFFFFFFF, 1000, 300) = {any}\n", .{ balance_after_pool_settle(0xFFFFFFFF, 1000, 300) }); } diff --git a/gen/zig/tri_compute_receipt.zig b/gen/zig/tri_compute_receipt.zig index 0e021240..36b1d15a 100644 --- a/gen/zig/tri_compute_receipt.zig +++ b/gen/zig/tri_compute_receipt.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const RECEIPT_GENESIS: u32 = 0x54524352; @@ -321,17 +329,17 @@ fn verify_chain3_full(d0: u32, d1: u32, d2: u32, claimed: u32) bool { } test "leaf_verifies" { const leaf = receipt_leaf(0xE0E0, 0x11, 0xABCD, 2, 1); - if (!(verify_leaf(0xE0E0, 0x11, 0xABCD, 2, 1, leaf) == true)) @panic("honest leaf verifies"); + if (!(verify_leaf(0xE0E0, 0x11, 0xABCD, 2, 1, leaf) == true)) __t27_assert_fail("\n honest leaf verifies:\n verify_leaf(0xE0E0, 0x11, 0xABCD, 2, 1, leaf) = {any}\n", .{ verify_leaf(0xE0E0, 0x11, 0xABCD, 2, 1, leaf) }); } test "output_tamper_evident" { const honest = receipt_leaf(0xE0E0, 0x11, 0xABCD, 2, 1); const forged = receipt_leaf(0xE0E0, 0x11, 0xABCD, 999, 1); - if (!(honest != forged)) @panic("rewriting the output changes the receipt leaf"); + if (!(honest != forged)) __t27_assert_fail("\n rewriting the output changes the receipt leaf:\n honest = {any}\n forged = {any}\n", .{ honest, forged }); } test "executor_bound" { const a = receipt_leaf(0xE0E0, 0x11, 0xABCD, 2, 1); const b = receipt_leaf(0xBEEF, 0x11, 0xABCD, 2, 1); - if (!(a != b)) @panic("different executor => different receipt"); + if (!(a != b)) __t27_assert_fail("\n different executor => different receipt:\n a = {any}\n b = {any}\n", .{ a, b }); } test "chain_deterministic" { const l0 = receipt_leaf(0xE0E0, 0x11, 0x1111, 5, 1); @@ -340,16 +348,16 @@ test "chain_deterministic" { const h0 = receipt_step(RECEIPT_GENESIS, l0); const h1 = receipt_step(h0, l1); const h2 = receipt_step(h1, l2); - if (!(verify_chain3(l0, l1, l2, h2) == true)) @panic("honest chain verifies"); + if (!(verify_chain3(l0, l1, l2, h2) == true)) __t27_assert_fail("\n honest chain verifies:\n verify_chain3(l0, l1, l2, h2) = {any}\n", .{ verify_chain3(l0, l1, l2, h2) }); } test "chain_order_sensitive" { const la = receipt_leaf(0xE0E0, 0x11, 0x1111, 5, 1); const lb = receipt_leaf(0xE0E0, 0x12, 0x2222, 7, 2); - const @"f0" = receipt_step(RECEIPT_GENESIS, la); - const forward = receipt_step(@"f0", lb); + const f0 = receipt_step(RECEIPT_GENESIS, la); + const forward = receipt_step(f0, lb); const r0 = receipt_step(RECEIPT_GENESIS, lb); const swapped = receipt_step(r0, la); - if (!(forward != swapped)) @panic("reordering receipts changes the head"); + if (!(forward != swapped)) __t27_assert_fail("\n reordering receipts changes the head:\n forward = {any}\n swapped = {any}\n", .{ forward, swapped }); } test "chain_rejects_wrong_head" { const l0 = receipt_leaf(0xE0E0, 0x11, 0x1111, 5, 1); @@ -358,38 +366,38 @@ test "chain_rejects_wrong_head" { const h0 = receipt_step(RECEIPT_GENESIS, l0); const h1 = receipt_step(h0, l1); const h2 = receipt_step(h1, l2); - if (!(verify_chain3(l0, l1, l2, h2 ^ 1) == false)) @panic("wrong head rejected"); + if (!(verify_chain3(l0, l1, l2, h2 ^ 1) == false)) __t27_assert_fail("\n wrong head rejected:\n verify_chain3(l0, l1, l2, h2 ^ 1) = {any}\n", .{ verify_chain3(l0, l1, l2, h2 ^ 1) }); } test "leaf64_independent_lanes" { const lo = receipt_leaf(0xE0E0, 0x11, 0xABCD, 2, 1); const hi = receipt_leaf_hi(0xE0E0, 0x11, 0xABCD, 2, 1); - if (!(lo != hi)) @panic("hi lane must decorrelate from lo (real 64-bit commit)"); + if (!(lo != hi)) __t27_assert_fail("\n hi lane must decorrelate from lo (real 64-bit commit):\n lo = {any}\n hi = {any}\n", .{ lo, hi }); } test "leaf64_verifies_and_tamper" { const lo = receipt_leaf(0xE0E0, 0x11, 0xABCD, 2, 1); const hi = receipt_leaf_hi(0xE0E0, 0x11, 0xABCD, 2, 1); - if (!(verify_leaf64(0xE0E0, 0x11, 0xABCD, 2, 1, lo, hi) == true)) @panic("honest 64-bit commit verifies"); - if (!(verify_leaf64(0xE0E0, 0x11, 0xABCD, 999, 1, lo, hi) == false)) @panic("tampered output fails 64-bit verify"); + if (!(verify_leaf64(0xE0E0, 0x11, 0xABCD, 2, 1, lo, hi) == true)) __t27_assert_fail("\n honest 64-bit commit verifies:\n verify_leaf64(0xE0E0, 0x11, 0xABCD, 2, 1, lo, hi) = {any}\n", .{ verify_leaf64(0xE0E0, 0x11, 0xABCD, 2, 1, lo, hi) }); + if (!(verify_leaf64(0xE0E0, 0x11, 0xABCD, 999, 1, lo, hi) == false)) __t27_assert_fail("\n tampered output fails 64-bit verify:\n verify_leaf64(0xE0E0, 0x11, 0xABCD, 999, 1, lo, hi) = {any}\n", .{ verify_leaf64(0xE0E0, 0x11, 0xABCD, 999, 1, lo, hi) }); } test "device_binding" { const unbound = receipt_leaf_bound(0, 0xE0E0, 0x11, 0xABCD, 2, 1); const chip_a = receipt_leaf_bound(0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 2, 1); const chip_b = receipt_leaf_bound(0xC0FFEE02, 0xE0E0, 0x11, 0xABCD, 2, 1); - if (!(chip_a != chip_b)) @panic("different chip => different receipt"); - if (!(chip_a != unbound)) @panic("chip-bound differs from unbound (script) receipt"); + if (!(chip_a != chip_b)) __t27_assert_fail("\n different chip => different receipt:\n chip_a = {any}\n chip_b = {any}\n", .{ chip_a, chip_b }); + if (!(chip_a != unbound)) __t27_assert_fail("\n chip-bound differs from unbound (script) receipt:\n chip_a = {any}\n unbound = {any}\n", .{ chip_a, unbound }); } test "sign_digest_binds_all" { const d = sign_digest(0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 2, 1, 0x1234); - if (!(sign_digest(0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 999, 1, 0x1234) != d)) @panic("output change flips digest"); - if (!(sign_digest(0xC0FFEE02, 0xE0E0, 0x11, 0xABCD, 2, 1, 0x1234) != d)) @panic("device change flips digest"); - if (!(sign_digest(0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 2, 1, 0x9999) != d)) @panic("chain-head change flips digest"); + if (!(sign_digest(0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 999, 1, 0x1234) != d)) __t27_assert_fail("\n output change flips digest:\n sign_digest(0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 999, 1, 0x1234) = {any}\n d = {any}\n", .{ sign_digest(0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 999, 1, 0x1234), d }); + if (!(sign_digest(0xC0FFEE02, 0xE0E0, 0x11, 0xABCD, 2, 1, 0x1234) != d)) __t27_assert_fail("\n device change flips digest:\n sign_digest(0xC0FFEE02, 0xE0E0, 0x11, 0xABCD, 2, 1, 0x1234) = {any}\n d = {any}\n", .{ sign_digest(0xC0FFEE02, 0xE0E0, 0x11, 0xABCD, 2, 1, 0x1234), d }); + if (!(sign_digest(0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 2, 1, 0x9999) != d)) __t27_assert_fail("\n chain-head change flips digest:\n sign_digest(0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 2, 1, 0x9999) = {any}\n d = {any}\n", .{ sign_digest(0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 2, 1, 0x9999), d }); } test "gf_op_bound" { const r_mul = receipt_leaf_gf(GF16, GF_MUL, 0x3C00, 0x4000, 0x4200, 0xC0FFEE01, 0xE0E0, 1); const r_add = receipt_leaf_gf(GF16, GF_ADD, 0x3C00, 0x4000, 0x4200, 0xC0FFEE01, 0xE0E0, 1); - if (!(r_mul != r_add)) @panic("GoldenFloat op is bound (GF16 MUL != GF16 ADD)"); + if (!(r_mul != r_add)) __t27_assert_fail("\n GoldenFloat op is bound (GF16 MUL != GF16 ADD):\n r_mul = {any}\n r_add = {any}\n", .{ r_mul, r_add }); const r_mul2 = receipt_leaf_gf(GF16, GF_MUL, 0x3C00, 0x4000, 0x4300, 0xC0FFEE01, 0xE0E0, 1); - if (!(r_mul != r_mul2)) @panic("the GF16 result is bound into the receipt"); + if (!(r_mul != r_mul2)) __t27_assert_fail("\n the GF16 result is bound into the receipt:\n r_mul = {any}\n r_mul2 = {any}\n", .{ r_mul, r_mul2 }); } test "full_chain_deterministic_and_tamper_evident" { const d0 = sign_digest(0xC0FFEE01, 0xE0E0, 0x11, 0x1111, 0x4200, 1, RECEIPT_GENESIS); @@ -398,81 +406,81 @@ test "full_chain_deterministic_and_tamper_evident" { const h1 = chain_step_full(h0, d1); const d2 = sign_digest(0xC0FFEE01, 0xE0E0, 0x13, 0x3333, 0x4400, 3, h1); const h2 = chain_step_full(h1, d2); - if (!(verify_chain3_full(d0, d1, d2, h2) == true)) @panic("honest full chain verifies"); + if (!(verify_chain3_full(d0, d1, d2, h2) == true)) __t27_assert_fail("\n honest full chain verifies:\n verify_chain3_full(d0, d1, d2, h2) = {any}\n", .{ verify_chain3_full(d0, d1, d2, h2) }); const t1 = sign_digest(0xC0FFEE01, 0xE0E0, 0x12, 0x2222, 0x9999, 2, h0); - if (!(t1 != d1)) @panic("output tamper changes the signed digest"); - if (!(verify_chain3_full(d0, t1, d2, h2) == false)) @panic("tampered receipt breaks the ledger head"); + if (!(t1 != d1)) __t27_assert_fail("\n output tamper changes the signed digest:\n t1 = {any}\n d1 = {any}\n", .{ t1, d1 }); + if (!(verify_chain3_full(d0, t1, d2, h2) == false)) __t27_assert_fail("\n tampered receipt breaks the ledger head:\n verify_chain3_full(d0, t1, d2, h2) = {any}\n", .{ verify_chain3_full(d0, t1, d2, h2) }); } test "full_chain_binds_device" { const d_chip = sign_digest(0xC0FFEE01, 0xE0E0, 0x11, 0x1111, 0x4200, 1, RECEIPT_GENESIS); const d_script = sign_digest(0, 0xE0E0, 0x11, 0x1111, 0x4200, 1, RECEIPT_GENESIS); - if (!(d_chip != d_script)) @panic("the ledger digest distinguishes silicon from a script"); + if (!(d_chip != d_script)) __t27_assert_fail("\n the ledger digest distinguishes silicon from a script:\n d_chip = {any}\n d_script = {any}\n", .{ d_chip, d_script }); } test "request_bound_signature" { const dA = sign_digest_req(0x1001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS); const dB = sign_digest_req(0x1002, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS); - if (!(dA != dB)) @panic("same result, different request => different signed digest"); + if (!(dA != dB)) __t27_assert_fail("\n same result, different request => different signed digest:\n dA = {any}\n dB = {any}\n", .{ dA, dB }); const dA2 = sign_digest_req(0x1001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x9999, 1, RECEIPT_GENESIS); - if (!(dA != dA2)) @panic("a tampered result still flips the request-bound digest"); + if (!(dA != dA2)) __t27_assert_fail("\n a tampered result still flips the request-bound digest:\n dA = {any}\n dA2 = {any}\n", .{ dA, dA2 }); } test "format_family_bound" { const binary = receipt_leaf_gf_fmt(FMT_GF_BINARY, GF16, GF_MUL, 0x3C00, 0x4000, 0x4100, 0xC0FFEE01, 0xE0E0, 1); const ternary = receipt_leaf_gf_fmt(FMT_GFT, GF16, GF_MUL, 0x3C00, 0x4000, 0x4100, 0xC0FFEE01, 0xE0E0, 1); - if (!(binary != ternary)) @panic("GF16 (binary) and GF-T16 (ternary) attest to different receipts"); + if (!(binary != ternary)) __t27_assert_fail("\n GF16 (binary) and GF-T16 (ternary) attest to different receipts:\n binary = {any}\n ternary = {any}\n", .{ binary, ternary }); } test "rung_attestations_are_distinct" { const r16 = receipt_leaf_gf_rung(FMT_GFT, 16, GFT16_RUNG_ET, GF_MUL, 0x11, 0x22, 0x33, 0xC0FFEE01, 0xE0E0, 1); const r32 = receipt_leaf_gf_rung(FMT_GFT, 32, GFT32_RUNG_ET, GF_MUL, 0x11, 0x22, 0x33, 0xC0FFEE01, 0xE0E0, 1); const r64 = receipt_leaf_gf_rung(FMT_GFT, 64, GFT64_RUNG_ET, GF_MUL, 0x11, 0x22, 0x33, 0xC0FFEE01, 0xE0E0, 1); const r128 = receipt_leaf_gf_rung(FMT_GFT, 128, GFT128_RUNG_ET, GF_MUL, 0x11, 0x22, 0x33, 0xC0FFEE01, 0xE0E0, 1); - if (!(r16 != r32)) @panic("GF-T16 != GF-T32 attestation"); - if (!(r16 != r64)) @panic("GF-T16 != GF-T64 attestation"); - if (!(r32 != r64)) @panic("GF-T32 != GF-T64 attestation"); - if (!(r64 != r128)) @panic("GF-T64 != GF-T128 attestation"); - if (!(r16 != r128)) @panic("GF-T16 != GF-T128 attestation"); + if (!(r16 != r32)) __t27_assert_fail("\n GF-T16 != GF-T32 attestation:\n r16 = {any}\n r32 = {any}\n", .{ r16, r32 }); + if (!(r16 != r64)) __t27_assert_fail("\n GF-T16 != GF-T64 attestation:\n r16 = {any}\n r64 = {any}\n", .{ r16, r64 }); + if (!(r32 != r64)) __t27_assert_fail("\n GF-T32 != GF-T64 attestation:\n r32 = {any}\n r64 = {any}\n", .{ r32, r64 }); + if (!(r64 != r128)) __t27_assert_fail("\n GF-T64 != GF-T128 attestation:\n r64 = {any}\n r128 = {any}\n", .{ r64, r128 }); + if (!(r16 != r128)) __t27_assert_fail("\n GF-T16 != GF-T128 attestation:\n r16 = {any}\n r128 = {any}\n", .{ r16, r128 }); } test "wrong_rung_geometry_is_caught" { const good = receipt_leaf_gf_rung(FMT_GFT, 64, GFT64_RUNG_ET, GF_MUL, 0x11, 0x22, 0x33, 0xC0FFEE01, 0xE0E0, 1); const bad = receipt_leaf_gf_rung(FMT_GFT, 64, GFT16_RUNG_ET, GF_MUL, 0x11, 0x22, 0x33, 0xC0FFEE01, 0xE0E0, 1); const again = receipt_leaf_gf_rung(FMT_GFT, 64, GFT64_RUNG_ET, GF_MUL, 0x11, 0x22, 0x33, 0xC0FFEE01, 0xE0E0, 1); - if (!(good != bad)) @panic("width 64 with GF-T16's Et attests differently -- geometry bound"); - if (!(good == again)) @panic("same rung + inputs -> same attestation (deterministic)"); + if (!(good != bad)) __t27_assert_fail("\n width 64 with GF-T16's Et attests differently -- geometry bound:\n good = {any}\n bad = {any}\n", .{ good, bad }); + if (!(good == again)) __t27_assert_fail("\n same rung + inputs -> same attestation (deterministic):\n good = {any}\n again = {any}\n", .{ good, again }); } test "sha256_preimage_layout" { - if (!(digest_pre(0, 0x2001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS) == TAG_RECEIPT)) @panic("word 0 is the domain tag"); - if (!(digest_pre(3, 0x2001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS) == 0xE0E0)) @panic("executor lands in word 3"); - if (!(digest_pre(8, 0x2001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS) == RECEIPT_GENESIS)) @panic("prev_head lands in word 8"); - if (!(digest_pre(9, 0, 0, 0, 0, 0, 0, 0, 0) == SHA_PAD)) @panic("word 9 starts the SHA-256 padding"); - if (!(digest_pre(15, 0, 0, 0, 0, 0, 0, 0, 0) == DIGEST_MSG_BITS)) @panic("word 15 is the 288-bit message length"); - if (!(digest_pre(12, 0x2001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS) == 0)) @panic("words 10..14 are zero pad"); + if (!(digest_pre(0, 0x2001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS) == TAG_RECEIPT)) __t27_assert_fail("\n word 0 is the domain tag:\n digest_pre(0, 0x2001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS) = {any}\n TAG_RECEIPT = {any}\n", .{ digest_pre(0, 0x2001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS), TAG_RECEIPT }); + if (!(digest_pre(3, 0x2001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS) == 0xE0E0)) __t27_assert_fail("\n executor lands in word 3:\n digest_pre(3, 0x2001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS) = {any}\n", .{ digest_pre(3, 0x2001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS) }); + if (!(digest_pre(8, 0x2001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS) == RECEIPT_GENESIS)) __t27_assert_fail("\n prev_head lands in word 8:\n digest_pre(8, 0x2001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS) = {any}\n RECEIPT_GENESIS = {any}\n", .{ digest_pre(8, 0x2001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS), RECEIPT_GENESIS }); + if (!(digest_pre(9, 0, 0, 0, 0, 0, 0, 0, 0) == SHA_PAD)) __t27_assert_fail("\n word 9 starts the SHA-256 padding:\n digest_pre(9, 0, 0, 0, 0, 0, 0, 0, 0) = {any}\n SHA_PAD = {any}\n", .{ digest_pre(9, 0, 0, 0, 0, 0, 0, 0, 0), SHA_PAD }); + if (!(digest_pre(15, 0, 0, 0, 0, 0, 0, 0, 0) == DIGEST_MSG_BITS)) __t27_assert_fail("\n word 15 is the 288-bit message length:\n digest_pre(15, 0, 0, 0, 0, 0, 0, 0, 0) = {any}\n DIGEST_MSG_BITS = {any}\n", .{ digest_pre(15, 0, 0, 0, 0, 0, 0, 0, 0), DIGEST_MSG_BITS }); + if (!(digest_pre(12, 0x2001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS) == 0)) __t27_assert_fail("\n words 10..14 are zero pad:\n digest_pre(12, 0x2001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS) = {any}\n", .{ digest_pre(12, 0x2001, 0xC0FFEE01, 0xE0E0, 0x11, 0xABCD, 0x4100, 1, RECEIPT_GENESIS) }); } test "sha256_preimage_domain_sep" { - if (!(digest_pre(0, 0, 0, 0, 0, 0, 0, 0, 0) == TAG_RECEIPT)) @panic("tag fixed even for all-zero fields"); - if (!(TAG_RECEIPT != 0)) @panic("domain tag is non-zero"); + if (!(digest_pre(0, 0, 0, 0, 0, 0, 0, 0, 0) == TAG_RECEIPT)) __t27_assert_fail("\n tag fixed even for all-zero fields:\n digest_pre(0, 0, 0, 0, 0, 0, 0, 0, 0) = {any}\n TAG_RECEIPT = {any}\n", .{ digest_pre(0, 0, 0, 0, 0, 0, 0, 0, 0), TAG_RECEIPT }); + if (!(TAG_RECEIPT != 0)) __t27_assert_fail("\n domain tag is non-zero:\n TAG_RECEIPT = {any}\n", .{ TAG_RECEIPT }); } test "ledger_entry_layout" { - if (!(ledger_entry_pre(0, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) == 0xAA)) @panic("prev_head word 0 at idx 0"); - if (!(ledger_entry_pre(8, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) == 0xD0)) @panic("digest word 0 at idx 8"); - if (!(ledger_entry_pre(16, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) == 1000)) @panic("balance_after at idx 16"); - if (!(ledger_entry_pre(17, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) == 9)) @panic("epoch at idx 17"); - if (!(ledger_entry_pre(18, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) == TAG_LEDGER)) @panic("ledger tag at idx 18"); - if (!(ledger_entry_pre(19, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) == SHA_PAD)) @panic("SHA pad marker at idx 19"); - if (!(ledger_entry_pre(31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) == LEDGER_MSG_BITS)) @panic("608-bit length at idx 31"); - if (!(ledger_entry_pre(24, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) == 0)) @panic("interior padding word is zero"); + if (!(ledger_entry_pre(0, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) == 0xAA)) __t27_assert_fail("\n prev_head word 0 at idx 0:\n ledger_entry_pre(0, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) = {any}\n", .{ ledger_entry_pre(0, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) }); + if (!(ledger_entry_pre(8, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) == 0xD0)) __t27_assert_fail("\n digest word 0 at idx 8:\n ledger_entry_pre(8, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) = {any}\n", .{ ledger_entry_pre(8, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) }); + if (!(ledger_entry_pre(16, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) == 1000)) __t27_assert_fail("\n balance_after at idx 16:\n ledger_entry_pre(16, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) = {any}\n", .{ ledger_entry_pre(16, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) }); + if (!(ledger_entry_pre(17, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) == 9)) __t27_assert_fail("\n epoch at idx 17:\n ledger_entry_pre(17, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) = {any}\n", .{ ledger_entry_pre(17, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) }); + if (!(ledger_entry_pre(18, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) == TAG_LEDGER)) __t27_assert_fail("\n ledger tag at idx 18:\n ledger_entry_pre(18, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) = {any}\n TAG_LEDGER = {any}\n", .{ ledger_entry_pre(18, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9), TAG_LEDGER }); + if (!(ledger_entry_pre(19, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) == SHA_PAD)) __t27_assert_fail("\n SHA pad marker at idx 19:\n ledger_entry_pre(19, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) = {any}\n SHA_PAD = {any}\n", .{ ledger_entry_pre(19, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), SHA_PAD }); + if (!(ledger_entry_pre(31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) == LEDGER_MSG_BITS)) __t27_assert_fail("\n 608-bit length at idx 31:\n ledger_entry_pre(31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) = {any}\n LEDGER_MSG_BITS = {any}\n", .{ ledger_entry_pre(31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), LEDGER_MSG_BITS }); + if (!(ledger_entry_pre(24, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) == 0)) __t27_assert_fail("\n interior padding word is zero:\n ledger_entry_pre(24, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) = {any}\n", .{ ledger_entry_pre(24, 0xAA, 1, 2, 3, 4, 5, 6, 7, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 1000, 9) }); } test "merkle_pair_layout" { - if (!(merkle_pair_pre(0, 0xA0, 1, 2, 3, 4, 5, 6, 7, 0xB0, 1, 2, 3, 4, 5, 6, 7) == 0xA0)) @panic("left child word 0 at idx 0"); - if (!(merkle_pair_pre(8, 0xA0, 1, 2, 3, 4, 5, 6, 7, 0xB0, 1, 2, 3, 4, 5, 6, 7) == 0xB0)) @panic("right child word 0 at idx 8"); - if (!(merkle_pair_pre(15, 0xA0, 1, 2, 3, 4, 5, 6, 7, 0xB0, 1, 2, 3, 4, 5, 6, 7) == 7)) @panic("right child word 7 at idx 15"); - if (!(merkle_pair_pre(16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) == SHA_PAD)) @panic("SHA pad marker at idx 16"); - if (!(merkle_pair_pre(31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) == MERKLE_MSG_BITS)) @panic("512-bit length at idx 31"); - if (!(merkle_pair_pre(20, 0xA0, 1, 2, 3, 4, 5, 6, 7, 0xB0, 1, 2, 3, 4, 5, 6, 7) == 0)) @panic("interior padding word is zero"); + if (!(merkle_pair_pre(0, 0xA0, 1, 2, 3, 4, 5, 6, 7, 0xB0, 1, 2, 3, 4, 5, 6, 7) == 0xA0)) __t27_assert_fail("\n left child word 0 at idx 0:\n merkle_pair_pre(0, 0xA0, 1, 2, 3, 4, 5, 6, 7, 0xB0, 1, 2, 3, 4, 5, 6, 7) = {any}\n", .{ merkle_pair_pre(0, 0xA0, 1, 2, 3, 4, 5, 6, 7, 0xB0, 1, 2, 3, 4, 5, 6, 7) }); + if (!(merkle_pair_pre(8, 0xA0, 1, 2, 3, 4, 5, 6, 7, 0xB0, 1, 2, 3, 4, 5, 6, 7) == 0xB0)) __t27_assert_fail("\n right child word 0 at idx 8:\n merkle_pair_pre(8, 0xA0, 1, 2, 3, 4, 5, 6, 7, 0xB0, 1, 2, 3, 4, 5, 6, 7) = {any}\n", .{ merkle_pair_pre(8, 0xA0, 1, 2, 3, 4, 5, 6, 7, 0xB0, 1, 2, 3, 4, 5, 6, 7) }); + if (!(merkle_pair_pre(15, 0xA0, 1, 2, 3, 4, 5, 6, 7, 0xB0, 1, 2, 3, 4, 5, 6, 7) == 7)) __t27_assert_fail("\n right child word 7 at idx 15:\n merkle_pair_pre(15, 0xA0, 1, 2, 3, 4, 5, 6, 7, 0xB0, 1, 2, 3, 4, 5, 6, 7) = {any}\n", .{ merkle_pair_pre(15, 0xA0, 1, 2, 3, 4, 5, 6, 7, 0xB0, 1, 2, 3, 4, 5, 6, 7) }); + if (!(merkle_pair_pre(16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) == SHA_PAD)) __t27_assert_fail("\n SHA pad marker at idx 16:\n merkle_pair_pre(16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) = {any}\n SHA_PAD = {any}\n", .{ merkle_pair_pre(16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), SHA_PAD }); + if (!(merkle_pair_pre(31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) == MERKLE_MSG_BITS)) __t27_assert_fail("\n 512-bit length at idx 31:\n merkle_pair_pre(31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) = {any}\n MERKLE_MSG_BITS = {any}\n", .{ merkle_pair_pre(31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), MERKLE_MSG_BITS }); + if (!(merkle_pair_pre(20, 0xA0, 1, 2, 3, 4, 5, 6, 7, 0xB0, 1, 2, 3, 4, 5, 6, 7) == 0)) __t27_assert_fail("\n interior padding word is zero:\n merkle_pair_pre(20, 0xA0, 1, 2, 3, 4, 5, 6, 7, 0xB0, 1, 2, 3, 4, 5, 6, 7) = {any}\n", .{ merkle_pair_pre(20, 0xA0, 1, 2, 3, 4, 5, 6, 7, 0xB0, 1, 2, 3, 4, 5, 6, 7) }); } test "input_digest_layout" { - if (!(input_digest_pre(0, 9, 9, 9, 9, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 9, 9, 9) == TAG_INPUT)) @panic("tag at word 0"); - if (!(input_digest_pre(5, 9, 9, 9, 9, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 9, 9, 9) == 0xA0)) @panic("operand hash word 0 at idx 5"); - if (!(input_digest_pre(12, 9, 9, 9, 9, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 9, 9, 9) == 0xA7)) @panic("operand hash word 7 at idx 12"); - if (!(input_digest_pre(13, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0x4100, 1, 0x54524352) == 0x4100)) @panic("out at idx 13"); - if (!(input_digest_pre(16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) == SHA_PAD)) @panic("pad at idx 16"); - if (!(input_digest_pre(31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) == MERKLE_MSG_BITS)) @panic("512-bit length at idx 31"); + if (!(input_digest_pre(0, 9, 9, 9, 9, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 9, 9, 9) == TAG_INPUT)) __t27_assert_fail("\n tag at word 0:\n input_digest_pre(0, 9, 9, 9, 9, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 9, 9, 9) = {any}\n TAG_INPUT = {any}\n", .{ input_digest_pre(0, 9, 9, 9, 9, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 9, 9, 9), TAG_INPUT }); + if (!(input_digest_pre(5, 9, 9, 9, 9, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 9, 9, 9) == 0xA0)) __t27_assert_fail("\n operand hash word 0 at idx 5:\n input_digest_pre(5, 9, 9, 9, 9, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 9, 9, 9) = {any}\n", .{ input_digest_pre(5, 9, 9, 9, 9, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 9, 9, 9) }); + if (!(input_digest_pre(12, 9, 9, 9, 9, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 9, 9, 9) == 0xA7)) __t27_assert_fail("\n operand hash word 7 at idx 12:\n input_digest_pre(12, 9, 9, 9, 9, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 9, 9, 9) = {any}\n", .{ input_digest_pre(12, 9, 9, 9, 9, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 9, 9, 9) }); + if (!(input_digest_pre(13, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0x4100, 1, 0x54524352) == 0x4100)) __t27_assert_fail("\n out at idx 13:\n input_digest_pre(13, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0x4100, 1, 0x54524352) = {any}\n", .{ input_digest_pre(13, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0x4100, 1, 0x54524352) }); + if (!(input_digest_pre(16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) == SHA_PAD)) __t27_assert_fail("\n pad at idx 16:\n input_digest_pre(16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) = {any}\n SHA_PAD = {any}\n", .{ input_digest_pre(16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), SHA_PAD }); + if (!(input_digest_pre(31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) == MERKLE_MSG_BITS)) __t27_assert_fail("\n 512-bit length at idx 31:\n input_digest_pre(31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) = {any}\n MERKLE_MSG_BITS = {any}\n", .{ input_digest_pre(31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), MERKLE_MSG_BITS }); } diff --git a/gen/zig/tri_compute_reputation.zig b/gen/zig/tri_compute_reputation.zig index 13f675ca..3f07e2f3 100644 --- a/gen/zig/tri_compute_reputation.zig +++ b/gen/zig/tri_compute_reputation.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const REP_INIT: u32 = 100; @@ -64,40 +72,40 @@ fn can_admit(rep: u32, min_rep: u32) bool { return rep >= min_rep; } test "honest_raises_capped" { - if (!(rep_after_honest(100, 20) == 120)) @panic("honest work gains reputation"); - if (!(rep_after_honest(990, 50) == REP_MAX)) @panic("reputation is capped at REP_MAX"); + if (!(rep_after_honest(100, 20) == 120)) __t27_assert_fail("\n honest work gains reputation:\n rep_after_honest(100, 20) = {any}\n", .{ rep_after_honest(100, 20) }); + if (!(rep_after_honest(990, 50) == REP_MAX)) __t27_assert_fail("\n reputation is capped at REP_MAX:\n rep_after_honest(990, 50) = {any}\n REP_MAX = {any}\n", .{ rep_after_honest(990, 50), REP_MAX }); } test "rung_scales_honest_trust" { - if (!(rung_honest_gain(5, 4) == 5)) @panic("GF-T16 base gain"); - if (!(rung_honest_gain(5, 6) == 11)) @panic("GF-T32 gains more (+2 trits * 3)"); - if (!(rung_honest_gain(5, 9) == 20)) @panic("GF-T64 gains more still (+5 trits)"); - if (!(rung_honest_gain(5, 14) == 35)) @panic("GF-T128 gains most (+10 trits)"); - if (!(rung_honest_gain(5, 3) == 5)) @panic("sub-flagship uses the base (never shrinks)"); - if (!(rep_after_resolution_rung(100, RESOLVE_HONEST, 5, 9) == 120)) @panic("honest GF-T64: +20 trust"); - if (!(rep_after_resolution_rung(100, RESOLVE_HONEST, 5, 4) == 105)) @panic("honest GF-T16: +5 trust"); - if (!(rep_after_resolution_rung(100, RESOLVE_SLASH, 5, 9) == 50)) @panic("a GF-T64 slash still halves (fraud is fraud)"); - if (!(rep_after_resolution_rung(999, RESOLVE_HONEST, 100, 14) == REP_MAX)) @panic("cap holds even at a high rung + big gain"); + if (!(rung_honest_gain(5, 4) == 5)) __t27_assert_fail("\n GF-T16 base gain:\n rung_honest_gain(5, 4) = {any}\n", .{ rung_honest_gain(5, 4) }); + if (!(rung_honest_gain(5, 6) == 11)) __t27_assert_fail("\n GF-T32 gains more (+2 trits * 3):\n rung_honest_gain(5, 6) = {any}\n", .{ rung_honest_gain(5, 6) }); + if (!(rung_honest_gain(5, 9) == 20)) __t27_assert_fail("\n GF-T64 gains more still (+5 trits):\n rung_honest_gain(5, 9) = {any}\n", .{ rung_honest_gain(5, 9) }); + if (!(rung_honest_gain(5, 14) == 35)) __t27_assert_fail("\n GF-T128 gains most (+10 trits):\n rung_honest_gain(5, 14) = {any}\n", .{ rung_honest_gain(5, 14) }); + if (!(rung_honest_gain(5, 3) == 5)) __t27_assert_fail("\n sub-flagship uses the base (never shrinks):\n rung_honest_gain(5, 3) = {any}\n", .{ rung_honest_gain(5, 3) }); + if (!(rep_after_resolution_rung(100, RESOLVE_HONEST, 5, 9) == 120)) __t27_assert_fail("\n honest GF-T64: +20 trust:\n rep_after_resolution_rung(100, RESOLVE_HONEST, 5, 9) = {any}\n", .{ rep_after_resolution_rung(100, RESOLVE_HONEST, 5, 9) }); + if (!(rep_after_resolution_rung(100, RESOLVE_HONEST, 5, 4) == 105)) __t27_assert_fail("\n honest GF-T16: +5 trust:\n rep_after_resolution_rung(100, RESOLVE_HONEST, 5, 4) = {any}\n", .{ rep_after_resolution_rung(100, RESOLVE_HONEST, 5, 4) }); + if (!(rep_after_resolution_rung(100, RESOLVE_SLASH, 5, 9) == 50)) __t27_assert_fail("\n a GF-T64 slash still halves (fraud is fraud):\n rep_after_resolution_rung(100, RESOLVE_SLASH, 5, 9) = {any}\n", .{ rep_after_resolution_rung(100, RESOLVE_SLASH, 5, 9) }); + if (!(rep_after_resolution_rung(999, RESOLVE_HONEST, 100, 14) == REP_MAX)) __t27_assert_fail("\n cap holds even at a high rung + big gain:\n rep_after_resolution_rung(999, RESOLVE_HONEST, 100, 14) = {any}\n REP_MAX = {any}\n", .{ rep_after_resolution_rung(999, RESOLVE_HONEST, 100, 14), REP_MAX }); } test "gain_overflow_cannot_defeat_the_cap" { - if (!(rep_after_honest(1000, 4294966296) == REP_MAX)) @panic("gain wrapping rep+gain to 0 still caps at REP_MAX, not 0"); - if (!(rep_after_honest(0, 4294967295) == REP_MAX)) @panic("a u32-max gain caps at REP_MAX, no wrap"); - if (!(rep_after_resolution(1000, RESOLVE_HONEST, 4294966296) == REP_MAX)) @panic("driver: overflowing honest gain caps at REP_MAX"); + if (!(rep_after_honest(1000, 4294966296) == REP_MAX)) __t27_assert_fail("\n gain wrapping rep+gain to 0 still caps at REP_MAX, not 0:\n rep_after_honest(1000, 4294966296) = {any}\n REP_MAX = {any}\n", .{ rep_after_honest(1000, 4294966296), REP_MAX }); + if (!(rep_after_honest(0, 4294967295) == REP_MAX)) __t27_assert_fail("\n a u32-max gain caps at REP_MAX, no wrap:\n rep_after_honest(0, 4294967295) = {any}\n REP_MAX = {any}\n", .{ rep_after_honest(0, 4294967295), REP_MAX }); + if (!(rep_after_resolution(1000, RESOLVE_HONEST, 4294966296) == REP_MAX)) __t27_assert_fail("\n driver: overflowing honest gain caps at REP_MAX:\n rep_after_resolution(1000, RESOLVE_HONEST, 4294966296) = {any}\n REP_MAX = {any}\n", .{ rep_after_resolution(1000, RESOLVE_HONEST, 4294966296), REP_MAX }); } test "outcome_drives_reputation" { - if (!(rep_after_resolution(1000, RESOLVE_SLASH, 20) == 500)) @panic("proven fraud halves reputation"); - if (!(rep_after_resolution(100, RESOLVE_HONEST, 20) == 120)) @panic("proven honest gains reputation"); - if (!(rep_after_resolution(990, RESOLVE_HONEST, 50) == REP_MAX)) @panic("gain still respects the cap"); + if (!(rep_after_resolution(1000, RESOLVE_SLASH, 20) == 500)) __t27_assert_fail("\n proven fraud halves reputation:\n rep_after_resolution(1000, RESOLVE_SLASH, 20) = {any}\n", .{ rep_after_resolution(1000, RESOLVE_SLASH, 20) }); + if (!(rep_after_resolution(100, RESOLVE_HONEST, 20) == 120)) __t27_assert_fail("\n proven honest gains reputation:\n rep_after_resolution(100, RESOLVE_HONEST, 20) = {any}\n", .{ rep_after_resolution(100, RESOLVE_HONEST, 20) }); + if (!(rep_after_resolution(990, RESOLVE_HONEST, 50) == REP_MAX)) __t27_assert_fail("\n gain still respects the cap:\n rep_after_resolution(990, RESOLVE_HONEST, 50) = {any}\n REP_MAX = {any}\n", .{ rep_after_resolution(990, RESOLVE_HONEST, 50), REP_MAX }); } test "non_terminal_outcomes_are_noops" { - if (!(rep_after_resolution(800, 2, 20) == 800)) @panic("MALFORMED does not move reputation"); - if (!(rep_after_resolution(800, 3, 20) == 800)) @panic("STALE (replay) does not move reputation"); - if (!(rep_after_resolution(800, 4, 20) == 800)) @panic("FAMILY_MISMATCH does not move reputation"); + if (!(rep_after_resolution(800, 2, 20) == 800)) __t27_assert_fail("\n MALFORMED does not move reputation:\n rep_after_resolution(800, 2, 20) = {any}\n", .{ rep_after_resolution(800, 2, 20) }); + if (!(rep_after_resolution(800, 3, 20) == 800)) __t27_assert_fail("\n STALE (replay) does not move reputation:\n rep_after_resolution(800, 3, 20) = {any}\n", .{ rep_after_resolution(800, 3, 20) }); + if (!(rep_after_resolution(800, 4, 20) == 800)) __t27_assert_fail("\n FAMILY_MISMATCH does not move reputation:\n rep_after_resolution(800, 4, 20) = {any}\n", .{ rep_after_resolution(800, 4, 20) }); } test "verifier_reputation_driver" { - if (!(rep_after_verifier(1000, 1, 1, 20) == 500)) @panic("dissenting verifier is halved"); - if (!(rep_after_verifier(100, 1, 0, 20) == 120)) @panic("agreeing verifier gains"); - if (!(rep_after_verifier(800, 0, 0, 20) == 800)) @panic("no quorum -> verifier reputation unchanged"); - if (!(rep_after_verifier(800, 0, 1, 20) == 800)) @panic("no quorum: even a 'dissent' flag is ignored"); + if (!(rep_after_verifier(1000, 1, 1, 20) == 500)) __t27_assert_fail("\n dissenting verifier is halved:\n rep_after_verifier(1000, 1, 1, 20) = {any}\n", .{ rep_after_verifier(1000, 1, 1, 20) }); + if (!(rep_after_verifier(100, 1, 0, 20) == 120)) __t27_assert_fail("\n agreeing verifier gains:\n rep_after_verifier(100, 1, 0, 20) = {any}\n", .{ rep_after_verifier(100, 1, 0, 20) }); + if (!(rep_after_verifier(800, 0, 0, 20) == 800)) __t27_assert_fail("\n no quorum -> verifier reputation unchanged:\n rep_after_verifier(800, 0, 0, 20) = {any}\n", .{ rep_after_verifier(800, 0, 0, 20) }); + if (!(rep_after_verifier(800, 0, 1, 20) == 800)) __t27_assert_fail("\n no quorum: even a 'dissent' flag is ignored:\n rep_after_verifier(800, 0, 1, 20) = {any}\n", .{ rep_after_verifier(800, 0, 1, 20) }); } test "bad_verifier_is_locked_out" { const d1 = rep_after_verifier(1000, 1, 1, 0); @@ -105,32 +113,32 @@ test "bad_verifier_is_locked_out" { const d3 = rep_after_verifier(d2, 1, 1, 0); const d4 = rep_after_verifier(d3, 1, 1, 0); const d5 = rep_after_verifier(d4, 1, 1, 0); - if (!(can_admit(d4, 50) == true)) @panic("after 4 dissents (62) still admissible"); - if (!(can_admit(d5, 50) == false)) @panic("the fifth dissent (31) locks the verifier out"); + if (!(can_admit(d4, 50) == true)) __t27_assert_fail("\n after 4 dissents (62) still admissible:\n can_admit(d4, 50) = {any}\n", .{ can_admit(d4, 50) }); + if (!(can_admit(d5, 50) == false)) __t27_assert_fail("\n the fifth dissent (31) locks the verifier out:\n can_admit(d5, 50) = {any}\n", .{ can_admit(d5, 50) }); } test "slash_has_memory_through_the_driver" { const r = rep_after_resolution(1000, RESOLVE_SLASH, 20); - if (!(rep_after_resolution(r, RESOLVE_HONEST, 20) == 520)) @panic("one honest job only partly repairs a proven slash"); + if (!(rep_after_resolution(r, RESOLVE_HONEST, 20) == 520)) __t27_assert_fail("\n one honest job only partly repairs a proven slash:\n rep_after_resolution(r, RESOLVE_HONEST, 20) = {any}\n", .{ rep_after_resolution(r, RESOLVE_HONEST, 20) }); } test "slash_halves" { - if (!(rep_after_slash(1000) == 500)) @panic("a slash halves reputation"); + if (!(rep_after_slash(1000) == 500)) __t27_assert_fail("\n a slash halves reputation:\n rep_after_slash(1000) = {any}\n", .{ rep_after_slash(1000) }); const r = rep_after_slash(1000); - if (!(rep_after_honest(r, 20) == 520)) @panic("one honest job only partly repairs a slash"); + if (!(rep_after_honest(r, 20) == 520)) __t27_assert_fail("\n one honest job only partly repairs a slash:\n rep_after_honest(r, 20) = {any}\n", .{ rep_after_honest(r, 20) }); } test "reputation_weights_the_split" { const honest = weighted_work(16, 1000); const slashed = weighted_work(16, 500); - if (!(honest > slashed)) @panic("same work, higher reputation => bigger pool weight"); - if (!(honest == 16000)) @panic("weight = raw_work * reputation"); + if (!(honest > slashed)) __t27_assert_fail("\n same work, higher reputation => bigger pool weight:\n honest = {any}\n slashed = {any}\n", .{ honest, slashed }); + if (!(honest == 16000)) __t27_assert_fail("\n weight = raw_work * reputation:\n honest = {any}\n", .{ honest }); } test "zero_reputation_zero_weight" { - if (!(weighted_work(48, 0) == 0)) @panic("no reputation => no share"); + if (!(weighted_work(48, 0) == 0)) __t27_assert_fail("\n no reputation => no share:\n weighted_work(48, 0) = {any}\n", .{ weighted_work(48, 0) }); } test "admission_floor" { - if (!(can_admit(REP_INIT, 50) == true)) @panic("a fresh node (REP_INIT) is admissible"); - if (!(can_admit(50, 50) == true)) @panic("exactly at the floor is admitted"); - if (!(can_admit(49, 50) == false)) @panic("one below the floor is excluded"); - if (!(can_admit(0, 50) == false)) @panic("a slashed-to-zero node cannot take work"); + if (!(can_admit(REP_INIT, 50) == true)) __t27_assert_fail("\n a fresh node (REP_INIT) is admissible:\n can_admit(REP_INIT, 50) = {any}\n", .{ can_admit(REP_INIT, 50) }); + if (!(can_admit(50, 50) == true)) __t27_assert_fail("\n exactly at the floor is admitted:\n can_admit(50, 50) = {any}\n", .{ can_admit(50, 50) }); + if (!(can_admit(49, 50) == false)) __t27_assert_fail("\n one below the floor is excluded:\n can_admit(49, 50) = {any}\n", .{ can_admit(49, 50) }); + if (!(can_admit(0, 50) == false)) __t27_assert_fail("\n a slashed-to-zero node cannot take work:\n can_admit(0, 50) = {any}\n", .{ can_admit(0, 50) }); } test "repeated_fraud_locks_out" { const r1 = rep_after_resolution(1000, RESOLVE_SLASH, 0); @@ -138,12 +146,12 @@ test "repeated_fraud_locks_out" { const r3 = rep_after_resolution(r2, RESOLVE_SLASH, 0); const r4 = rep_after_resolution(r3, RESOLVE_SLASH, 0); const r5 = rep_after_resolution(r4, RESOLVE_SLASH, 0); - if (!(can_admit(r4, 50) == true)) @panic("after 4 frauds (rep 62) still just admissible"); - if (!(can_admit(r5, 50) == false)) @panic("the fifth proven fraud (rep 31) locks the node out"); + if (!(can_admit(r4, 50) == true)) __t27_assert_fail("\n after 4 frauds (rep 62) still just admissible:\n can_admit(r4, 50) = {any}\n", .{ can_admit(r4, 50) }); + if (!(can_admit(r5, 50) == false)) __t27_assert_fail("\n the fifth proven fraud (rep 31) locks the node out:\n can_admit(r5, 50) = {any}\n", .{ can_admit(r5, 50) }); } test "weighted_work_saturates" { - if (!(weighted_work(16, 1000) == 16000)) @panic("normal weight is exact"); - if (!(weighted_work(48, 0) == 0)) @panic("zero reputation -> zero weight (regression)"); - if (!(weighted_work(100000, 1000) == 100000000)) @panic("1e5 * 1e3 = 1e8 fits, exact"); - if (!(weighted_work(5000000, 1000) == 4294967295)) @panic("overflowing weight saturates to u32 max, no wrap"); + if (!(weighted_work(16, 1000) == 16000)) __t27_assert_fail("\n normal weight is exact:\n weighted_work(16, 1000) = {any}\n", .{ weighted_work(16, 1000) }); + if (!(weighted_work(48, 0) == 0)) __t27_assert_fail("\n zero reputation -> zero weight (regression):\n weighted_work(48, 0) = {any}\n", .{ weighted_work(48, 0) }); + if (!(weighted_work(100000, 1000) == 100000000)) __t27_assert_fail("\n 1e5 * 1e3 = 1e8 fits, exact:\n weighted_work(100000, 1000) = {any}\n", .{ weighted_work(100000, 1000) }); + if (!(weighted_work(5000000, 1000) == 4294967295)) __t27_assert_fail("\n overflowing weight saturates to u32 max, no wrap:\n weighted_work(5000000, 1000) = {any}\n", .{ weighted_work(5000000, 1000) }); } diff --git a/gen/zig/tri_compute_safety.zig b/gen/zig/tri_compute_safety.zig index 72e889a0..ce9991d6 100644 --- a/gen/zig/tri_compute_safety.zig +++ b/gen/zig/tri_compute_safety.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module fn payable(fresh: u32, finite: u32, already_settled: u32) u32 { @@ -40,36 +48,36 @@ fn reward_gate_authentic(base_reward: u32, sig_ok: u32, fresh: u32, finite: u32, } } test "no_double_pay" { - if (!(reward_gate(16, 1, 1, 1) == 0)) @panic("already-settled receipt pays nothing"); + if (!(reward_gate(16, 1, 1, 1) == 0)) __t27_assert_fail("\n already-settled receipt pays nothing:\n reward_gate(16, 1, 1, 1) = {any}\n", .{ reward_gate(16, 1, 1, 1) }); } test "replay_pays_nothing" { - if (!(reward_gate(16, 0, 1, 0) == 0)) @panic("stale/replayed receipt pays nothing"); + if (!(reward_gate(16, 0, 1, 0) == 0)) __t27_assert_fail("\n stale/replayed receipt pays nothing:\n reward_gate(16, 0, 1, 0) = {any}\n", .{ reward_gate(16, 0, 1, 0) }); } test "garbage_pays_nothing" { - if (!(reward_gate(16, 1, 0, 0) == 0)) @panic("inf/nan result pays nothing"); + if (!(reward_gate(16, 1, 0, 0) == 0)) __t27_assert_fail("\n inf/nan result pays nothing:\n reward_gate(16, 1, 0, 0) = {any}\n", .{ reward_gate(16, 1, 0, 0) }); } test "honest_path_pays" { - if (!(reward_gate(16, 1, 1, 0) == 16)) @panic("fresh + finite + new pays the reward"); - if (!(payable(1, 1, 0) == 1)) @panic("the gate opens only on the honest path"); + if (!(reward_gate(16, 1, 1, 0) == 16)) __t27_assert_fail("\n fresh + finite + new pays the reward:\n reward_gate(16, 1, 1, 0) = {any}\n", .{ reward_gate(16, 1, 1, 0) }); + if (!(payable(1, 1, 0) == 1)) __t27_assert_fail("\n the gate opens only on the honest path:\n payable(1, 1, 0) = {any}\n", .{ payable(1, 1, 0) }); } test "gate_needs_all_three" { - if (!(payable(0, 1, 0) == 0)) @panic("not fresh -> closed"); - if (!(payable(1, 0, 0) == 0)) @panic("not finite -> closed"); - if (!(payable(1, 1, 1) == 0)) @panic("already settled -> closed"); - if (!(payable(1, 1, 0) == 1)) @panic("all three -> open"); + if (!(payable(0, 1, 0) == 0)) __t27_assert_fail("\n not fresh -> closed:\n payable(0, 1, 0) = {any}\n", .{ payable(0, 1, 0) }); + if (!(payable(1, 0, 0) == 0)) __t27_assert_fail("\n not finite -> closed:\n payable(1, 0, 0) = {any}\n", .{ payable(1, 0, 0) }); + if (!(payable(1, 1, 1) == 0)) __t27_assert_fail("\n already settled -> closed:\n payable(1, 1, 1) = {any}\n", .{ payable(1, 1, 1) }); + if (!(payable(1, 1, 0) == 1)) __t27_assert_fail("\n all three -> open:\n payable(1, 1, 0) = {any}\n", .{ payable(1, 1, 0) }); } test "forgery_pays_nothing" { - if (!(reward_gate_authentic(16, 0, 1, 1, 0) == 0)) @panic("unsigned/forged receipt pays nothing despite fresh+finite+new"); - if (!(payable_authentic(0, 1, 1, 0) == 0)) @panic("no valid signature -> gate closed"); + if (!(reward_gate_authentic(16, 0, 1, 1, 0) == 0)) __t27_assert_fail("\n unsigned/forged receipt pays nothing despite fresh+finite+new:\n reward_gate_authentic(16, 0, 1, 1, 0) = {any}\n", .{ reward_gate_authentic(16, 0, 1, 1, 0) }); + if (!(payable_authentic(0, 1, 1, 0) == 0)) __t27_assert_fail("\n no valid signature -> gate closed:\n payable_authentic(0, 1, 1, 0) = {any}\n", .{ payable_authentic(0, 1, 1, 0) }); } test "authentic_gate_needs_all_four" { - if (!(reward_gate_authentic(16, 1, 1, 1, 0) == 16)) @panic("sig + fresh + finite + new -> pays"); - if (!(payable_authentic(1, 0, 1, 0) == 0)) @panic("valid sig but stale -> closed"); - if (!(payable_authentic(1, 1, 0, 0) == 0)) @panic("valid sig but inf/nan -> closed"); - if (!(payable_authentic(1, 1, 1, 1) == 0)) @panic("valid sig but already settled -> closed"); - if (!(payable_authentic(1, 1, 1, 0) == 1)) @panic("all four -> open"); + if (!(reward_gate_authentic(16, 1, 1, 1, 0) == 16)) __t27_assert_fail("\n sig + fresh + finite + new -> pays:\n reward_gate_authentic(16, 1, 1, 1, 0) = {any}\n", .{ reward_gate_authentic(16, 1, 1, 1, 0) }); + if (!(payable_authentic(1, 0, 1, 0) == 0)) __t27_assert_fail("\n valid sig but stale -> closed:\n payable_authentic(1, 0, 1, 0) = {any}\n", .{ payable_authentic(1, 0, 1, 0) }); + if (!(payable_authentic(1, 1, 0, 0) == 0)) __t27_assert_fail("\n valid sig but inf/nan -> closed:\n payable_authentic(1, 1, 0, 0) = {any}\n", .{ payable_authentic(1, 1, 0, 0) }); + if (!(payable_authentic(1, 1, 1, 1) == 0)) __t27_assert_fail("\n valid sig but already settled -> closed:\n payable_authentic(1, 1, 1, 1) = {any}\n", .{ payable_authentic(1, 1, 1, 1) }); + if (!(payable_authentic(1, 1, 1, 0) == 1)) __t27_assert_fail("\n all four -> open:\n payable_authentic(1, 1, 1, 0) = {any}\n", .{ payable_authentic(1, 1, 1, 0) }); } test "authentic_is_stricter" { - if (!(payable_authentic(1, 1, 1, 0) == payable(1, 1, 0))) @panic("with a valid sig it matches payable exactly"); - if (!(payable_authentic(0, 1, 1, 0) == 0)) @panic("without the sig it is strictly stricter"); + if (!(payable_authentic(1, 1, 1, 0) == payable(1, 1, 0))) __t27_assert_fail("\n with a valid sig it matches payable exactly:\n payable_authentic(1, 1, 1, 0) = {any}\n payable(1, 1, 0) = {any}\n", .{ payable_authentic(1, 1, 1, 0), payable(1, 1, 0) }); + if (!(payable_authentic(0, 1, 1, 0) == 0)) __t27_assert_fail("\n without the sig it is strictly stricter:\n payable_authentic(0, 1, 1, 0) = {any}\n", .{ payable_authentic(0, 1, 1, 0) }); } diff --git a/gen/zig/tri_compute_settle.zig b/gen/zig/tri_compute_settle.zig index 2d26bddb..dcab2eea 100644 --- a/gen/zig/tri_compute_settle.zig +++ b/gen/zig/tri_compute_settle.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const SETTLE_GENESIS: u32 = 0x54524353; @@ -148,133 +156,133 @@ fn settle_signed(prev_balance: u32, gf_width: u32, fresh: u32, gf_result: u32, e return settle_canonical(prev_balance, gf_width, sig_ok, fresh, already_settled, FMT_GF_BINARY, gf_result, exp_bits, mant_bits, 1, 0); } test "fresh_pays_stale_free" { - if (!(compute_reward(16, 1) == 16)) @panic("fresh GF16 op pays 16 $TRI"); - if (!(compute_reward(16, 0) == 0)) @panic("replayed/stale receipt pays 0"); - if (!(compute_reward(32, 1) == 32)) @panic("wider GF pays more"); + if (!(compute_reward(16, 1) == 16)) __t27_assert_fail("\n fresh GF16 op pays 16 $TRI:\n compute_reward(16, 1) = {any}\n", .{ compute_reward(16, 1) }); + if (!(compute_reward(16, 0) == 0)) __t27_assert_fail("\n replayed/stale receipt pays 0:\n compute_reward(16, 0) = {any}\n", .{ compute_reward(16, 0) }); + if (!(compute_reward(32, 1) == 32)) __t27_assert_fail("\n wider GF pays more:\n compute_reward(32, 1) = {any}\n", .{ compute_reward(32, 1) }); } test "balance_only_grows_on_fresh" { const b0 = settle_balance(100, 16, 1); const b1 = settle_balance(b0, 16, 0); - if (!(b0 == 116)) @panic("fresh settle credits the executor"); - if (!(b1 == 116)) @panic("a replayed receipt adds nothing"); + if (!(b0 == 116)) __t27_assert_fail("\n fresh settle credits the executor:\n b0 = {any}\n", .{ b0 }); + if (!(b1 == 116)) __t27_assert_fail("\n a replayed receipt adds nothing:\n b1 = {any}\n", .{ b1 }); } test "balance_saturates" { - if (!(settle_balance(0xFFFFFFF0, 32, 1) == 0xFFFFFFFF)) @panic("saturates, no wrap"); + if (!(settle_balance(0xFFFFFFF0, 32, 1) == 0xFFFFFFFF)) __t27_assert_fail("\n saturates, no wrap:\n settle_balance(0xFFFFFFF0, 32, 1) = {any}\n", .{ settle_balance(0xFFFFFFF0, 32, 1) }); } test "settle_root_tamper_evident" { const h0 = settle_head(SETTLE_GENESIS, 0x1111); const honest = settle_head(h0, 0x2222); const t0 = settle_head(SETTLE_GENESIS, 0x9999); const tampered = settle_head(t0, 0x2222); - if (!(honest != tampered)) @panic("tampering a settled digest changes the root"); + if (!(honest != tampered)) __t27_assert_fail("\n tampering a settled digest changes the root:\n honest = {any}\n tampered = {any}\n", .{ honest, tampered }); const r0 = settle_head(SETTLE_GENESIS, 0x2222); const swapped = settle_head(r0, 0x1111); - if (!(honest != swapped)) @panic("reordering settlements changes the root"); + if (!(honest != swapped)) __t27_assert_fail("\n reordering settlements changes the root:\n honest = {any}\n swapped = {any}\n", .{ honest, swapped }); } test "finite_gate" { - if (!(is_finite_gf16(0x4200) == true)) @panic("4.0 is finite"); - if (!(is_finite_gf16(0x7E01) == false)) @panic("NaN (0x7E01) is not finite"); - if (!(is_finite_gf16(0x7E00) == false)) @panic("+inf (0x7E00) is not finite"); - if (!(is_finite_gf16(0xFE00) == false)) @panic("-inf (0xFE00) is not finite"); + if (!(is_finite_gf16(0x4200) == true)) __t27_assert_fail("\n 4.0 is finite:\n is_finite_gf16(0x4200) = {any}\n", .{ is_finite_gf16(0x4200) }); + if (!(is_finite_gf16(0x7E01) == false)) __t27_assert_fail("\n NaN (0x7E01) is not finite:\n is_finite_gf16(0x7E01) = {any}\n", .{ is_finite_gf16(0x7E01) }); + if (!(is_finite_gf16(0x7E00) == false)) __t27_assert_fail("\n +inf (0x7E00) is not finite:\n is_finite_gf16(0x7E00) = {any}\n", .{ is_finite_gf16(0x7E00) }); + if (!(is_finite_gf16(0xFE00) == false)) __t27_assert_fail("\n -inf (0xFE00) is not finite:\n is_finite_gf16(0xFE00) = {any}\n", .{ is_finite_gf16(0xFE00) }); } test "settle_rejects_garbage" { - if (!(settle_checked(100, 16, 1, 0x4200) == 116)) @panic("fresh finite GF16 pays 16"); - if (!(settle_checked(100, 16, 1, 0x7E01) == 100)) @panic("fresh NaN pays nothing"); - if (!(settle_checked(100, 16, 1, 0x7E00) == 100)) @panic("fresh inf pays nothing"); - if (!(settle_checked(100, 16, 0, 0x4200) == 100)) @panic("stale pays nothing even if finite"); + if (!(settle_checked(100, 16, 1, 0x4200) == 116)) __t27_assert_fail("\n fresh finite GF16 pays 16:\n settle_checked(100, 16, 1, 0x4200) = {any}\n", .{ settle_checked(100, 16, 1, 0x4200) }); + if (!(settle_checked(100, 16, 1, 0x7E01) == 100)) __t27_assert_fail("\n fresh NaN pays nothing:\n settle_checked(100, 16, 1, 0x7E01) = {any}\n", .{ settle_checked(100, 16, 1, 0x7E01) }); + if (!(settle_checked(100, 16, 1, 0x7E00) == 100)) __t27_assert_fail("\n fresh inf pays nothing:\n settle_checked(100, 16, 1, 0x7E00) = {any}\n", .{ settle_checked(100, 16, 1, 0x7E00) }); + if (!(settle_checked(100, 16, 0, 0x4200) == 100)) __t27_assert_fail("\n stale pays nothing even if finite:\n settle_checked(100, 16, 0, 0x4200) = {any}\n", .{ settle_checked(100, 16, 0, 0x4200) }); } test "settle_checked_gf_per_format" { - if (!(settle_checked_gf(100, 16, 1, 0x4200, 6, 9) == 116)) @panic("GF16 fresh finite pays"); - if (!(settle_checked_gf(100, 16, 1, 0x7E00, 6, 9) == 100)) @panic("GF16 inf pays nothing"); - if (!(settle_checked_gf(100, 8, 1, 0x20, 3, 4) == 108)) @panic("GF8 fresh finite pays width 8"); - if (!(settle_checked_gf(100, 8, 1, 0x70, 3, 4) == 100)) @panic("GF8 inf (exp=7) pays nothing"); - if (!(settle_checked_gf(100, 8, 0, 0x20, 3, 4) == 100)) @panic("stale GF8 pays nothing"); + if (!(settle_checked_gf(100, 16, 1, 0x4200, 6, 9) == 116)) __t27_assert_fail("\n GF16 fresh finite pays:\n settle_checked_gf(100, 16, 1, 0x4200, 6, 9) = {any}\n", .{ settle_checked_gf(100, 16, 1, 0x4200, 6, 9) }); + if (!(settle_checked_gf(100, 16, 1, 0x7E00, 6, 9) == 100)) __t27_assert_fail("\n GF16 inf pays nothing:\n settle_checked_gf(100, 16, 1, 0x7E00, 6, 9) = {any}\n", .{ settle_checked_gf(100, 16, 1, 0x7E00, 6, 9) }); + if (!(settle_checked_gf(100, 8, 1, 0x20, 3, 4) == 108)) __t27_assert_fail("\n GF8 fresh finite pays width 8:\n settle_checked_gf(100, 8, 1, 0x20, 3, 4) = {any}\n", .{ settle_checked_gf(100, 8, 1, 0x20, 3, 4) }); + if (!(settle_checked_gf(100, 8, 1, 0x70, 3, 4) == 100)) __t27_assert_fail("\n GF8 inf (exp=7) pays nothing:\n settle_checked_gf(100, 8, 1, 0x70, 3, 4) = {any}\n", .{ settle_checked_gf(100, 8, 1, 0x70, 3, 4) }); + if (!(settle_checked_gf(100, 8, 0, 0x20, 3, 4) == 100)) __t27_assert_fail("\n stale GF8 pays nothing:\n settle_checked_gf(100, 8, 0, 0x20, 3, 4) = {any}\n", .{ settle_checked_gf(100, 8, 0, 0x20, 3, 4) }); } test "settle_gft_offset" { - if (!(settle_checked_gft(100, 16, 1, 40, 80) == 116)) @panic("GF-T16 finite (offset 40) pays"); - if (!(settle_checked_gft(100, 16, 1, 80, 80) == 100)) @panic("GF-T16 special (offset 80) pays nothing"); - if (!(settle_checked_gft(100, 16, 0, 40, 80) == 100)) @panic("stale GF-T16 pays nothing"); - if (!(settle_checked_gft(100, 16, 1, 79, 80) == 116)) @panic("GF-T16 boundary (offset 79, just below the special row) pays"); - if (!(settle_checked_gft(100, 16, 1, 100, 80) == 100)) @panic("GF-T16 OUT-OF-RANGE offset (100 > 80) pays nothing -- garbage-pay hole closed"); + if (!(settle_checked_gft(100, 16, 1, 40, 80) == 116)) __t27_assert_fail("\n GF-T16 finite (offset 40) pays:\n settle_checked_gft(100, 16, 1, 40, 80) = {any}\n", .{ settle_checked_gft(100, 16, 1, 40, 80) }); + if (!(settle_checked_gft(100, 16, 1, 80, 80) == 100)) __t27_assert_fail("\n GF-T16 special (offset 80) pays nothing:\n settle_checked_gft(100, 16, 1, 80, 80) = {any}\n", .{ settle_checked_gft(100, 16, 1, 80, 80) }); + if (!(settle_checked_gft(100, 16, 0, 40, 80) == 100)) __t27_assert_fail("\n stale GF-T16 pays nothing:\n settle_checked_gft(100, 16, 0, 40, 80) = {any}\n", .{ settle_checked_gft(100, 16, 0, 40, 80) }); + if (!(settle_checked_gft(100, 16, 1, 79, 80) == 116)) __t27_assert_fail("\n GF-T16 boundary (offset 79, just below the special row) pays:\n settle_checked_gft(100, 16, 1, 79, 80) = {any}\n", .{ settle_checked_gft(100, 16, 1, 79, 80) }); + if (!(settle_checked_gft(100, 16, 1, 100, 80) == 100)) __t27_assert_fail("\n GF-T16 OUT-OF-RANGE offset (100 > 80) pays nothing -- garbage-pay hole closed:\n settle_checked_gft(100, 16, 1, 100, 80) = {any}\n", .{ settle_checked_gft(100, 16, 1, 100, 80) }); } test "settle_gft_width_derived_offset_max" { - if (!(gft_offset_max_w(8) == 26)) @panic("width 8 -> GF-T8 special row 26"); - if (!(gft_offset_max_w(16) == 80)) @panic("width 16 -> GF-T16 special row 80"); - if (!(settle_checked_gft_w(100, 16, 1, 40) == 116)) @panic("GF-T16 finite pays, width-derived ceiling"); - if (!(settle_checked_gft_w(100, 16, 1, 80) == 100)) @panic("GF-T16 special row withholds"); - if (!(settle_checked_gft_w(100, 16, 1, 100) == 100)) @panic("GF-T16 out-of-range withholds"); - if (!(settle_checked_gft_w(100, 8, 1, 25) == 108)) @panic("GF-T8 finite (offset 25) pays"); - if (!(settle_checked_gft_w(100, 8, 1, 26) == 100)) @panic("GF-T8 special row (26) withholds"); - if (!(settle_checked_gft_w(100, 8, 1, 40) == 100)) @panic("an offset valid for GF-T16 is out of range for GF-T8 -> withholds"); - if (!(gft_offset_max_w(32) == 728)) @panic("width 32 -> GF-T32 special row 728 (Et6, not 242)"); - if (!(settle_checked_gft_w(100, 32, 1, 500) == 132)) @panic("GF-T32 offset 500 (in (242,728]) is finite and PAYS -- the fix"); - if (!(settle_checked_gft_w(100, 32, 1, 727) == 132)) @panic("GF-T32 offset 727 finite pays"); - if (!(settle_checked_gft_w(100, 32, 1, 728) == 100)) @panic("GF-T32 special row 728 withholds"); - if (!(settle_checked_gft_w(100, 7, 1, 5) == 100)) @panic("off-ladder width -> fail-closed, nothing settles"); + if (!(gft_offset_max_w(8) == 26)) __t27_assert_fail("\n width 8 -> GF-T8 special row 26:\n gft_offset_max_w(8) = {any}\n", .{ gft_offset_max_w(8) }); + if (!(gft_offset_max_w(16) == 80)) __t27_assert_fail("\n width 16 -> GF-T16 special row 80:\n gft_offset_max_w(16) = {any}\n", .{ gft_offset_max_w(16) }); + if (!(settle_checked_gft_w(100, 16, 1, 40) == 116)) __t27_assert_fail("\n GF-T16 finite pays, width-derived ceiling:\n settle_checked_gft_w(100, 16, 1, 40) = {any}\n", .{ settle_checked_gft_w(100, 16, 1, 40) }); + if (!(settle_checked_gft_w(100, 16, 1, 80) == 100)) __t27_assert_fail("\n GF-T16 special row withholds:\n settle_checked_gft_w(100, 16, 1, 80) = {any}\n", .{ settle_checked_gft_w(100, 16, 1, 80) }); + if (!(settle_checked_gft_w(100, 16, 1, 100) == 100)) __t27_assert_fail("\n GF-T16 out-of-range withholds:\n settle_checked_gft_w(100, 16, 1, 100) = {any}\n", .{ settle_checked_gft_w(100, 16, 1, 100) }); + if (!(settle_checked_gft_w(100, 8, 1, 25) == 108)) __t27_assert_fail("\n GF-T8 finite (offset 25) pays:\n settle_checked_gft_w(100, 8, 1, 25) = {any}\n", .{ settle_checked_gft_w(100, 8, 1, 25) }); + if (!(settle_checked_gft_w(100, 8, 1, 26) == 100)) __t27_assert_fail("\n GF-T8 special row (26) withholds:\n settle_checked_gft_w(100, 8, 1, 26) = {any}\n", .{ settle_checked_gft_w(100, 8, 1, 26) }); + if (!(settle_checked_gft_w(100, 8, 1, 40) == 100)) __t27_assert_fail("\n an offset valid for GF-T16 is out of range for GF-T8 -> withholds:\n settle_checked_gft_w(100, 8, 1, 40) = {any}\n", .{ settle_checked_gft_w(100, 8, 1, 40) }); + if (!(gft_offset_max_w(32) == 728)) __t27_assert_fail("\n width 32 -> GF-T32 special row 728 (Et6, not 242):\n gft_offset_max_w(32) = {any}\n", .{ gft_offset_max_w(32) }); + if (!(settle_checked_gft_w(100, 32, 1, 500) == 132)) __t27_assert_fail("\n GF-T32 offset 500 (in (242,728]) is finite and PAYS -- the fix:\n settle_checked_gft_w(100, 32, 1, 500) = {any}\n", .{ settle_checked_gft_w(100, 32, 1, 500) }); + if (!(settle_checked_gft_w(100, 32, 1, 727) == 132)) __t27_assert_fail("\n GF-T32 offset 727 finite pays:\n settle_checked_gft_w(100, 32, 1, 727) = {any}\n", .{ settle_checked_gft_w(100, 32, 1, 727) }); + if (!(settle_checked_gft_w(100, 32, 1, 728) == 100)) __t27_assert_fail("\n GF-T32 special row 728 withholds:\n settle_checked_gft_w(100, 32, 1, 728) = {any}\n", .{ settle_checked_gft_w(100, 32, 1, 728) }); + if (!(settle_checked_gft_w(100, 7, 1, 5) == 100)) __t27_assert_fail("\n off-ladder width -> fail-closed, nothing settles:\n settle_checked_gft_w(100, 7, 1, 5) = {any}\n", .{ settle_checked_gft_w(100, 7, 1, 5) }); } test "settle_gft64_gft128_new_rungs" { - if (!(gft_offset_max_w(64) == 19682)) @panic("width 64 -> GF-T64 special row 19682"); - if (!(gft_offset_max_w(128) == 4782968)) @panic("width 128 -> GF-T128 special row 4782968"); - if (!(settle_checked_gft_w(100, 64, 1, 9841) == 164)) @panic("GF-T64 unity offset 9841 finite -> pays 64"); - if (!(settle_checked_gft_w(100, 64, 1, 19681) == 164)) @panic("GF-T64 offset just below the row pays"); - if (!(settle_checked_gft_w(100, 64, 1, 19682) == 100)) @panic("GF-T64 special row 19682 withholds"); - if (!(settle_checked_gft_w(100, 64, 1, 19683) == 100)) @panic("GF-T64 out-of-range withholds"); - if (!(settle_checked_gft_w(100, 128, 1, 100) == 228)) @panic("GF-T128 finite -> pays 128"); - if (!(settle_checked_gft_w(100, 128, 1, 4782968) == 100)) @panic("GF-T128 special row withholds"); - if (!(settle_checked_gft_w(100, 32, 1, 15000) == 100)) @panic("a GF-T64-range offset is out of range for GF-T32"); + if (!(gft_offset_max_w(64) == 19682)) __t27_assert_fail("\n width 64 -> GF-T64 special row 19682:\n gft_offset_max_w(64) = {any}\n", .{ gft_offset_max_w(64) }); + if (!(gft_offset_max_w(128) == 4782968)) __t27_assert_fail("\n width 128 -> GF-T128 special row 4782968:\n gft_offset_max_w(128) = {any}\n", .{ gft_offset_max_w(128) }); + if (!(settle_checked_gft_w(100, 64, 1, 9841) == 164)) __t27_assert_fail("\n GF-T64 unity offset 9841 finite -> pays 64:\n settle_checked_gft_w(100, 64, 1, 9841) = {any}\n", .{ settle_checked_gft_w(100, 64, 1, 9841) }); + if (!(settle_checked_gft_w(100, 64, 1, 19681) == 164)) __t27_assert_fail("\n GF-T64 offset just below the row pays:\n settle_checked_gft_w(100, 64, 1, 19681) = {any}\n", .{ settle_checked_gft_w(100, 64, 1, 19681) }); + if (!(settle_checked_gft_w(100, 64, 1, 19682) == 100)) __t27_assert_fail("\n GF-T64 special row 19682 withholds:\n settle_checked_gft_w(100, 64, 1, 19682) = {any}\n", .{ settle_checked_gft_w(100, 64, 1, 19682) }); + if (!(settle_checked_gft_w(100, 64, 1, 19683) == 100)) __t27_assert_fail("\n GF-T64 out-of-range withholds:\n settle_checked_gft_w(100, 64, 1, 19683) = {any}\n", .{ settle_checked_gft_w(100, 64, 1, 19683) }); + if (!(settle_checked_gft_w(100, 128, 1, 100) == 228)) __t27_assert_fail("\n GF-T128 finite -> pays 128:\n settle_checked_gft_w(100, 128, 1, 100) = {any}\n", .{ settle_checked_gft_w(100, 128, 1, 100) }); + if (!(settle_checked_gft_w(100, 128, 1, 4782968) == 100)) __t27_assert_fail("\n GF-T128 special row withholds:\n settle_checked_gft_w(100, 128, 1, 4782968) = {any}\n", .{ settle_checked_gft_w(100, 128, 1, 4782968) }); + if (!(settle_checked_gft_w(100, 32, 1, 15000) == 100)) __t27_assert_fail("\n a GF-T64-range offset is out of range for GF-T32:\n settle_checked_gft_w(100, 32, 1, 15000) = {any}\n", .{ settle_checked_gft_w(100, 32, 1, 15000) }); } test "settle_full_gate" { - if (!(settle_full(100, 16, 1, 0x4200, 6, 9, 0) == 116)) @panic("fresh finite new -> pays"); - if (!(settle_full(100, 16, 1, 0x4200, 6, 9, 1) == 100)) @panic("already settled -> no double pay"); - if (!(settle_full(100, 16, 1, 0x7E00, 6, 9, 0) == 100)) @panic("inf -> pays nothing"); - if (!(settle_full(100, 16, 0, 0x4200, 6, 9, 0) == 100)) @panic("stale -> pays nothing"); + if (!(settle_full(100, 16, 1, 0x4200, 6, 9, 0) == 116)) __t27_assert_fail("\n fresh finite new -> pays:\n settle_full(100, 16, 1, 0x4200, 6, 9, 0) = {any}\n", .{ settle_full(100, 16, 1, 0x4200, 6, 9, 0) }); + if (!(settle_full(100, 16, 1, 0x4200, 6, 9, 1) == 100)) __t27_assert_fail("\n already settled -> no double pay:\n settle_full(100, 16, 1, 0x4200, 6, 9, 1) = {any}\n", .{ settle_full(100, 16, 1, 0x4200, 6, 9, 1) }); + if (!(settle_full(100, 16, 1, 0x7E00, 6, 9, 0) == 100)) __t27_assert_fail("\n inf -> pays nothing:\n settle_full(100, 16, 1, 0x7E00, 6, 9, 0) = {any}\n", .{ settle_full(100, 16, 1, 0x7E00, 6, 9, 0) }); + if (!(settle_full(100, 16, 0, 0x4200, 6, 9, 0) == 100)) __t27_assert_fail("\n stale -> pays nothing:\n settle_full(100, 16, 0, 0x4200, 6, 9, 0) = {any}\n", .{ settle_full(100, 16, 0, 0x4200, 6, 9, 0) }); } test "settle_full_h_gate" { - if (!(settle_full_h(100, 16, 1, 0x7E00, 6, 9, 1, 0) == 100)) @panic("GF16 inf -> pays 0"); - if (!(settle_full_h(100, 16, 1, 0x4200, 6, 9, 1, 0) == 116)) @panic("GF16 finite pays"); - if (!(settle_full_h(100, 8, 1, 0x70, 3, 4, 0, 0) == 108)) @panic("GF8 max-exp is normal -> pays"); - if (!(settle_full_h(100, 16, 1, 0x4200, 6, 9, 1, 1) == 100)) @panic("already settled -> no double pay"); + if (!(settle_full_h(100, 16, 1, 0x7E00, 6, 9, 1, 0) == 100)) __t27_assert_fail("\n GF16 inf -> pays 0:\n settle_full_h(100, 16, 1, 0x7E00, 6, 9, 1, 0) = {any}\n", .{ settle_full_h(100, 16, 1, 0x7E00, 6, 9, 1, 0) }); + if (!(settle_full_h(100, 16, 1, 0x4200, 6, 9, 1, 0) == 116)) __t27_assert_fail("\n GF16 finite pays:\n settle_full_h(100, 16, 1, 0x4200, 6, 9, 1, 0) = {any}\n", .{ settle_full_h(100, 16, 1, 0x4200, 6, 9, 1, 0) }); + if (!(settle_full_h(100, 8, 1, 0x70, 3, 4, 0, 0) == 108)) __t27_assert_fail("\n GF8 max-exp is normal -> pays:\n settle_full_h(100, 8, 1, 0x70, 3, 4, 0, 0) = {any}\n", .{ settle_full_h(100, 8, 1, 0x70, 3, 4, 0, 0) }); + if (!(settle_full_h(100, 16, 1, 0x4200, 6, 9, 1, 1) == 100)) __t27_assert_fail("\n already settled -> no double pay:\n settle_full_h(100, 16, 1, 0x4200, 6, 9, 1, 1) = {any}\n", .{ settle_full_h(100, 16, 1, 0x4200, 6, 9, 1, 1) }); } test "signed_gate" { - if (!(settle_signed(1000, 16, 1, 0x4100, 6, 9, 0, 1) == 1016)) @panic("valid sig + fresh + finite settles the reward"); - if (!(settle_signed(1000, 16, 1, 0x4100, 6, 9, 0, 0) == 1000)) @panic("no valid sig -> no payout even if fresh+finite"); - if (!(settle_signed(1000, 16, 0, 0x4100, 6, 9, 0, 1) == 1000)) @panic("valid sig does not bypass freshness"); - if (!(settle_signed(1000, 16, 1, 0x7E00, 6, 9, 0, 1) == 1000)) @panic("valid sig does not bypass the finiteness gate"); + if (!(settle_signed(1000, 16, 1, 0x4100, 6, 9, 0, 1) == 1016)) __t27_assert_fail("\n valid sig + fresh + finite settles the reward:\n settle_signed(1000, 16, 1, 0x4100, 6, 9, 0, 1) = {any}\n", .{ settle_signed(1000, 16, 1, 0x4100, 6, 9, 0, 1) }); + if (!(settle_signed(1000, 16, 1, 0x4100, 6, 9, 0, 0) == 1000)) __t27_assert_fail("\n no valid sig -> no payout even if fresh+finite:\n settle_signed(1000, 16, 1, 0x4100, 6, 9, 0, 0) = {any}\n", .{ settle_signed(1000, 16, 1, 0x4100, 6, 9, 0, 0) }); + if (!(settle_signed(1000, 16, 0, 0x4100, 6, 9, 0, 1) == 1000)) __t27_assert_fail("\n valid sig does not bypass freshness:\n settle_signed(1000, 16, 0, 0x4100, 6, 9, 0, 1) = {any}\n", .{ settle_signed(1000, 16, 0, 0x4100, 6, 9, 0, 1) }); + if (!(settle_signed(1000, 16, 1, 0x7E00, 6, 9, 0, 1) == 1000)) __t27_assert_fail("\n valid sig does not bypass the finiteness gate:\n settle_signed(1000, 16, 1, 0x7E00, 6, 9, 0, 1) = {any}\n", .{ settle_signed(1000, 16, 1, 0x7E00, 6, 9, 0, 1) }); } test "format_aware_reward" { - if (!(compute_reward_fmt(16, 1, WORK_BPS_UNIT) == 16)) @panic("unit factor == flat compute_reward"); - if (!(compute_reward_fmt(16, 1, WORK_BPS_UNIT) == compute_reward(16, 1))) @panic("identity to the flat schedule"); - if (!(compute_reward_fmt(16, 1, 12500) == 20)) @panic("1.25x factor earns more (16*1.25)"); - if (!(compute_reward_fmt(16, 1, 8000) == 12)) @panic("0.8x factor earns less (16*0.8=12.8 floor 12)"); - if (!(compute_reward_fmt(16, 0, 12500) == 0)) @panic("a stale receipt pays 0 at any factor"); - if (!(compute_reward_fmt(1080, 1, 20000) == 2160)) @panic("max width * 2x: no u32 overflow (u64 widened)"); + if (!(compute_reward_fmt(16, 1, WORK_BPS_UNIT) == 16)) __t27_assert_fail("\n unit factor == flat compute_reward:\n compute_reward_fmt(16, 1, WORK_BPS_UNIT) = {any}\n", .{ compute_reward_fmt(16, 1, WORK_BPS_UNIT) }); + if (!(compute_reward_fmt(16, 1, WORK_BPS_UNIT) == compute_reward(16, 1))) __t27_assert_fail("\n identity to the flat schedule:\n compute_reward_fmt(16, 1, WORK_BPS_UNIT) = {any}\n compute_reward(16, 1) = {any}\n", .{ compute_reward_fmt(16, 1, WORK_BPS_UNIT), compute_reward(16, 1) }); + if (!(compute_reward_fmt(16, 1, 12500) == 20)) __t27_assert_fail("\n 1.25x factor earns more (16*1.25):\n compute_reward_fmt(16, 1, 12500) = {any}\n", .{ compute_reward_fmt(16, 1, 12500) }); + if (!(compute_reward_fmt(16, 1, 8000) == 12)) __t27_assert_fail("\n 0.8x factor earns less (16*0.8=12.8 floor 12):\n compute_reward_fmt(16, 1, 8000) = {any}\n", .{ compute_reward_fmt(16, 1, 8000) }); + if (!(compute_reward_fmt(16, 0, 12500) == 0)) __t27_assert_fail("\n a stale receipt pays 0 at any factor:\n compute_reward_fmt(16, 0, 12500) = {any}\n", .{ compute_reward_fmt(16, 0, 12500) }); + if (!(compute_reward_fmt(1080, 1, 20000) == 2160)) __t27_assert_fail("\n max width * 2x: no u32 overflow (u64 widened):\n compute_reward_fmt(1080, 1, 20000) = {any}\n", .{ compute_reward_fmt(1080, 1, 20000) }); } test "payability_predicate" { - if (!(payable_flag(FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) == 1)) @panic("GF16 finite payable"); - if (!(payable_flag(FMT_GF_BINARY, 0x7E00, 6, 9, 1, 0) == 0)) @panic("GF16 inf not payable"); - if (!(payable_flag(FMT_GF_BINARY, 0x70, 3, 4, 0, 0) == 1)) @panic("GF8 max-exp normal (no inf) payable"); - if (!(payable_flag(FMT_GF_BINARY, 0x70, 3, 4, 1, 0) == 0)) @panic("GF8 max-exp with has_inf not payable"); - if (!(payable_flag(FMT_GFT, 40, 0, 0, 0, 80) == 1)) @panic("GF-T16 offset 40 payable"); - if (!(payable_flag(FMT_GFT, 80, 0, 0, 0, 80) == 0)) @panic("GF-T16 reserved offset 80 not payable"); - if (!(payable_flag(FMT_GFT, 79, 0, 0, 0, 80) == 1)) @panic("GF-T16 offset 79 (boundary) payable"); - if (!(payable_flag(FMT_GFT, 100, 0, 0, 0, 80) == 0)) @panic("GF-T16 out-of-range offset 100 NOT payable (was a garbage-pay hole)"); - if (!(payable_flag(FMT_GFT, 4294967295, 0, 0, 0, 80) == 0)) @panic("GF-T16 max-u32 garbage offset not payable"); + if (!(payable_flag(FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) == 1)) __t27_assert_fail("\n GF16 finite payable:\n payable_flag(FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) = {any}\n", .{ payable_flag(FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) }); + if (!(payable_flag(FMT_GF_BINARY, 0x7E00, 6, 9, 1, 0) == 0)) __t27_assert_fail("\n GF16 inf not payable:\n payable_flag(FMT_GF_BINARY, 0x7E00, 6, 9, 1, 0) = {any}\n", .{ payable_flag(FMT_GF_BINARY, 0x7E00, 6, 9, 1, 0) }); + if (!(payable_flag(FMT_GF_BINARY, 0x70, 3, 4, 0, 0) == 1)) __t27_assert_fail("\n GF8 max-exp normal (no inf) payable:\n payable_flag(FMT_GF_BINARY, 0x70, 3, 4, 0, 0) = {any}\n", .{ payable_flag(FMT_GF_BINARY, 0x70, 3, 4, 0, 0) }); + if (!(payable_flag(FMT_GF_BINARY, 0x70, 3, 4, 1, 0) == 0)) __t27_assert_fail("\n GF8 max-exp with has_inf not payable:\n payable_flag(FMT_GF_BINARY, 0x70, 3, 4, 1, 0) = {any}\n", .{ payable_flag(FMT_GF_BINARY, 0x70, 3, 4, 1, 0) }); + if (!(payable_flag(FMT_GFT, 40, 0, 0, 0, 80) == 1)) __t27_assert_fail("\n GF-T16 offset 40 payable:\n payable_flag(FMT_GFT, 40, 0, 0, 0, 80) = {any}\n", .{ payable_flag(FMT_GFT, 40, 0, 0, 0, 80) }); + if (!(payable_flag(FMT_GFT, 80, 0, 0, 0, 80) == 0)) __t27_assert_fail("\n GF-T16 reserved offset 80 not payable:\n payable_flag(FMT_GFT, 80, 0, 0, 0, 80) = {any}\n", .{ payable_flag(FMT_GFT, 80, 0, 0, 0, 80) }); + if (!(payable_flag(FMT_GFT, 79, 0, 0, 0, 80) == 1)) __t27_assert_fail("\n GF-T16 offset 79 (boundary) payable:\n payable_flag(FMT_GFT, 79, 0, 0, 0, 80) = {any}\n", .{ payable_flag(FMT_GFT, 79, 0, 0, 0, 80) }); + if (!(payable_flag(FMT_GFT, 100, 0, 0, 0, 80) == 0)) __t27_assert_fail("\n GF-T16 out-of-range offset 100 NOT payable (was a garbage-pay hole):\n payable_flag(FMT_GFT, 100, 0, 0, 0, 80) = {any}\n", .{ payable_flag(FMT_GFT, 100, 0, 0, 0, 80) }); + if (!(payable_flag(FMT_GFT, 4294967295, 0, 0, 0, 80) == 0)) __t27_assert_fail("\n GF-T16 max-u32 garbage offset not payable:\n payable_flag(FMT_GFT, 4294967295, 0, 0, 0, 80) = {any}\n", .{ payable_flag(FMT_GFT, 4294967295, 0, 0, 0, 80) }); } test "canonical_all_gates" { - if (!(settle_canonical(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) == 116)) @panic("all gates pass -> pays"); - if (!(settle_canonical(100, 16, 0, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) == 100)) @panic("no sig -> pays 0"); - if (!(settle_canonical(100, 16, 1, 1, 1, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) == 100)) @panic("already settled -> no double pay"); - if (!(settle_canonical(100, 16, 1, 0, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) == 100)) @panic("stale -> pays 0"); - if (!(settle_canonical(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x7E00, 6, 9, 1, 0) == 100)) @panic("GF16 inf -> pays 0"); - if (!(settle_canonical(100, 8, 1, 1, 0, FMT_GF_BINARY, 0x70, 3, 4, 0, 0) == 108)) @panic("GF8 no-inf max-exp -> pays width 8"); - if (!(settle_canonical(100, 16, 1, 1, 0, FMT_GFT, 40, 0, 0, 0, 80) == 116)) @panic("GF-T16 finite -> pays"); - if (!(settle_canonical(100, 16, 1, 1, 0, FMT_GFT, 80, 0, 0, 0, 80) == 100)) @panic("GF-T16 reserved offset -> pays 0"); + if (!(settle_canonical(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) == 116)) __t27_assert_fail("\n all gates pass -> pays:\n settle_canonical(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) = {any}\n", .{ settle_canonical(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) }); + if (!(settle_canonical(100, 16, 0, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) == 100)) __t27_assert_fail("\n no sig -> pays 0:\n settle_canonical(100, 16, 0, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) = {any}\n", .{ settle_canonical(100, 16, 0, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) }); + if (!(settle_canonical(100, 16, 1, 1, 1, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) == 100)) __t27_assert_fail("\n already settled -> no double pay:\n settle_canonical(100, 16, 1, 1, 1, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) = {any}\n", .{ settle_canonical(100, 16, 1, 1, 1, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) }); + if (!(settle_canonical(100, 16, 1, 0, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) == 100)) __t27_assert_fail("\n stale -> pays 0:\n settle_canonical(100, 16, 1, 0, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) = {any}\n", .{ settle_canonical(100, 16, 1, 0, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) }); + if (!(settle_canonical(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x7E00, 6, 9, 1, 0) == 100)) __t27_assert_fail("\n GF16 inf -> pays 0:\n settle_canonical(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x7E00, 6, 9, 1, 0) = {any}\n", .{ settle_canonical(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x7E00, 6, 9, 1, 0) }); + if (!(settle_canonical(100, 8, 1, 1, 0, FMT_GF_BINARY, 0x70, 3, 4, 0, 0) == 108)) __t27_assert_fail("\n GF8 no-inf max-exp -> pays width 8:\n settle_canonical(100, 8, 1, 1, 0, FMT_GF_BINARY, 0x70, 3, 4, 0, 0) = {any}\n", .{ settle_canonical(100, 8, 1, 1, 0, FMT_GF_BINARY, 0x70, 3, 4, 0, 0) }); + if (!(settle_canonical(100, 16, 1, 1, 0, FMT_GFT, 40, 0, 0, 0, 80) == 116)) __t27_assert_fail("\n GF-T16 finite -> pays:\n settle_canonical(100, 16, 1, 1, 0, FMT_GFT, 40, 0, 0, 0, 80) = {any}\n", .{ settle_canonical(100, 16, 1, 1, 0, FMT_GFT, 40, 0, 0, 0, 80) }); + if (!(settle_canonical(100, 16, 1, 1, 0, FMT_GFT, 80, 0, 0, 0, 80) == 100)) __t27_assert_fail("\n GF-T16 reserved offset -> pays 0:\n settle_canonical(100, 16, 1, 1, 0, FMT_GFT, 80, 0, 0, 0, 80) = {any}\n", .{ settle_canonical(100, 16, 1, 1, 0, FMT_GFT, 80, 0, 0, 0, 80) }); } test "canonical_fmt_scales_reward" { - if (!(settle_canonical_fmt(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, WORK_BPS_UNIT) == 116)) @panic("unit factor == settle_canonical"); - if (!(settle_canonical_fmt(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, WORK_BPS_UNIT) == settle_canonical(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0))) @panic("identity to the flat path"); - if (!(settle_canonical_fmt(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, 12500) == 120)) @panic("1.25x factor credits 20 (100+16*1.25)"); - if (!(settle_canonical_fmt(100, 16, 0, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, 12500) == 100)) @panic("no sig -> pays 0 at any factor"); - if (!(settle_canonical_fmt(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x7E00, 6, 9, 1, 0, 12500) == 100)) @panic("inf -> pays 0 at any factor"); - if (!(settle_canonical_fmt(100, 16, 1, 1, 1, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, 12500) == 100)) @panic("already settled -> no double pay at any factor"); + if (!(settle_canonical_fmt(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, WORK_BPS_UNIT) == 116)) __t27_assert_fail("\n unit factor == settle_canonical:\n settle_canonical_fmt(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, WORK_BPS_UNIT) = {any}\n", .{ settle_canonical_fmt(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, WORK_BPS_UNIT) }); + if (!(settle_canonical_fmt(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, WORK_BPS_UNIT) == settle_canonical(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0))) __t27_assert_fail("\n identity to the flat path:\n settle_canonical_fmt(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, WORK_BPS_UNIT) = {any}\n settle_canonical(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) = {any}\n", .{ settle_canonical_fmt(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, WORK_BPS_UNIT), settle_canonical(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0) }); + if (!(settle_canonical_fmt(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, 12500) == 120)) __t27_assert_fail("\n 1.25x factor credits 20 (100+16*1.25):\n settle_canonical_fmt(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, 12500) = {any}\n", .{ settle_canonical_fmt(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, 12500) }); + if (!(settle_canonical_fmt(100, 16, 0, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, 12500) == 100)) __t27_assert_fail("\n no sig -> pays 0 at any factor:\n settle_canonical_fmt(100, 16, 0, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, 12500) = {any}\n", .{ settle_canonical_fmt(100, 16, 0, 1, 0, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, 12500) }); + if (!(settle_canonical_fmt(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x7E00, 6, 9, 1, 0, 12500) == 100)) __t27_assert_fail("\n inf -> pays 0 at any factor:\n settle_canonical_fmt(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x7E00, 6, 9, 1, 0, 12500) = {any}\n", .{ settle_canonical_fmt(100, 16, 1, 1, 0, FMT_GF_BINARY, 0x7E00, 6, 9, 1, 0, 12500) }); + if (!(settle_canonical_fmt(100, 16, 1, 1, 1, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, 12500) == 100)) __t27_assert_fail("\n already settled -> no double pay at any factor:\n settle_canonical_fmt(100, 16, 1, 1, 1, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, 12500) = {any}\n", .{ settle_canonical_fmt(100, 16, 1, 1, 1, FMT_GF_BINARY, 0x4200, 6, 9, 1, 0, 12500) }); } diff --git a/gen/zig/tri_depin.zig b/gen/zig/tri_depin.zig index bb8a39c4..abed2715 100644 --- a/gen/zig/tri_depin.zig +++ b/gen/zig/tri_depin.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const TRI_GENESIS: u32 = 0x54524921; @@ -53,40 +61,40 @@ fn bytes_add_verified(total: u32, nbytes: u32, computed_digest: u32, expected_di test "absorb_reproducible" { const a1 = relay_absorb(relay_absorb(TRI_GENESIS, 0xAAAA0001, 70), 0xBBBB0002, 140); const a2 = relay_absorb(relay_absorb(TRI_GENESIS, 0xAAAA0001, 70), 0xBBBB0002, 140); - if (!(a1 == a2)) @panic("reproducible"); + if (!(a1 == a2)) __t27_assert_fail("\n reproducible:\n a1 = {any}\n a2 = {any}\n", .{ a1, a2 }); } test "absorb_tamper_evident" { const good = relay_absorb(relay_absorb(TRI_GENESIS, 0xAAAA0001, 70), 0xBBBB0002, 140); const bad = relay_absorb(relay_absorb(TRI_GENESIS, 0xAAAA0009, 70), 0xBBBB0002, 140); - if (!(good != bad)) @panic("tamper changes acc"); + if (!(good != bad)) __t27_assert_fail("\n tamper changes acc:\n good = {any}\n bad = {any}\n", .{ good, bad }); } test "absorb_order_sensitive" { const ab = relay_absorb(relay_absorb(TRI_GENESIS, 0xAAAA0001, 70), 0xBBBB0002, 140); const ba = relay_absorb(relay_absorb(TRI_GENESIS, 0xBBBB0002, 140), 0xAAAA0001, 70); - if (!(ab != ba)) @panic("order matters"); + if (!(ab != ba)) __t27_assert_fail("\n order matters:\n ab = {any}\n ba = {any}\n", .{ ab, ba }); } test "absorb_size_bound" { const small_acc = relay_absorb(TRI_GENESIS, 0xAAAA0001, 70); const big = relay_absorb(TRI_GENESIS, 0xAAAA0001, 1200); - if (!(small_acc != big)) @panic("bytes bound in acc"); + if (!(small_acc != big)) __t27_assert_fail("\n bytes bound in acc:\n small_acc = {any}\n big = {any}\n", .{ small_acc, big }); } test "seal_identity_bound" { const acc = relay_absorb(TRI_GENESIS, 0xAAAA0001, 70); const sealA = epoch_seal(acc, 70, 0x1111AAAA, 42); const sealB = epoch_seal(acc, 70, 0x2222BBBB, 42); - if (!(sealA != sealB)) @panic("identity bound"); + if (!(sealA != sealB)) __t27_assert_fail("\n identity bound:\n sealA = {any}\n sealB = {any}\n", .{ sealA, sealB }); } test "seal_epoch_bound" { const acc = relay_absorb(TRI_GENESIS, 0xAAAA0001, 70); const s1 = epoch_seal(acc, 70, 0x1111AAAA, 42); const s2 = epoch_seal(acc, 70, 0x1111AAAA, 43); - if (!(s1 != s2)) @panic("epoch bound"); + if (!(s1 != s2)) __t27_assert_fail("\n epoch bound:\n s1 = {any}\n s2 = {any}\n", .{ s1, s2 }); } test "seal_total_bytes_bound" { const acc = relay_absorb(TRI_GENESIS, 0xAAAA0001, 70); const honest = epoch_seal(acc, 70, 0xCAFEF00D, 7); const inflated = epoch_seal(acc, 700000, 0xCAFEF00D, 7); - if (!(honest != inflated)) @panic("total_bytes bound"); + if (!(honest != inflated)) __t27_assert_fail("\n total_bytes bound:\n honest = {any}\n inflated = {any}\n", .{ honest, inflated }); } test "verify_accepts_honest" { const acc = relay_absorb(relay_absorb(TRI_GENESIS, 0x11110001, 70), 0x22220002, 90); @@ -101,59 +109,59 @@ test "verify_rejects_history_forgery" { const s = epoch_seal(acc, tot, 0xCAFEF00D, 7); const forged = relay_absorb(acc, 0x33330003, 90); const ok = verify_epoch(s, forged, tot, 0xCAFEF00D, 7); - if (!(ok == false)) @panic("rejects history forgery"); + if (!(ok == false)) __t27_assert_fail("\n rejects history forgery:\n ok = {any}\n", .{ ok }); } test "verify_rejects_byte_inflation" { const acc = relay_absorb(relay_absorb(TRI_GENESIS, 0x11110001, 70), 0x22220002, 90); const tot = bytes_add(bytes_add(0, 70), 90); const s = epoch_seal(acc, tot, 0xCAFEF00D, 7); const ok = verify_epoch(s, acc, 1600000, 0xCAFEF00D, 7); - if (!(ok == false)) @panic("rejects byte inflation"); + if (!(ok == false)) __t27_assert_fail("\n rejects byte inflation:\n ok = {any}\n", .{ ok }); } test "seal_no_free_mint" { const empty = epoch_seal(TRI_GENESIS, 0, 0xCAFEF00D, 7); const one = epoch_seal(relay_absorb(TRI_GENESIS, 0xAAAA0001, 70), 70, 0xCAFEF00D, 7); - if (!(empty != one)) @panic("no free mint"); + if (!(empty != one)) __t27_assert_fail("\n no free mint:\n empty = {any}\n one = {any}\n", .{ empty, one }); } test "bytes_monotonic" { const t0 = bytes_add(0, 70); const t1 = bytes_add(t0, 140); - if (!(t1 > t0)) @panic("monotonic"); - if (!(t0 == 70)) @panic("sum ok"); - if (!(t1 == 210)) @panic("sum ok 2"); + if (!(t1 > t0)) __t27_assert_fail("\n monotonic:\n t1 = {any}\n t0 = {any}\n", .{ t1, t0 }); + if (!(t0 == 70)) __t27_assert_fail("\n sum ok:\n t0 = {any}\n", .{ t0 }); + if (!(t1 == 210)) __t27_assert_fail("\n sum ok 2:\n t1 = {any}\n", .{ t1 }); } test "bytes_saturate" { const cap = bytes_add(0xFFFFFF00, 0x0000FFFF); - if (!(cap == 0xFFFFFFFF)) @panic("saturates"); + if (!(cap == 0xFFFFFFFF)) __t27_assert_fail("\n saturates:\n cap = {any}\n", .{ cap }); } test "mix_avalanche" { const m0 = mix32(0x00000000); const m1 = mix32(0x00000001); - if (!(m0 != m1)) @panic("one-bit input differs"); - if (!(mix32(0x80000000) != mix32(0x00000000))) @panic("high bit differs"); + if (!(m0 != m1)) __t27_assert_fail("\n one-bit input differs:\n m0 = {any}\n m1 = {any}\n", .{ m0, m1 }); + if (!(mix32(0x80000000) != mix32(0x00000000))) __t27_assert_fail("\n high bit differs:\n mix32(0x80000000) = {any}\n mix32(0x00000000) = {any}\n", .{ mix32(0x80000000), mix32(0x00000000) }); } test "verified_accepts_intact" { const clean = relay_absorb_verified(TRI_GENESIS, 0xABCD1234, 0xABCD1234, 200); const plain = relay_absorb(TRI_GENESIS, 0xABCD1234, 200); - if (!(clean == plain)) @panic("intact datagram metered normally"); - if (!(clean != TRI_GENESIS)) @panic("accumulator advanced"); + if (!(clean == plain)) __t27_assert_fail("\n intact datagram metered normally:\n clean = {any}\n plain = {any}\n", .{ clean, plain }); + if (!(clean != TRI_GENESIS)) __t27_assert_fail("\n accumulator advanced:\n clean = {any}\n TRI_GENESIS = {any}\n", .{ clean, TRI_GENESIS }); } test "verified_drops_corrupt" { const acc = relay_absorb_verified(TRI_GENESIS, 0xDEADBEEF, 0xABCD1234, 200); const tot = bytes_add_verified(0, 200, 0xDEADBEEF, 0xABCD1234); - if (!(acc == TRI_GENESIS)) @panic("corrupt datagram dropped from acc"); - if (!(tot == 0)) @panic("corrupt datagram not counted"); + if (!(acc == TRI_GENESIS)) __t27_assert_fail("\n corrupt datagram dropped from acc:\n acc = {any}\n TRI_GENESIS = {any}\n", .{ acc, TRI_GENESIS }); + if (!(tot == 0)) __t27_assert_fail("\n corrupt datagram not counted:\n tot = {any}\n", .{ tot }); } test "verified_lossy_equals_clean_subset" { const subset = relay_absorb(relay_absorb(TRI_GENESIS, 0x11110001, 70), 0x33330003, 90); const s1 = relay_absorb_verified(TRI_GENESIS, 0x11110001, 0x11110001, 70); const s2 = relay_absorb_verified(s1, 0x22220002, 0x2222FFFF, 80); const s3 = relay_absorb_verified(s2, 0x33330003, 0x33330003, 90); - if (!(s3 == subset)) @panic("lossy stream == clean subset"); + if (!(s3 == subset)) __t27_assert_fail("\n lossy stream == clean subset:\n s3 = {any}\n subset = {any}\n", .{ s3, subset }); } test "verified_bytes_only_clean" { const b1 = bytes_add_verified(0, 70, 0x11110001, 0x11110001); const b2 = bytes_add_verified(b1, 80, 0x22220002, 0x2222FFFF); const b3 = bytes_add_verified(b2, 90, 0x33330003, 0x33330003); - if (!(b3 == 160)) @panic("only 70+90 counted, corrupted 80 excluded"); + if (!(b3 == 160)) __t27_assert_fail("\n only 70+90 counted, corrupted 80 excluded:\n b3 = {any}\n", .{ b3 }); } diff --git a/gen/zig/tri_fec.zig b/gen/zig/tri_fec.zig index 62c8728e..5ee15c2b 100644 --- a/gen/zig/tri_fec.zig +++ b/gen/zig/tri_fec.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module fn fec_parity4(a: u32, b: u32, c: u32, d: u32) u32 { @@ -17,25 +25,25 @@ fn fec_recover(parity: u32, survivors_xor: u32) u32 { test "recover_position_a" { const p = fec_parity4(0x11111111, 0x22222222, 0x33333333, 0x44444444); const surv = fec_xor(fec_xor(0x22222222, 0x33333333), 0x44444444); - if (!(fec_recover(p, surv) == 0x11111111)) @panic("recovered a"); + if (!(fec_recover(p, surv) == 0x11111111)) __t27_assert_fail("\n recovered a:\n fec_recover(p, surv) = {any}\n", .{ fec_recover(p, surv) }); } test "recover_position_c" { const p = fec_parity4(0x0A0A0A0A, 0x0B0B0B0B, 0x0C0C0C0C, 0x0D0D0D0D); const surv = fec_xor(fec_xor(0x0A0A0A0A, 0x0B0B0B0B), 0x0D0D0D0D); - if (!(fec_recover(p, surv) == 0x0C0C0C0C)) @panic("recovered c"); + if (!(fec_recover(p, surv) == 0x0C0C0C0C)) __t27_assert_fail("\n recovered c:\n fec_recover(p, surv) = {any}\n", .{ fec_recover(p, surv) }); } test "group_check_is_zero" { const p = fec_parity4(0xDEADBEEF, 0x0BADF00D, 0xFEEDFACE, 0x8BADF00D); const allxor = fec_xor(fec_xor(fec_xor(fec_xor(0xDEADBEEF, 0x0BADF00D), 0xFEEDFACE), 0x8BADF00D), p); - if (!(allxor == 0)) @panic("data XOR parity == 0"); + if (!(allxor == 0)) __t27_assert_fail("\n data XOR parity == 0:\n allxor = {any}\n", .{ allxor }); } test "bad_survivors_wrong_recovery" { const p = fec_parity4(0x11111111, 0x22222222, 0x33333333, 0x44444444); const surv_bad = fec_xor(fec_xor(0x22222222, 0x33333333), 0x40404040); - if (!(fec_recover(p, surv_bad) != 0x11111111)) @panic("bad survivors -> bad recovery"); + if (!(fec_recover(p, surv_bad) != 0x11111111)) __t27_assert_fail("\n bad survivors -> bad recovery:\n fec_recover(p, surv_bad) = {any}\n", .{ fec_recover(p, surv_bad) }); } test "recover_roundtrip" { const p = fec_parity4(1, 2, 4, 8); const surv = fec_xor(fec_xor(1, 2), 4); - if (!(fec_recover(p, surv) == 8)) @panic("roundtrip d=8"); + if (!(fec_recover(p, surv) == 8)) __t27_assert_fail("\n roundtrip d=8:\n fec_recover(p, surv) = {any}\n", .{ fec_recover(p, surv) }); } diff --git a/gen/zig/tri_gft_add.zig b/gen/zig/tri_gft_add.zig index 786a7331..0a651b0c 100644 --- a/gen/zig/tri_gft_add.zig +++ b/gen/zig/tri_gft_add.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MANT_ONE: u32 = 512; @@ -117,52 +125,52 @@ fn gft_dot4_mant_p(o0: u32, m0: u32, o1: u32, m1: u32, o2: u32, m2: u32, o3: u32 return gft_add_mant_c_p(s01o, s23o, s01m, s23m, mant_one, sig_bits); } test "add_doubles" { - if (!(gft_add_offset_c(40, 40, 0, 0, 80) == 41)) @panic("1.0 + 1.0 = 2.0 -> exponent 41"); - if (!(gft_add_mant_c(40, 40, 0, 0) == 0)) @panic("2.0 mantissa 0"); - if (!(gft_add_offset_c(40, 40, 256, 256, 80) == 41)) @panic("1.5 + 1.5 = 3.0 -> exponent 41"); - if (!(gft_add_mant_c(40, 40, 256, 256) == 256)) @panic("3.0 = 1.5 * 2^1 -> mantissa 256"); + if (!(gft_add_offset_c(40, 40, 0, 0, 80) == 41)) __t27_assert_fail("\n 1.0 + 1.0 = 2.0 -> exponent 41:\n gft_add_offset_c(40, 40, 0, 0, 80) = {any}\n", .{ gft_add_offset_c(40, 40, 0, 0, 80) }); + if (!(gft_add_mant_c(40, 40, 0, 0) == 0)) __t27_assert_fail("\n 2.0 mantissa 0:\n gft_add_mant_c(40, 40, 0, 0) = {any}\n", .{ gft_add_mant_c(40, 40, 0, 0) }); + if (!(gft_add_offset_c(40, 40, 256, 256, 80) == 41)) __t27_assert_fail("\n 1.5 + 1.5 = 3.0 -> exponent 41:\n gft_add_offset_c(40, 40, 256, 256, 80) = {any}\n", .{ gft_add_offset_c(40, 40, 256, 256, 80) }); + if (!(gft_add_mant_c(40, 40, 256, 256) == 256)) __t27_assert_fail("\n 3.0 = 1.5 * 2^1 -> mantissa 256:\n gft_add_mant_c(40, 40, 256, 256) = {any}\n", .{ gft_add_mant_c(40, 40, 256, 256) }); } test "add_aligns" { - if (!(gft_add_offset_c(40, 39, 0, 0, 80) == 40)) @panic("1.0 + 0.5 = 1.5 -> exponent 40"); - if (!(gft_add_mant_c(40, 39, 0, 0) == 256)) @panic("1.5 -> mantissa 256"); - if (!(gft_add_offset_c(39, 40, 0, 0, 80) == 40)) @panic("0.5 + 1.0 == 1.0 + 0.5 (offset)"); - if (!(gft_add_mant_c(39, 40, 0, 0) == 256)) @panic("0.5 + 1.0 == 1.0 + 0.5 (mant)"); + if (!(gft_add_offset_c(40, 39, 0, 0, 80) == 40)) __t27_assert_fail("\n 1.0 + 0.5 = 1.5 -> exponent 40:\n gft_add_offset_c(40, 39, 0, 0, 80) = {any}\n", .{ gft_add_offset_c(40, 39, 0, 0, 80) }); + if (!(gft_add_mant_c(40, 39, 0, 0) == 256)) __t27_assert_fail("\n 1.5 -> mantissa 256:\n gft_add_mant_c(40, 39, 0, 0) = {any}\n", .{ gft_add_mant_c(40, 39, 0, 0) }); + if (!(gft_add_offset_c(39, 40, 0, 0, 80) == 40)) __t27_assert_fail("\n 0.5 + 1.0 == 1.0 + 0.5 (offset):\n gft_add_offset_c(39, 40, 0, 0, 80) = {any}\n", .{ gft_add_offset_c(39, 40, 0, 0, 80) }); + if (!(gft_add_mant_c(39, 40, 0, 0) == 256)) __t27_assert_fail("\n 0.5 + 1.0 == 1.0 + 0.5 (mant):\n gft_add_mant_c(39, 40, 0, 0) = {any}\n", .{ gft_add_mant_c(39, 40, 0, 0) }); } test "add_absorbs_small" { - if (!(gft_add_offset_c(60, 40, 100, 200, 80) == 60)) @panic("big + tiny keeps big's exponent"); - if (!(gft_add_mant_c(60, 40, 100, 200) == 100)) @panic("big + tiny keeps big's mantissa"); + if (!(gft_add_offset_c(60, 40, 100, 200, 80) == 60)) __t27_assert_fail("\n big + tiny keeps big's exponent:\n gft_add_offset_c(60, 40, 100, 200, 80) = {any}\n", .{ gft_add_offset_c(60, 40, 100, 200, 80) }); + if (!(gft_add_mant_c(60, 40, 100, 200) == 100)) __t27_assert_fail("\n big + tiny keeps big's mantissa:\n gft_add_mant_c(60, 40, 100, 200) = {any}\n", .{ gft_add_mant_c(60, 40, 100, 200) }); } test "verify_catches_add_fraud" { - if (!(verify_gft_add(40, 40, 0, 0, 41, 0, 80) == true)) @panic("honest 1.0+1.0=2.0 accepted"); - if (!(verify_gft_add(40, 40, 0, 0, 40, 0, 80) == false)) @panic("wrong exponent (missed carry) rejected"); - if (!(verify_gft_add(40, 39, 0, 0, 40, 255, 80) == false)) @panic("wrong mantissa rejected"); + if (!(verify_gft_add(40, 40, 0, 0, 41, 0, 80) == true)) __t27_assert_fail("\n honest 1.0+1.0=2.0 accepted:\n verify_gft_add(40, 40, 0, 0, 41, 0, 80) = {any}\n", .{ verify_gft_add(40, 40, 0, 0, 41, 0, 80) }); + if (!(verify_gft_add(40, 40, 0, 0, 40, 0, 80) == false)) __t27_assert_fail("\n wrong exponent (missed carry) rejected:\n verify_gft_add(40, 40, 0, 0, 40, 0, 80) = {any}\n", .{ verify_gft_add(40, 40, 0, 0, 40, 0, 80) }); + if (!(verify_gft_add(40, 39, 0, 0, 40, 255, 80) == false)) __t27_assert_fail("\n wrong mantissa rejected:\n verify_gft_add(40, 39, 0, 0, 40, 255, 80) = {any}\n", .{ verify_gft_add(40, 39, 0, 0, 40, 255, 80) }); } test "per_rung_add" { - if (!(gft_add_offset_p(40, 40, 0, 0, 80, 512, 10) == 41)) @panic("GF-T16 1.0+1.0=2.0 -> offset 41"); - if (!(gft_add_mant_p(40, 40, 0, 0, 512, 10) == 0)) @panic("GF-T16 2.0 mantissa 0"); - if (!(verify_gft_add_p(13, 13, 0, 0, 14, 0, 26, 16, 5) == true)) @panic("GF-T8 1.0+1.0 = exp 14, mant 0"); - if (!(verify_gft_add_p(13, 12, 0, 0, 13, 8, 26, 16, 5) == true)) @panic("GF-T8 1.0+0.5 = 1.5 (M 8), exp 13"); - if (!(verify_gft_add_p(13, 13, 0, 0, 13, 0, 26, 16, 5) == false)) @panic("GF-T8 missed carry rejected"); - if (!(verify_gft_add_p(4, 4, 0, 0, 5, 0, 8, 2, 2) == true)) @panic("GF-T4 1.0+1.0 = exp 5, mant 0"); + if (!(gft_add_offset_p(40, 40, 0, 0, 80, 512, 10) == 41)) __t27_assert_fail("\n GF-T16 1.0+1.0=2.0 -> offset 41:\n gft_add_offset_p(40, 40, 0, 0, 80, 512, 10) = {any}\n", .{ gft_add_offset_p(40, 40, 0, 0, 80, 512, 10) }); + if (!(gft_add_mant_p(40, 40, 0, 0, 512, 10) == 0)) __t27_assert_fail("\n GF-T16 2.0 mantissa 0:\n gft_add_mant_p(40, 40, 0, 0, 512, 10) = {any}\n", .{ gft_add_mant_p(40, 40, 0, 0, 512, 10) }); + if (!(verify_gft_add_p(13, 13, 0, 0, 14, 0, 26, 16, 5) == true)) __t27_assert_fail("\n GF-T8 1.0+1.0 = exp 14, mant 0:\n verify_gft_add_p(13, 13, 0, 0, 14, 0, 26, 16, 5) = {any}\n", .{ verify_gft_add_p(13, 13, 0, 0, 14, 0, 26, 16, 5) }); + if (!(verify_gft_add_p(13, 12, 0, 0, 13, 8, 26, 16, 5) == true)) __t27_assert_fail("\n GF-T8 1.0+0.5 = 1.5 (M 8), exp 13:\n verify_gft_add_p(13, 12, 0, 0, 13, 8, 26, 16, 5) = {any}\n", .{ verify_gft_add_p(13, 12, 0, 0, 13, 8, 26, 16, 5) }); + if (!(verify_gft_add_p(13, 13, 0, 0, 13, 0, 26, 16, 5) == false)) __t27_assert_fail("\n GF-T8 missed carry rejected:\n verify_gft_add_p(13, 13, 0, 0, 13, 0, 26, 16, 5) = {any}\n", .{ verify_gft_add_p(13, 13, 0, 0, 13, 0, 26, 16, 5) }); + if (!(verify_gft_add_p(4, 4, 0, 0, 5, 0, 8, 2, 2) == true)) __t27_assert_fail("\n GF-T4 1.0+1.0 = exp 5, mant 0:\n verify_gft_add_p(4, 4, 0, 0, 5, 0, 8, 2, 2) = {any}\n", .{ verify_gft_add_p(4, 4, 0, 0, 5, 0, 8, 2, 2) }); } test "gft32_add" { - if (!(verify_gft_add_p(364, 364, 0, 0, 365, 0, 728, 33554432, 26) == true)) @panic("GF-T32 1.0+1.0 = 2.0 -> offset 365"); - if (!(gft_add_mant_c_p(364, 364, 0, 0, 33554432, 26) == 0)) @panic("GF-T32 2.0 mantissa 0"); - if (!(verify_gft_add_p(364, 364, 0, 0, 364, 0, 728, 33554432, 26) == false)) @panic("GF-T32 missed carry rejected"); + if (!(verify_gft_add_p(364, 364, 0, 0, 365, 0, 728, 33554432, 26) == true)) __t27_assert_fail("\n GF-T32 1.0+1.0 = 2.0 -> offset 365:\n verify_gft_add_p(364, 364, 0, 0, 365, 0, 728, 33554432, 26) = {any}\n", .{ verify_gft_add_p(364, 364, 0, 0, 365, 0, 728, 33554432, 26) }); + if (!(gft_add_mant_c_p(364, 364, 0, 0, 33554432, 26) == 0)) __t27_assert_fail("\n GF-T32 2.0 mantissa 0:\n gft_add_mant_c_p(364, 364, 0, 0, 33554432, 26) = {any}\n", .{ gft_add_mant_c_p(364, 364, 0, 0, 33554432, 26) }); + if (!(verify_gft_add_p(364, 364, 0, 0, 364, 0, 728, 33554432, 26) == false)) __t27_assert_fail("\n GF-T32 missed carry rejected:\n verify_gft_add_p(364, 364, 0, 0, 364, 0, 728, 33554432, 26) = {any}\n", .{ verify_gft_add_p(364, 364, 0, 0, 364, 0, 728, 33554432, 26) }); } test "dot4_uses_the_canonical_tree_order" { - if (!(gft_dot4_offset(40, 64, 45, 0, 46, 256, 40, 64, 80) == 47)) @panic("tree dot4 offset 47"); - if (!(gft_dot4_mant(40, 64, 45, 0, 46, 256, 40, 64, 80) == 9)) @panic("tree dot4 mantissa 9 (the left fold's 8 is wrong)"); - if (!(gft_dot4_offset(40, 0, 40, 0, 40, 0, 40, 0, 80) == 42)) @panic("4 x 1.0 = 4.0 -> offset 42"); - if (!(gft_dot4_mant(40, 0, 40, 0, 40, 0, 40, 0, 80) == 0)) @panic("4.0 mantissa 0"); + if (!(gft_dot4_offset(40, 64, 45, 0, 46, 256, 40, 64, 80) == 47)) __t27_assert_fail("\n tree dot4 offset 47:\n gft_dot4_offset(40, 64, 45, 0, 46, 256, 40, 64, 80) = {any}\n", .{ gft_dot4_offset(40, 64, 45, 0, 46, 256, 40, 64, 80) }); + if (!(gft_dot4_mant(40, 64, 45, 0, 46, 256, 40, 64, 80) == 9)) __t27_assert_fail("\n tree dot4 mantissa 9 (the left fold's 8 is wrong):\n gft_dot4_mant(40, 64, 45, 0, 46, 256, 40, 64, 80) = {any}\n", .{ gft_dot4_mant(40, 64, 45, 0, 46, 256, 40, 64, 80) }); + if (!(gft_dot4_offset(40, 0, 40, 0, 40, 0, 40, 0, 80) == 42)) __t27_assert_fail("\n 4 x 1.0 = 4.0 -> offset 42:\n gft_dot4_offset(40, 0, 40, 0, 40, 0, 40, 0, 80) = {any}\n", .{ gft_dot4_offset(40, 0, 40, 0, 40, 0, 40, 0, 80) }); + if (!(gft_dot4_mant(40, 0, 40, 0, 40, 0, 40, 0, 80) == 0)) __t27_assert_fail("\n 4.0 mantissa 0:\n gft_dot4_mant(40, 0, 40, 0, 40, 0, 40, 0, 80) = {any}\n", .{ gft_dot4_mant(40, 0, 40, 0, 40, 0, 40, 0, 80) }); } test "dot4_p_canonical_tree_per_rung" { - if (!(gft_dot4_offset_p(40, 64, 45, 0, 46, 256, 40, 64, 80, 512, 10) == 47)) @panic("GF-T16 _p tree offset 47"); - if (!(gft_dot4_mant_p(40, 64, 45, 0, 46, 256, 40, 64, 80, 512, 10) == 9)) @panic("GF-T16 _p tree mantissa 9"); - if (!(gft_dot4_offset_p(13, 0, 13, 0, 13, 0, 13, 0, 26, 16, 5) == 15)) @panic("GF-T8 4 x 1.0 = 4.0 -> offset 15"); - if (!(gft_dot4_mant_p(13, 0, 13, 0, 13, 0, 13, 0, 26, 16, 5) == 0)) @panic("GF-T8 4.0 mantissa 0"); - if (!(gft_dot4_offset_p(364, 0, 364, 0, 364, 0, 364, 0, 728, 33554432, 26) == 366)) @panic("GF-T32 4 x 1.0 = 4.0 -> offset 366"); - if (!(gft_dot4_mant_p(364, 0, 364, 0, 364, 0, 364, 0, 728, 33554432, 26) == 0)) @panic("GF-T32 4.0 mantissa 0"); + if (!(gft_dot4_offset_p(40, 64, 45, 0, 46, 256, 40, 64, 80, 512, 10) == 47)) __t27_assert_fail("\n GF-T16 _p tree offset 47:\n gft_dot4_offset_p(40, 64, 45, 0, 46, 256, 40, 64, 80, 512, 10) = {any}\n", .{ gft_dot4_offset_p(40, 64, 45, 0, 46, 256, 40, 64, 80, 512, 10) }); + if (!(gft_dot4_mant_p(40, 64, 45, 0, 46, 256, 40, 64, 80, 512, 10) == 9)) __t27_assert_fail("\n GF-T16 _p tree mantissa 9:\n gft_dot4_mant_p(40, 64, 45, 0, 46, 256, 40, 64, 80, 512, 10) = {any}\n", .{ gft_dot4_mant_p(40, 64, 45, 0, 46, 256, 40, 64, 80, 512, 10) }); + if (!(gft_dot4_offset_p(13, 0, 13, 0, 13, 0, 13, 0, 26, 16, 5) == 15)) __t27_assert_fail("\n GF-T8 4 x 1.0 = 4.0 -> offset 15:\n gft_dot4_offset_p(13, 0, 13, 0, 13, 0, 13, 0, 26, 16, 5) = {any}\n", .{ gft_dot4_offset_p(13, 0, 13, 0, 13, 0, 13, 0, 26, 16, 5) }); + if (!(gft_dot4_mant_p(13, 0, 13, 0, 13, 0, 13, 0, 26, 16, 5) == 0)) __t27_assert_fail("\n GF-T8 4.0 mantissa 0:\n gft_dot4_mant_p(13, 0, 13, 0, 13, 0, 13, 0, 26, 16, 5) = {any}\n", .{ gft_dot4_mant_p(13, 0, 13, 0, 13, 0, 13, 0, 26, 16, 5) }); + if (!(gft_dot4_offset_p(364, 0, 364, 0, 364, 0, 364, 0, 728, 33554432, 26) == 366)) __t27_assert_fail("\n GF-T32 4 x 1.0 = 4.0 -> offset 366:\n gft_dot4_offset_p(364, 0, 364, 0, 364, 0, 364, 0, 728, 33554432, 26) = {any}\n", .{ gft_dot4_offset_p(364, 0, 364, 0, 364, 0, 364, 0, 728, 33554432, 26) }); + if (!(gft_dot4_mant_p(364, 0, 364, 0, 364, 0, 364, 0, 728, 33554432, 26) == 0)) __t27_assert_fail("\n GF-T32 4.0 mantissa 0:\n gft_dot4_mant_p(364, 0, 364, 0, 364, 0, 364, 0, 728, 33554432, 26) = {any}\n", .{ gft_dot4_mant_p(364, 0, 364, 0, 364, 0, 364, 0, 728, 33554432, 26) }); } fn bench_add_mantissa_sweep() void { // bench: add_mantissa_sweep @@ -183,21 +191,21 @@ fn bench_add_mantissa_sweep() void { const m13 = gft_add_mant(40, 40, 416, 224); const m14 = gft_add_mant(40, 40, 448, 320); const m15 = gft_add_mant(40, 40, 480, 416); - if (!(m0 == 0)) @panic("1.0+1.0 -> mantissa 0 with carry"); - if (!(o0 == 41)) @panic("1.0+1.0 -> offset 41"); - if (!(m1 == 64)) @panic("sweep step 1: (32+96)/2"); - if (!(m2 == 128)) @panic("sweep step 2: (64+192)/2"); - if (!(m3 == 192)) @panic("sweep step 3: (96+288)/2"); - if (!(m4 == 256)) @panic("sweep step 4: (128+384)/2"); - if (!(m5 == 320)) @panic("sweep step 5: (160+480)/2"); - if (!(m6 == 128)) @panic("sweep step 6: (192+64)/2"); - if (!(m7 == 192)) @panic("sweep step 7: (224+160)/2"); - if (!(m8 == 256)) @panic("sweep step 8: (256+256)/2"); - if (!(m9 == 320)) @panic("sweep step 9: (288+352)/2"); - if (!(m10 == 384)) @panic("sweep step 10: (320+448)/2"); - if (!(m11 == 192)) @panic("sweep step 11: (352+32)/2"); - if (!(m12 == 256)) @panic("sweep step 12: (384+128)/2"); - if (!(m13 == 320)) @panic("sweep step 13: (416+224)/2"); - if (!(m14 == 384)) @panic("sweep step 14: (448+320)/2"); - if (!(m15 == 448)) @panic("sweep step 15: (480+416)/2"); + if (!(m0 == 0)) __t27_assert_fail("\n 1.0+1.0 -> mantissa 0 with carry:\n m0 = {any}\n", .{ m0 }); + if (!(o0 == 41)) __t27_assert_fail("\n 1.0+1.0 -> offset 41:\n o0 = {any}\n", .{ o0 }); + if (!(m1 == 64)) __t27_assert_fail("\n sweep step 1: (32+96)/2:\n m1 = {any}\n", .{ m1 }); + if (!(m2 == 128)) __t27_assert_fail("\n sweep step 2: (64+192)/2:\n m2 = {any}\n", .{ m2 }); + if (!(m3 == 192)) __t27_assert_fail("\n sweep step 3: (96+288)/2:\n m3 = {any}\n", .{ m3 }); + if (!(m4 == 256)) __t27_assert_fail("\n sweep step 4: (128+384)/2:\n m4 = {any}\n", .{ m4 }); + if (!(m5 == 320)) __t27_assert_fail("\n sweep step 5: (160+480)/2:\n m5 = {any}\n", .{ m5 }); + if (!(m6 == 128)) __t27_assert_fail("\n sweep step 6: (192+64)/2:\n m6 = {any}\n", .{ m6 }); + if (!(m7 == 192)) __t27_assert_fail("\n sweep step 7: (224+160)/2:\n m7 = {any}\n", .{ m7 }); + if (!(m8 == 256)) __t27_assert_fail("\n sweep step 8: (256+256)/2:\n m8 = {any}\n", .{ m8 }); + if (!(m9 == 320)) __t27_assert_fail("\n sweep step 9: (288+352)/2:\n m9 = {any}\n", .{ m9 }); + if (!(m10 == 384)) __t27_assert_fail("\n sweep step 10: (320+448)/2:\n m10 = {any}\n", .{ m10 }); + if (!(m11 == 192)) __t27_assert_fail("\n sweep step 11: (352+32)/2:\n m11 = {any}\n", .{ m11 }); + if (!(m12 == 256)) __t27_assert_fail("\n sweep step 12: (384+128)/2:\n m12 = {any}\n", .{ m12 }); + if (!(m13 == 320)) __t27_assert_fail("\n sweep step 13: (416+224)/2:\n m13 = {any}\n", .{ m13 }); + if (!(m14 == 384)) __t27_assert_fail("\n sweep step 14: (448+320)/2:\n m14 = {any}\n", .{ m14 }); + if (!(m15 == 448)) __t27_assert_fail("\n sweep step 15: (480+416)/2:\n m15 = {any}\n", .{ m15 }); } diff --git a/gen/zig/tri_gft_arith.zig b/gen/zig/tri_gft_arith.zig index bbe97c87..f8f938df 100644 --- a/gen/zig/tri_gft_arith.zig +++ b/gen/zig/tri_gft_arith.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const GFT16_BIAS: u32 = 40; @@ -124,70 +132,70 @@ fn gft_mul_result(offset_a: u32, ma: u32, offset_b: u32, mb: u32, bias: u32, off return gft_result_encode(gft_mul_offset_full(offset_a, ma, offset_b, mb, bias, offset_max), gft_mul_mant(ma, mb)); } test "mul_exponent_law" { - if (!(gft_mul_offset(40, 40, GFT16_BIAS, GFT16_OFFSET_MAX) == 40)) @panic("unity * unity = unity (offset 40)"); - if (!(gft_mul_offset(41, 41, GFT16_BIAS, GFT16_OFFSET_MAX) == 42)) @panic("phi^1 * phi^1 = phi^2"); - if (!(gft_mul_offset(50, 60, GFT16_BIAS, GFT16_OFFSET_MAX) == 70)) @panic("phi^10 * phi^20 = phi^30"); - if (!(gft_mul_offset(40, 55, GFT16_BIAS, GFT16_OFFSET_MAX) == 55)) @panic("unity * x = x"); + if (!(gft_mul_offset(40, 40, GFT16_BIAS, GFT16_OFFSET_MAX) == 40)) __t27_assert_fail("\n unity * unity = unity (offset 40):\n gft_mul_offset(40, 40, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n", .{ gft_mul_offset(40, 40, GFT16_BIAS, GFT16_OFFSET_MAX) }); + if (!(gft_mul_offset(41, 41, GFT16_BIAS, GFT16_OFFSET_MAX) == 42)) __t27_assert_fail("\n phi^1 * phi^1 = phi^2:\n gft_mul_offset(41, 41, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n", .{ gft_mul_offset(41, 41, GFT16_BIAS, GFT16_OFFSET_MAX) }); + if (!(gft_mul_offset(50, 60, GFT16_BIAS, GFT16_OFFSET_MAX) == 70)) __t27_assert_fail("\n phi^10 * phi^20 = phi^30:\n gft_mul_offset(50, 60, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n", .{ gft_mul_offset(50, 60, GFT16_BIAS, GFT16_OFFSET_MAX) }); + if (!(gft_mul_offset(40, 55, GFT16_BIAS, GFT16_OFFSET_MAX) == 55)) __t27_assert_fail("\n unity * x = x:\n gft_mul_offset(40, 55, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n", .{ gft_mul_offset(40, 55, GFT16_BIAS, GFT16_OFFSET_MAX) }); } test "mul_saturation" { - if (!(gft_mul_offset(79, 79, GFT16_BIAS, GFT16_OFFSET_MAX) == 80)) @panic("big * big overflows to the inf row"); - if (!(gft_mul_offset(70, 60, GFT16_BIAS, GFT16_OFFSET_MAX) == 80)) @panic("90 >= offset_max -> inf"); - if (!(gft_mul_offset(10, 10, GFT16_BIAS, GFT16_OFFSET_MAX) == 0)) @panic("tiny * tiny underflows to offset 0"); - if (!(gft_mul_offset(0, 0, GFT16_BIAS, GFT16_OFFSET_MAX) == 0)) @panic("min * min = min"); + if (!(gft_mul_offset(79, 79, GFT16_BIAS, GFT16_OFFSET_MAX) == 80)) __t27_assert_fail("\n big * big overflows to the inf row:\n gft_mul_offset(79, 79, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n", .{ gft_mul_offset(79, 79, GFT16_BIAS, GFT16_OFFSET_MAX) }); + if (!(gft_mul_offset(70, 60, GFT16_BIAS, GFT16_OFFSET_MAX) == 80)) __t27_assert_fail("\n 90 >= offset_max -> inf:\n gft_mul_offset(70, 60, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n", .{ gft_mul_offset(70, 60, GFT16_BIAS, GFT16_OFFSET_MAX) }); + if (!(gft_mul_offset(10, 10, GFT16_BIAS, GFT16_OFFSET_MAX) == 0)) __t27_assert_fail("\n tiny * tiny underflows to offset 0:\n gft_mul_offset(10, 10, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n", .{ gft_mul_offset(10, 10, GFT16_BIAS, GFT16_OFFSET_MAX) }); + if (!(gft_mul_offset(0, 0, GFT16_BIAS, GFT16_OFFSET_MAX) == 0)) __t27_assert_fail("\n min * min = min:\n gft_mul_offset(0, 0, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n", .{ gft_mul_offset(0, 0, GFT16_BIAS, GFT16_OFFSET_MAX) }); } test "verify_catches_fraud" { - if (!(verify_gft_mul_offset(41, 41, 42, GFT16_BIAS, GFT16_OFFSET_MAX) == true)) @panic("honest phi^2 accepted"); - if (!(verify_gft_mul_offset(41, 41, 43, GFT16_BIAS, GFT16_OFFSET_MAX) == false)) @panic("wrong product exponent rejected"); - if (!(verify_gft_mul_offset(50, 60, 71, GFT16_BIAS, GFT16_OFFSET_MAX) == false)) @panic("off-by-one exponent rejected"); + if (!(verify_gft_mul_offset(41, 41, 42, GFT16_BIAS, GFT16_OFFSET_MAX) == true)) __t27_assert_fail("\n honest phi^2 accepted:\n verify_gft_mul_offset(41, 41, 42, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n", .{ verify_gft_mul_offset(41, 41, 42, GFT16_BIAS, GFT16_OFFSET_MAX) }); + if (!(verify_gft_mul_offset(41, 41, 43, GFT16_BIAS, GFT16_OFFSET_MAX) == false)) __t27_assert_fail("\n wrong product exponent rejected:\n verify_gft_mul_offset(41, 41, 43, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n", .{ verify_gft_mul_offset(41, 41, 43, GFT16_BIAS, GFT16_OFFSET_MAX) }); + if (!(verify_gft_mul_offset(50, 60, 71, GFT16_BIAS, GFT16_OFFSET_MAX) == false)) __t27_assert_fail("\n off-by-one exponent rejected:\n verify_gft_mul_offset(50, 60, 71, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n", .{ verify_gft_mul_offset(50, 60, 71, GFT16_BIAS, GFT16_OFFSET_MAX) }); } test "sign_law" { - if (!(gft_mul_sign(0, 0) == 0)) @panic("(+)(+) = +"); - if (!(gft_mul_sign(1, 1) == 0)) @panic("(-)(-) = +"); - if (!(gft_mul_sign(0, 1) == 1)) @panic("(+)(-) = -"); + if (!(gft_mul_sign(0, 0) == 0)) __t27_assert_fail("\n (+)(+) = +:\n gft_mul_sign(0, 0) = {any}\n", .{ gft_mul_sign(0, 0) }); + if (!(gft_mul_sign(1, 1) == 0)) __t27_assert_fail("\n (-)(-) = +:\n gft_mul_sign(1, 1) = {any}\n", .{ gft_mul_sign(1, 1) }); + if (!(gft_mul_sign(0, 1) == 1)) __t27_assert_fail("\n (+)(-) = -:\n gft_mul_sign(0, 1) = {any}\n", .{ gft_mul_sign(0, 1) }); } test "mantissa_product" { - if (!(gft_mul_mant_carry(0, 0) == 0)) @panic("1.0 * 1.0 = 1.0, no carry"); - if (!(gft_mul_mant(0, 0) == 0)) @panic("1.0 * 1.0 mantissa 0"); - if (!(gft_mul_mant_carry(0, 256) == 0)) @panic("1.0 * 1.5 = 1.5, no carry"); - if (!(gft_mul_mant(0, 256) == 256)) @panic("1.0 * 1.5 mantissa = 256 (1.5)"); - if (!(gft_mul_mant_carry(256, 256) == 1)) @panic("1.5 * 1.5 = 2.25 carries"); - if (!(gft_mul_mant(256, 256) == 64)) @panic("1.5 * 1.5 -> 1.125 after renorm, mantissa 64"); + if (!(gft_mul_mant_carry(0, 0) == 0)) __t27_assert_fail("\n 1.0 * 1.0 = 1.0, no carry:\n gft_mul_mant_carry(0, 0) = {any}\n", .{ gft_mul_mant_carry(0, 0) }); + if (!(gft_mul_mant(0, 0) == 0)) __t27_assert_fail("\n 1.0 * 1.0 mantissa 0:\n gft_mul_mant(0, 0) = {any}\n", .{ gft_mul_mant(0, 0) }); + if (!(gft_mul_mant_carry(0, 256) == 0)) __t27_assert_fail("\n 1.0 * 1.5 = 1.5, no carry:\n gft_mul_mant_carry(0, 256) = {any}\n", .{ gft_mul_mant_carry(0, 256) }); + if (!(gft_mul_mant(0, 256) == 256)) __t27_assert_fail("\n 1.0 * 1.5 mantissa = 256 (1.5):\n gft_mul_mant(0, 256) = {any}\n", .{ gft_mul_mant(0, 256) }); + if (!(gft_mul_mant_carry(256, 256) == 1)) __t27_assert_fail("\n 1.5 * 1.5 = 2.25 carries:\n gft_mul_mant_carry(256, 256) = {any}\n", .{ gft_mul_mant_carry(256, 256) }); + if (!(gft_mul_mant(256, 256) == 64)) __t27_assert_fail("\n 1.5 * 1.5 -> 1.125 after renorm, mantissa 64:\n gft_mul_mant(256, 256) = {any}\n", .{ gft_mul_mant(256, 256) }); } test "full_exponent_uses_carry" { - if (!(gft_mul_offset_full(41, 0, 41, 0, GFT16_BIAS, GFT16_OFFSET_MAX) == 42)) @panic("no mantissa carry -> exponent 42"); - if (!(gft_mul_offset_full(41, 256, 41, 256, GFT16_BIAS, GFT16_OFFSET_MAX) == 43)) @panic("1.5*1.5 carry -> exponent 43"); + if (!(gft_mul_offset_full(41, 0, 41, 0, GFT16_BIAS, GFT16_OFFSET_MAX) == 42)) __t27_assert_fail("\n no mantissa carry -> exponent 42:\n gft_mul_offset_full(41, 0, 41, 0, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n", .{ gft_mul_offset_full(41, 0, 41, 0, GFT16_BIAS, GFT16_OFFSET_MAX) }); + if (!(gft_mul_offset_full(41, 256, 41, 256, GFT16_BIAS, GFT16_OFFSET_MAX) == 43)) __t27_assert_fail("\n 1.5*1.5 carry -> exponent 43:\n gft_mul_offset_full(41, 256, 41, 256, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n", .{ gft_mul_offset_full(41, 256, 41, 256, GFT16_BIAS, GFT16_OFFSET_MAX) }); } test "full_verify_catches_mantissa" { - if (!(verify_gft_mul_full(40, 0, 40, 256, 40, 256, GFT16_BIAS, GFT16_OFFSET_MAX) == true)) @panic("unity * 1.5 = 1.5 accepted"); - if (!(verify_gft_mul_full(40, 0, 40, 256, 40, 255, GFT16_BIAS, GFT16_OFFSET_MAX) == false)) @panic("wrong result mantissa rejected"); - if (!(verify_gft_mul_full(41, 256, 41, 256, 43, 64, GFT16_BIAS, GFT16_OFFSET_MAX) == true)) @panic("1.5*1.5 -> exp 43, mant 64 accepted"); - if (!(verify_gft_mul_full(41, 256, 41, 256, 42, 64, GFT16_BIAS, GFT16_OFFSET_MAX) == false)) @panic("ignoring the carry (exp 42) rejected"); + if (!(verify_gft_mul_full(40, 0, 40, 256, 40, 256, GFT16_BIAS, GFT16_OFFSET_MAX) == true)) __t27_assert_fail("\n unity * 1.5 = 1.5 accepted:\n verify_gft_mul_full(40, 0, 40, 256, 40, 256, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n", .{ verify_gft_mul_full(40, 0, 40, 256, 40, 256, GFT16_BIAS, GFT16_OFFSET_MAX) }); + if (!(verify_gft_mul_full(40, 0, 40, 256, 40, 255, GFT16_BIAS, GFT16_OFFSET_MAX) == false)) __t27_assert_fail("\n wrong result mantissa rejected:\n verify_gft_mul_full(40, 0, 40, 256, 40, 255, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n", .{ verify_gft_mul_full(40, 0, 40, 256, 40, 255, GFT16_BIAS, GFT16_OFFSET_MAX) }); + if (!(verify_gft_mul_full(41, 256, 41, 256, 43, 64, GFT16_BIAS, GFT16_OFFSET_MAX) == true)) __t27_assert_fail("\n 1.5*1.5 -> exp 43, mant 64 accepted:\n verify_gft_mul_full(41, 256, 41, 256, 43, 64, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n", .{ verify_gft_mul_full(41, 256, 41, 256, 43, 64, GFT16_BIAS, GFT16_OFFSET_MAX) }); + if (!(verify_gft_mul_full(41, 256, 41, 256, 42, 64, GFT16_BIAS, GFT16_OFFSET_MAX) == false)) __t27_assert_fail("\n ignoring the carry (exp 42) rejected:\n verify_gft_mul_full(41, 256, 41, 256, 42, 64, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n", .{ verify_gft_mul_full(41, 256, 41, 256, 42, 64, GFT16_BIAS, GFT16_OFFSET_MAX) }); } test "result_encode" { - if (!(gft_result_encode(42, 0) == (42 << 9))) @panic("encode offset 42, mant 0"); - if (!(gft_mul_result(41, 0, 41, 0, GFT16_BIAS, GFT16_OFFSET_MAX) == gft_result_encode(42, 0))) @panic("phi^1*phi^1 recomputes to encoded (42,0)"); - if (!(gft_mul_result(41, 256, 41, 256, GFT16_BIAS, GFT16_OFFSET_MAX) == gft_result_encode(43, 64))) @panic("1.5*1.5 recomputes to encoded (43,64)"); - if (!(gft_mul_result(41, 0, 41, 0, GFT16_BIAS, GFT16_OFFSET_MAX) != gft_result_encode(43, 0))) @panic("a wrong claimed result differs"); + if (!(gft_result_encode(42, 0) == (42 << 9))) __t27_assert_fail("\n encode offset 42, mant 0:\n gft_result_encode(42, 0) = {any}\n 42 << 9 = {any}\n", .{ gft_result_encode(42, 0), 42 << 9 }); + if (!(gft_mul_result(41, 0, 41, 0, GFT16_BIAS, GFT16_OFFSET_MAX) == gft_result_encode(42, 0))) __t27_assert_fail("\n phi^1*phi^1 recomputes to encoded (42,0):\n gft_mul_result(41, 0, 41, 0, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n gft_result_encode(42, 0) = {any}\n", .{ gft_mul_result(41, 0, 41, 0, GFT16_BIAS, GFT16_OFFSET_MAX), gft_result_encode(42, 0) }); + if (!(gft_mul_result(41, 256, 41, 256, GFT16_BIAS, GFT16_OFFSET_MAX) == gft_result_encode(43, 64))) __t27_assert_fail("\n 1.5*1.5 recomputes to encoded (43,64):\n gft_mul_result(41, 256, 41, 256, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n gft_result_encode(43, 64) = {any}\n", .{ gft_mul_result(41, 256, 41, 256, GFT16_BIAS, GFT16_OFFSET_MAX), gft_result_encode(43, 64) }); + if (!(gft_mul_result(41, 0, 41, 0, GFT16_BIAS, GFT16_OFFSET_MAX) != gft_result_encode(43, 0))) __t27_assert_fail("\n a wrong claimed result differs:\n gft_mul_result(41, 0, 41, 0, GFT16_BIAS, GFT16_OFFSET_MAX) = {any}\n gft_result_encode(43, 0) = {any}\n", .{ gft_mul_result(41, 0, 41, 0, GFT16_BIAS, GFT16_OFFSET_MAX), gft_result_encode(43, 0) }); } test "per_rung_multiply" { - if (!(gft_mul_offset_full_p(40, 0, 40, 0, 40, 80, 512) == 40)) @panic("GF-T16 unity*unity offset 40"); - if (!(gft_mul_offset_full_p(41, 256, 41, 256, 40, 80, 512) == 43)) @panic("GF-T16 1.5*1.5 carry -> 43"); - if (!(gft_mul_mant_p(256, 256, 512) == 64)) @panic("GF-T16 1.5*1.5 mantissa 64"); - if (!(gft_mul_mant_carry_p(8, 8, 16) == 1)) @panic("GF-T8 1.5*1.5 carries"); - if (!(gft_mul_mant_p(8, 8, 16) == 2)) @panic("GF-T8 1.5*1.5 -> mantissa 2"); - if (!(verify_gft_mul_full_p(13, 8, 13, 8, 14, 2, 13, 26, 16) == true)) @panic("GF-T8 1.5*1.5 = exp 14, mant 2"); - if (!(verify_gft_mul_full_p(13, 0, 13, 0, 13, 0, 13, 26, 16) == true)) @panic("GF-T8 unity*unity = exp 13, mant 0"); - if (!(verify_gft_mul_full_p(4, 1, 4, 1, 5, 0, 4, 8, 2) == true)) @panic("GF-T4 1.5*1.5 = exp 5, mant 0"); - if (!(verify_gft_mul_full_p(4, 1, 4, 1, 4, 0, 4, 8, 2) == false)) @panic("GF-T4 wrong exponent rejected"); + if (!(gft_mul_offset_full_p(40, 0, 40, 0, 40, 80, 512) == 40)) __t27_assert_fail("\n GF-T16 unity*unity offset 40:\n gft_mul_offset_full_p(40, 0, 40, 0, 40, 80, 512) = {any}\n", .{ gft_mul_offset_full_p(40, 0, 40, 0, 40, 80, 512) }); + if (!(gft_mul_offset_full_p(41, 256, 41, 256, 40, 80, 512) == 43)) __t27_assert_fail("\n GF-T16 1.5*1.5 carry -> 43:\n gft_mul_offset_full_p(41, 256, 41, 256, 40, 80, 512) = {any}\n", .{ gft_mul_offset_full_p(41, 256, 41, 256, 40, 80, 512) }); + if (!(gft_mul_mant_p(256, 256, 512) == 64)) __t27_assert_fail("\n GF-T16 1.5*1.5 mantissa 64:\n gft_mul_mant_p(256, 256, 512) = {any}\n", .{ gft_mul_mant_p(256, 256, 512) }); + if (!(gft_mul_mant_carry_p(8, 8, 16) == 1)) __t27_assert_fail("\n GF-T8 1.5*1.5 carries:\n gft_mul_mant_carry_p(8, 8, 16) = {any}\n", .{ gft_mul_mant_carry_p(8, 8, 16) }); + if (!(gft_mul_mant_p(8, 8, 16) == 2)) __t27_assert_fail("\n GF-T8 1.5*1.5 -> mantissa 2:\n gft_mul_mant_p(8, 8, 16) = {any}\n", .{ gft_mul_mant_p(8, 8, 16) }); + if (!(verify_gft_mul_full_p(13, 8, 13, 8, 14, 2, 13, 26, 16) == true)) __t27_assert_fail("\n GF-T8 1.5*1.5 = exp 14, mant 2:\n verify_gft_mul_full_p(13, 8, 13, 8, 14, 2, 13, 26, 16) = {any}\n", .{ verify_gft_mul_full_p(13, 8, 13, 8, 14, 2, 13, 26, 16) }); + if (!(verify_gft_mul_full_p(13, 0, 13, 0, 13, 0, 13, 26, 16) == true)) __t27_assert_fail("\n GF-T8 unity*unity = exp 13, mant 0:\n verify_gft_mul_full_p(13, 0, 13, 0, 13, 0, 13, 26, 16) = {any}\n", .{ verify_gft_mul_full_p(13, 0, 13, 0, 13, 0, 13, 26, 16) }); + if (!(verify_gft_mul_full_p(4, 1, 4, 1, 5, 0, 4, 8, 2) == true)) __t27_assert_fail("\n GF-T4 1.5*1.5 = exp 5, mant 0:\n verify_gft_mul_full_p(4, 1, 4, 1, 5, 0, 4, 8, 2) = {any}\n", .{ verify_gft_mul_full_p(4, 1, 4, 1, 5, 0, 4, 8, 2) }); + if (!(verify_gft_mul_full_p(4, 1, 4, 1, 4, 0, 4, 8, 2) == false)) __t27_assert_fail("\n GF-T4 wrong exponent rejected:\n verify_gft_mul_full_p(4, 1, 4, 1, 4, 0, 4, 8, 2) = {any}\n", .{ verify_gft_mul_full_p(4, 1, 4, 1, 4, 0, 4, 8, 2) }); } test "gft32_multiply" { - if (!(gft_mul_mant_carry_u64(0, 0, 33554432) == 0)) @panic("GF-T32 1.0*1.0 no carry"); - if (!(gft_mul_mant_u64(0, 0, 33554432) == 0)) @panic("GF-T32 unity mantissa 0"); - if (!(verify_gft_mul_full_u64(364, 0, 364, 0, 364, 0, 364, 728, 33554432) == true)) @panic("GF-T32 unity*unity = offset 364, mant 0"); - if (!(gft_mul_mant_carry_u64(16777216, 16777216, 33554432) == 1)) @panic("GF-T32 1.5*1.5 carries"); - if (!(gft_mul_mant_u64(16777216, 16777216, 33554432) == 4194304)) @panic("GF-T32 1.5*1.5 -> mantissa 2^22"); - if (!(verify_gft_mul_full_u64(364, 16777216, 364, 16777216, 365, 4194304, 364, 728, 33554432) == true)) @panic("GF-T32 1.5*1.5 = offset 365, mant 2^22"); - if (!(verify_gft_mul_full_u64(364, 16777216, 364, 16777216, 364, 4194304, 364, 728, 33554432) == false)) @panic("GF-T32 missed carry rejected"); + if (!(gft_mul_mant_carry_u64(0, 0, 33554432) == 0)) __t27_assert_fail("\n GF-T32 1.0*1.0 no carry:\n gft_mul_mant_carry_u64(0, 0, 33554432) = {any}\n", .{ gft_mul_mant_carry_u64(0, 0, 33554432) }); + if (!(gft_mul_mant_u64(0, 0, 33554432) == 0)) __t27_assert_fail("\n GF-T32 unity mantissa 0:\n gft_mul_mant_u64(0, 0, 33554432) = {any}\n", .{ gft_mul_mant_u64(0, 0, 33554432) }); + if (!(verify_gft_mul_full_u64(364, 0, 364, 0, 364, 0, 364, 728, 33554432) == true)) __t27_assert_fail("\n GF-T32 unity*unity = offset 364, mant 0:\n verify_gft_mul_full_u64(364, 0, 364, 0, 364, 0, 364, 728, 33554432) = {any}\n", .{ verify_gft_mul_full_u64(364, 0, 364, 0, 364, 0, 364, 728, 33554432) }); + if (!(gft_mul_mant_carry_u64(16777216, 16777216, 33554432) == 1)) __t27_assert_fail("\n GF-T32 1.5*1.5 carries:\n gft_mul_mant_carry_u64(16777216, 16777216, 33554432) = {any}\n", .{ gft_mul_mant_carry_u64(16777216, 16777216, 33554432) }); + if (!(gft_mul_mant_u64(16777216, 16777216, 33554432) == 4194304)) __t27_assert_fail("\n GF-T32 1.5*1.5 -> mantissa 2^22:\n gft_mul_mant_u64(16777216, 16777216, 33554432) = {any}\n", .{ gft_mul_mant_u64(16777216, 16777216, 33554432) }); + if (!(verify_gft_mul_full_u64(364, 16777216, 364, 16777216, 365, 4194304, 364, 728, 33554432) == true)) __t27_assert_fail("\n GF-T32 1.5*1.5 = offset 365, mant 2^22:\n verify_gft_mul_full_u64(364, 16777216, 364, 16777216, 365, 4194304, 364, 728, 33554432) = {any}\n", .{ verify_gft_mul_full_u64(364, 16777216, 364, 16777216, 365, 4194304, 364, 728, 33554432) }); + if (!(verify_gft_mul_full_u64(364, 16777216, 364, 16777216, 364, 4194304, 364, 728, 33554432) == false)) __t27_assert_fail("\n GF-T32 missed carry rejected:\n verify_gft_mul_full_u64(364, 16777216, 364, 16777216, 364, 4194304, 364, 728, 33554432) = {any}\n", .{ verify_gft_mul_full_u64(364, 16777216, 364, 16777216, 364, 4194304, 364, 728, 33554432) }); } fn bench_mul_mantissa_sweep() void { // bench: mul_mantissa_sweep @@ -205,18 +213,18 @@ fn bench_mul_mantissa_sweep() void { const c7 = gft_mul_mant_carry(511, 511); const o0 = gft_mul_offset(44, 44, 40, 80); const of = gft_mul_offset_full(44, 256, 44, 256, 40, 80); - if (!(m0 == 0)) @panic("1.0 * 1.0 mantissa 0"); - if (!(c0 == 0)) @panic("1.0 * 1.0 no carry"); - if (!(m1 == 288)) @panic("1.25^2 = 1.5625 -> mantissa 288"); - if (!(c1 == 0)) @panic("1.25^2 no carry"); - if (!(m2 == 256)) @panic("1.5 * 1.0 = 1.5"); - if (!(m3 == 64)) @panic("1.5^2 = 2.25 -> mantissa 64"); - if (!(c3 == 1)) @panic("1.5^2 carries"); - if (!(m4 == 272)) @panic("1.75^2 = 3.0625 -> mantissa 272"); - if (!(m5 == 28)) @panic("1.875 * 1.125 -> mantissa 28 (carry regime)"); - if (!(m6 == 28)) @panic("multiply is commutative across the carry regime"); - if (!(m7 == 510)) @panic("max mantissa product stays in range"); - if (!(c7 == 1)) @panic("max product carries"); - if (!(o0 == 48)) @panic("offset path: 44 + 44 - bias 40"); - if (!(of == 49)) @panic("full offset includes the mantissa carry"); + if (!(m0 == 0)) __t27_assert_fail("\n 1.0 * 1.0 mantissa 0:\n m0 = {any}\n", .{ m0 }); + if (!(c0 == 0)) __t27_assert_fail("\n 1.0 * 1.0 no carry:\n c0 = {any}\n", .{ c0 }); + if (!(m1 == 288)) __t27_assert_fail("\n 1.25^2 = 1.5625 -> mantissa 288:\n m1 = {any}\n", .{ m1 }); + if (!(c1 == 0)) __t27_assert_fail("\n 1.25^2 no carry:\n c1 = {any}\n", .{ c1 }); + if (!(m2 == 256)) __t27_assert_fail("\n 1.5 * 1.0 = 1.5:\n m2 = {any}\n", .{ m2 }); + if (!(m3 == 64)) __t27_assert_fail("\n 1.5^2 = 2.25 -> mantissa 64:\n m3 = {any}\n", .{ m3 }); + if (!(c3 == 1)) __t27_assert_fail("\n 1.5^2 carries:\n c3 = {any}\n", .{ c3 }); + if (!(m4 == 272)) __t27_assert_fail("\n 1.75^2 = 3.0625 -> mantissa 272:\n m4 = {any}\n", .{ m4 }); + if (!(m5 == 28)) __t27_assert_fail("\n 1.875 * 1.125 -> mantissa 28 (carry regime):\n m5 = {any}\n", .{ m5 }); + if (!(m6 == 28)) __t27_assert_fail("\n multiply is commutative across the carry regime:\n m6 = {any}\n", .{ m6 }); + if (!(m7 == 510)) __t27_assert_fail("\n max mantissa product stays in range:\n m7 = {any}\n", .{ m7 }); + if (!(c7 == 1)) __t27_assert_fail("\n max product carries:\n c7 = {any}\n", .{ c7 }); + if (!(o0 == 48)) __t27_assert_fail("\n offset path: 44 + 44 - bias 40:\n o0 = {any}\n", .{ o0 }); + if (!(of == 49)) __t27_assert_fail("\n full offset includes the mantissa carry:\n of = {any}\n", .{ of }); } diff --git a/gen/zig/tri_gft_ladder.zig b/gen/zig/tri_gft_ladder.zig index dd2a45c1..e3381e57 100644 --- a/gen/zig/tri_gft_ladder.zig +++ b/gen/zig/tri_gft_ladder.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const GFT4_ET: u32 = 2; @@ -204,76 +212,76 @@ fn width_to_et(width: u32) u32 { return 0; } test "offset_max_per_rung" { - if (!(gft_offset_max(GFT4_ET) == 8)) @panic("GF-T4: 3^2 - 1 = 8"); - if (!(gft_offset_max(GFT8_ET) == 26)) @panic("GF-T8: 3^3 - 1 = 26"); - if (!(gft_offset_max(GFT16_ET) == 80)) @panic("GF-T16: 3^4 - 1 = 80 (matches gfvalid)"); - if (!(gft_offset_max(GFT32_ET) == 728)) @panic("GF-T32: 3^6 - 1 = 728"); + if (!(gft_offset_max(GFT4_ET) == 8)) __t27_assert_fail("\n GF-T4: 3^2 - 1 = 8:\n gft_offset_max(GFT4_ET) = {any}\n", .{ gft_offset_max(GFT4_ET) }); + if (!(gft_offset_max(GFT8_ET) == 26)) __t27_assert_fail("\n GF-T8: 3^3 - 1 = 26:\n gft_offset_max(GFT8_ET) = {any}\n", .{ gft_offset_max(GFT8_ET) }); + if (!(gft_offset_max(GFT16_ET) == 80)) __t27_assert_fail("\n GF-T16: 3^4 - 1 = 80 (matches gfvalid):\n gft_offset_max(GFT16_ET) = {any}\n", .{ gft_offset_max(GFT16_ET) }); + if (!(gft_offset_max(GFT32_ET) == 728)) __t27_assert_fail("\n GF-T32: 3^6 - 1 = 728:\n gft_offset_max(GFT32_ET) = {any}\n", .{ gft_offset_max(GFT32_ET) }); } test "ladder_finiteness" { - if (!(is_finite_gft_n(79, GFT16_ET) == true)) @panic("GF-T16 offset 79 is finite"); - if (!(is_finite_gft_n(80, GFT16_ET) == false)) @panic("GF-T16 offset 80 is the special row"); - if (!(is_finite_gft_n(40, GFT16_ET) == true)) @panic("GF-T16 unity exponent finite"); - if (!(is_finite_gft_n(727, GFT32_ET) == true)) @panic("GF-T32 offset 727 is finite"); - if (!(is_finite_gft_n(728, GFT32_ET) == false)) @panic("GF-T32 offset 728 is the special row"); - if (!(is_finite_gft_n(7, GFT4_ET) == true)) @panic("GF-T4 offset 7 is finite"); - if (!(is_finite_gft_n(8, GFT4_ET) == false)) @panic("GF-T4 offset 8 is special"); + if (!(is_finite_gft_n(79, GFT16_ET) == true)) __t27_assert_fail("\n GF-T16 offset 79 is finite:\n is_finite_gft_n(79, GFT16_ET) = {any}\n", .{ is_finite_gft_n(79, GFT16_ET) }); + if (!(is_finite_gft_n(80, GFT16_ET) == false)) __t27_assert_fail("\n GF-T16 offset 80 is the special row:\n is_finite_gft_n(80, GFT16_ET) = {any}\n", .{ is_finite_gft_n(80, GFT16_ET) }); + if (!(is_finite_gft_n(40, GFT16_ET) == true)) __t27_assert_fail("\n GF-T16 unity exponent finite:\n is_finite_gft_n(40, GFT16_ET) = {any}\n", .{ is_finite_gft_n(40, GFT16_ET) }); + if (!(is_finite_gft_n(727, GFT32_ET) == true)) __t27_assert_fail("\n GF-T32 offset 727 is finite:\n is_finite_gft_n(727, GFT32_ET) = {any}\n", .{ is_finite_gft_n(727, GFT32_ET) }); + if (!(is_finite_gft_n(728, GFT32_ET) == false)) __t27_assert_fail("\n GF-T32 offset 728 is the special row:\n is_finite_gft_n(728, GFT32_ET) = {any}\n", .{ is_finite_gft_n(728, GFT32_ET) }); + if (!(is_finite_gft_n(7, GFT4_ET) == true)) __t27_assert_fail("\n GF-T4 offset 7 is finite:\n is_finite_gft_n(7, GFT4_ET) = {any}\n", .{ is_finite_gft_n(7, GFT4_ET) }); + if (!(is_finite_gft_n(8, GFT4_ET) == false)) __t27_assert_fail("\n GF-T4 offset 8 is special:\n is_finite_gft_n(8, GFT4_ET) = {any}\n", .{ is_finite_gft_n(8, GFT4_ET) }); } test "rung_dependent_classification" { - if (!(is_finite_gft_n(80, GFT16_ET) == false)) @panic("80 is special at GF-T16"); - if (!(is_finite_gft_n(80, GFT32_ET) == true)) @panic("80 is finite at GF-T32"); - if (!(gft_offset_in_range(80, GFT16_ET) == true)) @panic("80 is in range for GF-T16"); - if (!(gft_offset_in_range(81, GFT16_ET) == false)) @panic("81 exceeds GF-T16's 3^4 offsets"); + if (!(is_finite_gft_n(80, GFT16_ET) == false)) __t27_assert_fail("\n 80 is special at GF-T16:\n is_finite_gft_n(80, GFT16_ET) = {any}\n", .{ is_finite_gft_n(80, GFT16_ET) }); + if (!(is_finite_gft_n(80, GFT32_ET) == true)) __t27_assert_fail("\n 80 is finite at GF-T32:\n is_finite_gft_n(80, GFT32_ET) = {any}\n", .{ is_finite_gft_n(80, GFT32_ET) }); + if (!(gft_offset_in_range(80, GFT16_ET) == true)) __t27_assert_fail("\n 80 is in range for GF-T16:\n gft_offset_in_range(80, GFT16_ET) = {any}\n", .{ gft_offset_in_range(80, GFT16_ET) }); + if (!(gft_offset_in_range(81, GFT16_ET) == false)) __t27_assert_fail("\n 81 exceeds GF-T16's 3^4 offsets:\n gft_offset_in_range(81, GFT16_ET) = {any}\n", .{ gft_offset_in_range(81, GFT16_ET) }); } test "bias_per_rung" { - if (!(gft_bias(GFT4_ET) == 4)) @panic("GF-T4 bias (3^2-1)/2 = 4"); - if (!(gft_bias(GFT8_ET) == 13)) @panic("GF-T8 bias (3^3-1)/2 = 13"); - if (!(gft_bias(GFT16_ET) == 40)) @panic("GF-T16 bias = 40 (matches tri_gft_arith)"); - if (!(gft_bias(GFT32_ET) == 364)) @panic("GF-T32 bias (3^6-1)/2 = 364"); - if (!((gft_bias(GFT16_ET) * 2) == gft_offset_max(GFT16_ET))) @panic("bias*2 = offset_max"); + if (!(gft_bias(GFT4_ET) == 4)) __t27_assert_fail("\n GF-T4 bias (3^2-1)/2 = 4:\n gft_bias(GFT4_ET) = {any}\n", .{ gft_bias(GFT4_ET) }); + if (!(gft_bias(GFT8_ET) == 13)) __t27_assert_fail("\n GF-T8 bias (3^3-1)/2 = 13:\n gft_bias(GFT8_ET) = {any}\n", .{ gft_bias(GFT8_ET) }); + if (!(gft_bias(GFT16_ET) == 40)) __t27_assert_fail("\n GF-T16 bias = 40 (matches tri_gft_arith):\n gft_bias(GFT16_ET) = {any}\n", .{ gft_bias(GFT16_ET) }); + if (!(gft_bias(GFT32_ET) == 364)) __t27_assert_fail("\n GF-T32 bias (3^6-1)/2 = 364:\n gft_bias(GFT32_ET) = {any}\n", .{ gft_bias(GFT32_ET) }); + if (!((gft_bias(GFT16_ET) * 2) == gft_offset_max(GFT16_ET))) __t27_assert_fail("\n bias*2 = offset_max:\n gft_bias(GFT16_ET) * 2 = {any}\n gft_offset_max(GFT16_ET) = {any}\n", .{ gft_bias(GFT16_ET) * 2, gft_offset_max(GFT16_ET) }); } test "mantissa_per_rung" { - if (!(gft_mant_bits(GFT4_ET) == 1)) @panic("GF-T4 mantissa 1 bit"); - if (!(gft_mant_bits(GFT8_ET) == 4)) @panic("GF-T8 mantissa 4 bits"); - if (!(gft_mant_bits(GFT16_ET) == 9)) @panic("GF-T16 mantissa 9 bits"); - if (!(gft_mant_bits(GFT32_ET) == 25)) @panic("GF-T32 mantissa 25 bits"); - if (!(gft_mant_one(GFT16_ET) == 512)) @panic("GF-T16 significand scale 2^9 = 512"); - if (!(gft_mant_one(GFT8_ET) == 16)) @panic("GF-T8 scale 2^4 = 16"); + if (!(gft_mant_bits(GFT4_ET) == 1)) __t27_assert_fail("\n GF-T4 mantissa 1 bit:\n gft_mant_bits(GFT4_ET) = {any}\n", .{ gft_mant_bits(GFT4_ET) }); + if (!(gft_mant_bits(GFT8_ET) == 4)) __t27_assert_fail("\n GF-T8 mantissa 4 bits:\n gft_mant_bits(GFT8_ET) = {any}\n", .{ gft_mant_bits(GFT8_ET) }); + if (!(gft_mant_bits(GFT16_ET) == 9)) __t27_assert_fail("\n GF-T16 mantissa 9 bits:\n gft_mant_bits(GFT16_ET) = {any}\n", .{ gft_mant_bits(GFT16_ET) }); + if (!(gft_mant_bits(GFT32_ET) == 25)) __t27_assert_fail("\n GF-T32 mantissa 25 bits:\n gft_mant_bits(GFT32_ET) = {any}\n", .{ gft_mant_bits(GFT32_ET) }); + if (!(gft_mant_one(GFT16_ET) == 512)) __t27_assert_fail("\n GF-T16 significand scale 2^9 = 512:\n gft_mant_one(GFT16_ET) = {any}\n", .{ gft_mant_one(GFT16_ET) }); + if (!(gft_mant_one(GFT8_ET) == 16)) __t27_assert_fail("\n GF-T8 scale 2^4 = 16:\n gft_mant_one(GFT8_ET) = {any}\n", .{ gft_mant_one(GFT8_ET) }); } test "width_routing" { - if (!(width_to_et(8) == GFT8_ET)) @panic("width 8 -> Et 3"); - if (!(width_to_et(16) == GFT16_ET)) @panic("width 16 -> Et 4"); - if (!(gft_bias(width_to_et(8)) == 13)) @panic("GF-T8 bias via width"); - if (!(gft_offset_max(width_to_et(16)) == 80)) @panic("GF-T16 offset_max via width"); - if (!(gft_mant_one(width_to_et(4)) == 2)) @panic("GF-T4 mant scale via width"); + if (!(width_to_et(8) == GFT8_ET)) __t27_assert_fail("\n width 8 -> Et 3:\n width_to_et(8) = {any}\n GFT8_ET = {any}\n", .{ width_to_et(8), GFT8_ET }); + if (!(width_to_et(16) == GFT16_ET)) __t27_assert_fail("\n width 16 -> Et 4:\n width_to_et(16) = {any}\n GFT16_ET = {any}\n", .{ width_to_et(16), GFT16_ET }); + if (!(gft_bias(width_to_et(8)) == 13)) __t27_assert_fail("\n GF-T8 bias via width:\n gft_bias(width_to_et(8)) = {any}\n", .{ gft_bias(width_to_et(8)) }); + if (!(gft_offset_max(width_to_et(16)) == 80)) __t27_assert_fail("\n GF-T16 offset_max via width:\n gft_offset_max(width_to_et(16)) = {any}\n", .{ gft_offset_max(width_to_et(16)) }); + if (!(gft_mant_one(width_to_et(4)) == 2)) __t27_assert_fail("\n GF-T4 mant scale via width:\n gft_mant_one(width_to_et(4)) = {any}\n", .{ gft_mant_one(width_to_et(4)) }); } test "golden_rule_reproduces_the_ladder" { - if (!(fib(6) == 8)) @panic("fib(6) = 8"); - if (!(fib(10) == 55)) @panic("fib(10) = 55"); - if (!(gft_et_of_rung(1) == GFT4_ET)) @panic("GF-T4 Et via rule"); - if (!(gft_mant_of_rung(1) == GFT4_MANT)) @panic("GF-T4 mant via rule"); - if (!(gft_et_of_rung(3) == GFT16_ET)) @panic("GF-T16 Et via rule"); - if (!(gft_mant_of_rung(3) == GFT16_MANT)) @panic("GF-T16 mant = 9 via rule"); - if (!(gft_et_of_rung(4) == GFT32_ET)) @panic("GF-T32 Et = 6 via rule"); - if (!(gft_mant_of_rung(4) == GFT32_MANT)) @panic("GF-T32 mant = 25 via rule"); - if (!(gft_et_of_rung(5) == GFT64_ET)) @panic("GF-T64 Et = 9 via rule"); - if (!(gft_mant_of_rung(5) == GFT64_MANT)) @panic("GF-T64 mant = 64 via rule"); - if (!(gft_et_of_rung(6) == GFT128_ET)) @panic("GF-T128 Et = 14 via rule"); - if (!(gft_mant_of_rung(9) == GFT1024_MANT)) @panic("GF-T1024 mant = 3025 via rule"); + if (!(fib(6) == 8)) __t27_assert_fail("\n fib(6) = 8:\n fib(6) = {any}\n", .{ fib(6) }); + if (!(fib(10) == 55)) __t27_assert_fail("\n fib(10) = 55:\n fib(10) = {any}\n", .{ fib(10) }); + if (!(gft_et_of_rung(1) == GFT4_ET)) __t27_assert_fail("\n GF-T4 Et via rule:\n gft_et_of_rung(1) = {any}\n GFT4_ET = {any}\n", .{ gft_et_of_rung(1), GFT4_ET }); + if (!(gft_mant_of_rung(1) == GFT4_MANT)) __t27_assert_fail("\n GF-T4 mant via rule:\n gft_mant_of_rung(1) = {any}\n GFT4_MANT = {any}\n", .{ gft_mant_of_rung(1), GFT4_MANT }); + if (!(gft_et_of_rung(3) == GFT16_ET)) __t27_assert_fail("\n GF-T16 Et via rule:\n gft_et_of_rung(3) = {any}\n GFT16_ET = {any}\n", .{ gft_et_of_rung(3), GFT16_ET }); + if (!(gft_mant_of_rung(3) == GFT16_MANT)) __t27_assert_fail("\n GF-T16 mant = 9 via rule:\n gft_mant_of_rung(3) = {any}\n GFT16_MANT = {any}\n", .{ gft_mant_of_rung(3), GFT16_MANT }); + if (!(gft_et_of_rung(4) == GFT32_ET)) __t27_assert_fail("\n GF-T32 Et = 6 via rule:\n gft_et_of_rung(4) = {any}\n GFT32_ET = {any}\n", .{ gft_et_of_rung(4), GFT32_ET }); + if (!(gft_mant_of_rung(4) == GFT32_MANT)) __t27_assert_fail("\n GF-T32 mant = 25 via rule:\n gft_mant_of_rung(4) = {any}\n GFT32_MANT = {any}\n", .{ gft_mant_of_rung(4), GFT32_MANT }); + if (!(gft_et_of_rung(5) == GFT64_ET)) __t27_assert_fail("\n GF-T64 Et = 9 via rule:\n gft_et_of_rung(5) = {any}\n GFT64_ET = {any}\n", .{ gft_et_of_rung(5), GFT64_ET }); + if (!(gft_mant_of_rung(5) == GFT64_MANT)) __t27_assert_fail("\n GF-T64 mant = 64 via rule:\n gft_mant_of_rung(5) = {any}\n GFT64_MANT = {any}\n", .{ gft_mant_of_rung(5), GFT64_MANT }); + if (!(gft_et_of_rung(6) == GFT128_ET)) __t27_assert_fail("\n GF-T128 Et = 14 via rule:\n gft_et_of_rung(6) = {any}\n GFT128_ET = {any}\n", .{ gft_et_of_rung(6), GFT128_ET }); + if (!(gft_mant_of_rung(9) == GFT1024_MANT)) __t27_assert_fail("\n GF-T1024 mant = 3025 via rule:\n gft_mant_of_rung(9) = {any}\n GFT1024_MANT = {any}\n", .{ gft_mant_of_rung(9), GFT1024_MANT }); } test "higher_rungs_geometry" { - if (!(gft_offset_max(GFT64_ET) == 19682)) @panic("GF-T64: 3^9 - 1 = 19682"); - if (!(gft_bias(GFT64_ET) == 9841)) @panic("GF-T64 bias (3^9-1)/2 = 9841"); - if (!(gft_offset_max(GFT128_ET) == 4782968)) @panic("GF-T128: 3^14 - 1 = 4782968"); - if (!(is_finite_gft_n(19681, GFT64_ET) == true)) @panic("GF-T64 offset 19681 finite"); - if (!(is_finite_gft_n(19682, GFT64_ET) == false)) @panic("GF-T64 offset 19682 is the special row"); + if (!(gft_offset_max(GFT64_ET) == 19682)) __t27_assert_fail("\n GF-T64: 3^9 - 1 = 19682:\n gft_offset_max(GFT64_ET) = {any}\n", .{ gft_offset_max(GFT64_ET) }); + if (!(gft_bias(GFT64_ET) == 9841)) __t27_assert_fail("\n GF-T64 bias (3^9-1)/2 = 9841:\n gft_bias(GFT64_ET) = {any}\n", .{ gft_bias(GFT64_ET) }); + if (!(gft_offset_max(GFT128_ET) == 4782968)) __t27_assert_fail("\n GF-T128: 3^14 - 1 = 4782968:\n gft_offset_max(GFT128_ET) = {any}\n", .{ gft_offset_max(GFT128_ET) }); + if (!(is_finite_gft_n(19681, GFT64_ET) == true)) __t27_assert_fail("\n GF-T64 offset 19681 finite:\n is_finite_gft_n(19681, GFT64_ET) = {any}\n", .{ is_finite_gft_n(19681, GFT64_ET) }); + if (!(is_finite_gft_n(19682, GFT64_ET) == false)) __t27_assert_fail("\n GF-T64 offset 19682 is the special row:\n is_finite_gft_n(19682, GFT64_ET) = {any}\n", .{ is_finite_gft_n(19682, GFT64_ET) }); } test "wide_rung_geometry" { - if (!(gft_pow3_u64(GFT128_ET) == 4782969)) @panic("wide path agrees with u32 at GF-T128"); - if (!(gft_offset_max_u64(GFT256_ET) == 31381059608)) @panic("GF-T256: 3^22 - 1"); - if (!(gft_bias_u64(GFT256_ET) == 15690529804)) @panic("GF-T256 bias (3^22-1)/2"); - if (!(gft_offset_max_u64(GFT512_ET) == 50031545098999706)) @panic("GF-T512: 3^35 - 1 (largest rung in u64)"); - if (!(gft_bias_u64(GFT512_ET) == 25015772549499853)) @panic("GF-T512 bias (3^35-1)/2"); - if (!(gft_pow3_u64(GFT1024_ET) == 0)) @panic("GF-T1024 (Et56) exceeds u64 -- bignum, absent not wrong"); + if (!(gft_pow3_u64(GFT128_ET) == 4782969)) __t27_assert_fail("\n wide path agrees with u32 at GF-T128:\n gft_pow3_u64(GFT128_ET) = {any}\n", .{ gft_pow3_u64(GFT128_ET) }); + if (!(gft_offset_max_u64(GFT256_ET) == 31381059608)) __t27_assert_fail("\n GF-T256: 3^22 - 1:\n gft_offset_max_u64(GFT256_ET) = {any}\n", .{ gft_offset_max_u64(GFT256_ET) }); + if (!(gft_bias_u64(GFT256_ET) == 15690529804)) __t27_assert_fail("\n GF-T256 bias (3^22-1)/2:\n gft_bias_u64(GFT256_ET) = {any}\n", .{ gft_bias_u64(GFT256_ET) }); + if (!(gft_offset_max_u64(GFT512_ET) == 50031545098999706)) __t27_assert_fail("\n GF-T512: 3^35 - 1 (largest rung in u64):\n gft_offset_max_u64(GFT512_ET) = {any}\n", .{ gft_offset_max_u64(GFT512_ET) }); + if (!(gft_bias_u64(GFT512_ET) == 25015772549499853)) __t27_assert_fail("\n GF-T512 bias (3^35-1)/2:\n gft_bias_u64(GFT512_ET) = {any}\n", .{ gft_bias_u64(GFT512_ET) }); + if (!(gft_pow3_u64(GFT1024_ET) == 0)) __t27_assert_fail("\n GF-T1024 (Et56) exceeds u64 -- bignum, absent not wrong:\n gft_pow3_u64(GFT1024_ET) = {any}\n", .{ gft_pow3_u64(GFT1024_ET) }); } fn bench_ladder_rung_walk() void { // bench: ladder_rung_walk @@ -291,18 +299,18 @@ fn bench_ladder_rung_walk() void { const x9 = gft_offset_max(9); const b4 = gft_bias(4); const b9 = gft_bias(9); - if (!(e1 == 2)) @panic("GF-T4 Et 2"); - if (!(e2 == 3)) @panic("GF-T8 Et 3"); - if (!(e3 == 4)) @panic("GF-T16 Et 4"); - if (!(e4 == 6)) @panic("GF-T32 Et 6"); - if (!(e5 == 9)) @panic("GF-T64 Et 9"); - if (!(e6 == 14)) @panic("GF-T128 Et 14"); - if (!(m1 == 1)) @panic("GF-T4 mant 1"); - if (!(m3 == 9)) @panic("GF-T16 mant 9"); - if (!(m5 == 64)) @panic("GF-T64 mant 64"); - if (!(x2 == 8)) @panic("3^2 - 1"); - if (!(x4 == 80)) @panic("3^4 - 1"); - if (!(x9 == 19682)) @panic("3^9 - 1"); - if (!(b4 == 40)) @panic("GF-T16 bias"); - if (!(b9 == 9841)) @panic("GF-T64 bias"); + if (!(e1 == 2)) __t27_assert_fail("\n GF-T4 Et 2:\n e1 = {any}\n", .{ e1 }); + if (!(e2 == 3)) __t27_assert_fail("\n GF-T8 Et 3:\n e2 = {any}\n", .{ e2 }); + if (!(e3 == 4)) __t27_assert_fail("\n GF-T16 Et 4:\n e3 = {any}\n", .{ e3 }); + if (!(e4 == 6)) __t27_assert_fail("\n GF-T32 Et 6:\n e4 = {any}\n", .{ e4 }); + if (!(e5 == 9)) __t27_assert_fail("\n GF-T64 Et 9:\n e5 = {any}\n", .{ e5 }); + if (!(e6 == 14)) __t27_assert_fail("\n GF-T128 Et 14:\n e6 = {any}\n", .{ e6 }); + if (!(m1 == 1)) __t27_assert_fail("\n GF-T4 mant 1:\n m1 = {any}\n", .{ m1 }); + if (!(m3 == 9)) __t27_assert_fail("\n GF-T16 mant 9:\n m3 = {any}\n", .{ m3 }); + if (!(m5 == 64)) __t27_assert_fail("\n GF-T64 mant 64:\n m5 = {any}\n", .{ m5 }); + if (!(x2 == 8)) __t27_assert_fail("\n 3^2 - 1:\n x2 = {any}\n", .{ x2 }); + if (!(x4 == 80)) __t27_assert_fail("\n 3^4 - 1:\n x4 = {any}\n", .{ x4 }); + if (!(x9 == 19682)) __t27_assert_fail("\n 3^9 - 1:\n x9 = {any}\n", .{ x9 }); + if (!(b4 == 40)) __t27_assert_fail("\n GF-T16 bias:\n b4 = {any}\n", .{ b4 }); + if (!(b9 == 9841)) __t27_assert_fail("\n GF-T64 bias:\n b9 = {any}\n", .{ b9 }); } diff --git a/gen/zig/tri_gft_sub.zig b/gen/zig/tri_gft_sub.zig index c63ebaeb..73be739c 100644 --- a/gen/zig/tri_gft_sub.zig +++ b/gen/zig/tri_gft_sub.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MANT_ONE: u32 = 512; @@ -496,48 +504,48 @@ fn verify_gft_sub_u64(oa: u32, ob: u32, ma: u64, mb: u64, claimed_offset: u32, c } } test "hi_bit_ladder" { - if (!(hi_bit(1) == 0)) @panic("bit 0"); - if (!(hi_bit(481) == 8)) @panic("481 -> bit 8"); - if (!(hi_bit(523776) == 18)) @panic("523776 -> bit 18"); - if (!(hi_bit(1073741824) == 30)) @panic("2^30 -> bit 30"); + if (!(hi_bit(1) == 0)) __t27_assert_fail("\n bit 0:\n hi_bit(1) = {any}\n", .{ hi_bit(1) }); + if (!(hi_bit(481) == 8)) __t27_assert_fail("\n 481 -> bit 8:\n hi_bit(481) = {any}\n", .{ hi_bit(481) }); + if (!(hi_bit(523776) == 18)) __t27_assert_fail("\n 523776 -> bit 18:\n hi_bit(523776) = {any}\n", .{ hi_bit(523776) }); + if (!(hi_bit(1073741824) == 30)) __t27_assert_fail("\n 2^30 -> bit 30:\n hi_bit(1073741824) = {any}\n", .{ hi_bit(1073741824) }); } test "subtract_same_exp" { - if (!(gft_sub_offset_c(40, 40, 256, 0) == 39)) @panic("1.5 - 1.0 = 0.5 -> offset 39"); - if (!(gft_sub_mant_c(40, 40, 256, 0) == 0)) @panic("0.5 -> mantissa 0"); + if (!(gft_sub_offset_c(40, 40, 256, 0) == 39)) __t27_assert_fail("\n 1.5 - 1.0 = 0.5 -> offset 39:\n gft_sub_offset_c(40, 40, 256, 0) = {any}\n", .{ gft_sub_offset_c(40, 40, 256, 0) }); + if (!(gft_sub_mant_c(40, 40, 256, 0) == 0)) __t27_assert_fail("\n 0.5 -> mantissa 0:\n gft_sub_mant_c(40, 40, 256, 0) = {any}\n", .{ gft_sub_mant_c(40, 40, 256, 0) }); } test "exact_cancellation" { - if (!(gft_sub_offset_c(40, 40, 100, 100) == 0)) @panic("x - x = 0 -> offset 0"); - if (!(gft_sub_mant_c(40, 40, 100, 100) == 0)) @panic("x - x = 0 -> mantissa 0"); + if (!(gft_sub_offset_c(40, 40, 100, 100) == 0)) __t27_assert_fail("\n x - x = 0 -> offset 0:\n gft_sub_offset_c(40, 40, 100, 100) = {any}\n", .{ gft_sub_offset_c(40, 40, 100, 100) }); + if (!(gft_sub_mant_c(40, 40, 100, 100) == 0)) __t27_assert_fail("\n x - x = 0 -> mantissa 0:\n gft_sub_mant_c(40, 40, 100, 100) = {any}\n", .{ gft_sub_mant_c(40, 40, 100, 100) }); } test "near_cancellation_exact" { - if (!(gft_sub_offset_c(30, 31, 31, 0) == 29)) @panic("near-cancel exponent 29"); - if (!(gft_sub_mant_c(30, 31, 31, 0) == 450)) @panic("near-cancel mantissa 450 (not the truncated 452)"); - if (!(gft_sub_offset_c(25, 35, 0, 0) == 34)) @panic("2^-5 - 2^-15 exponent 34"); - if (!(gft_sub_mant_c(25, 35, 0, 0) == 511)) @panic("all-ones mantissa 511"); + if (!(gft_sub_offset_c(30, 31, 31, 0) == 29)) __t27_assert_fail("\n near-cancel exponent 29:\n gft_sub_offset_c(30, 31, 31, 0) = {any}\n", .{ gft_sub_offset_c(30, 31, 31, 0) }); + if (!(gft_sub_mant_c(30, 31, 31, 0) == 450)) __t27_assert_fail("\n near-cancel mantissa 450 (not the truncated 452):\n gft_sub_mant_c(30, 31, 31, 0) = {any}\n", .{ gft_sub_mant_c(30, 31, 31, 0) }); + if (!(gft_sub_offset_c(25, 35, 0, 0) == 34)) __t27_assert_fail("\n 2^-5 - 2^-15 exponent 34:\n gft_sub_offset_c(25, 35, 0, 0) = {any}\n", .{ gft_sub_offset_c(25, 35, 0, 0) }); + if (!(gft_sub_mant_c(25, 35, 0, 0) == 511)) __t27_assert_fail("\n all-ones mantissa 511:\n gft_sub_mant_c(25, 35, 0, 0) = {any}\n", .{ gft_sub_mant_c(25, 35, 0, 0) }); } test "far_apart_borrow" { - if (!(gft_sub_offset_c(70, 40, 100, 0) == 70)) @panic("big(M>0) - tiny keeps exponent"); - if (!(gft_sub_mant_c(70, 40, 100, 0) == 99)) @panic("mantissa borrows one ULP -> 99"); - if (!(gft_sub_offset_c(70, 40, 0, 0) == 69)) @panic("big(M=0) - tiny renorms down one"); - if (!(gft_sub_mant_c(70, 40, 0, 0) == 511)) @panic("and mantissa is all ones"); + if (!(gft_sub_offset_c(70, 40, 100, 0) == 70)) __t27_assert_fail("\n big(M>0) - tiny keeps exponent:\n gft_sub_offset_c(70, 40, 100, 0) = {any}\n", .{ gft_sub_offset_c(70, 40, 100, 0) }); + if (!(gft_sub_mant_c(70, 40, 100, 0) == 99)) __t27_assert_fail("\n mantissa borrows one ULP -> 99:\n gft_sub_mant_c(70, 40, 100, 0) = {any}\n", .{ gft_sub_mant_c(70, 40, 100, 0) }); + if (!(gft_sub_offset_c(70, 40, 0, 0) == 69)) __t27_assert_fail("\n big(M=0) - tiny renorms down one:\n gft_sub_offset_c(70, 40, 0, 0) = {any}\n", .{ gft_sub_offset_c(70, 40, 0, 0) }); + if (!(gft_sub_mant_c(70, 40, 0, 0) == 511)) __t27_assert_fail("\n and mantissa is all ones:\n gft_sub_mant_c(70, 40, 0, 0) = {any}\n", .{ gft_sub_mant_c(70, 40, 0, 0) }); } test "verify_catches_sub_fraud" { - if (!(verify_gft_sub(40, 40, 256, 0, 39, 0) == true)) @panic("honest 1.5-1.0=0.5 accepted"); - if (!(verify_gft_sub(40, 40, 256, 0, 40, 0) == false)) @panic("wrong exponent rejected"); - if (!(verify_gft_sub(30, 31, 31, 0, 29, 452) == false)) @panic("the 2-ULP-off truncated result rejected"); + if (!(verify_gft_sub(40, 40, 256, 0, 39, 0) == true)) __t27_assert_fail("\n honest 1.5-1.0=0.5 accepted:\n verify_gft_sub(40, 40, 256, 0, 39, 0) = {any}\n", .{ verify_gft_sub(40, 40, 256, 0, 39, 0) }); + if (!(verify_gft_sub(40, 40, 256, 0, 40, 0) == false)) __t27_assert_fail("\n wrong exponent rejected:\n verify_gft_sub(40, 40, 256, 0, 40, 0) = {any}\n", .{ verify_gft_sub(40, 40, 256, 0, 40, 0) }); + if (!(verify_gft_sub(30, 31, 31, 0, 29, 452) == false)) __t27_assert_fail("\n the 2-ULP-off truncated result rejected:\n verify_gft_sub(30, 31, 31, 0, 29, 452) = {any}\n", .{ verify_gft_sub(30, 31, 31, 0, 29, 452) }); } test "per_rung_subtract" { - if (!(gft_sub_offset_c_p(40, 40, 256, 0, 512, 9) == 39)) @panic("GF-T16 view: 1.5-1.0 -> offset 39"); - if (!(gft_sub_mant_c_p(40, 40, 256, 0, 512, 9) == 0)) @panic("GF-T16 view mantissa 0"); - if (!(verify_gft_sub_p(13, 13, 8, 0, 12, 0, 16, 4) == true)) @panic("GF-T8 1.5-1.0 = 0.5 (offset 12)"); - if (!(verify_gft_sub_p(13, 13, 8, 0, 13, 0, 16, 4) == false)) @panic("GF-T8 missed renorm rejected"); - if (!(verify_gft_sub_p(4, 4, 1, 0, 3, 0, 2, 1) == true)) @panic("GF-T4 1.5-1.0 = 0.5 (offset 3)"); + if (!(gft_sub_offset_c_p(40, 40, 256, 0, 512, 9) == 39)) __t27_assert_fail("\n GF-T16 view: 1.5-1.0 -> offset 39:\n gft_sub_offset_c_p(40, 40, 256, 0, 512, 9) = {any}\n", .{ gft_sub_offset_c_p(40, 40, 256, 0, 512, 9) }); + if (!(gft_sub_mant_c_p(40, 40, 256, 0, 512, 9) == 0)) __t27_assert_fail("\n GF-T16 view mantissa 0:\n gft_sub_mant_c_p(40, 40, 256, 0, 512, 9) = {any}\n", .{ gft_sub_mant_c_p(40, 40, 256, 0, 512, 9) }); + if (!(verify_gft_sub_p(13, 13, 8, 0, 12, 0, 16, 4) == true)) __t27_assert_fail("\n GF-T8 1.5-1.0 = 0.5 (offset 12):\n verify_gft_sub_p(13, 13, 8, 0, 12, 0, 16, 4) = {any}\n", .{ verify_gft_sub_p(13, 13, 8, 0, 12, 0, 16, 4) }); + if (!(verify_gft_sub_p(13, 13, 8, 0, 13, 0, 16, 4) == false)) __t27_assert_fail("\n GF-T8 missed renorm rejected:\n verify_gft_sub_p(13, 13, 8, 0, 13, 0, 16, 4) = {any}\n", .{ verify_gft_sub_p(13, 13, 8, 0, 13, 0, 16, 4) }); + if (!(verify_gft_sub_p(4, 4, 1, 0, 3, 0, 2, 1) == true)) __t27_assert_fail("\n GF-T4 1.5-1.0 = 0.5 (offset 3):\n verify_gft_sub_p(4, 4, 1, 0, 3, 0, 2, 1) = {any}\n", .{ verify_gft_sub_p(4, 4, 1, 0, 3, 0, 2, 1) }); } test "gft32_subtract" { - if (!(verify_gft_sub_u64(364, 364, 16777216, 0, 363, 0, 33554432, 25, 38) == true)) @panic("GF-T32 1.5-1.0 = 0.5 -> offset 363"); - if (!(verify_gft_sub_u64(364, 364, 16777216, 0, 364, 0, 33554432, 25, 38) == false)) @panic("GF-T32 missed renorm rejected"); - if (!(gft_sub_mant_c_u64(364, 364, 100, 100, 33554432, 25, 38) == 0)) @panic("GF-T32 x - x = 0 mantissa"); - if (!(gft_sub_offset_c_u64(364, 364, 100, 100, 33554432, 25, 38) == 0)) @panic("GF-T32 x - x = 0 offset (zero sentinel)"); + if (!(verify_gft_sub_u64(364, 364, 16777216, 0, 363, 0, 33554432, 25, 38) == true)) __t27_assert_fail("\n GF-T32 1.5-1.0 = 0.5 -> offset 363:\n verify_gft_sub_u64(364, 364, 16777216, 0, 363, 0, 33554432, 25, 38) = {any}\n", .{ verify_gft_sub_u64(364, 364, 16777216, 0, 363, 0, 33554432, 25, 38) }); + if (!(verify_gft_sub_u64(364, 364, 16777216, 0, 364, 0, 33554432, 25, 38) == false)) __t27_assert_fail("\n GF-T32 missed renorm rejected:\n verify_gft_sub_u64(364, 364, 16777216, 0, 364, 0, 33554432, 25, 38) = {any}\n", .{ verify_gft_sub_u64(364, 364, 16777216, 0, 364, 0, 33554432, 25, 38) }); + if (!(gft_sub_mant_c_u64(364, 364, 100, 100, 33554432, 25, 38) == 0)) __t27_assert_fail("\n GF-T32 x - x = 0 mantissa:\n gft_sub_mant_c_u64(364, 364, 100, 100, 33554432, 25, 38) = {any}\n", .{ gft_sub_mant_c_u64(364, 364, 100, 100, 33554432, 25, 38) }); + if (!(gft_sub_offset_c_u64(364, 364, 100, 100, 33554432, 25, 38) == 0)) __t27_assert_fail("\n GF-T32 x - x = 0 offset (zero sentinel):\n gft_sub_offset_c_u64(364, 364, 100, 100, 33554432, 25, 38) = {any}\n", .{ gft_sub_offset_c_u64(364, 364, 100, 100, 33554432, 25, 38) }); } fn bench_sub_mantissa_sweep() void { // bench: sub_mantissa_sweep @@ -555,18 +563,18 @@ fn bench_sub_mantissa_sweep() void { const mz = gft_sub_mant(45, 44, 0, 0); const ox = gft_sub_offset(50, 44, 256, 384); const mx = gft_sub_mant(50, 44, 256, 384); - if (!(o1 == 40)) @panic("step 1 offset: deep cancellation drops 4 exponents"); - if (!(m1 == 256)) @panic("step 1 mantissa"); - if (!(o2 == 41)) @panic("step 2 offset"); - if (!(m2 == 256)) @panic("step 2 mantissa"); - if (!(m3 == 64)) @panic("step 3 mantissa"); - if (!(m4 == 256)) @panic("step 4 mantissa"); - if (!(m5 == 448)) @panic("step 5 mantissa"); - if (!(m6 == 64)) @panic("step 6 mantissa"); - if (!(m7 == 160)) @panic("step 7 mantissa"); - if (!(m8 == 256)) @panic("step 8 mantissa"); - if (!(oz == 44)) @panic("2.0 - 1.0 = 1.0: offset back to 44"); - if (!(mz == 0)) @panic("2.0 - 1.0 = 1.0: mantissa 0"); - if (!(ox == 50)) @panic("far-ish pair keeps the larger exponent"); - if (!(mx == 242)) @panic("cross-exponent mantissa from the oracle"); + if (!(o1 == 40)) __t27_assert_fail("\n step 1 offset: deep cancellation drops 4 exponents:\n o1 = {any}\n", .{ o1 }); + if (!(m1 == 256)) __t27_assert_fail("\n step 1 mantissa:\n m1 = {any}\n", .{ m1 }); + if (!(o2 == 41)) __t27_assert_fail("\n step 2 offset:\n o2 = {any}\n", .{ o2 }); + if (!(m2 == 256)) __t27_assert_fail("\n step 2 mantissa:\n m2 = {any}\n", .{ m2 }); + if (!(m3 == 64)) __t27_assert_fail("\n step 3 mantissa:\n m3 = {any}\n", .{ m3 }); + if (!(m4 == 256)) __t27_assert_fail("\n step 4 mantissa:\n m4 = {any}\n", .{ m4 }); + if (!(m5 == 448)) __t27_assert_fail("\n step 5 mantissa:\n m5 = {any}\n", .{ m5 }); + if (!(m6 == 64)) __t27_assert_fail("\n step 6 mantissa:\n m6 = {any}\n", .{ m6 }); + if (!(m7 == 160)) __t27_assert_fail("\n step 7 mantissa:\n m7 = {any}\n", .{ m7 }); + if (!(m8 == 256)) __t27_assert_fail("\n step 8 mantissa:\n m8 = {any}\n", .{ m8 }); + if (!(oz == 44)) __t27_assert_fail("\n 2.0 - 1.0 = 1.0: offset back to 44:\n oz = {any}\n", .{ oz }); + if (!(mz == 0)) __t27_assert_fail("\n 2.0 - 1.0 = 1.0: mantissa 0:\n mz = {any}\n", .{ mz }); + if (!(ox == 50)) __t27_assert_fail("\n far-ish pair keeps the larger exponent:\n ox = {any}\n", .{ ox }); + if (!(mx == 242)) __t27_assert_fail("\n cross-exponent mantissa from the oracle:\n mx = {any}\n", .{ mx }); } diff --git a/gen/zig/tri_ilv.zig b/gen/zig/tri_ilv.zig index ec5c6c02..f9549f4f 100644 --- a/gen/zig/tri_ilv.zig +++ b/gen/zig/tri_ilv.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const DEPTH_CAP: u32 = 64; @@ -28,42 +36,42 @@ fn depth_survives(depth: u32, burst: u32) bool { return depth >= burst; } test "ilv_roundtrip" { - if (!(ilv_orig(ilv_tx_pos(0, 8, 4), 8, 4) == 0)) @panic("o=0"); - if (!(ilv_orig(ilv_tx_pos(7, 8, 4), 8, 4) == 7)) @panic("o=7"); - if (!(ilv_orig(ilv_tx_pos(31, 8, 4), 8, 4) == 31)) @panic("o=31"); - if (!(ilv_orig(ilv_tx_pos(13, 8, 4), 8, 4) == 13)) @panic("o=13"); + if (!(ilv_orig(ilv_tx_pos(0, 8, 4), 8, 4) == 0)) __t27_assert_fail("\n o=0:\n ilv_orig(ilv_tx_pos(0, 8, 4), 8, 4) = {any}\n", .{ ilv_orig(ilv_tx_pos(0, 8, 4), 8, 4) }); + if (!(ilv_orig(ilv_tx_pos(7, 8, 4), 8, 4) == 7)) __t27_assert_fail("\n o=7:\n ilv_orig(ilv_tx_pos(7, 8, 4), 8, 4) = {any}\n", .{ ilv_orig(ilv_tx_pos(7, 8, 4), 8, 4) }); + if (!(ilv_orig(ilv_tx_pos(31, 8, 4), 8, 4) == 31)) __t27_assert_fail("\n o=31:\n ilv_orig(ilv_tx_pos(31, 8, 4), 8, 4) = {any}\n", .{ ilv_orig(ilv_tx_pos(31, 8, 4), 8, 4) }); + if (!(ilv_orig(ilv_tx_pos(13, 8, 4), 8, 4) == 13)) __t27_assert_fail("\n o=13:\n ilv_orig(ilv_tx_pos(13, 8, 4), 8, 4) = {any}\n", .{ ilv_orig(ilv_tx_pos(13, 8, 4), 8, 4) }); } test "ilv_adjacent_differ" { const c0 = ilv_codeword(ilv_orig(0, 8, 4), 4); const c1 = ilv_codeword(ilv_orig(1, 8, 4), 4); const c2 = ilv_codeword(ilv_orig(2, 8, 4), 4); - if (!(c0 != c1)) @panic("tx0 vs tx1 different codeword"); - if (!(c1 != c2)) @panic("tx1 vs tx2 different codeword"); - if (!(c0 == 0)) @panic("tx0 -> codeword 0"); - if (!(c1 == 1)) @panic("tx1 -> codeword 1"); + if (!(c0 != c1)) __t27_assert_fail("\n tx0 vs tx1 different codeword:\n c0 = {any}\n c1 = {any}\n", .{ c0, c1 }); + if (!(c1 != c2)) __t27_assert_fail("\n tx1 vs tx2 different codeword:\n c1 = {any}\n c2 = {any}\n", .{ c1, c2 }); + if (!(c0 == 0)) __t27_assert_fail("\n tx0 -> codeword 0:\n c0 = {any}\n", .{ c0 }); + if (!(c1 == 1)) __t27_assert_fail("\n tx1 -> codeword 1:\n c1 = {any}\n", .{ c1 }); } test "ilv_burst_spreads" { - if (!(ilv_codeword(ilv_orig(0, 8, 4), 4) == 0)) @panic("t0->cw0"); - if (!(ilv_codeword(ilv_orig(3, 8, 4), 4) == 3)) @panic("t3->cw3"); - if (!(ilv_codeword(ilv_orig(7, 8, 4), 4) == 7)) @panic("t7->cw7"); - if (!(ilv_codeword(ilv_orig(8, 8, 4), 4) == 0)) @panic("t8->cw0 (next column)"); + if (!(ilv_codeword(ilv_orig(0, 8, 4), 4) == 0)) __t27_assert_fail("\n t0->cw0:\n ilv_codeword(ilv_orig(0, 8, 4), 4) = {any}\n", .{ ilv_codeword(ilv_orig(0, 8, 4), 4) }); + if (!(ilv_codeword(ilv_orig(3, 8, 4), 4) == 3)) __t27_assert_fail("\n t3->cw3:\n ilv_codeword(ilv_orig(3, 8, 4), 4) = {any}\n", .{ ilv_codeword(ilv_orig(3, 8, 4), 4) }); + if (!(ilv_codeword(ilv_orig(7, 8, 4), 4) == 7)) __t27_assert_fail("\n t7->cw7:\n ilv_codeword(ilv_orig(7, 8, 4), 4) = {any}\n", .{ ilv_codeword(ilv_orig(7, 8, 4), 4) }); + if (!(ilv_codeword(ilv_orig(8, 8, 4), 4) == 0)) __t27_assert_fail("\n t8->cw0 (next column):\n ilv_codeword(ilv_orig(8, 8, 4), 4) = {any}\n", .{ ilv_codeword(ilv_orig(8, 8, 4), 4) }); } test "ilv_is_permutation" { - if (!(ilv_tx_pos(0, 8, 4) != ilv_tx_pos(1, 8, 4))) @panic("distinct 0,1"); - if (!(ilv_tx_pos(4, 8, 4) != ilv_tx_pos(5, 8, 4))) @panic("distinct 4,5"); - if (!(ilv_tx_pos(0, 8, 4) == 0)) @panic("o0 -> t0"); - if (!(ilv_tx_pos(4, 8, 4) == 1)) @panic("o4(row1,col0) -> t1"); + if (!(ilv_tx_pos(0, 8, 4) != ilv_tx_pos(1, 8, 4))) __t27_assert_fail("\n distinct 0,1:\n ilv_tx_pos(0, 8, 4) = {any}\n ilv_tx_pos(1, 8, 4) = {any}\n", .{ ilv_tx_pos(0, 8, 4), ilv_tx_pos(1, 8, 4) }); + if (!(ilv_tx_pos(4, 8, 4) != ilv_tx_pos(5, 8, 4))) __t27_assert_fail("\n distinct 4,5:\n ilv_tx_pos(4, 8, 4) = {any}\n ilv_tx_pos(5, 8, 4) = {any}\n", .{ ilv_tx_pos(4, 8, 4), ilv_tx_pos(5, 8, 4) }); + if (!(ilv_tx_pos(0, 8, 4) == 0)) __t27_assert_fail("\n o0 -> t0:\n ilv_tx_pos(0, 8, 4) = {any}\n", .{ ilv_tx_pos(0, 8, 4) }); + if (!(ilv_tx_pos(4, 8, 4) == 1)) __t27_assert_fail("\n o4(row1,col0) -> t1:\n ilv_tx_pos(4, 8, 4) = {any}\n", .{ ilv_tx_pos(4, 8, 4) }); } test "choose_depth_matches_burst" { - if (!(choose_depth(5) == 5)) @panic("burst 5 -> depth 5"); - if (!(choose_depth(12) == 12)) @panic("burst 12 -> depth 12"); + if (!(choose_depth(5) == 5)) __t27_assert_fail("\n burst 5 -> depth 5:\n choose_depth(5) = {any}\n", .{ choose_depth(5) }); + if (!(choose_depth(12) == 12)) __t27_assert_fail("\n burst 12 -> depth 12:\n choose_depth(12) = {any}\n", .{ choose_depth(12) }); if (!(depth_survives(choose_depth(12), 12))) @panic("chosen depth survives its burst"); } test "choose_depth_beats_fixed" { - if (!(depth_survives(8, 12) == false)) @panic("fixed depth 8 fails a burst of 12"); - if (!(depth_survives(choose_depth(12), 12) == true)) @panic("adaptive depth survives 12"); + if (!(depth_survives(8, 12) == false)) __t27_assert_fail("\n fixed depth 8 fails a burst of 12:\n depth_survives(8, 12) = {any}\n", .{ depth_survives(8, 12) }); + if (!(depth_survives(choose_depth(12), 12) == true)) __t27_assert_fail("\n adaptive depth survives 12:\n depth_survives(choose_depth(12), 12) = {any}\n", .{ depth_survives(choose_depth(12), 12) }); } test "choose_depth_bounds" { - if (!(choose_depth(0) == 1)) @panic("no burst -> depth 1"); - if (!(choose_depth(1000) == DEPTH_CAP)) @panic("huge burst clamps to cap"); + if (!(choose_depth(0) == 1)) __t27_assert_fail("\n no burst -> depth 1:\n choose_depth(0) = {any}\n", .{ choose_depth(0) }); + if (!(choose_depth(1000) == DEPTH_CAP)) __t27_assert_fail("\n huge burst clamps to cap:\n choose_depth(1000) = {any}\n DEPTH_CAP = {any}\n", .{ choose_depth(1000), DEPTH_CAP }); } diff --git a/gen/zig/tri_ledger.zig b/gen/zig/tri_ledger.zig index 6102152b..8a80e1e7 100644 --- a/gen/zig/tri_ledger.zig +++ b/gen/zig/tri_ledger.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const LEDGER_GENESIS: u32 = 0x54524C47; @@ -38,13 +46,13 @@ test "balance_accumulates" { const b0 = balance_add(0, 713); const b1 = balance_add(b0, 258); const b2 = balance_add(b1, 27); - if (!(b0 == 713)) @panic("round 1"); - if (!(b1 == 971)) @panic("round 1+2"); - if (!(b2 == 998)) @panic("round 1+2+3"); - if (!(b2 > b1)) @panic("monotonic"); + if (!(b0 == 713)) __t27_assert_fail("\n round 1:\n b0 = {any}\n", .{ b0 }); + if (!(b1 == 971)) __t27_assert_fail("\n round 1+2:\n b1 = {any}\n", .{ b1 }); + if (!(b2 == 998)) __t27_assert_fail("\n round 1+2+3:\n b2 = {any}\n", .{ b2 }); + if (!(b2 > b1)) __t27_assert_fail("\n monotonic:\n b2 = {any}\n b1 = {any}\n", .{ b2, b1 }); } test "balance_saturates" { - if (!(balance_add(0xFFFFFF00, 0x0000FFFF) == 0xFFFFFFFF)) @panic("saturates"); + if (!(balance_add(0xFFFFFF00, 0x0000FFFF) == 0xFFFFFFFF)) __t27_assert_fail("\n saturates:\n balance_add(0xFFFFFF00, 0x0000FFFF) = {any}\n", .{ balance_add(0xFFFFFF00, 0x0000FFFF) }); } test "state_deterministic" { const a = verify_chain3(0x1111, 1, 0x2222, 2, 0x3333, 3, 0); @@ -52,7 +60,7 @@ test "state_deterministic" { const s0 = state_step(LEDGER_GENESIS, 0x1111, 1); const s1 = state_step(s0, 0x2222, 2); const s2 = state_step(s1, 0x3333, 3); - if (!(verify_chain3(0x1111, 1, 0x2222, 2, 0x3333, 3, s2) == true)) @panic("honest chain verifies"); + if (!(verify_chain3(0x1111, 1, 0x2222, 2, 0x3333, 3, s2) == true)) __t27_assert_fail("\n honest chain verifies:\n verify_chain3(0x1111, 1, 0x2222, 2, 0x3333, 3, s2) = {any}\n", .{ verify_chain3(0x1111, 1, 0x2222, 2, 0x3333, 3, s2) }); } test "state_tamper_evident" { const s0 = state_step(LEDGER_GENESIS, 0x1111, 1); @@ -61,18 +69,18 @@ test "state_tamper_evident" { const t0 = state_step(LEDGER_GENESIS, 0x9999, 1); const t1 = state_step(t0, 0x2222, 2); const tampered = state_step(t1, 0x3333, 3); - if (!(honest != tampered)) @panic("tampering an old round changes the state root"); + if (!(honest != tampered)) __t27_assert_fail("\n tampering an old round changes the state root:\n honest = {any}\n tampered = {any}\n", .{ honest, tampered }); } test "state_order_sensitive" { const s0 = state_step(LEDGER_GENESIS, 0xAAAA, 1); const forward = state_step(s0, 0xBBBB, 2); const r0 = state_step(LEDGER_GENESIS, 0xBBBB, 2); const swapped = state_step(r0, 0xAAAA, 1); - if (!(forward != swapped)) @panic("reordering rounds changes the state root"); + if (!(forward != swapped)) __t27_assert_fail("\n reordering rounds changes the state root:\n forward = {any}\n swapped = {any}\n", .{ forward, swapped }); } test "verify_rejects_wrong_root" { const s0 = state_step(LEDGER_GENESIS, 0x1111, 1); const s1 = state_step(s0, 0x2222, 2); const s2 = state_step(s1, 0x3333, 3); - if (!(verify_chain3(0x1111, 1, 0x2222, 2, 0x3333, 3, s2 ^ 1) == false)) @panic("wrong root rejected"); + if (!(verify_chain3(0x1111, 1, 0x2222, 2, 0x3333, 3, s2 ^ 1) == false)) __t27_assert_fail("\n wrong root rejected:\n verify_chain3(0x1111, 1, 0x2222, 2, 0x3333, 3, s2 ^ 1) = {any}\n", .{ verify_chain3(0x1111, 1, 0x2222, 2, 0x3333, 3, s2 ^ 1) }); } diff --git a/gen/zig/tri_merkle.zig b/gen/zig/tri_merkle.zig index 24d89c25..e16dd470 100644 --- a/gen/zig/tri_merkle.zig +++ b/gen/zig/tri_merkle.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const M_C: u32 = 0x9E3779B9; @@ -52,7 +60,7 @@ fn merkle_verify8(leaf: u32, s0: u32, s1: u32, s2: u32, idx: u32, root: u32) boo return n2 == root; } test "hpair_order_sensitive" { - if (!(hpair(0x11111111, 0x22222222) != hpair(0x22222222, 0x11111111))) @panic("order matters"); + if (!(hpair(0x11111111, 0x22222222) != hpair(0x22222222, 0x11111111))) __t27_assert_fail("\n order matters:\n hpair(0x11111111, 0x22222222) = {any}\n hpair(0x22222222, 0x11111111) = {any}\n", .{ hpair(0x11111111, 0x22222222), hpair(0x22222222, 0x11111111) }); } test "verify_valid_proof_idx3" { const l0 = leaf_hash(0, 1000, 31, 700); @@ -66,7 +74,7 @@ test "verify_valid_proof_idx3" { const root = merkle_root8(l0, l1, l2, l3, l4, l5, l6, l7); const s1 = hpair(l0, l1); const s2 = hpair(hpair(l4, l5), hpair(l6, l7)); - if (!(merkle_verify8(l3, l2, s1, s2, 3, root) == true)) @panic("valid proof for l3"); + if (!(merkle_verify8(l3, l2, s1, s2, 3, root) == true)) __t27_assert_fail("\n valid proof for l3:\n merkle_verify8(l3, l2, s1, s2, 3, root) = {any}\n", .{ merkle_verify8(l3, l2, s1, s2, 3, root) }); } test "verify_valid_proof_idx5" { const l0 = leaf_hash(0, 1000, 31, 700); @@ -80,7 +88,7 @@ test "verify_valid_proof_idx5" { const root = merkle_root8(l0, l1, l2, l3, l4, l5, l6, l7); const s1 = hpair(l6, l7); const s2 = hpair(hpair(l0, l1), hpair(l2, l3)); - if (!(merkle_verify8(l5, l4, s1, s2, 5, root) == true)) @panic("valid proof for l5"); + if (!(merkle_verify8(l5, l4, s1, s2, 5, root) == true)) __t27_assert_fail("\n valid proof for l5:\n merkle_verify8(l5, l4, s1, s2, 5, root) = {any}\n", .{ merkle_verify8(l5, l4, s1, s2, 5, root) }); } test "verify_rejects_forged_reward" { const l0 = leaf_hash(0, 1000, 31, 700); @@ -95,14 +103,14 @@ test "verify_rejects_forged_reward" { const s1 = hpair(l0, l1); const s2 = hpair(hpair(l4, l5), hpair(l6, l7)); const forged = leaf_hash(3, 4000, 20, 9999); - if (!(merkle_verify8(forged, l2, s1, s2, 3, root) == false)) @panic("forged reward rejected"); + if (!(merkle_verify8(forged, l2, s1, s2, 3, root) == false)) __t27_assert_fail("\n forged reward rejected:\n merkle_verify8(forged, l2, s1, s2, 3, root) = {any}\n", .{ merkle_verify8(forged, l2, s1, s2, 3, root) }); } test "root_tamper_evident" { const base = merkle_root8(1, 2, 3, 4, 5, 6, 7, 8); const one = merkle_root8(1, 2, 3, 4, 5, 6, 7, 9); const mid = merkle_root8(1, 2, 99, 4, 5, 6, 7, 8); - if (!(base != one)) @panic("changing a leaf changes the root"); - if (!(base != mid)) @panic("changing a middle leaf changes the root"); + if (!(base != one)) __t27_assert_fail("\n changing a leaf changes the root:\n base = {any}\n one = {any}\n", .{ base, one }); + if (!(base != mid)) __t27_assert_fail("\n changing a middle leaf changes the root:\n base = {any}\n mid = {any}\n", .{ base, mid }); } test "verify_rejects_wrong_sibling" { const l0 = leaf_hash(0, 1000, 31, 700); @@ -116,7 +124,7 @@ test "verify_rejects_wrong_sibling" { const root = merkle_root8(l0, l1, l2, l3, l4, l5, l6, l7); const s1 = hpair(l0, l1); const s2 = hpair(hpair(l4, l5), hpair(l6, l7)); - if (!(merkle_verify8(l3, l7, s1, s2, 3, root) == false)) @panic("wrong sibling s0 rejected"); + if (!(merkle_verify8(l3, l7, s1, s2, 3, root) == false)) __t27_assert_fail("\n wrong sibling s0 rejected:\n merkle_verify8(l3, l7, s1, s2, 3, root) = {any}\n", .{ merkle_verify8(l3, l7, s1, s2, 3, root) }); } test "account_balance_proof" { const a0 = account_leaf(0, 2108); @@ -130,7 +138,7 @@ test "account_balance_proof" { const state_root = merkle_root8(a0, a1, a2, a3, a4, a5, a6, a7); const s1 = hpair(a2, a3); const s2 = hpair(hpair(a4, a5), hpair(a6, a7)); - if (!(merkle_verify8(a0, a1, s1, s2, 0, state_root) == true)) @panic("node0 proves 2108 $TRI"); + if (!(merkle_verify8(a0, a1, s1, s2, 0, state_root) == true)) __t27_assert_fail("\n node0 proves 2108 $TRI:\n merkle_verify8(a0, a1, s1, s2, 0, state_root) = {any}\n", .{ merkle_verify8(a0, a1, s1, s2, 0, state_root) }); const forged = account_leaf(0, 999999); - if (!(merkle_verify8(forged, a1, s1, s2, 0, state_root) == false)) @panic("forged balance rejected"); + if (!(merkle_verify8(forged, a1, s1, s2, 0, state_root) == false)) __t27_assert_fail("\n forged balance rejected:\n merkle_verify8(forged, a1, s1, s2, 0, state_root) = {any}\n", .{ merkle_verify8(forged, a1, s1, s2, 0, state_root) }); } diff --git a/gen/zig/tri_node_identity.zig b/gen/zig/tri_node_identity.zig index 669e182b..ee7ad11b 100644 --- a/gen/zig/tri_node_identity.zig +++ b/gen/zig/tri_node_identity.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const SHA_PAD256: u32 = 0x80000000; @@ -51,18 +59,18 @@ fn who_ok(sig_ok: u32, claimed_executor: u32, hashed_pubkey_lo: u32) bool { } } test "pubkey_preimage_layout" { - if (!(pubkey_pre(0, 0xAA, 1, 2, 3, 4, 5, 6, 7) == 0xAA)) @panic("key word 0 at idx 0"); - if (!(pubkey_pre(7, 0xAA, 1, 2, 3, 4, 5, 6, 0xBB) == 0xBB)) @panic("key word 7 at idx 7"); - if (!(pubkey_pre(8, 0, 0, 0, 0, 0, 0, 0, 0) == SHA_PAD256)) @panic("pad marker at idx 8"); - if (!(pubkey_pre(15, 0, 0, 0, 0, 0, 0, 0, 0) == PUBKEY_BITS)) @panic("256-bit length at idx 15"); - if (!(pubkey_pre(11, 0xAA, 1, 2, 3, 4, 5, 6, 7) == 0)) @panic("interior pad word is zero"); + if (!(pubkey_pre(0, 0xAA, 1, 2, 3, 4, 5, 6, 7) == 0xAA)) __t27_assert_fail("\n key word 0 at idx 0:\n pubkey_pre(0, 0xAA, 1, 2, 3, 4, 5, 6, 7) = {any}\n", .{ pubkey_pre(0, 0xAA, 1, 2, 3, 4, 5, 6, 7) }); + if (!(pubkey_pre(7, 0xAA, 1, 2, 3, 4, 5, 6, 0xBB) == 0xBB)) __t27_assert_fail("\n key word 7 at idx 7:\n pubkey_pre(7, 0xAA, 1, 2, 3, 4, 5, 6, 0xBB) = {any}\n", .{ pubkey_pre(7, 0xAA, 1, 2, 3, 4, 5, 6, 0xBB) }); + if (!(pubkey_pre(8, 0, 0, 0, 0, 0, 0, 0, 0) == SHA_PAD256)) __t27_assert_fail("\n pad marker at idx 8:\n pubkey_pre(8, 0, 0, 0, 0, 0, 0, 0, 0) = {any}\n SHA_PAD256 = {any}\n", .{ pubkey_pre(8, 0, 0, 0, 0, 0, 0, 0, 0), SHA_PAD256 }); + if (!(pubkey_pre(15, 0, 0, 0, 0, 0, 0, 0, 0) == PUBKEY_BITS)) __t27_assert_fail("\n 256-bit length at idx 15:\n pubkey_pre(15, 0, 0, 0, 0, 0, 0, 0, 0) = {any}\n PUBKEY_BITS = {any}\n", .{ pubkey_pre(15, 0, 0, 0, 0, 0, 0, 0, 0), PUBKEY_BITS }); + if (!(pubkey_pre(11, 0xAA, 1, 2, 3, 4, 5, 6, 7) == 0)) __t27_assert_fail("\n interior pad word is zero:\n pubkey_pre(11, 0xAA, 1, 2, 3, 4, 5, 6, 7) = {any}\n", .{ pubkey_pre(11, 0xAA, 1, 2, 3, 4, 5, 6, 7) }); } test "identity_binding" { - if (!(identity_matches(0x1234ABCD, 0x1234ABCD) == true)) @panic("matching commitment accepted"); - if (!(identity_matches(0x0000E0E0, 0x1234ABCD) == false)) @panic("claimed executor != key commitment rejected"); + if (!(identity_matches(0x1234ABCD, 0x1234ABCD) == true)) __t27_assert_fail("\n matching commitment accepted:\n identity_matches(0x1234ABCD, 0x1234ABCD) = {any}\n", .{ identity_matches(0x1234ABCD, 0x1234ABCD) }); + if (!(identity_matches(0x0000E0E0, 0x1234ABCD) == false)) __t27_assert_fail("\n claimed executor != key commitment rejected:\n identity_matches(0x0000E0E0, 0x1234ABCD) = {any}\n", .{ identity_matches(0x0000E0E0, 0x1234ABCD) }); } test "who_needs_sig_and_identity" { - if (!(who_ok(1, 0x1234ABCD, 0x1234ABCD) == true)) @panic("valid sig + matching key -> who ok"); - if (!(who_ok(0, 0x1234ABCD, 0x1234ABCD) == false)) @panic("no signature -> who fails"); - if (!(who_ok(1, 0x0000E0E0, 0x1234ABCD) == false)) @panic("valid sig but wrong signer identity -> who fails"); + if (!(who_ok(1, 0x1234ABCD, 0x1234ABCD) == true)) __t27_assert_fail("\n valid sig + matching key -> who ok:\n who_ok(1, 0x1234ABCD, 0x1234ABCD) = {any}\n", .{ who_ok(1, 0x1234ABCD, 0x1234ABCD) }); + if (!(who_ok(0, 0x1234ABCD, 0x1234ABCD) == false)) __t27_assert_fail("\n no signature -> who fails:\n who_ok(0, 0x1234ABCD, 0x1234ABCD) = {any}\n", .{ who_ok(0, 0x1234ABCD, 0x1234ABCD) }); + if (!(who_ok(1, 0x0000E0E0, 0x1234ABCD) == false)) __t27_assert_fail("\n valid sig but wrong signer identity -> who fails:\n who_ok(1, 0x0000E0E0, 0x1234ABCD) = {any}\n", .{ who_ok(1, 0x0000E0E0, 0x1234ABCD) }); } diff --git a/gen/zig/tri_receipt_verify.zig b/gen/zig/tri_receipt_verify.zig index 57e2a863..8a3c32cf 100644 --- a/gen/zig/tri_receipt_verify.zig +++ b/gen/zig/tri_receipt_verify.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const OK: u32 = 0; @@ -43,25 +51,25 @@ fn reject_reason(sig_ok: u32, included: u32, compute_ok: u32) u32 { } } test "acceptance_needs_all_three" { - if (!(receipt_accepted(1, 1, 1) == true)) @panic("all three pass -> accepted"); - if (!(receipt_accepted(0, 1, 1) == false)) @panic("bad signature -> rejected"); - if (!(receipt_accepted(1, 0, 1) == false)) @panic("not in batch -> rejected"); - if (!(receipt_accepted(1, 1, 0) == false)) @panic("bad compute -> rejected"); - if (!(receipt_accepted(1, 0, 0) == false)) @panic("two failures -> rejected"); + if (!(receipt_accepted(1, 1, 1) == true)) __t27_assert_fail("\n all three pass -> accepted:\n receipt_accepted(1, 1, 1) = {any}\n", .{ receipt_accepted(1, 1, 1) }); + if (!(receipt_accepted(0, 1, 1) == false)) __t27_assert_fail("\n bad signature -> rejected:\n receipt_accepted(0, 1, 1) = {any}\n", .{ receipt_accepted(0, 1, 1) }); + if (!(receipt_accepted(1, 0, 1) == false)) __t27_assert_fail("\n not in batch -> rejected:\n receipt_accepted(1, 0, 1) = {any}\n", .{ receipt_accepted(1, 0, 1) }); + if (!(receipt_accepted(1, 1, 0) == false)) __t27_assert_fail("\n bad compute -> rejected:\n receipt_accepted(1, 1, 0) = {any}\n", .{ receipt_accepted(1, 1, 0) }); + if (!(receipt_accepted(1, 0, 0) == false)) __t27_assert_fail("\n two failures -> rejected:\n receipt_accepted(1, 0, 0) = {any}\n", .{ receipt_accepted(1, 0, 0) }); } test "signature_is_not_correctness" { - if (!(receipt_accepted(1, 1, 0) == false)) @panic("signed but wrong compute -> rejected"); - if (!(reject_reason(1, 1, 0) == BAD_COMPUTE)) @panic("reason: bad compute"); + if (!(receipt_accepted(1, 1, 0) == false)) __t27_assert_fail("\n signed but wrong compute -> rejected:\n receipt_accepted(1, 1, 0) = {any}\n", .{ receipt_accepted(1, 1, 0) }); + if (!(reject_reason(1, 1, 0) == BAD_COMPUTE)) __t27_assert_fail("\n reason: bad compute:\n reject_reason(1, 1, 0) = {any}\n BAD_COMPUTE = {any}\n", .{ reject_reason(1, 1, 0), BAD_COMPUTE }); } test "reason_codes" { - if (!(reject_reason(1, 1, 1) == OK)) @panic("accepted -> OK"); - if (!(reject_reason(0, 1, 1) == BAD_SIG)) @panic("bad sig first"); - if (!(reject_reason(1, 0, 1) == NOT_IN_BATCH)) @panic("not-in-batch when sig ok"); - if (!(reject_reason(0, 0, 0) == BAD_SIG)) @panic("signature checked first"); + if (!(reject_reason(1, 1, 1) == OK)) __t27_assert_fail("\n accepted -> OK:\n reject_reason(1, 1, 1) = {any}\n OK = {any}\n", .{ reject_reason(1, 1, 1), OK }); + if (!(reject_reason(0, 1, 1) == BAD_SIG)) __t27_assert_fail("\n bad sig first:\n reject_reason(0, 1, 1) = {any}\n BAD_SIG = {any}\n", .{ reject_reason(0, 1, 1), BAD_SIG }); + if (!(reject_reason(1, 0, 1) == NOT_IN_BATCH)) __t27_assert_fail("\n not-in-batch when sig ok:\n reject_reason(1, 0, 1) = {any}\n NOT_IN_BATCH = {any}\n", .{ reject_reason(1, 0, 1), NOT_IN_BATCH }); + if (!(reject_reason(0, 0, 0) == BAD_SIG)) __t27_assert_fail("\n signature checked first:\n reject_reason(0, 0, 0) = {any}\n BAD_SIG = {any}\n", .{ reject_reason(0, 0, 0), BAD_SIG }); } test "compute_dispatch_by_op" { - if (!(compute_ok_for_op(GF_OP_MUL, 1, 0) == 1)) @panic("MUL uses mul_ok"); - if (!(compute_ok_for_op(GF_OP_ADD, 0, 1) == 1)) @panic("ADD uses add_ok"); - if (!(compute_ok_for_op(GF_OP_MUL, 0, 1) == 0)) @panic("MUL ignores add_ok"); - if (!(compute_ok_for_op(0x99, 1, 1) == 0)) @panic("unknown op -> not recomputable"); + if (!(compute_ok_for_op(GF_OP_MUL, 1, 0) == 1)) __t27_assert_fail("\n MUL uses mul_ok:\n compute_ok_for_op(GF_OP_MUL, 1, 0) = {any}\n", .{ compute_ok_for_op(GF_OP_MUL, 1, 0) }); + if (!(compute_ok_for_op(GF_OP_ADD, 0, 1) == 1)) __t27_assert_fail("\n ADD uses add_ok:\n compute_ok_for_op(GF_OP_ADD, 0, 1) = {any}\n", .{ compute_ok_for_op(GF_OP_ADD, 0, 1) }); + if (!(compute_ok_for_op(GF_OP_MUL, 0, 1) == 0)) __t27_assert_fail("\n MUL ignores add_ok:\n compute_ok_for_op(GF_OP_MUL, 0, 1) = {any}\n", .{ compute_ok_for_op(GF_OP_MUL, 0, 1) }); + if (!(compute_ok_for_op(0x99, 1, 1) == 0)) __t27_assert_fail("\n unknown op -> not recomputable:\n compute_ok_for_op(0x99, 1, 1) = {any}\n", .{ compute_ok_for_op(0x99, 1, 1) }); } diff --git a/gen/zig/tri_settle.zig b/gen/zig/tri_settle.zig index 9be66656..18a9283e 100644 --- a/gen/zig/tri_settle.zig +++ b/gen/zig/tri_settle.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const PPM: u32 = 1000000; @@ -35,39 +43,39 @@ fn reward_units(node_bytes: u32, round_bytes: u32, pool: u32) u64 { test "share_proportional" { const half = reward_share_ppm(100, 200); const quarter = reward_share_ppm(50, 200); - if (!(half == 500000)) @panic("half"); - if (!(quarter == 250000)) @panic("quarter"); - if (!(half == (quarter + quarter))) @panic("2x bytes = 2x share"); + if (!(half == 500000)) __t27_assert_fail("\n half:\n half = {any}\n", .{ half }); + if (!(quarter == 250000)) __t27_assert_fail("\n quarter:\n quarter = {any}\n", .{ quarter }); + if (!(half == (quarter + quarter))) __t27_assert_fail("\n 2x bytes = 2x share:\n half = {any}\n quarter + quarter = {any}\n", .{ half, quarter + quarter }); } test "share_full" { - if (!(reward_share_ppm(200, 200) == PPM)) @panic("full share"); + if (!(reward_share_ppm(200, 200) == PPM)) __t27_assert_fail("\n full share:\n reward_share_ppm(200, 200) = {any}\n PPM = {any}\n", .{ reward_share_ppm(200, 200), PPM }); } test "share_zero_guard" { - if (!(reward_share_ppm(5, 0) == 0)) @panic("empty round pays nobody"); - if (!(reward_share_ppm(0, 200) == 0)) @panic("no work no share"); + if (!(reward_share_ppm(5, 0) == 0)) __t27_assert_fail("\n empty round pays nobody:\n reward_share_ppm(5, 0) = {any}\n", .{ reward_share_ppm(5, 0) }); + if (!(reward_share_ppm(0, 200) == 0)) __t27_assert_fail("\n no work no share:\n reward_share_ppm(0, 200) = {any}\n", .{ reward_share_ppm(0, 200) }); } test "units_no_free_mint" { - if (!(reward_units(0, 200, 1000) == 0)) @panic("no free mint"); + if (!(reward_units(0, 200, 1000) == 0)) __t27_assert_fail("\n no free mint:\n reward_units(0, 200, 1000) = {any}\n", .{ reward_units(0, 200, 1000) }); } test "units_proportional" { - if (!(reward_units(100, 200, 1000) == 500)) @panic("half of pool"); + if (!(reward_units(100, 200, 1000) == 500)) __t27_assert_fail("\n half of pool:\n reward_units(100, 200, 1000) = {any}\n", .{ reward_units(100, 200, 1000) }); } test "units_conservation" { const a = reward_units(100, 300, 1000); const b = reward_units(200, 300, 1000); - if (!(a == 333)) @panic("node a"); - if (!(b == 666)) @panic("node b"); - if (!((a + b) <= @as(u64, @intCast(1000)))) @panic("sum <= pool"); + if (!(a == 333)) __t27_assert_fail("\n node a:\n a = {any}\n", .{ a }); + if (!(b == 666)) __t27_assert_fail("\n node b:\n b = {any}\n", .{ b }); + if (!((a + b) <= @as(u64, @intCast(1000)))) __t27_assert_fail("\n sum <= pool:\n a + b = {any}\n @as(u64, @intCast(1000)) = {any}\n", .{ a + b, @as(u64, @intCast(1000)) }); } test "round_monotonic" { const r0 = round_add(0, 19974); const r1 = round_add(r0, 40000); - if (!(r1 > r0)) @panic("monotonic"); - if (!(r0 == 19974)) @panic("epoch1"); - if (!(r1 == 59974)) @panic("epoch1+2"); + if (!(r1 > r0)) __t27_assert_fail("\n monotonic:\n r1 = {any}\n r0 = {any}\n", .{ r1, r0 }); + if (!(r0 == 19974)) __t27_assert_fail("\n epoch1:\n r0 = {any}\n", .{ r0 }); + if (!(r1 == 59974)) __t27_assert_fail("\n epoch1+2:\n r1 = {any}\n", .{ r1 }); } test "round_saturates" { - if (!(round_add(0xFFFFFF00, 0x0000FFFF) == 0xFFFFFFFF)) @panic("saturates"); + if (!(round_add(0xFFFFFF00, 0x0000FFFF) == 0xFFFFFFFF)) __t27_assert_fail("\n saturates:\n round_add(0xFFFFFF00, 0x0000FFFF) = {any}\n", .{ round_add(0xFFFFFF00, 0x0000FFFF) }); } fn weighted_contrib(node_bytes: u32, quality: u32) u64 { return @as(u64, @intCast(node_bytes)) * @as(u64, @intCast(quality)); @@ -90,30 +98,30 @@ test "weighted_quality_rewards_coverage" { const wt = round_add_weighted(round_add_weighted(0, 1000, 47), 1000, 10); const a = reward_weighted(1000, 47, wt, 1000); const b = reward_weighted(1000, 10, wt, 1000); - if (!(a > b)) @panic("better link earns more per byte"); - if (!(wt == @as(u64, @intCast(57000)))) @panic("weighted total = 47000 + 10000"); + if (!(a > b)) __t27_assert_fail("\n better link earns more per byte:\n a = {any}\n b = {any}\n", .{ a, b }); + if (!(wt == @as(u64, @intCast(57000)))) __t27_assert_fail("\n weighted total = 47000 + 10000:\n wt = {any}\n @as(u64, @intCast(57000)) = {any}\n", .{ wt, @as(u64, @intCast(57000)) }); } test "weighted_equal_quality_is_proportional" { const wt = round_add_weighted(round_add_weighted(0, 100, 5), 200, 5); const a = reward_weighted(100, 5, wt, 1000); const b = reward_weighted(200, 5, wt, 1000); - if (!(a == 333)) @panic("third"); - if (!(b == 666)) @panic("two thirds"); + if (!(a == 333)) __t27_assert_fail("\n third:\n a = {any}\n", .{ a }); + if (!(b == 666)) __t27_assert_fail("\n two thirds:\n b = {any}\n", .{ b }); } test "weighted_conservation" { const wt = round_add_weighted(round_add_weighted(0, 1000, 47), 500, 30); const a = reward_weighted(1000, 47, wt, 10000); const b = reward_weighted(500, 30, wt, 10000); - if (!((a + b) <= @as(u64, @intCast(10000)))) @panic("sum <= pool"); + if (!((a + b) <= @as(u64, @intCast(10000)))) __t27_assert_fail("\n sum <= pool:\n a + b = {any}\n @as(u64, @intCast(10000)) = {any}\n", .{ a + b, @as(u64, @intCast(10000)) }); } test "weighted_zero_quality" { const wt = round_add_weighted(0, 1000, 47); - if (!(reward_weighted(1000, 0, wt, 1000) == 0)) @panic("dead link no reward"); + if (!(reward_weighted(1000, 0, wt, 1000) == 0)) __t27_assert_fail("\n dead link no reward:\n reward_weighted(1000, 0, wt, 1000) = {any}\n", .{ reward_weighted(1000, 0, wt, 1000) }); } test "weighted_large_total_not_zero" { const big = @as(u64, @intCast(4294967296)); const r = reward_weighted(1000000, 1000, big, 1000); - if (!(r > @as(u64, @intCast(0)))) @panic("large total not read as zero"); + if (!(r > @as(u64, @intCast(0)))) __t27_assert_fail("\n large total not read as zero:\n r = {any}\n @as(u64, @intCast(0)) = {any}\n", .{ r, @as(u64, @intCast(0)) }); } fn snr_to_quality(snr_db: u32) u32 { if (snr_db <= SNR_FLOOR) { @@ -125,17 +133,17 @@ fn snr_to_quality(snr_db: u32) u32 { } } test "snr_quality_floor" { - if (!(snr_to_quality(1) == 0)) @panic("1 dB unusable"); - if (!(snr_to_quality(3) == 0)) @panic("at floor unusable"); + if (!(snr_to_quality(1) == 0)) __t27_assert_fail("\n 1 dB unusable:\n snr_to_quality(1) = {any}\n", .{ snr_to_quality(1) }); + if (!(snr_to_quality(3) == 0)) __t27_assert_fail("\n at floor unusable:\n snr_to_quality(3) = {any}\n", .{ snr_to_quality(3) }); } test "snr_quality_measured" { - if (!(snr_to_quality(34) == 31)) @panic("strong link (.13->.12 -10 dB)"); - if (!(snr_to_quality(5) == 2)) @panic("weak link (.13->.12 -50 dB)"); - if (!(snr_to_quality(34) > snr_to_quality(5))) @panic("stronger link -> higher quality"); + if (!(snr_to_quality(34) == 31)) __t27_assert_fail("\n strong link (.13->.12 -10 dB):\n snr_to_quality(34) = {any}\n", .{ snr_to_quality(34) }); + if (!(snr_to_quality(5) == 2)) __t27_assert_fail("\n weak link (.13->.12 -50 dB):\n snr_to_quality(5) = {any}\n", .{ snr_to_quality(5) }); + if (!(snr_to_quality(34) > snr_to_quality(5))) __t27_assert_fail("\n stronger link -> higher quality:\n snr_to_quality(34) = {any}\n snr_to_quality(5) = {any}\n", .{ snr_to_quality(34), snr_to_quality(5) }); } test "snr_quality_ceiling" { - if (!(snr_to_quality(100) == 37)) @panic("saturates at CEIL-FLOOR"); - if (!(snr_to_quality(40) == 37)) @panic("at ceiling"); + if (!(snr_to_quality(100) == 37)) __t27_assert_fail("\n saturates at CEIL-FLOOR:\n snr_to_quality(100) = {any}\n", .{ snr_to_quality(100) }); + if (!(snr_to_quality(40) == 37)) __t27_assert_fail("\n at ceiling:\n snr_to_quality(40) = {any}\n", .{ snr_to_quality(40) }); } test "snr_drives_reward" { const qa = snr_to_quality(34); @@ -143,5 +151,5 @@ test "snr_drives_reward" { const wt = round_add_weighted(round_add_weighted(0, 10000, qa), 10000, qb); const ra = reward_weighted(10000, qa, wt, 1000); const rb = reward_weighted(10000, qb, wt, 1000); - if (!(ra > rb)) @panic("better coverage earns more $TRI"); + if (!(ra > rb)) __t27_assert_fail("\n better coverage earns more $TRI:\n ra = {any}\n rb = {any}\n", .{ ra, rb }); } diff --git a/gen/zig/tri_sha256.zig b/gen/zig/tri_sha256.zig index c721fcda..fa7231a5 100644 --- a/gen/zig/tri_sha256.zig +++ b/gen/zig/tri_sha256.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module fn rotr(x: u32, n: u32) u32 { @@ -83,655 +91,655 @@ fn sha256_compress(s0: u32, s1: u32, s2: u32, s3: u32, s4: u32, s5: u32, s6: u32 const c0: u32 = s2; const d0: u32 = s3; const e0: u32 = s4; - const @"f0": u32 = s5; + const f0: u32 = s5; const g0: u32 = s6; const h0: u32 = s7; - const t1_0: u32 = (((h0 +% bsig1(e0)) +% ch(e0, @"f0", g0)) +% 0x428A2F98) +% w0; + const t1_0: u32 = (((h0 +% bsig1(e0)) +% ch(e0, f0, g0)) +% 0x428A2F98) +% w0; const t2_0: u32 = bsig0(a0) +% maj(a0, b0, c0); const a1: u32 = t1_0 +% t2_0; const b1: u32 = a0; const c1: u32 = b0; const d1: u32 = c0; const e1: u32 = d0 +% t1_0; - const @"f1": u32 = e0; - const g1: u32 = @"f0"; + const f1: u32 = e0; + const g1: u32 = f0; const h1: u32 = g0; - const t1_1: u32 = (((h1 +% bsig1(e1)) +% ch(e1, @"f1", g1)) +% 0x71374491) +% w1; + const t1_1: u32 = (((h1 +% bsig1(e1)) +% ch(e1, f1, g1)) +% 0x71374491) +% w1; const t2_1: u32 = bsig0(a1) +% maj(a1, b1, c1); const a2: u32 = t1_1 +% t2_1; const b2: u32 = a1; const c2: u32 = b1; const d2: u32 = c1; const e2: u32 = d1 +% t1_1; - const @"f2": u32 = e1; - const g2: u32 = @"f1"; + const f2: u32 = e1; + const g2: u32 = f1; const h2: u32 = g1; - const t1_2: u32 = (((h2 +% bsig1(e2)) +% ch(e2, @"f2", g2)) +% 0xB5C0FBCF) +% w2; + const t1_2: u32 = (((h2 +% bsig1(e2)) +% ch(e2, f2, g2)) +% 0xB5C0FBCF) +% w2; const t2_2: u32 = bsig0(a2) +% maj(a2, b2, c2); const a3: u32 = t1_2 +% t2_2; const b3: u32 = a2; const c3: u32 = b2; const d3: u32 = c2; const e3: u32 = d2 +% t1_2; - const @"f3": u32 = e2; - const g3: u32 = @"f2"; + const f3: u32 = e2; + const g3: u32 = f2; const h3: u32 = g2; - const t1_3: u32 = (((h3 +% bsig1(e3)) +% ch(e3, @"f3", g3)) +% 0xE9B5DBA5) +% w3; + const t1_3: u32 = (((h3 +% bsig1(e3)) +% ch(e3, f3, g3)) +% 0xE9B5DBA5) +% w3; const t2_3: u32 = bsig0(a3) +% maj(a3, b3, c3); const a4: u32 = t1_3 +% t2_3; const b4: u32 = a3; const c4: u32 = b3; const d4: u32 = c3; const e4: u32 = d3 +% t1_3; - const @"f4": u32 = e3; - const g4: u32 = @"f3"; + const f4: u32 = e3; + const g4: u32 = f3; const h4: u32 = g3; - const t1_4: u32 = (((h4 +% bsig1(e4)) +% ch(e4, @"f4", g4)) +% 0x3956C25B) +% w4; + const t1_4: u32 = (((h4 +% bsig1(e4)) +% ch(e4, f4, g4)) +% 0x3956C25B) +% w4; const t2_4: u32 = bsig0(a4) +% maj(a4, b4, c4); const a5: u32 = t1_4 +% t2_4; const b5: u32 = a4; const c5: u32 = b4; const d5: u32 = c4; const e5: u32 = d4 +% t1_4; - const @"f5": u32 = e4; - const g5: u32 = @"f4"; + const f5: u32 = e4; + const g5: u32 = f4; const h5: u32 = g4; - const t1_5: u32 = (((h5 +% bsig1(e5)) +% ch(e5, @"f5", g5)) +% 0x59F111F1) +% w5; + const t1_5: u32 = (((h5 +% bsig1(e5)) +% ch(e5, f5, g5)) +% 0x59F111F1) +% w5; const t2_5: u32 = bsig0(a5) +% maj(a5, b5, c5); const a6: u32 = t1_5 +% t2_5; const b6: u32 = a5; const c6: u32 = b5; const d6: u32 = c5; const e6: u32 = d5 +% t1_5; - const @"f6": u32 = e5; - const g6: u32 = @"f5"; + const f6: u32 = e5; + const g6: u32 = f5; const h6: u32 = g5; - const t1_6: u32 = (((h6 +% bsig1(e6)) +% ch(e6, @"f6", g6)) +% 0x923F82A4) +% w6; + const t1_6: u32 = (((h6 +% bsig1(e6)) +% ch(e6, f6, g6)) +% 0x923F82A4) +% w6; const t2_6: u32 = bsig0(a6) +% maj(a6, b6, c6); const a7: u32 = t1_6 +% t2_6; const b7: u32 = a6; const c7: u32 = b6; const d7: u32 = c6; const e7: u32 = d6 +% t1_6; - const @"f7": u32 = e6; - const g7: u32 = @"f6"; + const f7: u32 = e6; + const g7: u32 = f6; const h7: u32 = g6; - const t1_7: u32 = (((h7 +% bsig1(e7)) +% ch(e7, @"f7", g7)) +% 0xAB1C5ED5) +% w7; + const t1_7: u32 = (((h7 +% bsig1(e7)) +% ch(e7, f7, g7)) +% 0xAB1C5ED5) +% w7; const t2_7: u32 = bsig0(a7) +% maj(a7, b7, c7); const a8: u32 = t1_7 +% t2_7; const b8: u32 = a7; const c8: u32 = b7; const d8: u32 = c7; const e8: u32 = d7 +% t1_7; - const @"f8": u32 = e7; - const g8: u32 = @"f7"; + const f8: u32 = e7; + const g8: u32 = f7; const h8: u32 = g7; - const t1_8: u32 = (((h8 +% bsig1(e8)) +% ch(e8, @"f8", g8)) +% 0xD807AA98) +% w8; + const t1_8: u32 = (((h8 +% bsig1(e8)) +% ch(e8, f8, g8)) +% 0xD807AA98) +% w8; const t2_8: u32 = bsig0(a8) +% maj(a8, b8, c8); const a9: u32 = t1_8 +% t2_8; const b9: u32 = a8; const c9: u32 = b8; const d9: u32 = c8; const e9: u32 = d8 +% t1_8; - const @"f9": u32 = e8; - const g9: u32 = @"f8"; + const f9: u32 = e8; + const g9: u32 = f8; const h9: u32 = g8; - const t1_9: u32 = (((h9 +% bsig1(e9)) +% ch(e9, @"f9", g9)) +% 0x12835B01) +% w9; + const t1_9: u32 = (((h9 +% bsig1(e9)) +% ch(e9, f9, g9)) +% 0x12835B01) +% w9; const t2_9: u32 = bsig0(a9) +% maj(a9, b9, c9); const a10: u32 = t1_9 +% t2_9; const b10: u32 = a9; const c10: u32 = b9; const d10: u32 = c9; const e10: u32 = d9 +% t1_9; - const @"f10": u32 = e9; - const g10: u32 = @"f9"; + const f10: u32 = e9; + const g10: u32 = f9; const h10: u32 = g9; - const t1_10: u32 = (((h10 +% bsig1(e10)) +% ch(e10, @"f10", g10)) +% 0x243185BE) +% w10; + const t1_10: u32 = (((h10 +% bsig1(e10)) +% ch(e10, f10, g10)) +% 0x243185BE) +% w10; const t2_10: u32 = bsig0(a10) +% maj(a10, b10, c10); const a11: u32 = t1_10 +% t2_10; const b11: u32 = a10; const c11: u32 = b10; const d11: u32 = c10; const e11: u32 = d10 +% t1_10; - const @"f11": u32 = e10; - const g11: u32 = @"f10"; + const f11: u32 = e10; + const g11: u32 = f10; const h11: u32 = g10; - const t1_11: u32 = (((h11 +% bsig1(e11)) +% ch(e11, @"f11", g11)) +% 0x550C7DC3) +% w11; + const t1_11: u32 = (((h11 +% bsig1(e11)) +% ch(e11, f11, g11)) +% 0x550C7DC3) +% w11; const t2_11: u32 = bsig0(a11) +% maj(a11, b11, c11); const a12: u32 = t1_11 +% t2_11; const b12: u32 = a11; const c12: u32 = b11; const d12: u32 = c11; const e12: u32 = d11 +% t1_11; - const @"f12": u32 = e11; - const g12: u32 = @"f11"; + const f12: u32 = e11; + const g12: u32 = f11; const h12: u32 = g11; - const t1_12: u32 = (((h12 +% bsig1(e12)) +% ch(e12, @"f12", g12)) +% 0x72BE5D74) +% w12; + const t1_12: u32 = (((h12 +% bsig1(e12)) +% ch(e12, f12, g12)) +% 0x72BE5D74) +% w12; const t2_12: u32 = bsig0(a12) +% maj(a12, b12, c12); const a13: u32 = t1_12 +% t2_12; const b13: u32 = a12; const c13: u32 = b12; const d13: u32 = c12; const e13: u32 = d12 +% t1_12; - const @"f13": u32 = e12; - const g13: u32 = @"f12"; + const f13: u32 = e12; + const g13: u32 = f12; const h13: u32 = g12; - const t1_13: u32 = (((h13 +% bsig1(e13)) +% ch(e13, @"f13", g13)) +% 0x80DEB1FE) +% w13; + const t1_13: u32 = (((h13 +% bsig1(e13)) +% ch(e13, f13, g13)) +% 0x80DEB1FE) +% w13; const t2_13: u32 = bsig0(a13) +% maj(a13, b13, c13); const a14: u32 = t1_13 +% t2_13; const b14: u32 = a13; const c14: u32 = b13; const d14: u32 = c13; const e14: u32 = d13 +% t1_13; - const @"f14": u32 = e13; - const g14: u32 = @"f13"; + const f14: u32 = e13; + const g14: u32 = f13; const h14: u32 = g13; - const t1_14: u32 = (((h14 +% bsig1(e14)) +% ch(e14, @"f14", g14)) +% 0x9BDC06A7) +% w14; + const t1_14: u32 = (((h14 +% bsig1(e14)) +% ch(e14, f14, g14)) +% 0x9BDC06A7) +% w14; const t2_14: u32 = bsig0(a14) +% maj(a14, b14, c14); const a15: u32 = t1_14 +% t2_14; const b15: u32 = a14; const c15: u32 = b14; const d15: u32 = c14; const e15: u32 = d14 +% t1_14; - const @"f15": u32 = e14; - const g15: u32 = @"f14"; + const f15: u32 = e14; + const g15: u32 = f14; const h15: u32 = g14; - const t1_15: u32 = (((h15 +% bsig1(e15)) +% ch(e15, @"f15", g15)) +% 0xC19BF174) +% w15; + const t1_15: u32 = (((h15 +% bsig1(e15)) +% ch(e15, f15, g15)) +% 0xC19BF174) +% w15; const t2_15: u32 = bsig0(a15) +% maj(a15, b15, c15); const a16: u32 = t1_15 +% t2_15; const b16: u32 = a15; const c16: u32 = b15; const d16: u32 = c15; const e16: u32 = d15 +% t1_15; - const @"f16": u32 = e15; - const g16: u32 = @"f15"; + const f16: u32 = e15; + const g16: u32 = f15; const h16: u32 = g15; - const t1_16: u32 = (((h16 +% bsig1(e16)) +% ch(e16, @"f16", g16)) +% 0xE49B69C1) +% w16; + const t1_16: u32 = (((h16 +% bsig1(e16)) +% ch(e16, f16, g16)) +% 0xE49B69C1) +% w16; const t2_16: u32 = bsig0(a16) +% maj(a16, b16, c16); const a17: u32 = t1_16 +% t2_16; const b17: u32 = a16; const c17: u32 = b16; const d17: u32 = c16; const e17: u32 = d16 +% t1_16; - const @"f17": u32 = e16; - const g17: u32 = @"f16"; + const f17: u32 = e16; + const g17: u32 = f16; const h17: u32 = g16; - const t1_17: u32 = (((h17 +% bsig1(e17)) +% ch(e17, @"f17", g17)) +% 0xEFBE4786) +% w17; + const t1_17: u32 = (((h17 +% bsig1(e17)) +% ch(e17, f17, g17)) +% 0xEFBE4786) +% w17; const t2_17: u32 = bsig0(a17) +% maj(a17, b17, c17); const a18: u32 = t1_17 +% t2_17; const b18: u32 = a17; const c18: u32 = b17; const d18: u32 = c17; const e18: u32 = d17 +% t1_17; - const @"f18": u32 = e17; - const g18: u32 = @"f17"; + const f18: u32 = e17; + const g18: u32 = f17; const h18: u32 = g17; - const t1_18: u32 = (((h18 +% bsig1(e18)) +% ch(e18, @"f18", g18)) +% 0x0FC19DC6) +% w18; + const t1_18: u32 = (((h18 +% bsig1(e18)) +% ch(e18, f18, g18)) +% 0x0FC19DC6) +% w18; const t2_18: u32 = bsig0(a18) +% maj(a18, b18, c18); const a19: u32 = t1_18 +% t2_18; const b19: u32 = a18; const c19: u32 = b18; const d19: u32 = c18; const e19: u32 = d18 +% t1_18; - const @"f19": u32 = e18; - const g19: u32 = @"f18"; + const f19: u32 = e18; + const g19: u32 = f18; const h19: u32 = g18; - const t1_19: u32 = (((h19 +% bsig1(e19)) +% ch(e19, @"f19", g19)) +% 0x240CA1CC) +% w19; + const t1_19: u32 = (((h19 +% bsig1(e19)) +% ch(e19, f19, g19)) +% 0x240CA1CC) +% w19; const t2_19: u32 = bsig0(a19) +% maj(a19, b19, c19); const a20: u32 = t1_19 +% t2_19; const b20: u32 = a19; const c20: u32 = b19; const d20: u32 = c19; const e20: u32 = d19 +% t1_19; - const @"f20": u32 = e19; - const g20: u32 = @"f19"; + const f20: u32 = e19; + const g20: u32 = f19; const h20: u32 = g19; - const t1_20: u32 = (((h20 +% bsig1(e20)) +% ch(e20, @"f20", g20)) +% 0x2DE92C6F) +% w20; + const t1_20: u32 = (((h20 +% bsig1(e20)) +% ch(e20, f20, g20)) +% 0x2DE92C6F) +% w20; const t2_20: u32 = bsig0(a20) +% maj(a20, b20, c20); const a21: u32 = t1_20 +% t2_20; const b21: u32 = a20; const c21: u32 = b20; const d21: u32 = c20; const e21: u32 = d20 +% t1_20; - const @"f21": u32 = e20; - const g21: u32 = @"f20"; + const f21: u32 = e20; + const g21: u32 = f20; const h21: u32 = g20; - const t1_21: u32 = (((h21 +% bsig1(e21)) +% ch(e21, @"f21", g21)) +% 0x4A7484AA) +% w21; + const t1_21: u32 = (((h21 +% bsig1(e21)) +% ch(e21, f21, g21)) +% 0x4A7484AA) +% w21; const t2_21: u32 = bsig0(a21) +% maj(a21, b21, c21); const a22: u32 = t1_21 +% t2_21; const b22: u32 = a21; const c22: u32 = b21; const d22: u32 = c21; const e22: u32 = d21 +% t1_21; - const @"f22": u32 = e21; - const g22: u32 = @"f21"; + const f22: u32 = e21; + const g22: u32 = f21; const h22: u32 = g21; - const t1_22: u32 = (((h22 +% bsig1(e22)) +% ch(e22, @"f22", g22)) +% 0x5CB0A9DC) +% w22; + const t1_22: u32 = (((h22 +% bsig1(e22)) +% ch(e22, f22, g22)) +% 0x5CB0A9DC) +% w22; const t2_22: u32 = bsig0(a22) +% maj(a22, b22, c22); const a23: u32 = t1_22 +% t2_22; const b23: u32 = a22; const c23: u32 = b22; const d23: u32 = c22; const e23: u32 = d22 +% t1_22; - const @"f23": u32 = e22; - const g23: u32 = @"f22"; + const f23: u32 = e22; + const g23: u32 = f22; const h23: u32 = g22; - const t1_23: u32 = (((h23 +% bsig1(e23)) +% ch(e23, @"f23", g23)) +% 0x76F988DA) +% w23; + const t1_23: u32 = (((h23 +% bsig1(e23)) +% ch(e23, f23, g23)) +% 0x76F988DA) +% w23; const t2_23: u32 = bsig0(a23) +% maj(a23, b23, c23); const a24: u32 = t1_23 +% t2_23; const b24: u32 = a23; const c24: u32 = b23; const d24: u32 = c23; const e24: u32 = d23 +% t1_23; - const @"f24": u32 = e23; - const g24: u32 = @"f23"; + const f24: u32 = e23; + const g24: u32 = f23; const h24: u32 = g23; - const t1_24: u32 = (((h24 +% bsig1(e24)) +% ch(e24, @"f24", g24)) +% 0x983E5152) +% w24; + const t1_24: u32 = (((h24 +% bsig1(e24)) +% ch(e24, f24, g24)) +% 0x983E5152) +% w24; const t2_24: u32 = bsig0(a24) +% maj(a24, b24, c24); const a25: u32 = t1_24 +% t2_24; const b25: u32 = a24; const c25: u32 = b24; const d25: u32 = c24; const e25: u32 = d24 +% t1_24; - const @"f25": u32 = e24; - const g25: u32 = @"f24"; + const f25: u32 = e24; + const g25: u32 = f24; const h25: u32 = g24; - const t1_25: u32 = (((h25 +% bsig1(e25)) +% ch(e25, @"f25", g25)) +% 0xA831C66D) +% w25; + const t1_25: u32 = (((h25 +% bsig1(e25)) +% ch(e25, f25, g25)) +% 0xA831C66D) +% w25; const t2_25: u32 = bsig0(a25) +% maj(a25, b25, c25); const a26: u32 = t1_25 +% t2_25; const b26: u32 = a25; const c26: u32 = b25; const d26: u32 = c25; const e26: u32 = d25 +% t1_25; - const @"f26": u32 = e25; - const g26: u32 = @"f25"; + const f26: u32 = e25; + const g26: u32 = f25; const h26: u32 = g25; - const t1_26: u32 = (((h26 +% bsig1(e26)) +% ch(e26, @"f26", g26)) +% 0xB00327C8) +% w26; + const t1_26: u32 = (((h26 +% bsig1(e26)) +% ch(e26, f26, g26)) +% 0xB00327C8) +% w26; const t2_26: u32 = bsig0(a26) +% maj(a26, b26, c26); const a27: u32 = t1_26 +% t2_26; const b27: u32 = a26; const c27: u32 = b26; const d27: u32 = c26; const e27: u32 = d26 +% t1_26; - const @"f27": u32 = e26; - const g27: u32 = @"f26"; + const f27: u32 = e26; + const g27: u32 = f26; const h27: u32 = g26; - const t1_27: u32 = (((h27 +% bsig1(e27)) +% ch(e27, @"f27", g27)) +% 0xBF597FC7) +% w27; + const t1_27: u32 = (((h27 +% bsig1(e27)) +% ch(e27, f27, g27)) +% 0xBF597FC7) +% w27; const t2_27: u32 = bsig0(a27) +% maj(a27, b27, c27); const a28: u32 = t1_27 +% t2_27; const b28: u32 = a27; const c28: u32 = b27; const d28: u32 = c27; const e28: u32 = d27 +% t1_27; - const @"f28": u32 = e27; - const g28: u32 = @"f27"; + const f28: u32 = e27; + const g28: u32 = f27; const h28: u32 = g27; - const t1_28: u32 = (((h28 +% bsig1(e28)) +% ch(e28, @"f28", g28)) +% 0xC6E00BF3) +% w28; + const t1_28: u32 = (((h28 +% bsig1(e28)) +% ch(e28, f28, g28)) +% 0xC6E00BF3) +% w28; const t2_28: u32 = bsig0(a28) +% maj(a28, b28, c28); const a29: u32 = t1_28 +% t2_28; const b29: u32 = a28; const c29: u32 = b28; const d29: u32 = c28; const e29: u32 = d28 +% t1_28; - const @"f29": u32 = e28; - const g29: u32 = @"f28"; + const f29: u32 = e28; + const g29: u32 = f28; const h29: u32 = g28; - const t1_29: u32 = (((h29 +% bsig1(e29)) +% ch(e29, @"f29", g29)) +% 0xD5A79147) +% w29; + const t1_29: u32 = (((h29 +% bsig1(e29)) +% ch(e29, f29, g29)) +% 0xD5A79147) +% w29; const t2_29: u32 = bsig0(a29) +% maj(a29, b29, c29); const a30: u32 = t1_29 +% t2_29; const b30: u32 = a29; const c30: u32 = b29; const d30: u32 = c29; const e30: u32 = d29 +% t1_29; - const @"f30": u32 = e29; - const g30: u32 = @"f29"; + const f30: u32 = e29; + const g30: u32 = f29; const h30: u32 = g29; - const t1_30: u32 = (((h30 +% bsig1(e30)) +% ch(e30, @"f30", g30)) +% 0x06CA6351) +% w30; + const t1_30: u32 = (((h30 +% bsig1(e30)) +% ch(e30, f30, g30)) +% 0x06CA6351) +% w30; const t2_30: u32 = bsig0(a30) +% maj(a30, b30, c30); const a31: u32 = t1_30 +% t2_30; const b31: u32 = a30; const c31: u32 = b30; const d31: u32 = c30; const e31: u32 = d30 +% t1_30; - const @"f31": u32 = e30; - const g31: u32 = @"f30"; + const f31: u32 = e30; + const g31: u32 = f30; const h31: u32 = g30; - const t1_31: u32 = (((h31 +% bsig1(e31)) +% ch(e31, @"f31", g31)) +% 0x14292967) +% w31; + const t1_31: u32 = (((h31 +% bsig1(e31)) +% ch(e31, f31, g31)) +% 0x14292967) +% w31; const t2_31: u32 = bsig0(a31) +% maj(a31, b31, c31); const a32: u32 = t1_31 +% t2_31; const b32: u32 = a31; const c32: u32 = b31; const d32: u32 = c31; const e32: u32 = d31 +% t1_31; - const @"f32": u32 = e31; - const g32: u32 = @"f31"; + const f32: u32 = e31; + const g32: u32 = f31; const h32: u32 = g31; - const t1_32: u32 = (((h32 +% bsig1(e32)) +% ch(e32, @"f32", g32)) +% 0x27B70A85) +% w32; + const t1_32: u32 = (((h32 +% bsig1(e32)) +% ch(e32, f32, g32)) +% 0x27B70A85) +% w32; const t2_32: u32 = bsig0(a32) +% maj(a32, b32, c32); const a33: u32 = t1_32 +% t2_32; const b33: u32 = a32; const c33: u32 = b32; const d33: u32 = c32; const e33: u32 = d32 +% t1_32; - const @"f33": u32 = e32; - const g33: u32 = @"f32"; + const f33: u32 = e32; + const g33: u32 = f32; const h33: u32 = g32; - const t1_33: u32 = (((h33 +% bsig1(e33)) +% ch(e33, @"f33", g33)) +% 0x2E1B2138) +% w33; + const t1_33: u32 = (((h33 +% bsig1(e33)) +% ch(e33, f33, g33)) +% 0x2E1B2138) +% w33; const t2_33: u32 = bsig0(a33) +% maj(a33, b33, c33); const a34: u32 = t1_33 +% t2_33; const b34: u32 = a33; const c34: u32 = b33; const d34: u32 = c33; const e34: u32 = d33 +% t1_33; - const @"f34": u32 = e33; - const g34: u32 = @"f33"; + const f34: u32 = e33; + const g34: u32 = f33; const h34: u32 = g33; - const t1_34: u32 = (((h34 +% bsig1(e34)) +% ch(e34, @"f34", g34)) +% 0x4D2C6DFC) +% w34; + const t1_34: u32 = (((h34 +% bsig1(e34)) +% ch(e34, f34, g34)) +% 0x4D2C6DFC) +% w34; const t2_34: u32 = bsig0(a34) +% maj(a34, b34, c34); const a35: u32 = t1_34 +% t2_34; const b35: u32 = a34; const c35: u32 = b34; const d35: u32 = c34; const e35: u32 = d34 +% t1_34; - const @"f35": u32 = e34; - const g35: u32 = @"f34"; + const f35: u32 = e34; + const g35: u32 = f34; const h35: u32 = g34; - const t1_35: u32 = (((h35 +% bsig1(e35)) +% ch(e35, @"f35", g35)) +% 0x53380D13) +% w35; + const t1_35: u32 = (((h35 +% bsig1(e35)) +% ch(e35, f35, g35)) +% 0x53380D13) +% w35; const t2_35: u32 = bsig0(a35) +% maj(a35, b35, c35); const a36: u32 = t1_35 +% t2_35; const b36: u32 = a35; const c36: u32 = b35; const d36: u32 = c35; const e36: u32 = d35 +% t1_35; - const @"f36": u32 = e35; - const g36: u32 = @"f35"; + const f36: u32 = e35; + const g36: u32 = f35; const h36: u32 = g35; - const t1_36: u32 = (((h36 +% bsig1(e36)) +% ch(e36, @"f36", g36)) +% 0x650A7354) +% w36; + const t1_36: u32 = (((h36 +% bsig1(e36)) +% ch(e36, f36, g36)) +% 0x650A7354) +% w36; const t2_36: u32 = bsig0(a36) +% maj(a36, b36, c36); const a37: u32 = t1_36 +% t2_36; const b37: u32 = a36; const c37: u32 = b36; const d37: u32 = c36; const e37: u32 = d36 +% t1_36; - const @"f37": u32 = e36; - const g37: u32 = @"f36"; + const f37: u32 = e36; + const g37: u32 = f36; const h37: u32 = g36; - const t1_37: u32 = (((h37 +% bsig1(e37)) +% ch(e37, @"f37", g37)) +% 0x766A0ABB) +% w37; + const t1_37: u32 = (((h37 +% bsig1(e37)) +% ch(e37, f37, g37)) +% 0x766A0ABB) +% w37; const t2_37: u32 = bsig0(a37) +% maj(a37, b37, c37); const a38: u32 = t1_37 +% t2_37; const b38: u32 = a37; const c38: u32 = b37; const d38: u32 = c37; const e38: u32 = d37 +% t1_37; - const @"f38": u32 = e37; - const g38: u32 = @"f37"; + const f38: u32 = e37; + const g38: u32 = f37; const h38: u32 = g37; - const t1_38: u32 = (((h38 +% bsig1(e38)) +% ch(e38, @"f38", g38)) +% 0x81C2C92E) +% w38; + const t1_38: u32 = (((h38 +% bsig1(e38)) +% ch(e38, f38, g38)) +% 0x81C2C92E) +% w38; const t2_38: u32 = bsig0(a38) +% maj(a38, b38, c38); const a39: u32 = t1_38 +% t2_38; const b39: u32 = a38; const c39: u32 = b38; const d39: u32 = c38; const e39: u32 = d38 +% t1_38; - const @"f39": u32 = e38; - const g39: u32 = @"f38"; + const f39: u32 = e38; + const g39: u32 = f38; const h39: u32 = g38; - const t1_39: u32 = (((h39 +% bsig1(e39)) +% ch(e39, @"f39", g39)) +% 0x92722C85) +% w39; + const t1_39: u32 = (((h39 +% bsig1(e39)) +% ch(e39, f39, g39)) +% 0x92722C85) +% w39; const t2_39: u32 = bsig0(a39) +% maj(a39, b39, c39); const a40: u32 = t1_39 +% t2_39; const b40: u32 = a39; const c40: u32 = b39; const d40: u32 = c39; const e40: u32 = d39 +% t1_39; - const @"f40": u32 = e39; - const g40: u32 = @"f39"; + const f40: u32 = e39; + const g40: u32 = f39; const h40: u32 = g39; - const t1_40: u32 = (((h40 +% bsig1(e40)) +% ch(e40, @"f40", g40)) +% 0xA2BFE8A1) +% w40; + const t1_40: u32 = (((h40 +% bsig1(e40)) +% ch(e40, f40, g40)) +% 0xA2BFE8A1) +% w40; const t2_40: u32 = bsig0(a40) +% maj(a40, b40, c40); const a41: u32 = t1_40 +% t2_40; const b41: u32 = a40; const c41: u32 = b40; const d41: u32 = c40; const e41: u32 = d40 +% t1_40; - const @"f41": u32 = e40; - const g41: u32 = @"f40"; + const f41: u32 = e40; + const g41: u32 = f40; const h41: u32 = g40; - const t1_41: u32 = (((h41 +% bsig1(e41)) +% ch(e41, @"f41", g41)) +% 0xA81A664B) +% w41; + const t1_41: u32 = (((h41 +% bsig1(e41)) +% ch(e41, f41, g41)) +% 0xA81A664B) +% w41; const t2_41: u32 = bsig0(a41) +% maj(a41, b41, c41); const a42: u32 = t1_41 +% t2_41; const b42: u32 = a41; const c42: u32 = b41; const d42: u32 = c41; const e42: u32 = d41 +% t1_41; - const @"f42": u32 = e41; - const g42: u32 = @"f41"; + const f42: u32 = e41; + const g42: u32 = f41; const h42: u32 = g41; - const t1_42: u32 = (((h42 +% bsig1(e42)) +% ch(e42, @"f42", g42)) +% 0xC24B8B70) +% w42; + const t1_42: u32 = (((h42 +% bsig1(e42)) +% ch(e42, f42, g42)) +% 0xC24B8B70) +% w42; const t2_42: u32 = bsig0(a42) +% maj(a42, b42, c42); const a43: u32 = t1_42 +% t2_42; const b43: u32 = a42; const c43: u32 = b42; const d43: u32 = c42; const e43: u32 = d42 +% t1_42; - const @"f43": u32 = e42; - const g43: u32 = @"f42"; + const f43: u32 = e42; + const g43: u32 = f42; const h43: u32 = g42; - const t1_43: u32 = (((h43 +% bsig1(e43)) +% ch(e43, @"f43", g43)) +% 0xC76C51A3) +% w43; + const t1_43: u32 = (((h43 +% bsig1(e43)) +% ch(e43, f43, g43)) +% 0xC76C51A3) +% w43; const t2_43: u32 = bsig0(a43) +% maj(a43, b43, c43); const a44: u32 = t1_43 +% t2_43; const b44: u32 = a43; const c44: u32 = b43; const d44: u32 = c43; const e44: u32 = d43 +% t1_43; - const @"f44": u32 = e43; - const g44: u32 = @"f43"; + const f44: u32 = e43; + const g44: u32 = f43; const h44: u32 = g43; - const t1_44: u32 = (((h44 +% bsig1(e44)) +% ch(e44, @"f44", g44)) +% 0xD192E819) +% w44; + const t1_44: u32 = (((h44 +% bsig1(e44)) +% ch(e44, f44, g44)) +% 0xD192E819) +% w44; const t2_44: u32 = bsig0(a44) +% maj(a44, b44, c44); const a45: u32 = t1_44 +% t2_44; const b45: u32 = a44; const c45: u32 = b44; const d45: u32 = c44; const e45: u32 = d44 +% t1_44; - const @"f45": u32 = e44; - const g45: u32 = @"f44"; + const f45: u32 = e44; + const g45: u32 = f44; const h45: u32 = g44; - const t1_45: u32 = (((h45 +% bsig1(e45)) +% ch(e45, @"f45", g45)) +% 0xD6990624) +% w45; + const t1_45: u32 = (((h45 +% bsig1(e45)) +% ch(e45, f45, g45)) +% 0xD6990624) +% w45; const t2_45: u32 = bsig0(a45) +% maj(a45, b45, c45); const a46: u32 = t1_45 +% t2_45; const b46: u32 = a45; const c46: u32 = b45; const d46: u32 = c45; const e46: u32 = d45 +% t1_45; - const @"f46": u32 = e45; - const g46: u32 = @"f45"; + const f46: u32 = e45; + const g46: u32 = f45; const h46: u32 = g45; - const t1_46: u32 = (((h46 +% bsig1(e46)) +% ch(e46, @"f46", g46)) +% 0xF40E3585) +% w46; + const t1_46: u32 = (((h46 +% bsig1(e46)) +% ch(e46, f46, g46)) +% 0xF40E3585) +% w46; const t2_46: u32 = bsig0(a46) +% maj(a46, b46, c46); const a47: u32 = t1_46 +% t2_46; const b47: u32 = a46; const c47: u32 = b46; const d47: u32 = c46; const e47: u32 = d46 +% t1_46; - const @"f47": u32 = e46; - const g47: u32 = @"f46"; + const f47: u32 = e46; + const g47: u32 = f46; const h47: u32 = g46; - const t1_47: u32 = (((h47 +% bsig1(e47)) +% ch(e47, @"f47", g47)) +% 0x106AA070) +% w47; + const t1_47: u32 = (((h47 +% bsig1(e47)) +% ch(e47, f47, g47)) +% 0x106AA070) +% w47; const t2_47: u32 = bsig0(a47) +% maj(a47, b47, c47); const a48: u32 = t1_47 +% t2_47; const b48: u32 = a47; const c48: u32 = b47; const d48: u32 = c47; const e48: u32 = d47 +% t1_47; - const @"f48": u32 = e47; - const g48: u32 = @"f47"; + const f48: u32 = e47; + const g48: u32 = f47; const h48: u32 = g47; - const t1_48: u32 = (((h48 +% bsig1(e48)) +% ch(e48, @"f48", g48)) +% 0x19A4C116) +% w48; + const t1_48: u32 = (((h48 +% bsig1(e48)) +% ch(e48, f48, g48)) +% 0x19A4C116) +% w48; const t2_48: u32 = bsig0(a48) +% maj(a48, b48, c48); const a49: u32 = t1_48 +% t2_48; const b49: u32 = a48; const c49: u32 = b48; const d49: u32 = c48; const e49: u32 = d48 +% t1_48; - const @"f49": u32 = e48; - const g49: u32 = @"f48"; + const f49: u32 = e48; + const g49: u32 = f48; const h49: u32 = g48; - const t1_49: u32 = (((h49 +% bsig1(e49)) +% ch(e49, @"f49", g49)) +% 0x1E376C08) +% w49; + const t1_49: u32 = (((h49 +% bsig1(e49)) +% ch(e49, f49, g49)) +% 0x1E376C08) +% w49; const t2_49: u32 = bsig0(a49) +% maj(a49, b49, c49); const a50: u32 = t1_49 +% t2_49; const b50: u32 = a49; const c50: u32 = b49; const d50: u32 = c49; const e50: u32 = d49 +% t1_49; - const @"f50": u32 = e49; - const g50: u32 = @"f49"; + const f50: u32 = e49; + const g50: u32 = f49; const h50: u32 = g49; - const t1_50: u32 = (((h50 +% bsig1(e50)) +% ch(e50, @"f50", g50)) +% 0x2748774C) +% w50; + const t1_50: u32 = (((h50 +% bsig1(e50)) +% ch(e50, f50, g50)) +% 0x2748774C) +% w50; const t2_50: u32 = bsig0(a50) +% maj(a50, b50, c50); const a51: u32 = t1_50 +% t2_50; const b51: u32 = a50; const c51: u32 = b50; const d51: u32 = c50; const e51: u32 = d50 +% t1_50; - const @"f51": u32 = e50; - const g51: u32 = @"f50"; + const f51: u32 = e50; + const g51: u32 = f50; const h51: u32 = g50; - const t1_51: u32 = (((h51 +% bsig1(e51)) +% ch(e51, @"f51", g51)) +% 0x34B0BCB5) +% w51; + const t1_51: u32 = (((h51 +% bsig1(e51)) +% ch(e51, f51, g51)) +% 0x34B0BCB5) +% w51; const t2_51: u32 = bsig0(a51) +% maj(a51, b51, c51); const a52: u32 = t1_51 +% t2_51; const b52: u32 = a51; const c52: u32 = b51; const d52: u32 = c51; const e52: u32 = d51 +% t1_51; - const @"f52": u32 = e51; - const g52: u32 = @"f51"; + const f52: u32 = e51; + const g52: u32 = f51; const h52: u32 = g51; - const t1_52: u32 = (((h52 +% bsig1(e52)) +% ch(e52, @"f52", g52)) +% 0x391C0CB3) +% w52; + const t1_52: u32 = (((h52 +% bsig1(e52)) +% ch(e52, f52, g52)) +% 0x391C0CB3) +% w52; const t2_52: u32 = bsig0(a52) +% maj(a52, b52, c52); const a53: u32 = t1_52 +% t2_52; const b53: u32 = a52; const c53: u32 = b52; const d53: u32 = c52; const e53: u32 = d52 +% t1_52; - const @"f53": u32 = e52; - const g53: u32 = @"f52"; + const f53: u32 = e52; + const g53: u32 = f52; const h53: u32 = g52; - const t1_53: u32 = (((h53 +% bsig1(e53)) +% ch(e53, @"f53", g53)) +% 0x4ED8AA4A) +% w53; + const t1_53: u32 = (((h53 +% bsig1(e53)) +% ch(e53, f53, g53)) +% 0x4ED8AA4A) +% w53; const t2_53: u32 = bsig0(a53) +% maj(a53, b53, c53); const a54: u32 = t1_53 +% t2_53; const b54: u32 = a53; const c54: u32 = b53; const d54: u32 = c53; const e54: u32 = d53 +% t1_53; - const @"f54": u32 = e53; - const g54: u32 = @"f53"; + const f54: u32 = e53; + const g54: u32 = f53; const h54: u32 = g53; - const t1_54: u32 = (((h54 +% bsig1(e54)) +% ch(e54, @"f54", g54)) +% 0x5B9CCA4F) +% w54; + const t1_54: u32 = (((h54 +% bsig1(e54)) +% ch(e54, f54, g54)) +% 0x5B9CCA4F) +% w54; const t2_54: u32 = bsig0(a54) +% maj(a54, b54, c54); const a55: u32 = t1_54 +% t2_54; const b55: u32 = a54; const c55: u32 = b54; const d55: u32 = c54; const e55: u32 = d54 +% t1_54; - const @"f55": u32 = e54; - const g55: u32 = @"f54"; + const f55: u32 = e54; + const g55: u32 = f54; const h55: u32 = g54; - const t1_55: u32 = (((h55 +% bsig1(e55)) +% ch(e55, @"f55", g55)) +% 0x682E6FF3) +% w55; + const t1_55: u32 = (((h55 +% bsig1(e55)) +% ch(e55, f55, g55)) +% 0x682E6FF3) +% w55; const t2_55: u32 = bsig0(a55) +% maj(a55, b55, c55); const a56: u32 = t1_55 +% t2_55; const b56: u32 = a55; const c56: u32 = b55; const d56: u32 = c55; const e56: u32 = d55 +% t1_55; - const @"f56": u32 = e55; - const g56: u32 = @"f55"; + const f56: u32 = e55; + const g56: u32 = f55; const h56: u32 = g55; - const t1_56: u32 = (((h56 +% bsig1(e56)) +% ch(e56, @"f56", g56)) +% 0x748F82EE) +% w56; + const t1_56: u32 = (((h56 +% bsig1(e56)) +% ch(e56, f56, g56)) +% 0x748F82EE) +% w56; const t2_56: u32 = bsig0(a56) +% maj(a56, b56, c56); const a57: u32 = t1_56 +% t2_56; const b57: u32 = a56; const c57: u32 = b56; const d57: u32 = c56; const e57: u32 = d56 +% t1_56; - const @"f57": u32 = e56; - const g57: u32 = @"f56"; + const f57: u32 = e56; + const g57: u32 = f56; const h57: u32 = g56; - const t1_57: u32 = (((h57 +% bsig1(e57)) +% ch(e57, @"f57", g57)) +% 0x78A5636F) +% w57; + const t1_57: u32 = (((h57 +% bsig1(e57)) +% ch(e57, f57, g57)) +% 0x78A5636F) +% w57; const t2_57: u32 = bsig0(a57) +% maj(a57, b57, c57); const a58: u32 = t1_57 +% t2_57; const b58: u32 = a57; const c58: u32 = b57; const d58: u32 = c57; const e58: u32 = d57 +% t1_57; - const @"f58": u32 = e57; - const g58: u32 = @"f57"; + const f58: u32 = e57; + const g58: u32 = f57; const h58: u32 = g57; - const t1_58: u32 = (((h58 +% bsig1(e58)) +% ch(e58, @"f58", g58)) +% 0x84C87814) +% w58; + const t1_58: u32 = (((h58 +% bsig1(e58)) +% ch(e58, f58, g58)) +% 0x84C87814) +% w58; const t2_58: u32 = bsig0(a58) +% maj(a58, b58, c58); const a59: u32 = t1_58 +% t2_58; const b59: u32 = a58; const c59: u32 = b58; const d59: u32 = c58; const e59: u32 = d58 +% t1_58; - const @"f59": u32 = e58; - const g59: u32 = @"f58"; + const f59: u32 = e58; + const g59: u32 = f58; const h59: u32 = g58; - const t1_59: u32 = (((h59 +% bsig1(e59)) +% ch(e59, @"f59", g59)) +% 0x8CC70208) +% w59; + const t1_59: u32 = (((h59 +% bsig1(e59)) +% ch(e59, f59, g59)) +% 0x8CC70208) +% w59; const t2_59: u32 = bsig0(a59) +% maj(a59, b59, c59); const a60: u32 = t1_59 +% t2_59; const b60: u32 = a59; const c60: u32 = b59; const d60: u32 = c59; const e60: u32 = d59 +% t1_59; - const @"f60": u32 = e59; - const g60: u32 = @"f59"; + const f60: u32 = e59; + const g60: u32 = f59; const h60: u32 = g59; - const t1_60: u32 = (((h60 +% bsig1(e60)) +% ch(e60, @"f60", g60)) +% 0x90BEFFFA) +% w60; + const t1_60: u32 = (((h60 +% bsig1(e60)) +% ch(e60, f60, g60)) +% 0x90BEFFFA) +% w60; const t2_60: u32 = bsig0(a60) +% maj(a60, b60, c60); const a61: u32 = t1_60 +% t2_60; const b61: u32 = a60; const c61: u32 = b60; const d61: u32 = c60; const e61: u32 = d60 +% t1_60; - const @"f61": u32 = e60; - const g61: u32 = @"f60"; + const f61: u32 = e60; + const g61: u32 = f60; const h61: u32 = g60; - const t1_61: u32 = (((h61 +% bsig1(e61)) +% ch(e61, @"f61", g61)) +% 0xA4506CEB) +% w61; + const t1_61: u32 = (((h61 +% bsig1(e61)) +% ch(e61, f61, g61)) +% 0xA4506CEB) +% w61; const t2_61: u32 = bsig0(a61) +% maj(a61, b61, c61); const a62: u32 = t1_61 +% t2_61; const b62: u32 = a61; const c62: u32 = b61; const d62: u32 = c61; const e62: u32 = d61 +% t1_61; - const @"f62": u32 = e61; - const g62: u32 = @"f61"; + const f62: u32 = e61; + const g62: u32 = f61; const h62: u32 = g61; - const t1_62: u32 = (((h62 +% bsig1(e62)) +% ch(e62, @"f62", g62)) +% 0xBEF9A3F7) +% w62; + const t1_62: u32 = (((h62 +% bsig1(e62)) +% ch(e62, f62, g62)) +% 0xBEF9A3F7) +% w62; const t2_62: u32 = bsig0(a62) +% maj(a62, b62, c62); const a63: u32 = t1_62 +% t2_62; const b63: u32 = a62; const c63: u32 = b62; const d63: u32 = c62; const e63: u32 = d62 +% t1_62; - const @"f63": u32 = e62; - const g63: u32 = @"f62"; + const f63: u32 = e62; + const g63: u32 = f62; const h63: u32 = g62; - const t1_63: u32 = (((h63 +% bsig1(e63)) +% ch(e63, @"f63", g63)) +% 0xC67178F2) +% w63; + const t1_63: u32 = (((h63 +% bsig1(e63)) +% ch(e63, f63, g63)) +% 0xC67178F2) +% w63; const t2_63: u32 = bsig0(a63) +% maj(a63, b63, c63); const a64: u32 = t1_63 +% t2_63; const b64: u32 = a63; const c64: u32 = b63; const d64: u32 = c63; const e64: u32 = d63 +% t1_63; - const @"f64": u32 = e63; - const g64: u32 = @"f63"; + const f64: u32 = e63; + const g64: u32 = f63; const h64: u32 = g63; const out0: u32 = s0 +% a64; const out1: u32 = s1 +% b64; const out2: u32 = s2 +% c64; const out3: u32 = s3 +% d64; const out4: u32 = s4 +% e64; - const out5: u32 = s5 +% @"f64"; + const out5: u32 = s5 +% f64; const out6: u32 = s6 +% g64; const out7: u32 = s7 +% h64; if (which == 0) { @@ -767,94 +775,94 @@ fn sha256_pad2_word(idx: u32, total_bits: u32) u32 { } test "sha256_abc_h0" { const h = sha256_word(0x61626380, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00000018, 0); - if (!(h == 0xBA7816BF)) @panic("abc h0"); + if (!(h == 0xBA7816BF)) __t27_assert_fail("\n abc h0:\n h = {any}\n", .{ h }); } test "sha256_abc_h1" { const h = sha256_word(0x61626380, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00000018, 1); - if (!(h == 0x8F01CFEA)) @panic("abc h1"); + if (!(h == 0x8F01CFEA)) __t27_assert_fail("\n abc h1:\n h = {any}\n", .{ h }); } test "sha256_abc_h2" { const h = sha256_word(0x61626380, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00000018, 2); - if (!(h == 0x414140DE)) @panic("abc h2"); + if (!(h == 0x414140DE)) __t27_assert_fail("\n abc h2:\n h = {any}\n", .{ h }); } test "sha256_abc_h3" { const h = sha256_word(0x61626380, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00000018, 3); - if (!(h == 0x5DAE2223)) @panic("abc h3"); + if (!(h == 0x5DAE2223)) __t27_assert_fail("\n abc h3:\n h = {any}\n", .{ h }); } test "sha256_abc_h4" { const h = sha256_word(0x61626380, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00000018, 4); - if (!(h == 0xB00361A3)) @panic("abc h4"); + if (!(h == 0xB00361A3)) __t27_assert_fail("\n abc h4:\n h = {any}\n", .{ h }); } test "sha256_abc_h5" { const h = sha256_word(0x61626380, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00000018, 5); - if (!(h == 0x96177A9C)) @panic("abc h5"); + if (!(h == 0x96177A9C)) __t27_assert_fail("\n abc h5:\n h = {any}\n", .{ h }); } test "sha256_abc_h6" { const h = sha256_word(0x61626380, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00000018, 6); - if (!(h == 0xB410FF61)) @panic("abc h6"); + if (!(h == 0xB410FF61)) __t27_assert_fail("\n abc h6:\n h = {any}\n", .{ h }); } test "sha256_abc_h7" { const h = sha256_word(0x61626380, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00000018, 7); - if (!(h == 0xF20015AD)) @panic("abc h7"); + if (!(h == 0xF20015AD)) __t27_assert_fail("\n abc h7:\n h = {any}\n", .{ h }); } test "sha256_empty_h0" { const h = sha256_word(0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00000000, 0); - if (!(h == 0xE3B0C442)) @panic("empty h0"); + if (!(h == 0xE3B0C442)) __t27_assert_fail("\n empty h0:\n h = {any}\n", .{ h }); } test "sha256_empty_h1" { const h = sha256_word(0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00000000, 1); - if (!(h == 0x98FC1C14)) @panic("empty h1"); + if (!(h == 0x98FC1C14)) __t27_assert_fail("\n empty h1:\n h = {any}\n", .{ h }); } test "sha256_empty_h2" { const h = sha256_word(0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00000000, 2); - if (!(h == 0x9AFBF4C8)) @panic("empty h2"); + if (!(h == 0x9AFBF4C8)) __t27_assert_fail("\n empty h2:\n h = {any}\n", .{ h }); } test "sha256_empty_h3" { const h = sha256_word(0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00000000, 3); - if (!(h == 0x996FB924)) @panic("empty h3"); + if (!(h == 0x996FB924)) __t27_assert_fail("\n empty h3:\n h = {any}\n", .{ h }); } test "sha256_empty_h4" { const h = sha256_word(0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00000000, 4); - if (!(h == 0x27AE41E4)) @panic("empty h4"); + if (!(h == 0x27AE41E4)) __t27_assert_fail("\n empty h4:\n h = {any}\n", .{ h }); } test "sha256_empty_h5" { const h = sha256_word(0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00000000, 5); - if (!(h == 0x649B934C)) @panic("empty h5"); + if (!(h == 0x649B934C)) __t27_assert_fail("\n empty h5:\n h = {any}\n", .{ h }); } test "sha256_empty_h6" { const h = sha256_word(0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00000000, 6); - if (!(h == 0xA495991B)) @panic("empty h6"); + if (!(h == 0xA495991B)) __t27_assert_fail("\n empty h6:\n h = {any}\n", .{ h }); } test "sha256_empty_h7" { const h = sha256_word(0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00000000, 7); - if (!(h == 0x7852B855)) @panic("empty h7"); + if (!(h == 0x7852B855)) __t27_assert_fail("\n empty h7:\n h = {any}\n", .{ h }); } test "sha256_two_block_64a" { - const @"i0" = sha256_word(0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0); - const @"i1" = sha256_word(0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 1); - const @"i2" = sha256_word(0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 2); - const @"i3" = sha256_word(0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 3); - const @"i4" = sha256_word(0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 4); - const @"i5" = sha256_word(0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 5); - const @"i6" = sha256_word(0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 6); - const @"i7" = sha256_word(0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 7); - if (!(sha256_compress(@"i0", @"i1", @"i2", @"i3", @"i4", @"i5", @"i6", @"i7", 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 0) == 0xFFE054FE)) @panic("64a h0"); - if (!(sha256_compress(@"i0", @"i1", @"i2", @"i3", @"i4", @"i5", @"i6", @"i7", 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 1) == 0x7AE0CB6D)) @panic("64a h1"); - if (!(sha256_compress(@"i0", @"i1", @"i2", @"i3", @"i4", @"i5", @"i6", @"i7", 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 2) == 0xC65C3AF9)) @panic("64a h2"); - if (!(sha256_compress(@"i0", @"i1", @"i2", @"i3", @"i4", @"i5", @"i6", @"i7", 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 3) == 0xB61D5209)) @panic("64a h3"); - if (!(sha256_compress(@"i0", @"i1", @"i2", @"i3", @"i4", @"i5", @"i6", @"i7", 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 4) == 0xF439851D)) @panic("64a h4"); - if (!(sha256_compress(@"i0", @"i1", @"i2", @"i3", @"i4", @"i5", @"i6", @"i7", 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 5) == 0xB43D0BA5)) @panic("64a h5"); - if (!(sha256_compress(@"i0", @"i1", @"i2", @"i3", @"i4", @"i5", @"i6", @"i7", 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 6) == 0x997337DF)) @panic("64a h6"); - if (!(sha256_compress(@"i0", @"i1", @"i2", @"i3", @"i4", @"i5", @"i6", @"i7", 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 7) == 0x154668EB)) @panic("64a h7"); + const i0 = sha256_word(0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0); + const i1 = sha256_word(0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 1); + const i2 = sha256_word(0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 2); + const i3 = sha256_word(0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 3); + const i4 = sha256_word(0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 4); + const i5 = sha256_word(0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 5); + const i6 = sha256_word(0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 6); + const i7 = sha256_word(0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 0x61616161, 7); + if (!(sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 0) == 0xFFE054FE)) __t27_assert_fail("\n 64a h0:\n sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 0) = {any}\n", .{ sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 0) }); + if (!(sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 1) == 0x7AE0CB6D)) __t27_assert_fail("\n 64a h1:\n sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 1) = {any}\n", .{ sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 1) }); + if (!(sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 2) == 0xC65C3AF9)) __t27_assert_fail("\n 64a h2:\n sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 2) = {any}\n", .{ sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 2) }); + if (!(sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 3) == 0xB61D5209)) __t27_assert_fail("\n 64a h3:\n sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 3) = {any}\n", .{ sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 3) }); + if (!(sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 4) == 0xF439851D)) __t27_assert_fail("\n 64a h4:\n sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 4) = {any}\n", .{ sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 4) }); + if (!(sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 5) == 0xB43D0BA5)) __t27_assert_fail("\n 64a h5:\n sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 5) = {any}\n", .{ sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 5) }); + if (!(sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 6) == 0x997337DF)) __t27_assert_fail("\n 64a h6:\n sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 6) = {any}\n", .{ sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 6) }); + if (!(sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 7) == 0x154668EB)) __t27_assert_fail("\n 64a h7:\n sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 7) = {any}\n", .{ sha256_compress(i0, i1, i2, i3, i4, i5, i6, i7, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 512, 7) }); } test "pad2_layout_512" { - if (!(sha256_pad2_word(0, 512) == 0x80000000)) @panic("word 0 is the 0x80 marker"); - if (!(sha256_pad2_word(15, 512) == 512)) @panic("word 15 is the 512-bit length"); - if (!(sha256_pad2_word(7, 512) == 0)) @panic("interior words are zero"); + if (!(sha256_pad2_word(0, 512) == 0x80000000)) __t27_assert_fail("\n word 0 is the 0x80 marker:\n sha256_pad2_word(0, 512) = {any}\n", .{ sha256_pad2_word(0, 512) }); + if (!(sha256_pad2_word(15, 512) == 512)) __t27_assert_fail("\n word 15 is the 512-bit length:\n sha256_pad2_word(15, 512) = {any}\n", .{ sha256_pad2_word(15, 512) }); + if (!(sha256_pad2_word(7, 512) == 0)) __t27_assert_fail("\n interior words are zero:\n sha256_pad2_word(7, 512) = {any}\n", .{ sha256_pad2_word(7, 512) }); } test "compress_iv_equals_word" { const a = sha256_word(0x61626380, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x18, 0); const b = sha256_compress(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19, 0x61626380, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x18, 0); - if (!(a == b)) @panic("sha256_word == sha256_compress(IV, ...)"); - if (!(a == 0xBA7816BF)) @panic("and both equal the abc h0 vector"); + if (!(a == b)) __t27_assert_fail("\n sha256_word == sha256_compress(IV, ...):\n a = {any}\n b = {any}\n", .{ a, b }); + if (!(a == 0xBA7816BF)) __t27_assert_fail("\n and both equal the abc h0 vector:\n a = {any}\n", .{ a }); } diff --git a/gen/zig/tri_slash.zig b/gen/zig/tri_slash.zig index ef8acf0b..bff735b7 100644 --- a/gen/zig/tri_slash.zig +++ b/gen/zig/tri_slash.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MIN_BOND: u32 = 100; @@ -31,28 +39,28 @@ fn settle_or_slash(balance: u32, reward: u32, bond: u32, matched: bool) u32 { } test "honest_node_paid" { const b = settle_or_slash(1000, 713, 100, true); - if (!(b == 1713)) @panic("honest node gains its reward"); + if (!(b == 1713)) __t27_assert_fail("\n honest node gains its reward:\n b = {any}\n", .{ b }); } test "cheat_node_slashed" { const b = settle_or_slash(1000, 713, 100, false); - if (!(b == 900)) @panic("cheat loses its bond, gets no reward"); + if (!(b == 900)) __t27_assert_fail("\n cheat loses its bond, gets no reward:\n b = {any}\n", .{ b }); } test "cheating_is_worse" { const honest = settle_or_slash(1000, 713, 100, true); const cheat = settle_or_slash(1000, 713, 100, false); - if (!(cheat < honest)) @panic("cheat < honest"); - if (!(cheat < 1000)) @panic("cheat loses vs doing nothing"); + if (!(cheat < honest)) __t27_assert_fail("\n cheat < honest:\n cheat = {any}\n honest = {any}\n", .{ cheat, honest }); + if (!(cheat < 1000)) __t27_assert_fail("\n cheat loses vs doing nothing:\n cheat = {any}\n", .{ cheat }); } test "slash_saturates_at_zero" { const b = settle_or_slash(50, 0, 100, false); - if (!(b == 0)) @panic("slash floored at 0"); + if (!(b == 0)) __t27_assert_fail("\n slash floored at 0:\n b = {any}\n", .{ b }); } test "bond_gate" { - if (!(bond_ok(100) == true)) @panic("at minimum"); - if (!(bond_ok(500) == true)) @panic("above minimum"); - if (!(bond_ok(50) == false)) @panic("below minimum rejected"); + if (!(bond_ok(100) == true)) __t27_assert_fail("\n at minimum:\n bond_ok(100) = {any}\n", .{ bond_ok(100) }); + if (!(bond_ok(500) == true)) __t27_assert_fail("\n above minimum:\n bond_ok(500) = {any}\n", .{ bond_ok(500) }); + if (!(bond_ok(50) == false)) __t27_assert_fail("\n below minimum rejected:\n bond_ok(50) = {any}\n", .{ bond_ok(50) }); } test "receipt_match" { - if (!(receipt_matches(0x6EAC3F90, 0x6EAC3F90) == true)) @panic("equal seals match"); - if (!(receipt_matches(0x6EAC3F90, 0xDEADBEEF) == false)) @panic("unequal seals mismatch"); + if (!(receipt_matches(0x6EAC3F90, 0x6EAC3F90) == true)) __t27_assert_fail("\n equal seals match:\n receipt_matches(0x6EAC3F90, 0x6EAC3F90) = {any}\n", .{ receipt_matches(0x6EAC3F90, 0x6EAC3F90) }); + if (!(receipt_matches(0x6EAC3F90, 0xDEADBEEF) == false)) __t27_assert_fail("\n unequal seals mismatch:\n receipt_matches(0x6EAC3F90, 0xDEADBEEF) = {any}\n", .{ receipt_matches(0x6EAC3F90, 0xDEADBEEF) }); } diff --git a/gen/zig/trust_manager.zig b/gen/zig/trust_manager.zig index d1267e16..824f4624 100644 --- a/gen/zig/trust_manager.zig +++ b/gen/zig/trust_manager.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const MAX_NODES: u32 = 8; @@ -143,78 +151,78 @@ fn reward_node(current_score: u32, reward: u32) u32 { } test "create_trust_score_basic" { const score = create_trust_score(5, 75, 8, 2); - if (!(get_trust_node_id(score) == 5)) @panic("node id"); - if (!(get_trust_score_value(score) == 75)) @panic("trust score"); - if (!(get_positive_interactions(score) == 8)) @panic("positive interactions"); - if (!(get_negative_interactions(score) == 2)) @panic("negative interactions"); + if (!(get_trust_node_id(score) == 5)) __t27_assert_fail("\n node id:\n get_trust_node_id(score) = {any}\n", .{ get_trust_node_id(score) }); + if (!(get_trust_score_value(score) == 75)) __t27_assert_fail("\n trust score:\n get_trust_score_value(score) = {any}\n", .{ get_trust_score_value(score) }); + if (!(get_positive_interactions(score) == 8)) __t27_assert_fail("\n positive interactions:\n get_positive_interactions(score) = {any}\n", .{ get_positive_interactions(score) }); + if (!(get_negative_interactions(score) == 2)) __t27_assert_fail("\n negative interactions:\n get_negative_interactions(score) = {any}\n", .{ get_negative_interactions(score) }); } test "create_trust_relationship_basic" { const rel = create_trust_relationship(1, 2, 80, 1000); - if (!(get_trust_source(rel) == 1)) @panic("source"); - if (!(get_trust_destination(rel) == 2)) @panic("destination"); - if (!(get_trust_level(rel) == 80)) @panic("trust level"); - if (!(get_trust_verified(rel) == 1000)) @panic("verified time"); + if (!(get_trust_source(rel) == 1)) __t27_assert_fail("\n source:\n get_trust_source(rel) = {any}\n", .{ get_trust_source(rel) }); + if (!(get_trust_destination(rel) == 2)) __t27_assert_fail("\n destination:\n get_trust_destination(rel) = {any}\n", .{ get_trust_destination(rel) }); + if (!(get_trust_level(rel) == 80)) __t27_assert_fail("\n trust level:\n get_trust_level(rel) = {any}\n", .{ get_trust_level(rel) }); + if (!(get_trust_verified(rel) == 1000)) __t27_assert_fail("\n verified time:\n get_trust_verified(rel) = {any}\n", .{ get_trust_verified(rel) }); } test "calculate_trust_score_balanced" { const score = calculate_trust_score(10, 10); - if (!(score == 50)) @panic("balanced trust"); + if (!(score == 50)) __t27_assert_fail("\n balanced trust:\n score = {any}\n", .{ score }); } test "calculate_trust_score_mostly_positive" { const score = calculate_trust_score(18, 2); - if (!(score == 90)) @panic("high trust"); + if (!(score == 90)) __t27_assert_fail("\n high trust:\n score = {any}\n", .{ score }); } test "calculate_trust_score_mostly_negative" { const score = calculate_trust_score(2, 18); - if (!(score == 10)) @panic("low trust"); + if (!(score == 10)) __t27_assert_fail("\n low trust:\n score = {any}\n", .{ score }); } test "calculate_trust_score_no_interactions" { - if (!(calculate_trust_score(0, 0) == 50)) @panic("neutral trust"); + if (!(calculate_trust_score(0, 0) == 50)) __t27_assert_fail("\n neutral trust:\n calculate_trust_score(0, 0) = {any}\n", .{ calculate_trust_score(0, 0) }); } test "update_trust_score_increases" { const current = create_trust_score(5, 50, 5, 5); const updated = update_trust_score(current, 3, 1); - if (!(get_trust_score_value(updated) >= 55)) @panic("trust increased"); + if (!(get_trust_score_value(updated) >= 55)) __t27_assert_fail("\n trust increased:\n get_trust_score_value(updated) = {any}\n", .{ get_trust_score_value(updated) }); } test "update_trust_score_decreases" { const current = create_trust_score(5, 50, 5, 5); const updated = update_trust_score(current, 1, 3); - if (!(get_trust_score_value(updated) < 50)) @panic("trust decreased"); + if (!(get_trust_score_value(updated) < 50)) __t27_assert_fail("\n trust decreased:\n get_trust_score_value(updated) = {any}\n", .{ get_trust_score_value(updated) }); } test "is_node_trusted_true" { const score = create_trust_score(5, 75, 15, 5); - if (!(is_node_trusted(score) == true)) @panic("trusted"); + if (!(is_node_trusted(score) == true)) __t27_assert_fail("\n trusted:\n is_node_trusted(score) = {any}\n", .{ is_node_trusted(score) }); } test "is_node_trusted_false" { const score = create_trust_score(5, 30, 3, 7); - if (!(is_node_trusted(score) == false)) @panic("not trusted"); + if (!(is_node_trusted(score) == false)) __t27_assert_fail("\n not trusted:\n is_node_trusted(score) = {any}\n", .{ is_node_trusted(score) }); } test "is_node_highly_trusted" { const score = create_trust_score(5, 85, 17, 3); - if (!(is_node_highly_trusted(score) == true)) @panic("highly trusted"); + if (!(is_node_highly_trusted(score) == true)) __t27_assert_fail("\n highly trusted:\n is_node_highly_trusted(score) = {any}\n", .{ is_node_highly_trusted(score) }); } test "is_node_low_trusted" { const score = create_trust_score(5, 15, 2, 8); - if (!(is_node_low_trusted(score) == true)) @panic("low trusted"); + if (!(is_node_low_trusted(score) == true)) __t27_assert_fail("\n low trusted:\n is_node_low_trusted(score) = {any}\n", .{ is_node_low_trusted(score) }); } test "find_most_trusted_middle" { const array = create_trust_array(create_trust_score(1, 60, 6, 4), create_trust_score(2, 90, 9, 1), create_trust_score(3, 45, 5, 5), create_trust_score(4, 75, 8, 2), 0, 0, 0, 0); - if (!(find_most_trusted(array) == 1)) @panic("node 1 most trusted"); + if (!(find_most_trusted(array) == 1)) __t27_assert_fail("\n node 1 most trusted:\n find_most_trusted(array) = {any}\n", .{ find_most_trusted(array) }); } test "should_route_via_node_true" { const array = create_trust_array(create_trust_score(1, 80, 8, 2), create_trust_score(2, 60, 6, 4), create_trust_score(3, 75, 7, 3), create_trust_score(4, 70, 7, 3), 0, 0, 0, 0); - if (!(should_route_via_node(array, 0, 70) == true)) @panic("can route via node 0"); + if (!(should_route_via_node(array, 0, 70) == true)) __t27_assert_fail("\n can route via node 0:\n should_route_via_node(array, 0, 70) = {any}\n", .{ should_route_via_node(array, 0, 70) }); } test "should_route_via_node_false" { const array = create_trust_array(create_trust_score(1, 80, 8, 2), create_trust_score(2, 60, 6, 4), create_trust_score(3, 75, 7, 3), create_trust_score(4, 70, 7, 3), 0, 0, 0, 0); - if (!(should_route_via_node(array, 2, 90) == false)) @panic("cannot route via node 2"); + if (!(should_route_via_node(array, 2, 90) == false)) __t27_assert_fail("\n cannot route via node 2:\n should_route_via_node(array, 2, 90) = {any}\n", .{ should_route_via_node(array, 2, 90) }); } test "penalize_node_reduces_trust" { const current = create_trust_score(5, 70, 7, 3); const penalized = penalize_node(current, 5); - if (!(get_trust_score_value(penalized) < 70)) @panic("trust reduced"); + if (!(get_trust_score_value(penalized) < 70)) __t27_assert_fail("\n trust reduced:\n get_trust_score_value(penalized) = {any}\n", .{ get_trust_score_value(penalized) }); } test "reward_node_increases_trust" { const current = create_trust_score(5, 70, 7, 3); const rewarded = reward_node(current, 5); - if (!(get_trust_score_value(rewarded) > 70)) @panic("trust increased"); + if (!(get_trust_score_value(rewarded) > 70)) __t27_assert_fail("\n trust increased:\n get_trust_score_value(rewarded) = {any}\n", .{ get_trust_score_value(rewarded) }); } diff --git a/gen/zig/twr_timestamp.zig b/gen/zig/twr_timestamp.zig index f5255491..05261b50 100644 --- a/gen/zig/twr_timestamp.zig +++ b/gen/zig/twr_timestamp.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module fn tick(counter: u32) u32 { @@ -20,25 +28,25 @@ fn twr_tof(t1: u32, t2: u32, t3: u32, t4: u32) u32 { test "tick_advances" { const c1 = tick(0); const c2 = tick(c1); - if (!(c2 == 2)) @panic("two ticks"); + if (!(c2 == 2)) __t27_assert_fail("\n two ticks:\n c2 = {any}\n", .{ c2 }); } test "capture_latches" { const c = capture(123456); - if (!(c == 123456)) @panic("latched value"); + if (!(c == 123456)) __t27_assert_fail("\n latched value:\n c = {any}\n", .{ c }); } test "elapsed_same_clock" { const d = elapsed(1000, 1300); - if (!(d == 300)) @panic("300 tick span"); + if (!(d == 300)) __t27_assert_fail("\n 300 tick span:\n d = {any}\n", .{ d }); } test "elapsed_wraps" { const d = elapsed(0xFFFFFFFE, 3); - if (!(d == 5)) @panic("wrap-around correct"); + if (!(d == 5)) __t27_assert_fail("\n wrap-around correct:\n d = {any}\n", .{ d }); } test "twr_cancels_offset" { const tof = twr_tof(1000, 101050, 101250, 1300); - if (!(tof == 50)) @panic("offset cancelled, ToF recovered"); + if (!(tof == 50)) __t27_assert_fail("\n offset cancelled, ToF recovered:\n tof = {any}\n", .{ tof }); } test "twr_zero_when_instant" { const tof = twr_tof(1000, 5000, 5300, 1300); - if (!(tof == 0)) @panic("symmetric -> zero range"); + if (!(tof == 0)) __t27_assert_fail("\n symmetric -> zero range:\n tof = {any}\n", .{ tof }); } diff --git a/gen/zig/video_bridge.zig b/gen/zig/video_bridge.zig index ea0e34ba..896782f1 100644 --- a/gen/zig/video_bridge.zig +++ b/gen/zig/video_bridge.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const VSTREAM_TYPE: u8 = 8; @@ -182,250 +190,250 @@ fn nal_fits(nal_size: u16) bool { return nal_size <= 17850; } test "frag_seq_roundtrip" { - if (!(frag_seq(0xAB, 0xCD) == 52651)) @panic("0xAB + 0xCD*256 = 52651"); + if (!(frag_seq(0xAB, 0xCD) == 52651)) __t27_assert_fail("\n 0xAB + 0xCD*256 = 52651:\n frag_seq(0xAB, 0xCD) = {any}\n", .{ frag_seq(0xAB, 0xCD) }); } test "frag_seq_zero" { - if (!(frag_seq(0, 0) == 0)) @panic("zero seq"); + if (!(frag_seq(0, 0) == 0)) __t27_assert_fail("\n zero seq:\n frag_seq(0, 0) = {any}\n", .{ frag_seq(0, 0) }); } test "frag_seq_max" { - if (!(frag_seq(255, 255) == 65535)) @panic("max u16"); + if (!(frag_seq(255, 255) == 65535)) __t27_assert_fail("\n max u16:\n frag_seq(255, 255) = {any}\n", .{ frag_seq(255, 255) }); } test "seq_lo_basic" { - if (!(seq_lo(256) == 0)) @panic("256 mod 256 = 0"); + if (!(seq_lo(256) == 0)) __t27_assert_fail("\n 256 mod 256 = 0:\n seq_lo(256) = {any}\n", .{ seq_lo(256) }); } test "seq_hi_basic" { - if (!(seq_hi(256) == 1)) @panic("256 / 256 = 1"); + if (!(seq_hi(256) == 1)) __t27_assert_fail("\n 256 / 256 = 1:\n seq_hi(256) = {any}\n", .{ seq_hi(256) }); } test "seq_lo_hi_roundtrip" { const lo: u8 = seq_lo(12345); const hi: u8 = seq_hi(12345); - if (!(frag_seq(lo, hi) == 12345)) @panic("roundtrip preserves value"); + if (!(frag_seq(lo, hi) == 12345)) __t27_assert_fail("\n roundtrip preserves value:\n frag_seq(lo, hi) = {any}\n", .{ frag_seq(lo, hi) }); } test "fragment_count_exact" { - if (!(fragment_count(70) == 1)) @panic("70 bytes = 1 fragment"); + if (!(fragment_count(70) == 1)) __t27_assert_fail("\n 70 bytes = 1 fragment:\n fragment_count(70) = {any}\n", .{ fragment_count(70) }); } test "fragment_count_remainder" { - if (!(fragment_count(100) == 2)) @panic("100 bytes = 2 fragments"); + if (!(fragment_count(100) == 2)) __t27_assert_fail("\n 100 bytes = 2 fragments:\n fragment_count(100) = {any}\n", .{ fragment_count(100) }); } test "fragment_count_zero" { - if (!(fragment_count(0) == 1)) @panic("0 bytes = 1 fragment"); + if (!(fragment_count(0) == 1)) __t27_assert_fail("\n 0 bytes = 1 fragment:\n fragment_count(0) = {any}\n", .{ fragment_count(0) }); } test "fragment_count_large" { - if (!(fragment_count(210) == 3)) @panic("210 bytes = 3 fragments"); + if (!(fragment_count(210) == 3)) __t27_assert_fail("\n 210 bytes = 3 fragments:\n fragment_count(210) = {any}\n", .{ fragment_count(210) }); } test "packet_size_basic" { - if (!(packet_size(70) == 75)) @panic("5 header + 70 data = 75"); + if (!(packet_size(70) == 75)) __t27_assert_fail("\n 5 header + 70 data = 75:\n packet_size(70) = {any}\n", .{ packet_size(70) }); } test "packet_size_empty" { - if (!(packet_size(0) == 5)) @panic("5 header + 0 data = 5"); + if (!(packet_size(0) == 5)) __t27_assert_fail("\n 5 header + 0 data = 5:\n packet_size(0) = {any}\n", .{ packet_size(0) }); } test "is_last_basic" { - if (!(is_last_fragment(2, 3) == true)) @panic("frag 2 of 3 is last"); + if (!(is_last_fragment(2, 3) == true)) __t27_assert_fail("\n frag 2 of 3 is last:\n is_last_fragment(2, 3) = {any}\n", .{ is_last_fragment(2, 3) }); } test "is_last_not_last" { - if (!(is_last_fragment(0, 3) == false)) @panic("frag 0 of 3 is not last"); + if (!(is_last_fragment(0, 3) == false)) __t27_assert_fail("\n frag 0 of 3 is not last:\n is_last_fragment(0, 3) = {any}\n", .{ is_last_fragment(0, 3) }); } test "is_first_basic" { - if (!(is_first_fragment(0) == true)) @panic("frag 0 is first"); + if (!(is_first_fragment(0) == true)) __t27_assert_fail("\n frag 0 is first:\n is_first_fragment(0) = {any}\n", .{ is_first_fragment(0) }); } test "is_first_not_first" { - if (!(is_first_fragment(1) == false)) @panic("frag 1 is not first"); + if (!(is_first_fragment(1) == false)) __t27_assert_fail("\n frag 1 is not first:\n is_first_fragment(1) = {any}\n", .{ is_first_fragment(1) }); } test "data_offset_value" { - if (!(data_offset() == 5)) @panic("payload starts at byte 5"); + if (!(data_offset() == 5)) __t27_assert_fail("\n payload starts at byte 5:\n data_offset() = {any}\n", .{ data_offset() }); } test "max_nal_size_value" { - if (!(max_nal_size() == 17850)) @panic("255 * 70 = 17850"); + if (!(max_nal_size() == 17850)) __t27_assert_fail("\n 255 * 70 = 17850:\n max_nal_size() = {any}\n", .{ max_nal_size() }); } test "nal_fits_small" { - if (!(nal_fits(100) == true)) @panic("100 <= 17850"); + if (!(nal_fits(100) == true)) __t27_assert_fail("\n 100 <= 17850:\n nal_fits(100) = {any}\n", .{ nal_fits(100) }); } test "nal_fits_exact" { - if (!(nal_fits(17850) == true)) @panic("17850 <= 17850"); + if (!(nal_fits(17850) == true)) __t27_assert_fail("\n 17850 <= 17850:\n nal_fits(17850) = {any}\n", .{ nal_fits(17850) }); } test "nal_fits_too_large" { - if (!(nal_fits(17851) == false)) @panic("17851 > 17850"); + if (!(nal_fits(17851) == false)) __t27_assert_fail("\n 17851 > 17850:\n nal_fits(17851) = {any}\n", .{ nal_fits(17851) }); } test "fec_group_of_first" { - if (!(fec_group_of(0, 129) == 0)) @panic("fragment 0 is in group 0"); + if (!(fec_group_of(0, 129) == 0)) __t27_assert_fail("\n fragment 0 is in group 0:\n fec_group_of(0, 129) = {any}\n", .{ fec_group_of(0, 129) }); } test "fec_group_of_interleaved" { - if (!(fec_group_of(1, 129) == 1)) @panic("the NEXT fragment is in the NEXT group"); + if (!(fec_group_of(1, 129) == 1)) __t27_assert_fail("\n the NEXT fragment is in the NEXT group:\n fec_group_of(1, 129) = {any}\n", .{ fec_group_of(1, 129) }); } test "fec_group_of_wraps_by_stride" { - if (!(fec_group_of(9, 129) == 0)) @panic("129 frags = 9 groups, so 9 rejoins group 0"); + if (!(fec_group_of(9, 129) == 0)) __t27_assert_fail("\n 129 frags = 9 groups, so 9 rejoins group 0:\n fec_group_of(9, 129) = {any}\n", .{ fec_group_of(9, 129) }); } test "fec_group_of_burst_spreads" { - if (!(fec_group_of(20, 129) == 2)) @panic("20 mod 9 = 2"); - if (!(fec_group_of(21, 129) == 3)) @panic("consecutive fragments land in DIFFERENT groups"); + if (!(fec_group_of(20, 129) == 2)) __t27_assert_fail("\n 20 mod 9 = 2:\n fec_group_of(20, 129) = {any}\n", .{ fec_group_of(20, 129) }); + if (!(fec_group_of(21, 129) == 3)) __t27_assert_fail("\n consecutive fragments land in DIFFERENT groups:\n fec_group_of(21, 129) = {any}\n", .{ fec_group_of(21, 129) }); } test "fec_group_count_exact" { - if (!(fec_group_count(32) == 2)) @panic("32 fragments = 2 full groups"); + if (!(fec_group_count(32) == 2)) __t27_assert_fail("\n 32 fragments = 2 full groups:\n fec_group_count(32) = {any}\n", .{ fec_group_count(32) }); } test "fec_group_count_remainder" { - if (!(fec_group_count(33) == 3)) @panic("33 fragments needs a third group"); + if (!(fec_group_count(33) == 3)) __t27_assert_fail("\n 33 fragments needs a third group:\n fec_group_count(33) = {any}\n", .{ fec_group_count(33) }); } test "fec_group_count_single" { - if (!(fec_group_count(1) == 1)) @panic("1 fragment still needs a parity"); + if (!(fec_group_count(1) == 1)) __t27_assert_fail("\n 1 fragment still needs a parity:\n fec_group_count(1) = {any}\n", .{ fec_group_count(1) }); } test "fec_group_count_empty" { - if (!(fec_group_count(0) == 0)) @panic("no fragments, no parity"); + if (!(fec_group_count(0) == 0)) __t27_assert_fail("\n no fragments, no parity:\n fec_group_count(0) = {any}\n", .{ fec_group_count(0) }); } test "fec_group_count_keyframe" { - if (!(fec_group_count(129) == 9)) @panic("a 9000B I-frame needs 9 parities"); + if (!(fec_group_count(129) == 9)) __t27_assert_fail("\n a 9000B I-frame needs 9 parities:\n fec_group_count(129) = {any}\n", .{ fec_group_count(129) }); } test "fec_group_first_is_the_index" { - if (!(fec_group_first(2) == 2)) @panic("interleaved: group 2 starts at fragment 2"); + if (!(fec_group_first(2) == 2)) __t27_assert_fail("\n interleaved: group 2 starts at fragment 2:\n fec_group_first(2) = {any}\n", .{ fec_group_first(2) }); } test "fec_group_len_interleaved" { - if (!(fec_group_len(0, 129) == 15)) @panic("frags 0,9,...,126 = 15 of them"); + if (!(fec_group_len(0, 129) == 15)) __t27_assert_fail("\n frags 0,9,...,126 = 15 of them:\n fec_group_len(0, 129) = {any}\n", .{ fec_group_len(0, 129) }); } test "fec_group_len_short_group" { - if (!(fec_group_len(8, 129) == 14)) @panic("frags 8,17,...,125 = 14 of them"); + if (!(fec_group_len(8, 129) == 14)) __t27_assert_fail("\n frags 8,17,...,125 = 14 of them:\n fec_group_len(8, 129) = {any}\n", .{ fec_group_len(8, 129) }); } test "fec_stride_is_the_burst_we_survive" { - if (!(fec_stride(129) == 9)) @panic("9 groups = 9 consecutive losses absorbed"); + if (!(fec_stride(129) == 9)) __t27_assert_fail("\n 9 groups = 9 consecutive losses absorbed:\n fec_stride(129) = {any}\n", .{ fec_stride(129) }); } test "fec_group_len_single" { - if (!(fec_group_len(0, 1) == 1)) @panic("a lone fragment is a group of one"); + if (!(fec_group_len(0, 1) == 1)) __t27_assert_fail("\n a lone fragment is a group of one:\n fec_group_len(0, 1) = {any}\n", .{ fec_group_len(0, 1) }); } test "fec_can_recover_one" { - if (!(fec_can_recover(1) == true)) @panic("exactly one loss is repairable"); + if (!(fec_can_recover(1) == true)) __t27_assert_fail("\n exactly one loss is repairable:\n fec_can_recover(1) = {any}\n", .{ fec_can_recover(1) }); } test "fec_can_recover_none" { - if (!(fec_can_recover(0) == false)) @panic("nothing missing, nothing to repair"); + if (!(fec_can_recover(0) == false)) __t27_assert_fail("\n nothing missing, nothing to repair:\n fec_can_recover(0) = {any}\n", .{ fec_can_recover(0) }); } test "fec_can_recover_two" { - if (!(fec_can_recover(2) == false)) @panic("one XOR cannot separate two losses"); + if (!(fec_can_recover(2) == false)) __t27_assert_fail("\n one XOR cannot separate two losses:\n fec_can_recover(2) = {any}\n", .{ fec_can_recover(2) }); } test "fb_util_half" { - if (!(fb_util_pct(400, 800) == 50)) @panic("400 of 800 is half the budget"); + if (!(fb_util_pct(400, 800) == 50)) __t27_assert_fail("\n 400 of 800 is half the budget:\n fb_util_pct(400, 800) = {any}\n", .{ fb_util_pct(400, 800) }); } test "fb_util_saturates" { - if (!(fb_util_pct(900, 800) == 100)) @panic("debt must not report over 100%"); + if (!(fb_util_pct(900, 800) == 100)) __t27_assert_fail("\n debt must not report over 100%:\n fb_util_pct(900, 800) = {any}\n", .{ fb_util_pct(900, 800) }); } test "fb_util_zero_rate" { - if (!(fb_util_pct(10, 0) == 100)) @panic("a zero-rate link is by definition full"); + if (!(fb_util_pct(10, 0) == 100)) __t27_assert_fail("\n a zero-rate link is by definition full:\n fb_util_pct(10, 0) = {any}\n", .{ fb_util_pct(10, 0) }); } test "fb_drop_none" { - if (!(fb_drop_pct(0, 300) == 0)) @panic("nothing dropped"); + if (!(fb_drop_pct(0, 300) == 0)) __t27_assert_fail("\n nothing dropped:\n fb_drop_pct(0, 300) = {any}\n", .{ fb_drop_pct(0, 300) }); } test "fb_drop_the_measured_44" { - if (!(fb_drop_pct(1055, 2392) == 44)) @panic("the live call's real numbers"); + if (!(fb_drop_pct(1055, 2392) == 44)) __t27_assert_fail("\n the live call's real numbers:\n fb_drop_pct(1055, 2392) = {any}\n", .{ fb_drop_pct(1055, 2392) }); } test "fb_drop_nothing_offered" { - if (!(fb_drop_pct(0, 0) == 0)) @panic("an idle link is not a dropping link"); + if (!(fb_drop_pct(0, 0) == 0)) __t27_assert_fail("\n an idle link is not a dropping link:\n fb_drop_pct(0, 0) = {any}\n", .{ fb_drop_pct(0, 0) }); } test "fb_back_off_on_any_drop" { - if (!(fb_should_back_off(10, 1, 85) == true)) @panic("a drop means it is already too late"); + if (!(fb_should_back_off(10, 1, 85) == true)) __t27_assert_fail("\n a drop means it is already too late:\n fb_should_back_off(10, 1, 85) = {any}\n", .{ fb_should_back_off(10, 1, 85) }); } test "fb_back_off_when_nearly_full" { - if (!(fb_should_back_off(85, 0, 85) == true)) @panic("85% is about to be too late"); + if (!(fb_should_back_off(85, 0, 85) == true)) __t27_assert_fail("\n 85% is about to be too late:\n fb_should_back_off(85, 0, 85) = {any}\n", .{ fb_should_back_off(85, 0, 85) }); } test "fb_hold_when_comfortable" { - if (!(fb_should_back_off(70, 0, 85) == false)) @panic("70% needs no action"); + if (!(fb_should_back_off(70, 0, 85) == false)) __t27_assert_fail("\n 70% needs no action:\n fb_should_back_off(70, 0, 85) = {any}\n", .{ fb_should_back_off(70, 0, 85) }); } test "fb_climb_only_when_clear" { - if (!(fb_may_climb(50, 0, 60) == true)) @panic("half empty, climb"); + if (!(fb_may_climb(50, 0, 60) == true)) __t27_assert_fail("\n half empty, climb:\n fb_may_climb(50, 0, 60) = {any}\n", .{ fb_may_climb(50, 0, 60) }); } test "fb_no_climb_after_a_drop" { - if (!(fb_may_climb(10, 5, 60) == false)) @panic("never climb into a link that just dropped"); + if (!(fb_may_climb(10, 5, 60) == false)) __t27_assert_fail("\n never climb into a link that just dropped:\n fb_may_climb(10, 5, 60) = {any}\n", .{ fb_may_climb(10, 5, 60) }); } test "fb_advice_backs_off_on_drops" { - if (!(fb_advice(10, 3, 75, 85) == ADVICE_BACK_OFF)) @panic("any drop overrides everything"); + if (!(fb_advice(10, 3, 75, 85) == ADVICE_BACK_OFF)) __t27_assert_fail("\n any drop overrides everything:\n fb_advice(10, 3, 75, 85) = {any}\n ADVICE_BACK_OFF = {any}\n", .{ fb_advice(10, 3, 75, 85), ADVICE_BACK_OFF }); } test "fb_advice_climbs_when_empty" { - if (!(fb_advice(20, 0, 75, 85) == ADVICE_CLIMB)) @panic("quiet link, climb"); + if (!(fb_advice(20, 0, 75, 85) == ADVICE_CLIMB)) __t27_assert_fail("\n quiet link, climb:\n fb_advice(20, 0, 75, 85) = {any}\n ADVICE_CLIMB = {any}\n", .{ fb_advice(20, 0, 75, 85), ADVICE_CLIMB }); } test "fb_advice_holds_in_the_band" { - if (!(fb_advice(80, 0, 75, 85) == ADVICE_HOLD)) @panic("75..85 is the hysteresis band"); + if (!(fb_advice(80, 0, 75, 85) == ADVICE_HOLD)) __t27_assert_fail("\n 75..85 is the hysteresis band:\n fb_advice(80, 0, 75, 85) = {any}\n ADVICE_HOLD = {any}\n", .{ fb_advice(80, 0, 75, 85), ADVICE_HOLD }); } test "fb_advice_backs_off_when_full" { - if (!(fb_advice(95, 0, 75, 85) == ADVICE_BACK_OFF)) @panic("95% is full enough"); + if (!(fb_advice(95, 0, 75, 85) == ADVICE_BACK_OFF)) __t27_assert_fail("\n 95% is full enough:\n fb_advice(95, 0, 75, 85) = {any}\n ADVICE_BACK_OFF = {any}\n", .{ fb_advice(95, 0, 75, 85), ADVICE_BACK_OFF }); } test "fb_hysteresis_gap_exists" { - if (!(fb_may_climb(70, 0, 60) == false)) @panic("70% must not climb"); - if (!(fb_should_back_off(70, 0, 85) == false)) @panic("...nor back off: it holds"); + if (!(fb_may_climb(70, 0, 60) == false)) __t27_assert_fail("\n 70% must not climb:\n fb_may_climb(70, 0, 60) = {any}\n", .{ fb_may_climb(70, 0, 60) }); + if (!(fb_should_back_off(70, 0, 85) == false)) __t27_assert_fail("\n ...nor back off: it holds:\n fb_should_back_off(70, 0, 85) = {any}\n", .{ fb_should_back_off(70, 0, 85) }); } test "video_seq_stays_low" { - if (!(video_seq(40000) == 7232)) @panic("video wraps inside 0..32767"); + if (!(video_seq(40000) == 7232)) __t27_assert_fail("\n video wraps inside 0..32767:\n video_seq(40000) = {any}\n", .{ video_seq(40000) }); } test "express_seq_stays_high" { - if (!(express_seq(0) == 32768)) @panic("express lives in the high half"); + if (!(express_seq(0) == 32768)) __t27_assert_fail("\n express lives in the high half:\n express_seq(0) = {any}\n", .{ express_seq(0) }); } test "seq_halves_never_collide" { - if (!(video_seq(100) != express_seq(100))) @panic("same counter, disjoint keys"); + if (!(video_seq(100) != express_seq(100))) __t27_assert_fail("\n same counter, disjoint keys:\n video_seq(100) = {any}\n express_seq(100) = {any}\n", .{ video_seq(100), express_seq(100) }); } test "effective_rate_idle_is_configured" { - if (!(fb_effective_rate(0, 0, 700) == 700)) @panic("an idle link says nothing"); + if (!(fb_effective_rate(0, 0, 700) == 700)) __t27_assert_fail("\n an idle link says nothing:\n fb_effective_rate(0, 0, 700) = {any}\n", .{ fb_effective_rate(0, 0, 700) }); } test "effective_rate_lossless_is_configured" { - if (!(fb_effective_rate(500, 495, 700) == 700)) @panic("keeping up: no signal"); + if (!(fb_effective_rate(500, 495, 700) == 700)) __t27_assert_fail("\n keeping up: no signal:\n fb_effective_rate(500, 495, 700) = {any}\n", .{ fb_effective_rate(500, 495, 700) }); } test "effective_rate_saturated_is_delivered" { - if (!(fb_effective_rate(700, 300, 700) == 300)) @panic("a lossy link states its capacity"); + if (!(fb_effective_rate(700, 300, 700) == 300)) __t27_assert_fail("\n a lossy link states its capacity:\n fb_effective_rate(700, 300, 700) = {any}\n", .{ fb_effective_rate(700, 300, 700) }); } test "effective_rate_boundary" { - if (!(fb_effective_rate(700, 630, 700) == 700)) @panic("exactly 90% still counts as keeping up"); - if (!(fb_effective_rate(700, 629, 700) == 629)) @panic("below 90% is loss"); + if (!(fb_effective_rate(700, 630, 700) == 700)) __t27_assert_fail("\n exactly 90% still counts as keeping up:\n fb_effective_rate(700, 630, 700) = {any}\n", .{ fb_effective_rate(700, 630, 700) }); + if (!(fb_effective_rate(700, 629, 700) == 629)) __t27_assert_fail("\n below 90% is loss:\n fb_effective_rate(700, 629, 700) = {any}\n", .{ fb_effective_rate(700, 629, 700) }); } test "chain_report_takes_the_bottleneck" { - if (!(fb_chain_report(500, 200) == 200)) @panic("downstream is the bottleneck"); + if (!(fb_chain_report(500, 200) == 200)) __t27_assert_fail("\n downstream is the bottleneck:\n fb_chain_report(500, 200) = {any}\n", .{ fb_chain_report(500, 200) }); } test "chain_report_takes_local_when_downstream_keeps_up" { - if (!(fb_chain_report(300, 500) == 300)) @panic("this hop is the bottleneck"); + if (!(fb_chain_report(300, 500) == 300)) __t27_assert_fail("\n this hop is the bottleneck:\n fb_chain_report(300, 500) = {any}\n", .{ fb_chain_report(300, 500) }); } test "chain_report_equal" { - if (!(fb_chain_report(400, 400) == 400)) @panic("no bottleneck, same figure"); + if (!(fb_chain_report(400, 400) == 400)) __t27_assert_fail("\n no bottleneck, same figure:\n fb_chain_report(400, 400) = {any}\n", .{ fb_chain_report(400, 400) }); } test "fec_packet_size_value" { - if (!(fec_packet_size() == 76)) @panic("6 header + 70 data = 76"); + if (!(fec_packet_size() == 76)) __t27_assert_fail("\n 6 header + 70 data = 76:\n fec_packet_size() = {any}\n", .{ fec_packet_size() }); } comptime { // invariant: frag_header_is_5_bytes - // invariant: frag_header_is_5_bytes verified (no statements) + if (!(FRAG_HEADER_LEN == 5)) __t27_assert_fail("\n assertion failed:\n FRAG_HEADER_LEN = {any}\n", .{ FRAG_HEADER_LEN }); } comptime { // invariant: max_data_is_70 - // invariant: max_data_is_70 verified (no statements) + if (!(MAX_FRAG_DATA == 70)) __t27_assert_fail("\n assertion failed:\n MAX_FRAG_DATA = {any}\n", .{ MAX_FRAG_DATA }); } comptime { // invariant: vstream_type_is_8 - // invariant: vstream_type_is_8 verified (no statements) + if (!(VSTREAM_TYPE == 8)) __t27_assert_fail("\n assertion failed:\n VSTREAM_TYPE = {any}\n", .{ VSTREAM_TYPE }); } comptime { // invariant: fec_type_differs_from_data_type - // invariant: fec_type_differs_from_data_type verified (no statements) + if (!(VSTREAM_FEC_TYPE != VSTREAM_TYPE)) __t27_assert_fail("\n assertion failed:\n VSTREAM_FEC_TYPE = {any}\n VSTREAM_TYPE = {any}\n", .{ VSTREAM_FEC_TYPE, VSTREAM_TYPE }); } comptime { // invariant: fec_header_is_one_longer - // invariant: fec_header_is_one_longer verified (no statements) + if (!(FEC_HEADER_LEN == 6)) __t27_assert_fail("\n assertion failed:\n FEC_HEADER_LEN = {any}\n", .{ FEC_HEADER_LEN }); } comptime { // invariant: audio_port_differs_from_video - // invariant: audio_port_differs_from_video verified (no statements) + if (!(AUDIO_IN_PORT != VIDEO_IN_PORT)) __t27_assert_fail("\n assertion failed:\n AUDIO_IN_PORT = {any}\n VIDEO_IN_PORT = {any}\n", .{ AUDIO_IN_PORT, VIDEO_IN_PORT }); } comptime { // invariant: feedback_port_is_its_own - // invariant: feedback_port_is_its_own verified (no statements) + if (!(FEEDBACK_PORT != AUDIO_IN_PORT)) __t27_assert_fail("\n assertion failed:\n FEEDBACK_PORT = {any}\n AUDIO_IN_PORT = {any}\n", .{ FEEDBACK_PORT, AUDIO_IN_PORT }); } comptime { // invariant: feedback_carries_advice - // invariant: feedback_carries_advice verified (no statements) + if (!(FEEDBACK_LEN == 6)) __t27_assert_fail("\n assertion failed:\n FEEDBACK_LEN = {any}\n", .{ FEEDBACK_LEN }); } comptime { // invariant: advice_values_are_distinct - // invariant: advice_values_are_distinct verified (no statements) + if (!(ADVICE_BACK_OFF != ADVICE_CLIMB)) __t27_assert_fail("\n assertion failed:\n ADVICE_BACK_OFF = {any}\n ADVICE_CLIMB = {any}\n", .{ ADVICE_BACK_OFF, ADVICE_CLIMB }); } comptime { // invariant: no_dead_zone - // invariant: no_dead_zone verified (no statements) + if (!(CLIMB_BELOW_PCT == BACK_OFF_AT_PCT)) __t27_assert_fail("\n assertion failed:\n CLIMB_BELOW_PCT = {any}\n BACK_OFF_AT_PCT = {any}\n", .{ CLIMB_BELOW_PCT, BACK_OFF_AT_PCT }); } comptime { // invariant: rx_report_type_is_distinct - // invariant: rx_report_type_is_distinct verified (no statements) + if (!(RX_REPORT_TYPE != VSTREAM_TYPE)) __t27_assert_fail("\n assertion failed:\n RX_REPORT_TYPE = {any}\n VSTREAM_TYPE = {any}\n", .{ RX_REPORT_TYPE, VSTREAM_TYPE }); } comptime { // invariant: rx_report_differs_from_fec - // invariant: rx_report_differs_from_fec verified (no statements) + if (!(RX_REPORT_TYPE != VSTREAM_FEC_TYPE)) __t27_assert_fail("\n assertion failed:\n RX_REPORT_TYPE = {any}\n VSTREAM_FEC_TYPE = {any}\n", .{ RX_REPORT_TYPE, VSTREAM_FEC_TYPE }); } diff --git a/gen/zig/wire.zig b/gen/zig/wire.zig index edfc51d7..de350fca 100644 --- a/gen/zig/wire.zig +++ b/gen/zig/wire.zig @@ -3,6 +3,14 @@ // phi^2 + 1/phi^2 = 3 | TRINITY const std = @import("std"); +fn __t27_assert_fail(comptime fmt: []const u8, args: anytype) noreturn { + if (@inComptime()) { + @compileError("assertion failed"); + } else { + std.debug.print(fmt, args); + @panic("assertion failed"); + } +} // use types: no references in this module const VERSION: u8 = 1; @@ -47,26 +55,48 @@ fn parse_accepts(b0: u8, b1: u8) bool { } } test "byte0_is_version" { + const b = header_byte(KIND_DATA, 16909060, 168496141, 8, 0); + if (!(b == 1)) __t27_assert_fail("\n assertion failed:\n b = {any}\n", .{ b }); } test "byte1_is_kind" { + const b = header_byte(KIND_DATA, 16909060, 168496141, 8, 1); + if (!(b == 1)) __t27_assert_fail("\n assertion failed:\n b = {any}\n", .{ b }); } test "src_be_first_and_last_byte" { + const b2 = header_byte(KIND_DATA, 16909060, 168496141, 8, 2); + const b5 = header_byte(KIND_DATA, 16909060, 168496141, 8, 5); + if (!(b2 == 1)) __t27_assert_fail("\n assertion failed:\n b2 = {any}\n", .{ b2 }); + if (!(b5 == 4)) __t27_assert_fail("\n assertion failed:\n b5 = {any}\n", .{ b5 }); } test "ttl_is_last_byte" { + const b = header_byte(KIND_HELLO, 1, 2, 4, 10); + if (!(b == 4)) __t27_assert_fail("\n assertion failed:\n b = {any}\n", .{ b }); } test "src_roundtrips_through_bytes" { + const b2 = header_byte(KIND_DATA, 16909060, 168496141, 8, 2); + const b3 = header_byte(KIND_DATA, 16909060, 168496141, 8, 3); + const b4 = header_byte(KIND_DATA, 16909060, 168496141, 8, 4); + const b5 = header_byte(KIND_DATA, 16909060, 168496141, 8, 5); + const w = u32_be(b2, b3, b4, b5); + if (!(w == 16909060)) __t27_assert_fail("\n assertion failed:\n w = {any}\n", .{ w }); } test "parse_accepts_valid" { + const ok = parse_accepts(1, KIND_DATA); + if (!(ok == true)) __t27_assert_fail("\n assertion failed:\n ok = {any}\n", .{ ok }); } test "parse_rejects_bad_version" { + const ok = parse_accepts(99, KIND_DATA); + if (!(ok == false)) __t27_assert_fail("\n assertion failed:\n ok = {any}\n", .{ ok }); } test "parse_rejects_bad_kind" { + const ok = parse_accepts(1, 2); + if (!(ok == false)) __t27_assert_fail("\n assertion failed:\n ok = {any}\n", .{ ok }); } comptime { // invariant: header_is_11_bytes - // invariant: header_is_11_bytes verified (no statements) + if (!(HEADER_LEN == 11)) __t27_assert_fail("\n assertion failed:\n HEADER_LEN = {any}\n", .{ HEADER_LEN }); } comptime { // invariant: kinds_distinct - // invariant: kinds_distinct verified (no statements) + if (!(KIND_HELLO != KIND_DATA)) __t27_assert_fail("\n assertion failed:\n KIND_HELLO = {any}\n KIND_DATA = {any}\n", .{ KIND_HELLO, KIND_DATA }); } diff --git a/src/bin/tri.rs b/src/bin/tri.rs new file mode 100644 index 00000000..3866a959 --- /dev/null +++ b/src/bin/tri.rs @@ -0,0 +1,476 @@ +//! tri - the operator's command line for a TRI-NET node. +//! +//! Why this exists. The README opens its Metrics table with "Все числа - с +//! on-device логов, без hearsay", and on 2026-08-17 three of those numbers had +//! drifted from the repository they claim to describe: 110 test blocks against +//! 118 actual, 4 463 source lines against 6 697, and one ported T27 spec +//! against 86. Nothing was measured wrongly. The numbers were written once and +//! never recomputed, which is a different failure and the only one a document +//! cannot catch by itself. +//! +//! So the commands here are built around one rule: a number that a machine can +//! re-derive is never stored as prose. `tri facts` recomputes the repository +//! side of the Metrics table and exits non-zero when the stored value and the +//! measured value disagree. `tri status` checks that every claim marked `hw` +//! still has its evidence file on disk. +//! +//! The second rule follows from the same session. A probe that could not run is +//! reported as UNKNOWN, never as zero and never as a failure. `tri boards` +//! distinguishes "answered", "did not answer" and "not probed", because a node +//! that was never contacted is not a node that is down. + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +const FACTS_FILE: &str = "tri-facts.json"; + +/// One re-derivable claim: what it asserts, and how a machine checks it. +struct Fact { + key: &'static str, + claim: &'static str, + /// Why this exact value and not another. A number without this is a number + /// nobody can audit. + note: &'static str, + measure: fn(&Path) -> Result, +} + +fn facts() -> Vec { + vec![ + Fact { + key: "rust_test_blocks", + claim: "Rust #[test] blocks in the repository", + note: "counted over src/ and tests/; the README's own source column \ + says grep -rE '^\\s*#\\[test\\]' src tests", + measure: |root| { + count_matching(root, &["src", "tests"], "rs", |l| { + l.trim_start().starts_with("#[test]") + }) + }, + }, + Fact { + key: "rust_source_lines", + claim: "Rust source lines", + note: "every .rs file under src/, counted by line, matching the \ + README's find src -name '*.rs' | xargs wc -l", + measure: |root| count_lines(root, &["src"], "rs"), + }, + Fact { + key: "t27_specs", + claim: "T27 spec files present", + note: "the README said 1 (specs/wire.t27) while 86 were on disk; \ + the count is the whole point of the row", + measure: |root| count_files(root, &["specs"], "t27"), + }, + Fact { + key: "rust_source_files", + claim: "Rust source files", + note: "a denominator for the line count, so a large change in one \ + is visible against the other", + measure: |root| count_files(root, &["src"], "rs"), + }, + Fact { + key: "declared_binaries", + claim: "binaries declared in Cargo.toml", + note: "autobins is off because binaries in src/bin/ have not \ + compiled (issue #96); the declared count is therefore not \ + the file count, and the gap is meant to be visible", + measure: |root| { + let s = read(&root.join("Cargo.toml"))?; + Ok(s.lines().filter(|l| l.trim() == "[[bin]]").count() as i64) + }, + }, + Fact { + key: "binary_sources", + claim: "binary sources in src/bin/", + note: "compare against declared_binaries: the difference is the \ + number of binaries that exist but are not built", + measure: |root| count_files(root, &["src/bin"], "rs"), + }, + ] +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let root = repo_root(); + let cmd = args.first().map(|s| s.as_str()).unwrap_or("help"); + let rest: Vec<&str> = args.iter().skip(1).map(|s| s.as_str()).collect(); + + let code = match cmd { + "facts" => cmd_facts(&root, &rest), + "status" => cmd_status(&root), + "boards" => cmd_boards(&rest), + "smoke" => cmd_smoke(&root), + "help" | "-h" | "--help" => { + usage(); + 0 + } + other => { + eprintln!("tri: unknown command '{other}'"); + usage(); + 2 + } + }; + std::process::exit(code); +} + +fn usage() { + println!( + "tri - operator command line for a TRI-NET node + + tri facts recompute the repository metrics and diff them against + {FACTS_FILE}; exit 1 on any disagreement + tri facts --update store the measured values as the new baseline + tri status check that every claim marked hw still has its evidence + file on disk + tri boards probe the node addresses; answered / silent / not probed + tri smoke run the M1 crypto smoke test + +A number this tool can re-derive is never trusted from prose. A probe that did +not run is reported UNKNOWN, never as zero." + ); +} + +// ---------------------------------------------------------------- facts + +fn cmd_facts(root: &Path, args: &[&str]) -> i32 { + let update = args.contains(&"--update"); + let stored = load_facts(root); + let mut measured: BTreeMap = BTreeMap::new(); + let mut drift = 0usize; + let mut unmeasurable = 0usize; + + println!( + "{:<22} {:>10} {:>10} verdict", + "fact", "stored", "measured" + ); + println!("{}", "-".repeat(72)); + + for f in facts() { + match (f.measure)(root) { + Err(e) => { + // Could not measure is not a disagreement. Saying otherwise + // would make an absent probe look like a failed one. + println!( + "{:<22} {:>10} {:>10} UNKNOWN ({e})", + f.key, + stored + .get(f.key) + .map(|v| v.to_string()) + .unwrap_or("-".into()), + "-" + ); + unmeasurable += 1; + } + Ok(m) => { + measured.insert(f.key.to_string(), m); + match stored.get(f.key) { + None => { + println!("{:<22} {:>10} {:>10} NEW {}", f.key, "-", m, f.claim); + drift += 1; + } + Some(&s) if s == m => { + println!("{:<22} {:>10} {:>10} agrees {}", f.key, s, m, f.claim) + } + Some(&s) => { + println!("{:<22} {:>10} {:>10} DISAGREES", f.key, s, m); + println!("{:<22} {}", "", f.claim); + println!("{:<22} {}", "", f.note); + drift += 1; + } + } + } + } + } + + println!(); + if update { + match write_facts(root, &measured) { + Ok(p) => { + println!("stored the measured values in {}", p.display()); + return 0; + } + Err(e) => { + eprintln!("could not write the baseline: {e}"); + return 1; + } + } + } + + if drift > 0 { + println!( + "FACTS DISAGREE - {drift} of {} re-derivable numbers no longer match the \ + repository.", + facts().len() + ); + println!( + "A stored number that changed does not mean the number needs editing. It \ + means the repository moved, and the note on each row says what would have \ + to be true for the new value to be right. Run 'tri facts --update' once \ + the new value is the intended one." + ); + return 1; + } + if unmeasurable > 0 { + println!("FACTS INCOMPLETE - {unmeasurable} could not be measured here; the rest agree."); + return 2; + } + println!( + "FACTS AGREE - all {} re-derived from the repository.", + facts().len() + ); + 0 +} + +fn load_facts(root: &Path) -> BTreeMap { + let mut out = BTreeMap::new(); + let Ok(text) = fs::read_to_string(root.join(FACTS_FILE)) else { + return out; + }; + // Deliberately a hand-rolled scan of "key": number rather than a serde + // model: the file is a flat map, and a parser that cannot fail on shape is + // one less thing to keep in step with the schema. + for line in text.lines() { + let line = line.trim().trim_end_matches(','); + let Some((k, v)) = line.split_once(':') else { + continue; + }; + let k = k.trim().trim_matches('"'); + let v = v.trim(); + if let Ok(n) = v.parse::() { + out.insert(k.to_string(), n); + } + } + out +} + +fn write_facts(root: &Path, measured: &BTreeMap) -> Result { + let path = root.join(FACTS_FILE); + let mut s = String::from("{\n"); + let n = measured.len(); + for (i, (k, v)) in measured.iter().enumerate() { + s.push_str(&format!( + " \"{k}\": {v}{}\n", + if i + 1 < n { "," } else { "" } + )); + } + s.push_str("}\n"); + fs::write(&path, s).map_err(|e| e.to_string())?; + Ok(path) +} + +// ---------------------------------------------------------------- status + +/// Claims the README marks `hw`, with the file it cites as evidence. A claim +/// whose evidence file is gone is reported, because "hw" without a log on disk +/// is the same shape of assertion this tool exists to refuse. +const HW_CLAIMS: &[(&str, &str)] = &[ + ( + "M1 crypto on ARM (X25519 + ChaCha20-Poly1305)", + "smoke/M1_RESULTS.md", + ), + ("AD9361 5.8 GHz PHY digital loopback", "radio/README.md"), +]; + +const SIM_CLAIMS: &[&str] = &[ + "M2 TUN/IP routing (ETX + discovery)", + "M3 iperf3 over 2 hops", + "M4 3-node triangle, shared uplink", +]; + +fn cmd_status(root: &Path) -> i32 { + let mut missing = 0; + println!("claims marked hw - evidence must be on disk\n"); + for (claim, ev) in HW_CLAIMS { + let p = root.join(ev); + if p.is_file() { + let bytes = fs::metadata(&p).map(|m| m.len()).unwrap_or(0); + println!(" [ok] {claim}\n {ev} ({bytes} bytes)"); + } else { + println!(" [MISSING] {claim}\n {ev} is not on disk"); + missing += 1; + } + } + println!("\nclaims marked -sim - no on-device run is asserted\n"); + for c in SIM_CLAIMS { + println!(" [-sim] {c}"); + } + println!( + "\nA -sim row is not a weaker version of hw. It is the absence of a run, and \ + it stays that way until a log says otherwise." + ); + if missing > 0 { + println!("\nSTATUS FAIL - {missing} hw claim(s) have no evidence file."); + return 1; + } + println!("\nSTATUS OK - every hw claim has its evidence file."); + 0 +} + +// ---------------------------------------------------------------- boards + +/// The three P203 Mini nodes. Override with TRI_NODES as a comma-separated list. +fn node_addrs() -> Vec { + match std::env::var("TRI_NODES") { + Ok(v) if !v.trim().is_empty() => v + .split(',') + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect(), + _ => vec![ + "192.168.1.10".into(), + "192.168.1.11".into(), + "192.168.1.12".into(), + ], + } +} + +fn cmd_boards(args: &[&str]) -> i32 { + let addrs = node_addrs(); + println!("probing {} node address(es)\n", addrs.len()); + let mut answered = 0; + let mut silent = 0; + let mut unprobed = 0; + + for a in &addrs { + match ping(a) { + Ok(true) => { + println!(" [answered] {a}"); + answered += 1; + } + Ok(false) => { + println!(" [silent] {a}"); + silent += 1; + } + Err(e) => { + // No ping binary, no permission, no route: the probe did not + // run. That is not the same as the node being down and is not + // reported as such. + println!(" [NOT PROBED] {a} - {e}"); + unprobed += 1; + } + } + } + + println!(); + println!("answered {answered}, silent {silent}, not probed {unprobed}"); + if unprobed > 0 { + println!( + "A node that was not probed is not a node that is down. Nothing about \ + those addresses is known from this run." + ); + } + if answered == addrs.len() { + println!("BOARDS OK - every address answered."); + return 0; + } + if args.contains(&"--strict") { + return 1; + } + 0 +} + +fn ping(addr: &str) -> Result { + let out = Command::new("ping") + .args(["-c", "1", "-W", "800", addr]) + .output() + .map_err(|e| format!("could not run ping: {e}"))?; + Ok(out.status.success()) +} + +// ---------------------------------------------------------------- smoke + +fn cmd_smoke(root: &Path) -> i32 { + println!("running the M1 crypto smoke test\n"); + let status = Command::new("cargo") + .args(["run", "--quiet", "--bin", "smoke-m1"]) + .current_dir(root) + .status(); + match status { + Ok(s) if s.success() => { + println!( + "\nSMOKE OK on the host. A host pass says the arithmetic is right and \ + says nothing about the node: append an on-device RC to \ + smoke/M1_RESULTS.md before any row claims hw." + ); + 0 + } + Ok(s) => { + println!("\nSMOKE FAIL - exit {:?}", s.code()); + 1 + } + Err(e) => { + println!("\nSMOKE NOT RUN - could not start cargo: {e}"); + 2 + } + } +} + +// ---------------------------------------------------------------- helpers + +fn repo_root() -> PathBuf { + // The manifest directory at compile time is the crate root, which is what + // every path here is relative to. Falling back to the current directory + // would silently measure whatever tree the operator happened to be in. + PathBuf::from(env!("CARGO_MANIFEST_DIR")) +} + +fn read(p: &Path) -> Result { + fs::read_to_string(p).map_err(|e| format!("{}: {e}", p.display())) +} + +fn walk(dir: &Path, ext: &str, out: &mut Vec) { + let Ok(entries) = fs::read_dir(dir) else { + return; + }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + walk(&p, ext, out); + } else if p.extension().and_then(|s| s.to_str()) == Some(ext) { + out.push(p); + } + } +} + +fn collect(root: &Path, dirs: &[&str], ext: &str) -> Result, String> { + let mut files = Vec::new(); + let mut any_dir = false; + for d in dirs { + let p = root.join(d); + if p.is_dir() { + any_dir = true; + walk(&p, ext, &mut files); + } + } + if !any_dir { + return Err(format!("none of {dirs:?} is a directory")); + } + Ok(files) +} + +fn count_files(root: &Path, dirs: &[&str], ext: &str) -> Result { + Ok(collect(root, dirs, ext)?.len() as i64) +} + +fn count_lines(root: &Path, dirs: &[&str], ext: &str) -> Result { + let mut n = 0i64; + for f in collect(root, dirs, ext)? { + n += read(&f)?.lines().count() as i64; + } + Ok(n) +} + +fn count_matching( + root: &Path, + dirs: &[&str], + ext: &str, + pred: fn(&str) -> bool, +) -> Result { + let mut n = 0i64; + for f in collect(root, dirs, ext)? { + n += read(&f)?.lines().filter(|l| pred(l)).count() as i64; + } + Ok(n) +} diff --git a/tri-facts.json b/tri-facts.json new file mode 100644 index 00000000..0df182e4 --- /dev/null +++ b/tri-facts.json @@ -0,0 +1,8 @@ +{ + "binary_sources": 30, + "declared_binaries": 2, + "rust_source_files": 39, + "rust_source_lines": 10805, + "rust_test_blocks": 432, + "t27_specs": 107 +}