Lean 4 Ledger
Our thesis is that it is already viable today to rewrite existing software in Lean 4 to obtain a formally proved binary that is both more compact and faster. Yesterday, Vincent and Guillaume suggested starting with Ledger's Bitcoin application; here is the result.
Important: this is a one-day POC—the specs are not complete, there are other important properties worth formally verifying, and this would require more review on our side as well as validation of our modeling choices on yours.
1. Methodology and Architecture
In terms of human time, I had already looked into it a bit when Charles mentioned it to me and had a rough idea of the Ledger stack: it took me about 1 h upfront to frame the problem, lay down the high-level specs, and design the pipeline, 15 min this morning to unblock an inference routing issue, and 1 h at the end to review and polish everything. Everything else ran autonomously.
Ledger maintains two Bitcoin apps: the legacy C app (app-bitcoin), compiled natively to the microcontroller's instruction set on top of BOLOS, and the new Rust V-App (vanadium), compiled to 32-bit RISC-V (RV32IMAC) and executed inside a VM running on BOLOS (to stream the app's code and data from the host, if I understood correctly).
Rather than touching the UI or APDU/ECALL transport (rewriting the UI in Lean 4 would have little value), we kept the original UI and I/O in each app and focused the effort on the shared logic where most of the attack surface lives. The result, Th0rgal/lean-ledger-bitcoin, contains two things of interest for you:
- A Lean kernel compiled into both apps (
FreestandingKernels.lean): this is the Lean code actually executed on the device.turbo-leancompiles it to 32-bit LLVM IR, replacing the sensitive paths we rewrote in each app. - A short spec on this kernel (
Spec.lean, 12 statements): each statement targets a compiled function, and its proof is checked by Lean (0 sorryAx). It currently covers17of the kernel's45functions.
The integrations fit into two patches: app-bitcoin-lean-opt.patch on the BOLOS side and vanadium-bitcoin-lean-opt.patch on the Vanadium side. The remaining C/Rust is the original code, lightly patched (around 200 lines modified on the C side and 700 on the Rust side, excluding tests). It does three things: calls the Lean kernel in place of the original checks, parses PSBTs and scripts, and talks to the hardware (keys, crypto, screen, and transport go through BOLOS syscalls). For that OS-facing part, using Lean wouldn't make sense; for the parsers, however, I think it would be a good idea. It's more work, but it would be worth it since they lend themselves well to formal verification.
2. Execution Plan
- Specs and cross-testing: formalization in Lean 4, followed by an executable kernel refined in a loop against both repos' test suites.
- 32-bit LLVM backend in
turbo-lean: allocation-free support forthumbv6m,thumbv8m.main, andriscv32imac. Going through LLVM IR felt safer than emitting assembly directly. This compilation chain is not yet proved end-to-end (it is checked via differential testing). Proving it would be relatively expensive in inference, but it would be a good investment since it only needs to be done once. - Integration: minimal FFI shim in each app, original UI and I/O preserved, kernel linked with LTO.
maxwelloptimization loop: iterations on reproducible benchmarks, with proofs and tests green, to get below the baselines.
3. Results
Here is the spec. It only covers code actually compiled into the apps and is not complete, but it illustrates what is possible:
- Transaction amounts: the kernel returns “valid” if and only if the amount is at most 21 million BTC. For a sum or difference, it returns “valid” if and only if the exact mathematical result stays between 0 and this cap, and in that case returns the exact result.
- Display: splitting an amount into BTC and satoshis without division is exact for every 64-bit amount.
- Derivation paths: the kernel classifies a path element as “hardened” if and only if it is at least 231, and rejects paths longer than 10 elements on BOLOS or 16 on Vanadium.
- Addresses: the kernel returns “valid” for a SegWit program in the exact allowed cases—20 or 32 bytes for version 0, and 2 to 40 bytes for versions 1 through 16.
- Requested signature types: the kernel returns “valid” if and only if the sighash is ALL, NONE, or SINGLE, with or without ANYONECANPAY, plus DEFAULT for Taproot.
- Transaction parsing: the kernel returns “valid” for a length prefix (CompactSize) if and only if it uses the shortest canonical encoding.
Each statement is an “if and only if” or an equality, paired with one accepted example and one rejected example.
On the performance side, we didn't go out of our way to optimize—especially since we go through LLVM rather than targeting the final hardware directly—yet we still get interesting numbers thanks to a few measurement and tuning iterations. The Lean 4 patched binary is smaller on both targets and faster on Vanadium; on BOLOS, latency is unchanged on Nano S+ and higher on Nano X:

