DEV Community

Cover image for One day, nine updates: making a Bitcoin wallet in Kisumu reliable
Stanley Chege Thuita
Stanley Chege Thuita

Posted on Edited on AI-assisted

One day, nine updates: making a Bitcoin wallet in Kisumu reliable

The short version, for everyone: Ye₿ente is a free, open-source Bitcoin wallet I build in Kisumu. When you tap Send, three things must be true: the money really goes, you never see "sent" for money that didn't go, and if it fails you get every sat back, exactly once. This post walks through the code that makes that true, on a Lightning node I run myself, including the bug where every send was refused while the node was perfectly healthy.

I build Ye₿ente, an open-source Bitcoin Lightning wallet, here in Kisumu, Kenya. It runs on my own Lightning node (LND), and it can pay any shop in kTown, a small network of local shops that take bitcoin and get paid in M-Pesa.

One day of work came down to one question: when someone taps Send, does the money actually go? Nine pull requests later, this is what the payment path looks like, and why.

GitHub logo altradits / altradits

YeBente is a free Bitcoin Lightning wallet for everyday people. Its AI agency now thinks with Meta Muse.

Altradits

Tests and security checks License: MIT

The code behind altradits.com: free Bitcoin tools and learning for people new to Bitcoin, including Ye₿ente, a custodial Bitcoin Lightning wallet for everyday amounts, and the admin dashboard that runs the Lightning node behind it.

What lives here

  • server.mjs, api/: the website and its API (Node.js, no framework).
  • lib/: shared code: wallets, Lightning, receipts, mail, security.
  • yebente/: the Ye₿ente wallet app (React + Vite). The shipped build in yebente/app is committed with the source that produced it.
  • assets/admin.js, admin.html: the node operator dashboard.
  • test/: the test suite, including the build-stage security guard.
  • docs/: manuals and guides (setup, Lightning, review process).
  • deploy/, .github/: signed-merge tooling, deploy and CI.

Quick start

Requirements: Node.js 20 or newer (CI runs 24).

npm ci --ignore-scripts
cp .env.example .env
npm run dev
Enter fullscreen mode Exit fullscreen mode

Open http://localhost:3000 (admin: /admin, token dev on a local machine only)…

Code links are pinned to commit 05a129d. The two files that matter most are lib/lightning.js (815 lines, everything that talks to the node) and lib/ywallet.js (the wallet ledger).

Contents

  1. How the wallet is built
  2. Three keys, least privilege
  3. Bug 1: sends refused while the node was healthy
  4. Before taking a sat: can the node send this?
  5. Debit first, under a lock, exactly once
  6. Paying: three answers, not two
  7. Asking the node what really happened
  8. Settling exactly once, and the 3-minute rule
  9. Bug 2: never show "sent" for a payment that didn't go
  10. Reading BOLT11 invoices by hand
  11. LNURL: don't trust the other side's invoice
  12. Bug 3: paying kTown shop QR codes
  13. The Send and Receive screens
  14. Testing against a fake Lightning node
  15. Honest limits

How the wallet is built

Piece What it does
LND node My own Lightning node. It holds the channels and the bitcoin, and makes and pays invoices
HTTPS tunnel The website's server reaches the node's REST API through a tunnel, with the node's own TLS certificate pinned
Wallet ledger Each Ye₿ente wallet is a balance in a ledger on the server. Payments between Ye₿ente wallets are ledger moves, free and instant
Send out Paying any other Lightning wallet, address or shop: the ledger is debited and the node pays
Receive The node makes an invoice; when it is paid, the ledger is credited

That makes Ye₿ente a custodial wallet: the node holds the bitcoin and the ledger says who owns how much. That is a real trade-off, and I come back to it under Honest limits. It is also why correctness on the send path matters so much: if the ledger and the node ever disagree, someone's money is wrong.

Three keys, least privilege

LND authenticates REST calls with macaroons, bearer tokens that carry a list of permissions baked in when they are created. The server never holds the admin macaroon. It holds three narrower ones:

Key (env var) Can Used for
LND_INVOICE_MACAROON Create and read invoices Receiving
LND_READONLY_MACAROON Read channels, payments, node info Balances, payment status
YEBENTE_LND_PAY_MACAROON Pay Sending, and nothing else

Every call goes through one small function, lndRequest, which pins the node's self-signed certificate and sends the macaroon as a header:

const req = https.request({
  // IPv4 only: the tunnel admits the server's IPv4 address, and an IPv6 connection is turned away.
  host: base.hostname, port: base.port || 443, family: 4, method,
  path: base.pathname.replace(/\/$/, "") + path, ca,
  headers: { "Grpc-Metadata-macaroon": String(macaroon || "").trim(), "Content-Type": "application/json", ... },
  timeout,
}, ...);
Enter fullscreen mode Exit fullscreen mode

family: 4 forces IPv4: the tunnel admits only the server's IPv4 address, so a connection that went out over IPv6 would be turned away. Pinning ca to the node's own certificate means nothing in the middle of the tunnel can impersonate the node.

Bug 1: sends refused while the node was healthy

Users saw "Sending is paused while the wallet reconnects." The node was fine: synced, one active channel. So why?

Before every send, the server asks the node how much it can send. That read used the pay key, and the pay key had been baked without offchain:read: it could pay, but it could not read channel balances. LND answered "permission denied", the code treated any failed read as "node unreachable", and every send was refused.

The fix is readForPay: reads on the send path try the pay key first, then fall back to the read-only key.

// Reads about sending (channels, payments): the pay key first, then the read-only
// key. A pay key baked without offchain:read can pay but not read, and a blank
// answer here used to block every send while the node was fine. Both keys only
// read on these calls; neither can be used to move money through them.
async function readForPay(path, opts = {}) {
  const keys = [...new Set([process.env.YEBENTE_LND_PAY_MACAROON, READ()].filter(Boolean))];
  let last = new Error("No node key can read this.");
  for (const [i, macaroon] of keys.entries()) {
    try {
      const r = await lndRequest("GET", path, null, { ...opts, macaroon,
        ...(i > 0 && opts.timeout ? { timeout: Math.min(opts.timeout, 8000) } : {}) });
      // A streamed answer can carry its refusal in the body: try the next key,
      // unless it's the node's own "never started" (a real answer, kept as is).
      const e = r?.error && String(r.error.message || r.error);
      if (opts.stream && e && !/not initiated/i.test(e) && i < keys.length - 1) {
        last = new Error(`LND: ${e.slice(0, 200)}`); continue;
      }
      return r;
    } catch (e) { last = e; }
  }
  throw last;
}
Enter fullscreen mode Exit fullscreen mode

Two details took longer than the main fix:

  • Streamed endpoints refuse inside a 200. LND's routerrpc endpoints stream one JSON object per line, and a permission error can arrive as {"error": ...} in the body with a success status. So readForPay checks the body too.
  • "Not initiated" is an answer, not a failure. When you ask LND to track a payment it never started, it says so as an error. That error must not trigger a retry with another key; it is the most important answer in the whole flow (see below).

