> **Sole author and maintainer (personal open-source project)** · June 2026 to present
> Source: https://www.simonbetton.com/case-studies/easydoge-km.md (markdown only; there is no HTML page for this document).
> Index of case studies: https://www.simonbetton.com/case-studies/index.md

# Case study: EasyDoge KM, a Dogecoin key-management SDK

## Quick facts

|  |  |
| --- | --- |
| **Role** | Sole author and maintainer. A personal open-source project, not employer work |
| **Product** | EasyDoge KM, a Dogecoin key-management SDK with one Rust implementation and five consuming surfaces: Rust, Swift, Kotlin, Expo, and a CLI with a terminal UI |
| **Timeline** | June 2026 to present, part time |
| **Team** | One person. Coding agents produced the audit plans, the audit-driven fixes, and the terminal-client rebuild under my direction and review |
| **Licence and status** | MIT. Pre-1.0, source on GitHub, registry publication to follow |

## Overview

Wallet products keep re-implementing the same key handling. A backend derives an address one way, the iOS app another, the React Native screen rounds a number in the bridge, and nobody notices until funds land somewhere unrecoverable.

EasyDoge KM is one Rust implementation of everything cryptographic, native bindings generated from it, and a test strategy built to catch the implementation and its own fixtures drifting together. The repository holds about 9,000 lines of non-generated Rust, 800 of TypeScript and JavaScript, 2,300 of Swift and Kotlin, and 7,000 lines of generated Swift and Kotlin. It shares no code or API surface with the key-management library my employer maintains and is built on a different BIP32 and transaction library.

## The problem

Dogecoin has its own network constants, and most HD wallet tooling defaults to Bitcoin's. Extended keys use different version bytes and the derivation path uses a different coin type. A library that falls back to Bitcoin defaults produces plausible output that is wrong, discovered at broadcast time or after a user has been told an address is theirs.

A self-custodial product also serves several runtimes: a Rust backend, an iOS app, an Android app, and increasingly a React Native app that wants the same behaviour without a JavaScript reimplementation of secp256k1. Each is a chance to disagree.

I set these constraints at the start: nothing in the library touches the network, so no UTXO fetching, fee lookup, broadcasting, or chain state; the core never persists a secret, storage being a platform adapter's job; recovering a seed phrase from an extended private key is a one-way boundary the API refuses to imply; and every public surface exposes the same behaviour, tested rather than asserted.

## Architecture

Key derivation, address encoding, signing, and transaction composition live in one Rust crate. A thin wrapper crate exposes it through UniFFI, which generates the Swift and Kotlin bindings. Facade packages add the platform-idiomatic parts: an async actor and Keychain storage on Swift, coroutines and Android Keystore encryption on Kotlin. The Expo native module and the terminal client are the other two consuming surfaces. Seven ADRs record the decisions below.

The domain is written down before it is coded, the way domain-driven design recommends, although the repository does not use the label. A glossary defines 24 terms. Some separate things that are easy to blur: a seed phrase from the BIP39 seed derived from it, an extended private key from an extended public key, and watch-only derivation from signing. Others name the workflow and its artifacts: pasted material and the inspector result produced from it, the compose-and-sign transaction builder, the signing envelope, coin selection, dust, and koinu as the unit amounts are counted in. The builder is modelled as a workflow with explicit outcomes (an unsigned transaction, a signed transaction, or a signing envelope still waiting for signatures) rather than a function that returns hex. Keeping these words consistent across Rust, Swift, Kotlin and TypeScript does the same job for five language surfaces that a bounded context does for services: a signing envelope means the same thing in every one.

## Decisions and what they cost

Extended keys serialise with Dogecoin's own version bytes by default. Every import names the network the caller intends, and a Bitcoin-style prefix is accepted as that named network rather than inferred from the bytes. The cost is that the core accepts both Bitcoin mainnet and testnet legacy prefixes for whichever network the caller names, so a caller that guesses wrong gets a plausible key. The terminal client did exactly that, trying mainnet first and classifying testnet-style keys as mainnet; the rebuild classifies on the version bytes first and only offers the genuinely ambiguous alternative. The trade-off stands: legacy keys import without ceremony, and the misclassification risk sits with callers.