What stands out to us:
- The
BIP-370nLockTimecomputation—where Vanadium appears to have a bug (to be confirmed with you)—was proved compliant with the rule for any list of inputs without intervention on our part. - A single Lean kernel serves three ISAs and two apps: it is emitted as LLVM IR and compiled with each app's flags, with a maximum stack frame of
96 B. - On Vanadium, signing executes
14.6%fewer RV32 instructions and loads5%fewer pages under an identical compiler profile. - Cross-formalizing both apps was enough to surface the 11 bugs in Section 4.
Reading notes. Measurements were taken under an emulator (Speculos), not on hardware. On Vanadium, the RAM and file-size reductions come mostly from build settings; the gain attributable to the code itself is 14.6% on executed instructions. On BOLOS, sizes and latencies were measured on two different builds: we are re-running a full benchmark to remove any ambiguity.
4. Bugs and Anomalies Found in Vanadium
While formalizing the C and Vanadium implementations, we spotted 11 bugs or spec divergences. We haven't manually verified all of them, but they look solid—with the bug on the Vanadium side every time.
| ID | Severity | Location | Upstream status | Description |
|---|---|---|---|---|
VND-01 | High | Unreported | andor(X, Y, Z) is compiled as [X] OP_NOTIF [Y] OP_ELSE [Z] OP_ENDIF instead of the BIP-379 [X] OP_NOTIF [Z] OP_ELSE [Y] OP_ENDIF. The device derives a different script and address than Bitcoin Core and app-bitcoin for the same policy, and the spending branches are swapped. | |
VND-02 | Low | Unreported · fixed upstream since (PR #301) | Unbounded u64 satoshi sums (missing MAX_MONEY bounds) and unchecked u64 as i64 casts on per-account balances — a defense-in-depth / specification gap reachable under a malformed host PSBT, now bounded in the patched kernel. | |
VND-03 | High | Unreported | For SegWit v0 inputs carrying both non_witness_utxo and witness_utxo, only the txid is checked: the witness_utxo amount and script are never compared with the referenced output (CVE-2020-14199 class), unlike app-bitcoin. Taproot inputs are unaffected. | |
VND-04 | Medium | Unreported | Non-compliant BIP-370 nLockTime computation: accepts zero height locks, rejects dual-locked inputs, and lets fallback_locktime overwrite a block-height lock into a timestamp. Impact is interoperability, not loss of funds. | |
VND-05 | Medium | Unreported | sh(wsh(...)) policies succeed during register_account, then unconditionally fail during address derivation and PSBT signing. | |
VND-06 | Medium | Known gap (upstream TODO) | Missing BIP-379 Miniscript B/V/K/W typechecking, non-malleability enforcement, height/time timelock mixing checks, and BIP-68 older(n) flag masking — now fully enforced in the patched V-App via llb_miniscript_check_postfix. | |
VND-07 | Low | Unreported · fixed upstream since (PR #301) | Off-by-one len() > 256 guard followed by u8 cast: a 256-step BIP-32 path wraps to depth = 0 in the serialized xpub. | |
VND-08 | Low | Unreported · fixed upstream since (PR #301) | In MuSig2 Round 2, the recomputed local pubnonce is not verified against PSBT_IN_MUSIG2_PUB_NONCE before emitting a partial signature. | |
VND-09 | Low | todo!() in code · fixed upstream since (PR #301) | Request::GetVersion panics via todo!(): a host can crash the app with a single request. | |
VND-10 | Low | Unreported | Any PSBT with an OP_RETURN output is rejected during display, so such transactions cannot be signed. | |
VND-11 | Low | Unreported · fixed upstream since (PR #301) | Non-canonical CompactSize encodings are accepted by the PSBT parser. |
5. Summary of Resources Invested (Initial Run)
The entire autonomous run (formalization, turbo-lean compiler patch, proofs of 2,494 theorems, C/Rust integration, and maxwell loops) ran in 19.9 h wall-clock over the window captured below up to the main repo merge (including a 2-hour pause caused by an inference provisioning issue that I fixed manually) across 30 active agents and 25 microVMs:
- 379.0 CPU hours of cumulative compute (
327.4 CPU-hacross 25 ephemeral AMD Zen cloud microVMs +51.6 CPU-hon our dedicated server during active turns). - 654.9 GB RAM hours on ephemeral cloud VMs (
1,049.6 GB RAM-hwhen including RAM reserved on our dedicated server during active turns). - 23.2M tokens / agent on average (
696.6Mcumulative tokens across30active agents:1coordinator +29subagents).
At public Google API and OrcaRouter (for GLM 5.3 uncensored) rates on the inference side, and AWS EC2 On-Demand rates for VM rental, this run would cost roughly ~$520 + ~$17 (about ~$537 total), excluding personal infrastructure (our dedicated server and upstream training GPUs used to optimize the compiler, whose amortized share for this run remains negligible).