The regression test fails on the old code with the exact message users saw, and passes with the fix. A security review checked it before merge (PR #495).

Lesson: least privilege is right, but test the reads your code depends on with the exact key it will use in production.

Before taking a sat: can the node send this?

Lightning channels have a reserve: each side must keep about 1% of the channel that it can never spend. So "local balance" is not "what I can send". spendableIn subtracts it per active channel:

// each active channel's local balance minus the reserve Lightning makes us keep
// in it (1% of the channel). The reserve can never be spent, so a channel whose
// balance is below it can send nothing.
export const spendableIn = (channels) =>
  channels.filter((c) => c.active).reduce((t, c) => t + Math.max(0, c.local - (c.localReserve || 0)), 0);
Enter fullscreen mode Exit fullscreen mode

payOut asks this before touching any balance, once more after a short pause if the tunnel blinked, and refuses cleanly if it still can't tell:

let canSend = await outboundSats();
if (canSend === null) { await new Promise((r) => setTimeout(r, 1500)); canSend = await outboundSats(); }
if (canSend === null) throw err("Sending is paused while the wallet reconnects. Nothing was taken. Try again in a few minutes.", 503);
if (canSend < dest.sats + fee) { ... throw err(`The node can send up to ${...} sats right now. Try a smaller amount.`, 503); }
Enter fullscreen mode Exit fullscreen mode

The words "Nothing was taken" matter. Refusing before the debit means the user never sees a payment that is stuck in limbo because the node was unreachable from the start.

Debit first, under a lock, exactly once

Then the ledger is debited for the amount plus a fee reserve, inside withLedger (a lock around the ledger, so two sends from the same wallet can't race past the balance check):

// The most a route may cost: reserved before paying, the unused part refunded.
export const feeReserve = (sats) => Math.max(10, Math.ceil(sats * 0.01));

const entry = await withLedger(async () => {
  const w = await getJSON(`yw:${from.id}`);
  await checkPin(w, pin);
  if (await getJSON(`ywpay:${dest.hash}`)) throw err("This invoice was already paid from a Ye₿ente wallet.", 409);
  await spendable(w, dest.sats, fee);
  w.balance -= dest.sats + fee;
  await setJSON(`yw:${w.id}`, w);
  const e = await record(w.id, { kind: "send", sats: -dest.sats, fee, counterparty: dest.label, status: "pending", ref: dest.hash, ... });
  await setJSON(`ywpay:${dest.hash}`, { walletId: w.id, entryId: e.id, sats: dest.sats, fee, at: now(), done: false });
  await pushId("ywpayopen", dest.hash);
  return e;
});
Enter fullscreen mode Exit fullscreen mode

Three design choices are in there:

  1. Debit before paying, never after. If the server crashes mid-payment, the worst case is a pending debit that the reconciler (below) settles. Paying first and debiting after would risk sending money the ledger never recorded.
  2. The payment hash is the idempotency key. A BOLT11 invoice can only be paid once, so ywpay:<hash> is created once. A double tap, a retry or a replayed request gets "already paid", not a second payment.
  3. Reserve the worst-case fee. Lightning routing fees are only known after the payment. Reserving 1% (minimum 10 sats) up front means the ledger never goes negative; the unused part comes back at settlement.

Paying: three answers, not two

LND 0.21 removed the old synchronous SendPaymentSync, so payments go through routerrpc's /v2/router/send, which streams status updates. With no_inflight_updates: true it sends only the final one, and the client keeps the last JSON line:

export async function payInvoice(pr, feeLimit) {
  try {
    const r = await lndRequest("POST", "/v2/router/send",
      { payment_request: pr, fee_limit_sat: String(feeLimit), timeout_seconds: 60, no_inflight_updates: true, allow_self_payment: false },
      { macaroon: process.env.YEBENTE_LND_PAY_MACAROON, timeout: 70000, stream: true });
    const p = r.result || r;
    if (p.status === "SUCCEEDED") return { status: "succeeded", feeSats: Number(p.fee_sat || 0), preimage: p.payment_preimage || null };
    if (p.status === "FAILED") return { status: "failed", error: ... };
    if (r.error) return { status: "unknown", error: ... };
  } catch (e) { ... return { status: "unknown", ... }; }
  // Only the node's own FAILED is final. Any other answer (an error, a dropped
  // tunnel, a gateway page) may come while the node is still paying, so it is
  // checked with paymentStatus before anything is refunded.
  return { status: "unknown" };
}
Enter fullscreen mode Exit fullscreen mode

This is the most important idea in the post. A Lightning payment has three outcomes from the caller's point of view: succeeded, failed, and I don't know. A timeout, a dropped tunnel or a 502 page from the gateway does not mean the payment failed. The node may still be routing it, and it may still succeed a minute later. If the wallet refunded on a timeout and the payment then succeeded, the user would have both the refund and the goods, and the node would be short.

So only the node's own FAILED is treated as final. Everything else is unknown.

Asking the node what really happened

When the answer is unknown, paymentStatus asks the node. First it looks in the list of recent payments; if the payment isn't there, it asks the router to track that specific hash:

export async function paymentStatus(hash) {
  const r = await readForPay("/v1/payments?include_incomplete=true&reversed=true&max_payments=500");
  const p = (r.payments || []).find((x) => x.payment_hash === hash);
  if (p?.status === "SUCCEEDED") return { status: "succeeded", feeSats: Number(p.fee_sat || 0) };
  if (p?.status === "FAILED") return { status: "failed" };
  if (p) return { status: "in_flight" };
  // Not among the latest payments: ask the node about this one. "Failed" only
  // when the node says it never started it; anything unclear stays in flight.
  const notStarted = (m) => /isn't initiated|not initiated/i.test(String(m || ""));
  try {
    const t = await readForPay(`/v2/router/track/${Buffer.from(hash, "hex").toString("base64url")}?no_inflight_updates=true`, { timeout: 15000, stream: true });
    const s = t.result || t;
    if (s.status === "SUCCEEDED") return { status: "succeeded", feeSats: Number(s.fee_sat || 0) };
    if (s.status === "FAILED" || notStarted(t.error?.message || t.error)) return { status: "failed" };
  } catch (e) {
    if (notStarted(e.message)) return { status: "failed" };
  }
  return { status: "in_flight" };
}
Enter fullscreen mode Exit fullscreen mode

"The node never started this payment" is the one case besides an explicit FAILED where refunding is safe: a payment that was never initiated can never complete. Note the base64url encoding of the hash in the path; the REST gateway wants the bytes, not hex.

Settling exactly once, and the 3-minute rule

finishPayment turns a final answer into ledger changes. It runs under the same lock, and the done flag makes it idempotent, so the request handler and the background reconciler can both call it without double refunds:

async function finishPayment(hash, res) {
  if (res.status !== "succeeded" && res.status !== "failed") return "pending";
  return withLedger(async () => {
    const p = await getJSON(`ywpay:${hash}`);
    if (!p || p.done) return p?.result || null;          // already settled: do nothing
    const w = await getJSON(`yw:${p.walletId}`);
    if (res.status === "succeeded") {
      const fee = Math.min(p.fee, Math.max(0, Number(res.feeSats) || 0));
      w.balance += p.fee - fee;                          // refund the unused fee reserve
      await entryUpdate(p.entryId, { status: "completed", fee, preimage: res.preimage || undefined });
    } else {
      w.balance += p.sats + p.fee;                       // failed: everything back
      await entryUpdate(p.entryId, { status: "failed", fee: 0, error: res.error || "The payment failed." });
    }
    await setJSON(`yw:${w.id}`, w);
    await setJSON(`ywpay:${hash}`, { ...p, done: true, result: res.status, finishedAt: now() });
    return res.status;
  });
}
Enter fullscreen mode Exit fullscreen mode

Payments still pending go on the ywpayopen list, and reconcilePayments asks the node about each one every few minutes, with one subtle rule:

// A payment younger than 3 minutes may still be on its way to the node (its send
// call can take 70 seconds), so it is left alone: asking now could refund it while it pays.
let SETTLE_AFTER = 3 * 60e3;
Enter fullscreen mode Exit fullscreen mode

Without it there is a race: the user taps Send, the request to the node is still travelling through a slow tunnel, the reconciler asks "do you know this payment?", the node truthfully says "not initiated", the reconciler refunds, and then the payment arrives and succeeds. Waiting longer than the send call's own 70-second timeout closes that window.

Bug 2: never show "sent" for a payment that didn't go

All of the above was correct on the server, but the app still played the sent animation when the server replied pending. A user who saw "Sent!" and then a refund an hour later would rightly stop trusting the wallet.

Now the API returns status: "pending" distinctly, and the app shows "Not confirmed yet", with no celebration, until the payment settles. If it fails, the sats come back and the entry says why (PR #491).

Lesson: the UI must have as many states as the protocol. Lightning has three outcomes, so the screen needs three.

Reading BOLT11 invoices by hand

The wallet reads two things out of an invoice before paying it: the amount (to check it matches what the user agreed to) and the payment hash (the idempotency key). Both are parsed directly, without a library.

The amount lives in the human-readable part, lnbc<amount><multiplier>1..., with multipliers m, u, n, p. BigInt avoids floating-point surprises:

export function bolt11Msats(pr) {
  const m = /^ln(?:bc|tb|bcrt)(\d+)([munp]?)1/i.exec(pr);
  if (!m) return null;
  const n = BigInt(m[1]);
  const per = { "": 100_000_000_000n, m: 100_000_000n, u: 100_000n, n: 100n, p: 0n };
  const msats = m[2].toLowerCase() === "p" ? n / 10n : n * per[m[2].toLowerCase()];
  // More than every bitcoin that can exist is not an amount (2010 overflow lesson).
  return msats > BigInt(MAX_MONEY_SATS) * 1000n ? null : Number(msats);
}
Enter fullscreen mode Exit fullscreen mode

The cap is a nod to Bitcoin's 2010 value-overflow incident, when a bug let a transaction create 184 billion bitcoin. An invoice claiming more than 21 million BTC is rejected as unreadable rather than converted into a nonsense Number.

The payment hash is tagged field p in the data part: 5-bit bech32 words, a 35-bit timestamp, then fields of type (5 bits), length (10 bits) and data. A 32-byte hash is 52 five-bit words, regrouped into bytes:

for (let i = 7; i + 3 <= words.length;) { // after the 35-bit timestamp: type, length, data
  const type = words[i], len = words[i + 1] * 32 + words[i + 2], data = words.slice(i + 3, i + 3 + len);
  if (type === want && len === 52) { // a 32-byte hash: 52 five-bit words
    let acc = 0, bits = 0, hex = "";
    for (const w of data) { acc = (acc << 5) | w; bits += 5;
      while (bits >= 8) { bits -= 8; hex += ((acc >> bits) & 255).toString(16).padStart(2, "0"); } }
    return hex.slice(0, 64);
  }
  i += 3 + len;
}
Enter fullscreen mode Exit fullscreen mode

The same function with want = 23 reads the description hash (field h). This parser does not verify the invoice's signature or checksum. It doesn't need to: it only extracts values for checks, and LND verifies the whole invoice before paying it.

LNURL: don't trust the other side's invoice

Paying a Lightning address (name@domain) means asking that domain for an invoice (LNURL-pay). The domain is untrusted, so payRequestInvoice treats every step as hostile:

  • Public HTTPS only. safeUrl resolves the host and refuses private and loopback addresses, checked on the IP actually connected to, with no redirects and a 64 kB response cap. Without this, a "Lightning address" could point the server at its own internal network (SSRF).
  • The amount must be exactly what we asked for. A malicious endpoint could return an invoice for more. That is refused, and recorded as an invoice_substitution attack.
  • The description must match. LUD-06 says the invoice's description hash must be the SHA-256 of the address's metadata. If it isn't, the invoice was made for something else:
const dh = bolt11DescriptionHash(pr);
if (dh && typeof pay.metadata === "string" && dh !== crypto.createHash("sha256").update(pay.metadata).digest("hex")) {
  import("./attacks.js").then((a) => a.recordAttack("invoice_substitution",
    { where: cb.hostname, detail: "description hash doesn't match the address's metadata" })).catch(() => {});
  throw err("The address returned an invoice for something else.");
}
Enter fullscreen mode Exit fullscreen mode

And if the invoice turns out to be one of our own wallets' invoices (ywinv:<hash> exists), the payment never touches Lightning at all: it becomes a free ledger transfer.

Bug 3: paying kTown shop QR codes

A kTown QR is an LNURL on our own domain (/.well-known/lnurlp/k-<id>). The wallet saw its own domain and read k-<id> as a wallet name: "No Ye₿ente wallet has that handle."

Now k- means a shop, and the wallet asks kTown for the shop's invoice directly, in-process:

// A kTown shop (its QR, or k-<id>@ our domain): asked for the shop's invoice directly,
// through kTown's own checks (amount, one record per payment), not over the network
// to ourselves. kTown fronts the payout partner, so the invoice commits to the
// partner's description, not kTown's: kTown has already checked it.
async function ktownInvoice(id, sats) { ... }
Enter fullscreen mode Exit fullscreen mode

Going over HTTP to ourselves would have failed anyway: kTown fronts the M-Pesa payout partner, so the invoice commits to the partner's description, not kTown's, and the LUD-06 check above would (correctly) reject it. New wallets can't take a k- name, so no wallet can pose as a shop (PR #493).

The Send and Receive screens

  • Send opens on the scanner: continuous focus, tap to focus, torch and zoom where the phone has them, and every other frame a sharp close-up of the middle for small or dense codes (PR #501).
  • Clipboard offer: copy an invoice or Lightning address and the app offers to paste it. It's read on the phone only, and used only if you tap Paste.
  • Approve last: no PIN box on the amount screen. Send opens your fingerprint, or a final PIN pop-up (PR #503).
  • Receive is one big QR with your address under it, one tap to copy, and an invoice that fills the screen until it's paid (PR #505).
  • No empty wallet: while the node reconnects, the buttons stay on screen, greyed out (PR #489).

Testing against a fake Lightning node

You can't test "the tunnel drops mid-payment" against a real node on demand. So the tests start a fake LND over real HTTPS, with a throwaway certificate made by openssl at test time, and script its behaviour:

const PAY = "aa".repeat(32), RO = "bb".repeat(32);
const lnd = https.createServer({ key, cert }, (req, res) => {
  const mac = req.headers["grpc-metadata-macaroon"];
  ...
  if (req.method === "GET") {
    // The pay key may not read; the read-only key may.
    if (mac === PAY) { node.reads.pay++; res.writeHead(403).end(JSON.stringify({ message: "permission denied" })); return; }
    ...
  }
  if (req.url === "/v2/router/send" && mac === PAY) {
    ...
    node.paid.set(hash, "IN_FLIGHT"); // the tunnel drops mid-call: no answer, but the node keeps paying
    res.writeHead(502).end("<html>bad gateway</html>"); return;
  }
});
Enter fullscreen mode Exit fullscreen mode

Invoices are built bit by bit in the test (bech32 words with a real p field), so the parser is exercised on the same shapes it sees in production. The test for bug 1 asserts both that the send completes and that the ledger is exact to the sat:

test("the pay key can't read: the send still goes, read through the read-only key", async () => {
  ...
  assert.equal(body.status, "completed");
  assert.ok(node.reads.ro > 0, "the read-only key answered the reads");
  const w = await yw.walletByHandle("paykeyok");
  assert.equal(w.balance, 5000 - 500 - 2, "500 sent, the 2-sat fee kept, the rest of the reserve refunded");
});
Enter fullscreen mode Exit fullscreen mode

The whole repo runs on Node's built-in test runner:

git clone https://github.com/altradits/altradits
cd altradits
npm install
npm test
Enter fullscreen mode Exit fullscreen mode

Our run at 05a129d (Node 24):

ℹ tests 783
ℹ pass 783
ℹ fail 0
Enter fullscreen mode Exit fullscreen mode

Every change gets an issue, a pull request, a test that fails on the old code first, CI, and a review before merge.

Honest limits

  • It is custodial. Ye₿ente balances are entries in a ledger; the bitcoin sits in a node I run. Users trust me and my node, the way they trust any custodial wallet. That is why there are hard limits on balance and payment size, a solvency check before anyone can buy sats (the node must be able to pay out what wallets would then hold, with a 10% margin), and a "dead man" switch that pauses outbound payments for a security check while transfers between wallets keep working.
  • One node, one tunnel. If the node is offline, sending out pauses (cleanly: nothing is taken). Payments between Ye₿ente wallets still work, because they never touch Lightning.
  • The fee reserve is a heuristic. 1% covers normal routes; an unusually expensive route fails rather than overspending, and the user gets everything back.
  • Not a self-custody wallet. If you want your own keys, use a self-custodial Lightning wallet. Ye₿ente's goal is the first step for people who have never held bitcoin, in a town where shops can now take it.

I'm working toward full-time Bitcoin open-source work, learning to review Bitcoin's code alongside building this. Contributions, reviews and questions are welcome: github.com/altradits/altradits.

Not sponsored. No paid posts. Try the wallet: altradits.com/yebente

Top comments (0)