The first version signed transaction hex the caller had already built, leaving every caller to select inputs, size fees, add change, and serialise a transaction. That is where clients of the same library start disagreeing about transaction id byte order and dust policy, so composition moved into the core. The builder takes known spendable outputs, intended outputs, a fee policy, a coin-selection strategy, a change destination, and signer material, and returns a signed transaction or a portable signing envelope when more signatures are needed. Fee and dust behaviour are explicit request policy rather than hidden defaults, and the result is audit-shaped: selected and skipped inputs, totals, fee, change and where it went, whether dust change was folded into the fee, estimated and actual size. The cost is that the core now owns coin selection and fee estimation, and the later audit found two open defects there: duplicate outpoints are counted rather than rejected, and P2SH fee estimation trusts caller metadata instead of the redeem script.

A signing envelope carries an unsigned transaction, per-input metadata, redeem scripts, and collected signatures between co-signers. It is the trust boundary in a multisig flow, and the original implementation trusted everything inside it. Every entry point now validates first: input descriptors must be unique, in range, and consistent with the unsigned transaction; a pay-to-script-hash redeem script must hash to the script it claims to unlock; signing covers only inputs the supplied key controls and errors when it controls none; combining and finalising verify every signature for DER encoding, sighash flag, key ownership, and validity against the real sighash.

## Proving it

Parity fixtures across five surfaces sound convincing and are partly an illusion: every one of those tests exercises the same Rust implementation, so a derivation bug that also exists in the fixture passes everywhere. So two fixture sets do different jobs.

The parity fixture is a shared vector consumed by the Rust, Swift, Kotlin, Expo, and CLI tests, and proves the surfaces agree with each other.

The cross-check fixture describes inputs only; no expected outputs are committed. Two independent engines read the same cases and compute results fresh: the Rust core, and a Node runner on bitcoinjs with Dogecoin's public-key-hash, script-hash, WIF, and extended-key parameters supplied explicitly. Canonical JSON from both is compared and the first mismatch is reported by path. The harness covers seed derivation, account and child key derivation, address derivation from private and public keys, WIF round trips, rejection of hardened public derivation, message signing, legacy transaction signing, and multisig descriptors. bitcoinjs has no Dogecoin message hashing, so the Node runner carries its own short implementation written from the specification; two implementations compared against each other is a stronger check than one compared against a number I wrote down.

The fixture set is small: two mnemonics, four BIP44 cases, and two cases each for messages, transactions, and multisig. It is a drift detector, not a conformance suite, and cannot find a bug no case exercises. When the audit found by reading code that BIP39 passphrases were not NFKD-normalised before seed derivation, the fix added a non-ASCII passphrase case and the bitcoinjs engine disagreed with the Rust core until the fix landed on that branch. That pull request is still open.

## The bridge wire contract

Amounts in Dogecoin are unsigned 64-bit integers of the smallest unit. The Expo bridge carried them as JavaScript numbers, so anything above 2^53 minus 1, roughly 90 million DOGE, lost precision before reaching native code, which is close enough to real balances to matter.

Reading the converters showed they would fail in opposite directions. On iOS, converting a Double to an unsigned 64-bit integer traps on negative, NaN, or oversized input, so malformed data would crash the app rather than return an error. On Android, the same conversion wraps a negative into an enormous positive amount, and a byte-width conversion truncates a dust threshold of 300 to 44. Ordinary bad input could alter a fee, a threshold, or an output or input value, or kill the process, with no error anywhere.

