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-lean compiles 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 covers 17 of the kernel's 45 functions.

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

  1. Specs and cross-testing: formalization in Lean 4, followed by an executable kernel refined in a loop against both repos' test suites.
  2. 32-bit LLVM backend in turbo-lean: allocation-free support for thumbv6m, thumbv8m.main, and riscv32imac. 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.
  3. Integration: minimal FFI shim in each app, original UI and I/O preserved, kernel linked with LTO.
  4. maxwell optimization 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:

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:

Vanadium V-App (Rust → + Lean 4)RV32IMAC · Ledger Flex
Flash / code (PT_LOAD RX)
Baseline
299.3 KiB (1,198 pages)
+ Lean 4
261.7 KiB (1,047 pages)-12.58%
Reserved RAM (static RW + stack budget)
Baseline
128.3 KiB (514 pages)
+ Lean 4
64.3 KiB (258 pages)-49.88%
ELF binary size
Baseline
529.8 KiB
+ Lean 4
262.1 KiB-50.53%
Executed instructions (RV32 · signing)
Baseline
234.2k insns
+ Lean 4
200.0k insns-14.60%
PSBT signing latency (Flex · median)
Baseline
4,976 ms (1,325 page_loads)
+ Lean 4
4,249 ms (1,232 page_loads)-14.61%
App tests 90/90 · common 85/85 · 11 bugs fixed
BOLOS App (C → + Lean 4)ARM Thumb · Nano S+ / X
Flash / code (PT_LOAD RX · Nano S+)
Baseline
89.1 KiB (91,231 B)
+ Lean 4
87.6 KiB (89,695 B)-1.68%
Static RAM (.bss + .data · Nano S+)
Baseline
6,376 B
+ Lean 4
6,232 B-2.26%
Total RAM (RW + worst-case stack · Nano S+)
Baseline
18,872 B
+ Lean 4
18,728 B (0 recursion)-0.76%
Emitted ARM Thumb instructions (Nano S+)
Baseline
30,364 insns
+ Lean 4
29,898 insns-1.53%
Taproot PSBT latency (Nano S+ · ARMv8-M · median)
Baseline
2,436 ms
+ Lean 4
2,435 ms-0.04%
Taproot PSBT latency (Nano X · ARMv6-M · median)
Baseline
2,438 ms
+ Lean 4
2,592 ms+6.34%
31/31 ctest · mainnet 2/2 · testnet suite (282 tests) running · 0 sorryAx
Taproot signing on Vanadium: baseline and Lean variant side by side, with cumulative executed instructions
A Taproot signature on Vanadium (Speculos Flex), baseline on the left, Lean variant on the right. At the bottom, cumulative executed RV32 instructions, one point per APDU exchange: 234,214 vs. 200,692 (−14.3%), and 1,307 page loads vs. 1,240. Everything is measured; runs are instrumented with auto-approval, so the displayed duration is not a real-world latency (mp4 version).

What stands out to us:

  • The BIP-370 nLockTime computation—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 loads 5% 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.

IDSeverityLocationUpstream statusDescription
VND-01HighUnreportedandor(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-02LowUnreported · 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-03HighUnreportedFor 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-04MediumUnreportedNon-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-05MediumUnreportedsh(wsh(...)) policies succeed during register_account, then unconditionally fail during address derivation and PSBT signing.
VND-06MediumKnown 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-07LowUnreported · 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-08LowUnreported · 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-09Lowtodo!() in code · fixed upstream since (PR #301)Request::GetVersion panics via todo!(): a host can crash the app with a single request.
VND-10LowUnreportedAny PSBT with an OP_RETURN output is rejected during display, so such transactions cannot be signed.
VND-11LowUnreported · 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-h across 25 ephemeral AMD Zen cloud microVMs + 51.6 CPU-h on our dedicated server during active turns).
  • 654.9 GB RAM hours on ephemeral cloud VMs (1,049.6 GB RAM-h when including RAM reserved on our dedicated server during active turns).
  • 23.2M tokens / agent on average (696.6M cumulative tokens across 30 active agents: 1 coordinator + 29 subagents).

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).

lean-ledger-bitcoin
696.6M tok·~$520 API·peak 104.9 M tok/h
Inference Flow · Model Pools → Execution Waves
Click a pool, ribbon, or wave to isolate its curve
Gemini Carbon 4472.0 M tok · 20 agents · ~$316 APICore · builtin/smart141.0 M tok · 1 coord · ~$163 APIGLM-5.3 uncensored74.6 M tok · 7 agents · ~$36.2 APIQwen3.8-27B9.0 M tok · 2 agents · ~$3.8 APIOrchestration & steering141.0 M tok · 201 turns · ~$163.4 APIWave 1 · Specs & turbo-lean129.6 M tok · 8 agents · ~$85.2 APIWave 1.5 · Audit & remediation131.3 M tok · 6 agents · ~$78.8 APIWave 2 · Lean kernels & proofs145.2 M tok · 7 agents · ~$94.4 APIWave 3 · C/Rust link & tests55.2 M tok · 4 agents · ~$36.7 APIWave 4 · maxwell loop94.3 M tok · 4 agents · ~$61.1 API
All Inference · Throughput (M tokens / h)Peak 104.9 M tok/h · Total 696.6 M tok · ~$520 Google API + OrcaRouter eq.
6012015:15 UTC20:0001:00inference pause (04:06–06:09)11:15 UTC
Full window (19.9 h wall-clock, including a 2-hour pause due to an inference provisioning issue fixed manually)Inference: ~$520 (Google API + OrcaRouter) · Compute: ~$17 AWS (excl. dedicated server)