The fix is a wire contract rather than a patch. Monetary amounts cross the bridge as canonical unsigned decimal strings, with TypeScript helpers to and from BigInt so callers do arithmetic in a type that can hold the value. Every other integer stays a JavaScript number but is range-checked natively against the exact Rust type it is headed for, whether an 8-bit threshold, a 32-bit sequence number, or a signed 32-bit version. Invalid input rejects the promise with a message naming the offending field. Only fields that already had defaults keep them; everything else is required, and absence is an error rather than a zero. One small codec on each native side, with its own unit tests, is the only place a JavaScript value becomes a Rust integer, and both platforms produce identical defaults and error text. Typed parameters on both native modules were widened so the platform layer cannot truncate a value before validation sees it.

The finding came from the audit described below, the implementation from a dispatched agent, and the review and merge from me. It is a breaking change to the Expo contract. Because CI does not compile the Expo native modules, the fix is verified by the codec unit tests on both platforms, review, and grep gates that confirm no unchecked conversion survives; it has not yet run on a device.

## A terminal client treated as a real interface

The terminal client started as a question-and-answer demo in a single 2,201-line file beside the CLI: a fixed header, a keybinding panel, a column of label and value lines, one address derived per keypress, the seed stretch re-run on every derivation, and no tests.

I redesigned it as a live address explorer with the discipline I would apply to a web UI, and a coding agent produced the implementation under my review. State, classification and derivation, rendering, and styling are separate modules, and the state machine is pure so it can be tested without a terminal. The layout is responsive against real breakpoints: two columns from 80 characters wide, receive and change side by side from 120, stacked below 80, and a resize prompt below 40 by 10. Derivation follows the cursor over a window of indices from a cached account extended public key, so the expensive seed stretch runs once per account instead of once per address.

Redaction is a tested rendering rule. Secrets stay hidden until explicitly revealed and hide again on escape, so a stray keypress cannot both reveal a generated phrase and quit. Input that might contain a secret is collected in masked popups showing only character and word counts, pasted private material is never echoed, and the secret type has a redacting debug representation so it cannot leak through formatting. Contrast is handled like a dark mode: the client reads the terminal's colour hint, treats a missing value as dark, never uses bright black for text because many dark palettes make it indistinguishable from the background, and drops the gold accent on light terminals where yellow fails contrast.

The rebuild cut the command-line entry point to 635 lines and added 48 headless unit tests at merge, 51 today, covering state transitions, redaction, and rendering at four terminal sizes including the degenerate ones. I also drove the real binary in a terminal multiplexer at 80 by 24, 120 by 40, and 60 by 20 and reviewed captures of every screen state before merge.

## Verification pipeline

Verification is one script locally and one CI job on macOS runners: an open-source readiness check, shell syntax checks, Rust formatting, the Rust test suite, the bitcoinjs cross-check, Clippy with warnings denied, a workspace build, a docs build, UniFFI binding regeneration, the Swift package tests, the Expo TypeScript check, and the Android Gradle tests.

The readiness check fails the build if unfinished-work marker comments appear anywhere in the repository, including planning documents. "I will come back to this" costs something at commit time, not review time.

Dependabot covers Cargo, Gradle, npm, and GitHub Actions. Twenty of the fifty commits on main, counting merges, are dependency maintenance, including a UniFFI upgrade that raised the minimum supported Rust version and regenerated every binding. Two known gaps remain: regenerated bindings are not yet checked for drift as a failure condition, and CI does not compile the Expo native module sources.

## Coding agents in the development pipeline

On 4 September 2026 I ran a third-party, MIT-licensed audit skill for Claude Code over the repository in its read-only mode. I did not write the skill. It produced 22 findings, wrote implementation plans for five, and left the remaining 17 documented so a later pass can plan them without re-auditing. The five were the skill's default ranking of impact against effort, not my triage.

Each plan carries a drift check that stops the executor if the code has moved since the plan was written, verification commands with expected results, and stop conditions where a decision is contested.

What I did with the plans is the part I own. I dispatched one executor per plan into its own git worktree so parallel work could not collide, reviewed each pull request as I would a colleague's, and merged. Co-author trailers and branch names keep agent-authored work visible in history.

The loop found four defect classes I had not caught, because the tests were green and the tests were the problem. Signing accepted any 32-bit sighash value rather than the six defined by consensus, producing unspendable signatures and, for one edge case, a reusable one. Signing envelopes were never authenticated; the existing tests finalised a transaction with a placeholder two-character signature against a script that did not hash to its redeem script. The Expo numeric transport was the bug described above. And Android stored-wallet handles lived in memory, so they stopped resolving after process death, which is routine on Android.

Android Keystore behaviour cannot run on a plain JVM, so that fix, like the Expo one, rests on unit tests, grep-based gates, and a manual device check still to come.

## No agent inside the product

There is no model, no inference, no network call, and no agentic behaviour in the library, and that is a decision. The library composes and signs transactions that move money and cannot be reversed. Every operation is deterministic, which is the property the cross-check harness exists to prove, and never touching the network is what makes the library usable in an air-gapped signing setup. An agent belongs one layer out, outside the trust boundary: explaining a fee, flagging an unusual destination, helping recover an incomplete multisig flow, drafting a request a human then reviews. The audit-shaped composition result gives such an assistant structured data instead of a hex string, and every signature in a signing envelope is verified before anything acts on it, whatever produced it.

## Results

Repository figures as of September 2026.

| Area | Before | After |
| --- | --- | --- |
| Rust test functions | 25 at the audit baseline | 93 |
| Architecture decision records | 3 in the initial commit | 7 |
| Sighash values accepted when signing | any 32-bit value | the six consensus-defined types; SIGHASH_SINGLE without a matching output rejected |
| Signature verification in envelopes | none; tests finalised with placeholder signatures | DER encoding, sighash flag, key ownership, and ECDSA validity checked at combine and finalise |
| Amounts across the Expo bridge | JavaScript numbers; precision lost above 2^53; native converters would crash on iOS and wrap on Android | canonical decimal strings; every other integer range-checked; errors name the field |
| Terminal client | one 2,201-line file, one address per keypress, no responsive layout, no tests | 635-line CLI entry point plus four TUI modules, live derivation over a cached account key, breakpoints at 40, 80, and 120 columns, 51 headless tests |
| Independent verification | fixtures generated by the implementation under test | inputs-only fixtures computed by two independent engines and compared |
| Audit findings | not measured | 22 documented; 5 planned; 3 merged; 2 in open pull requests; 17 deferred with reasons |

These are engineering outcomes, not product outcomes. Of the four defect classes the audit found, three concerned fund integrity or signature validity and all four were hidden behind a passing suite. Seventeen findings remain open, including high-severity ones in coin selection, fee estimation, and secrets passing through command-line arguments.

## Technologies and standards

Core and bindings: Rust, UniFFI-generated Swift and Kotlin bindings, Clippy, Cargo.

Platform surfaces: a Swift package with an async actor and Keychain storage; a Kotlin package with coroutines and Android Keystore encryption, tested through Gradle; an Expo native module with a TypeScript contract, BigInt helpers, and a per-platform wire codec; a Ratatui terminal client.

Verification and delivery: a Node cross-check harness on bitcoinjs with canonical JSON comparison, GitHub Actions on macOS runners, Dependabot, git worktrees for parallel agent work, a terminal multiplexer for headless capture.

Standards: BIP39, BIP32, BIP44 with the Dogecoin coin type, Base58Check, WIF, legacy P2PKH and P2SH multisig, DER-encoded ECDSA over secp256k1, the six consensus sighash types, Unicode NFKD normalisation; Conventional Commits, Semantic Versioning, ADRs, MIT licence.

## Learnings

A green suite proves little when its fixtures come from the implementation under test. The inputs-only cross-check against an independent engine is what I would build first next time, with more cases sooner.

Type boundaries are where money gets lost. The bridge bug needed no cryptographic mistake, only a JavaScript number carrying a 64-bit amount and two native converters failing in opposite directions.

Agent plans need a human read before dispatch, and agent claims of verification need checking, starting with anything CI does not compile.
