Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/mobile-bindings.yml
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ jobs:
wasm_exec.js \
sqlite-bridge.js \
sqlite-worker.js \
sqlite-node-vfs.js \
sqlite3.js \
sqlite3.wasm \
sqlite3-opfs-async-proxy.js
Expand Down
7 changes: 5 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -486,8 +486,8 @@ mobile-ios: #? Build the iOS .xcframework for sdk/wavewalletdk
WASM_WALLET_OUT := bin/wasm
WASMSQLITE_DIR := $(shell $(GOCC) list -m -f '{{.Dir}}' github.com/lightninglabs/go-wasmsqlite 2>/dev/null)

wasm-wallet: #? Build the wavewalletdk browser wasm blob + runtime assets into bin/wasm
@$(call print, "Building wavewalletdk browser wasm blob.")
wasm-wallet: #? Build the wavewalletdk wasm blob + runtime assets into bin/wasm
@$(call print, "Building wavewalletdk wasm blob.")
$(RM) -r $(WASM_WALLET_OUT)
mkdir -p $(WASM_WALLET_OUT)
GOOS=js GOARCH=wasm $(GOBUILD) -trimpath -ldflags="-s -w" \
Expand All @@ -501,6 +501,9 @@ wasm-wallet: #? Build the wavewalletdk browser wasm blob + runtime assets into b
cp $(WASMSQLITE_DIR)/assets/sqlite3-opfs-async-proxy.js $(WASM_WALLET_OUT)/
cp $(WASMSQLITE_DIR)/bridge/sqlite-bridge.js $(WASM_WALLET_OUT)/
cp $(WASMSQLITE_DIR)/bridge/sqlite-worker.js $(WASM_WALLET_OUT)/
# sqlite-node-vfs.js is loaded only by a Node host, but it ships in every
# bundle so one asset set serves both hosts.
cp $(WASMSQLITE_DIR)/bridge/sqlite-node-vfs.js $(WASM_WALLET_OUT)/

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Include the Node VFS in released runtime bundles

When users obtain the runtime through either tagged release channel, this newly copied asset is discarded: the archive command in .github/workflows/mobile-bindings.yml lines 189–197 and the explicit upload list in scripts/publish-wasm-assets.sh lines 35–44 both retain the old browser-only file set. A Node consumer of the release archive or hosted bundle therefore cannot load sqlite-node-vfs.js, so the Node-host support added here is unavailable outside a local make wasm-wallet build; add the asset to both packaging lists (and the corresponding consumer manifest).

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 blocker — This cp breaks make wasm-wallet today. bridge/sqlite-node-vfs.js does not exist in the pinned go-wasmsqlite (v0.0.0-20260627090804-0dce68fc5287); that module's bridge/ contains only sqlite-bridge.js and sqlite-worker.js. cp exits non-zero and takes the target down, and wasm-publish runs wasm-wallet first, so the release path goes with it.

Separately — and this one survives the go.mod bump — scripts/publish-wasm-assets.sh carries an explicit FILES=(...) allowlist, and uploads exactly that set on purpose ("so we publish exactly the manifest set and never leak stray files that a previous build may have left in the asset dir"). sqlite-node-vfs.js is not in it, so even once the copy works the published bundle will not contain the Node VFS — and neither the pre-flight existence check nor the post-upload verification notices, because both only iterate the files already listed. The comment here says the asset "ships in every bundle"; for the bundle that actually reaches consumers, it does not. So the codex thread on this is correct.

Add sqlite-node-vfs.js to FILES in scripts/publish-wasm-assets.sh as well. That script's header says the array must stay in sync with RUNTIME_ASSET_FILES in packages/web/src/runtime-manifest.ts and the FILES array in apps/web-wallet-demo/scripts/fetch-runtime-assets.sh, so this needs a companion wavelength-sdk change to land with it.

# The go-wasmsqlite assets are read-only in the module cache; make the
# copies writable so re-runs (and callers staging the bundle) aren't
# blocked by a read-only destination.
Expand Down
11 changes: 8 additions & 3 deletions cmd/wavewalletdk-wasm/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,14 @@ VM with no separate gateway.
- Every verb takes a JS request object and resolves/rejects a JS `Promise`;
never call back into JS synchronously from a goroutine without going
through `promise`, or a panic can escape and kill the Go runtime.
- `data_dir` must default to `browserDataDir` (`/wavelength`) when unset, because
the embedded daemon's config validation calls `os.UserHomeDir` for the
default `~/.waved`, which fails under `wasm_exec.js` (no `$HOME`).
- `data_dir` must default to `browserDataDir` (`/wavelength`) when unset **on a
browser host**, because the embedded daemon's config validation calls
`os.UserHomeDir` for the default `~/.waved`, which fails under
`wasm_exec.js` (no `$HOME`). Under a Node host that default is refused
instead: Node has a real filesystem, so `waved.ensureDataDir` would
`os.MkdirAll` at the filesystem root and fail with `EROFS`/`EACCES`. A Node
caller must set `data_dir` explicitly and gets a rejected promise if it
does not.
- The `executor` `js.Func` passed to `Promise.New` must be released right
after construction (the executor runs synchronously), otherwise every
wallet call leaks a Go callback handle for the life of the page.
Expand Down
11 changes: 8 additions & 3 deletions cmd/wavewalletdk-wasm/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,14 @@ VM with no separate gateway.
- Every verb takes a JS request object and resolves/rejects a JS `Promise`;
never call back into JS synchronously from a goroutine without going
through `promise`, or a panic can escape and kill the Go runtime.
- `data_dir` must default to `browserDataDir` (`/wavelength`) when unset, because
the embedded daemon's config validation calls `os.UserHomeDir` for the
default `~/.waved`, which fails under `wasm_exec.js` (no `$HOME`).
- `data_dir` must default to `browserDataDir` (`/wavelength`) when unset **on a
browser host**, because the embedded daemon's config validation calls
`os.UserHomeDir` for the default `~/.waved`, which fails under
`wasm_exec.js` (no `$HOME`). Under a Node host that default is refused
instead: Node has a real filesystem, so `waved.ensureDataDir` would
`os.MkdirAll` at the filesystem root and fail with `EROFS`/`EACCES`. A Node
caller must set `data_dir` explicitly and gets a rejected promise if it
does not.
- The `executor` `js.Func` passed to `Promise.New` must be released right
after construction (the executor runs synchronously), otherwise every
wallet call leaks a Go callback handle for the life of the page.
Expand Down
43 changes: 35 additions & 8 deletions cmd/wavewalletdk-wasm/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"io"
"syscall/js"

"github.com/lightninglabs/wavelength/internal/wasmhost"
"github.com/lightninglabs/wavelength/sdk/wavewalletdk/mobile"
)

Expand Down Expand Up @@ -50,7 +51,10 @@ func walletCall(_ js.Value, args []js.Value) any {
switch method {
// Lifecycle.
case "start":
cfg := startConfig(req)
cfg, err := startConfig(req)
if err != nil {
return rejected(err)
}

return promise(func() (any, error) {
return js.Null(), mobile.Start(cfg)
Expand Down Expand Up @@ -269,30 +273,53 @@ func jsError(err error) js.Value {
return js.Global().Get("Error").New(err.Error())
}

// browserDataDir is a WASM-safe default data directory. A browser has no $HOME
// for the daemon's `~` expansion to resolve against, and persistent state lives
// in OPFS-backed SQLite keyed by hashed file names rather than host directories
// (see waved.ensureDataDir, a no-op under js/wasm), so any fixed in-origin
// path is all the embedded daemon needs.
// browserDataDir is a WASM-safe default data directory for a browser host. A
// browser has no $HOME for the daemon's `~` expansion to resolve against, and
// persistent state lives in OPFS-backed SQLite keyed by hashed file names
// rather than host directories, so any fixed in-origin path is all the
// embedded daemon needs.
//
// A Node host inverts both halves of that reasoning, which is why this default
// is not for it. Node has a real filesystem, so waved.ensureDataDir creates
// this path rather than ignoring it, and the node:fs SQLite VFS writes to the
// configured path rather than to a hashed OPFS name. Injecting it there asks
// the host to mkdir at the filesystem root, which fails with EROFS or EACCES
// for any process not running as root.
const browserDataDir = "/wavelength"

// errNodeDataDirRequired reports that a Node host started the daemon without
// saying where its databases should live. There is no default worth guessing
// here: the daemon's databases are the only copy of the wallet's state, and a
// path picked from the process's working directory or environment would put
// them somewhere that changes with how the host happened to be launched.
var errNodeDataDirRequired = errors.New("data_dir must be set when the " +
"js/wasm host is Node, which stores databases on the host filesystem")

// startConfig renders the start request as a config JSON string, injecting the
// browser-safe data dir when the caller didn't set one. Without it the embedded
// daemon's config validation expands the default `~/.waved` via
// os.UserHomeDir, which fails with "$HOME is not defined" under wasm_exec.js
// and aborts start before the wallet boots.
func startConfig(req js.Value) string {
//
// A Node caller that omits the path is told so instead, because the browser
// default cannot be created there and the alternative is an EROFS from mkdir
// well after start was accepted.
func startConfig(req js.Value) (string, error) {
if req.IsUndefined() || req.IsNull() {
req = js.Global().Get("Object").New()
}

if v := req.Get("data_dir"); v.IsUndefined() || v.IsNull() ||
v.String() == "" {

if wasmhost.UnderNode() {
return "", errNodeDataDirRequired
}

req.Set("data_dir", browserDataDir)
}

return stringify(req)
return stringify(req), nil
}

// stringify renders a JS request value as a JSON string, or "" when absent.
Expand Down
55 changes: 43 additions & 12 deletions db/sqlite_open_wasm.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,33 +12,50 @@ import (
"time"

_ "github.com/lightninglabs/go-wasmsqlite"
"github.com/lightninglabs/wavelength/internal/wasmhost"
)

const (
wasmSQLiteDriverName = "wasmsqlite"
wasmSQLiteVFS = "opfs"
)
const wasmSQLiteDriverName = "wasmsqlite"

// openSQLiteDatabase opens SQLite through the browser-backed wasmsqlite
// driver.
// openSQLiteDatabase opens SQLite through the wasmsqlite driver, against
// whichever durable storage the host offers.
func openSQLiteDatabase(cfg SQLiteOpenConfig) (*SQLiteOpenResult, error) {
values := url.Values{}
values.Set("file", browserSQLiteFileName(cfg.DatabaseFileName))
values.Set("vfs", wasmSQLiteVFS)
values.Set("vfs", wasmhost.SQLiteVFS())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Upgrade the driver before selecting nodefs

For every Node-hosted run built from this commit, go.mod still pins go-wasmsqlite at v0.0.0-20260627090804-0dce68fc5287, which predates support for both vfs=nodefs and require_persistent. Consequently these new DSNs cannot provide the promised disk-backed storage: the open may fail or the unsupported persistence guard may be ignored, risking transient wallet and daemon state. The driver update that implements these options must land with this selection.

Useful? React with 👍 / 👎.

if wasmhost.UnderNode() {
// A Node host has a real filesystem, so the configured path is
// usable as-is and the OPFS name mangling below would only
// obscure where the database actually lives.
values.Set("file", cfg.DatabaseFileName)
} else {
values.Set("file", browserSQLiteFileName(cfg.DatabaseFileName))
}
values.Set("mode", "rwc")

// The daemon's databases are the only record of VTXO, swap, and round
// state; there is no server to re-fetch them from. Refusing an
// in-memory substitute makes a storage failure a startup error rather
// than a wallet that looks healthy and forgets everything on exit.
values.Set("require_persistent", "true")

pragmas := make([]string, 0, len(cfg.Pragmas)+1)
for _, pragma := range cfg.Pragmas {
switch strings.ToLower(pragma.Name) {
case "busy_timeout":
values.Set("busy_timeout", pragma.Value)

case "journal_mode":
// The driver takes the journal mode as its own DSN key
// rather than as a pragma, because it applies it last
// and then reads the effective mode back. See the
// locking_mode note below for why the order matters.
values.Set("journal_mode", pragma.Value)

case "fullfsync":
// fullfsync is a native filesystem durability hint and
// is not meaningful for browser OPFS.
// fullfsync asks Darwin for a stronger barrier than
// fsync. Neither wasm VFS can express it: OPFS has no
// such concept, and the node:fs VFS already issues a
// full fsync on every xSync.

default:
pragmas = append(
Expand All @@ -47,6 +64,16 @@ func openSQLiteDatabase(cfg SQLiteOpenConfig) (*SQLiteOpenResult, error) {
}
}

// Exclusive locking is not merely an optimization for a

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 minor — This comment is now accurate — I verified the hoist and the read-back in the merged driver, and measured journal_mode=wal end to end under nodefs. One thing worth confirming before merge, because it lands on the browser path rather than the new Node one.

The bump changes browser behaviour, not just Node behaviour. The driver's own CHANGELOG says the old pragma ordering "made journal_mode=WAL unreachable on every VFS this driver offers" and that "a WAL request silently produced a rollback journal". So today, on the pinned-before-this-PR driver, the shipping browser wallet is running on the rollback journal while this code asks for WAL. After the bump, applyJournalMode (bridge/sqlite-worker.js:594-618) reads the effective mode back and throws on mismatch. Two outcomes, and they are very different:

  • OPFS + locking_mode=EXCLUSIVE can deliver WAL-without-shm → the browser quietly gets the mode it has been asking for all along. Good.
  • It cannot → every browser open now throws journal_mode=WAL was requested but SQLite is in "delete" mode, and the browser wallet stops starting.

The analysis points at the first outcome: SQLite passes bNoShm = pPager->exclusiveMode into sqlite3WalOpen, so under EXCLUSIVE locking the wal-index is on the heap and the VFS's shm methods are never called at all — which is exactly why it works under nodefs, and nothing in that path is OPFS-specific. But I could not run it: this container has no browser (missing libglib-2.0, no root to install it), and I could not find the assertion anywhere in the merged module either — browser_e2e_test.go, driver_browser_js_wasm_test.go and tests/example-opfs-wl.spec.js contain no journal/WAL/locking assertions, while the Node suite covers it thoroughly (tests/node-backend.test.cjs:475, :508, :544).

So the one VFS whose WAL behaviour is untested is the one that is already in production. Please open the wasm wallet in a real browser once against this bump and confirm the database opens and reports wal — or add the OPFS counterpart of tests/node-backend.test.cjs:475 upstream. If it does open, it is worth saying in this comment that the browser was silently on the rollback journal before this bump, since that also means synchronous=normal meant something weaker there than this code assumed.

// single-connection handle: it is what makes WAL reachable at all here.
// Neither wasm VFS implements xShmMap, so the only WAL available is the
// mode SQLite documents for hosts without shared memory, where an
// EXCLUSIVE connection keeps the WAL index on the heap. The driver
// hoists the locking mode ahead of the journal mode for exactly that
// reason, and then reads back the mode it ended up in, so a regression
// here surfaces as a startup error rather than as a database quietly
// running on the rollback journal while `synchronous` was chosen for
// WAL.
pragmas = append(pragmas, "locking_mode=EXCLUSIVE")
values.Set("pragma", strings.Join(pragmas, ";"))

Expand Down Expand Up @@ -75,8 +102,8 @@ func openWASMSQLiteWithRetry(dsn string) (*sql.DB, error) {
return nil, err
}

// OPFS SQLite handles must be single-connection handles.
// Multiple SQL connections would race the same browser database
// A wasm SQLite handle must be a single-connection handle.
// Multiple SQL connections would race the same database
// through one worker.
db.SetMaxOpenConns(1)
db.SetMaxIdleConns(1)
Expand Down Expand Up @@ -111,6 +138,10 @@ func isWASMCantOpen(err error) bool {
// regtest and signet client.db, or two swaps.db) map to distinct OPFS files
// within one browser origin instead of silently colliding. This mirrors the
// scheme lwwallet uses for its own OPFS wallet database.
//
// None of that applies to a Node host, which keeps the configured path as
// given: it is already unique, and it has the considerable advantage of being
// findable on disk.
func browserSQLiteFileName(name string) string {
normalized := filepath.ToSlash(filepath.Clean(name))
base := filepath.Base(normalized)
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ require (
github.com/btcsuite/btcd/psbt/v2 v2.0.0
github.com/btcsuite/btcd/txscript/v2 v2.0.0
github.com/btcsuite/btcd/wire/v2 v2.0.0
github.com/lightninglabs/go-wasmsqlite v0.0.0-20260627090804-0dce68fc5287
github.com/lightninglabs/go-wasmsqlite v0.0.0-20260811033710-d14cd0d80aa0
)

require (
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -1040,8 +1040,8 @@ github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/lib/pq v1.3.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/lib/pq v1.11.1 h1:wuChtj2hfsGmmx3nf1m7xC2XpK6OtelS2shMY+bGMtI=
github.com/lib/pq v1.11.1/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
github.com/lightninglabs/go-wasmsqlite v0.0.0-20260627090804-0dce68fc5287 h1:q/7nFGq1Eln2DrV51SddoGP54Yfgvuxq6JmQHG+D8LA=
github.com/lightninglabs/go-wasmsqlite v0.0.0-20260627090804-0dce68fc5287/go.mod h1:qtLtxJq5KD9oP2I4lj0qRIWCU/fN8eNfTrHie4YrKTQ=
github.com/lightninglabs/go-wasmsqlite v0.0.0-20260811033710-d14cd0d80aa0 h1:p1jafKTSU+v8FOKD+kFa2TIU+w71116AFTet3lOIcTI=
github.com/lightninglabs/go-wasmsqlite v0.0.0-20260811033710-d14cd0d80aa0/go.mod h1:qtLtxJq5KD9oP2I4lj0qRIWCU/fN8eNfTrHie4YrKTQ=
github.com/lightninglabs/gozmq v0.0.0-20191113021534-d20a764486bf h1:HZKvJUHlcXI/f/O0Avg7t8sqkPo78HFzjmeYFl6DPnc=
github.com/lightninglabs/gozmq v0.0.0-20191113021534-d20a764486bf/go.mod h1:vxmQPeIQxPf6Jf9rM8R+B4rKBqLA2AjttNxkFBL2Plk=
github.com/lightninglabs/lightning-node-connect/hashmailrpc v1.0.4-0.20250610182311-2f1d46ef18b7 h1:373o5lNr1udAdhcf5+zq/0dYpRtkvYLl8Lk6wG7I0DY=
Expand Down
49 changes: 49 additions & 0 deletions internal/wasmhost/host.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
//go:build js && wasm

// Package wasmhost answers one question for the js/wasm build: which host is
// running this binary?
//
// The wavewalletdk wasm blob targets two very different hosts. A browser page
// has no filesystem and persists everything in OPFS. A Node process has a real
// filesystem, reached both through Go's own os package (once the host wires
// globalThis.fs to node:fs) and through the go-wasmsqlite nodefs VFS. Nothing
// else about the daemon differs, but storage differs completely, so the answer
// is needed in several packages and is worth deriving in exactly one place.
package wasmhost

import "syscall/js"

// UnderNode reports whether this binary is hosted by Node rather than by a
// browser page.
//
// Two signals are checked together because neither is sufficient alone. A
// bundler may define a process shim in a browser, so a node version string is
// not proof on its own; and a non-browser host other than Node would also lack
// a Worker constructor. Requiring both keeps a browser that fakes one of them
// from being mistaken for a filesystem host, which would send the daemon
// looking for storage that is not there.
func UnderNode() bool {
process := js.Global().Get("process")
if process.Type() != js.TypeObject {
return false
}

versions := process.Get("versions")
if versions.Type() != js.TypeObject ||
versions.Get("node").Type() != js.TypeString {
return false
}

return js.Global().Get("Worker").Type() != js.TypeFunction
}

// SQLiteVFS names the go-wasmsqlite VFS that gives this host durable storage.
// Both names are durable, so an open that asks for one and cannot have it
// fails rather than quietly running against memory.
func SQLiteVFS() string {
if UnderNode() {
return "nodefs"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 blocker — nodefs does not exist in the pinned driver, so this makes every Node run fail at the first database open until the go.mod bump lands. I traced it rather than guessing:

  • grep -rn nodefs over go list -m -f '{{.Dir}}' github.com/lightninglabs/go-wasmsqlite returns nothing at all.
  • bridge/sqlite-worker.js:59 normalizeRequestedVFS passes an unrecognized name straight through its default branch.
  • open() (sqlite-worker.js:369) therefore builds candidates = ["nodefs"], and openPersistentDB throws at lines 328-330: requested SQLite VFS is unavailable: nodefs.
  • Because requestedVFS !== "auto" and requestedVFS !== "opfs", the memory-fallback branch at 392-397 is skipped and the error rethrows.

The important part is the direction of failure: this is a hard open error, not a silent memory-backed database. So the codex P1 is right that the driver must be upgraded first, but it is a broken-startup bug, not a fund-safety one.

Merge-order consequence, plainly: this PR must not merge before the go-wasmsqlite bump, because with the currently pinned driver every Node-hosted start dies at the first open. The browser path is unaffected either way.

}

return "opfs"
}
42 changes: 38 additions & 4 deletions lwwallet/walletdb_wasm.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/btcsuite/btcwallet/walletdb"
_ "github.com/lightninglabs/go-wasmsqlite"
"github.com/lightninglabs/wavelength/internal/sqlbase"
"github.com/lightninglabs/wavelength/internal/wasmhost"
"github.com/lightningnetwork/lnd/lnwallet/btcwallet"
)

Expand All @@ -24,6 +25,11 @@ const (
wasmWalletDBBusyTimeoutMS = "30000"
wasmWalletDBMaxConnections = 1
wasmWalletDBFileNamePattern = "/wallet-%016x.db"

// nodeWalletDBFileName is the wallet store's name on a real filesystem,
// where the containing directory already distinguishes one wallet from
// another and the hashed browser name would only hide it.
nodeWalletDBFileName = "wallet.db"
)

// newWalletLoaderOptions opens btcwallet through an OPFS-backed SQLite
Expand Down Expand Up @@ -105,14 +111,41 @@ func openWASMWalletDB(dbDir string) (walletdb.DB, error) {
return nil, fmt.Errorf("open OPFS wallet database: %w", lastErr)
}

// wasmWalletDBDSN returns a go-wasmsqlite DSN for btcwallet's SQL walletdb.
// wasmWalletDBDSN returns a go-wasmsqlite DSN for btcwallet's SQL walletdb,
// pointed at whichever durable storage the js/wasm host provides.
func wasmWalletDBDSN(dbDir string) string {
values := url.Values{}
values.Set("file", wasmWalletDBFileName(dbDir))
values.Set("vfs", "opfs")
values.Set("vfs", wasmhost.SQLiteVFS())
if wasmhost.UnderNode() {
// The wallet database lives beside the daemon's own databases
// on a real filesystem, under the name the caller asked for.
values.Set(
"file", filepath.Join(dbDir, nodeWalletDBFileName),
)
} else {
values.Set("file", wasmWalletDBFileName(dbDir))
}
values.Set("mode", "rwc")
values.Set("busy_timeout", wasmWalletDBBusyTimeoutMS)

// WAL survives here only because of the locking_mode=EXCLUSIVE pragma
// below. No wasm VFS implements xShmMap, so this is the WAL mode SQLite
// documents for hosts without shared memory, which keeps the WAL index
// on the heap and requires the connection to already be exclusive. The
// driver hoists the locking mode ahead of the journal mode for that
// reason, and then reads the effective mode back, so dropping the
// exclusive lock would fail the open rather than silently move the
// wallet onto the rollback journal.
//
// The journal mode travels as its own DSN key rather than in the pragma
// list, because only that route is checked against the mode SQLite

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ nit — "only that route is checked" is not true of the driver you just pinned. extractJournalMode (bridge/sqlite-worker.js:534-565) deliberately pulls a journal_mode= entry out of the pragma list and routes it through the same checked applyJournalMode path, precisely so that a caller who writes it where every other pragma goes does not get the silent downgrade. Its own comment says as much: "Routing it to the checked path is kinder than rejecting it and gives the same answer."

Nothing breaks — passing it as the DSN key is still the right thing to do, and the equivalent comment in db/sqlite_open_wasm.go:48-51 states the rationale without the "only" and reads fine. This is just the one sentence in the new comments that a reader could check against the driver and find wrong. Suggest dropping "only", or noting instead that both routes converge on the checked path and the key is the clearer of the two.

(There is a real sharp edge nearby, though it is the dependency's rather than yours: supplying the journal mode as both the key and a pragma with different values is now a hard "conflicting journal modes" error. Neither builder here does that, so it cannot fire.)

// actually ended up in.
values.Set("journal_mode", "WAL")

// The wallet's seed and key state have no second copy anywhere, so an
// in-memory substitute for the store would be worse than not starting.
values.Set("require_persistent", "true")

values.Set(
"pragma",
strings.Join(
Expand All @@ -128,7 +161,8 @@ func wasmWalletDBDSN(dbDir string) string {
}

// wasmWalletDBFileName maps a native wallet DB directory to a stable
// origin-local OPFS database name.
// origin-local OPFS database name. It is a browser concern only; a Node host
// keeps the real directory.
func wasmWalletDBFileName(dbDir string) string {
normalized := filepath.ToSlash(filepath.Clean(dbDir))
normalized = strings.TrimSpace(normalized)
Expand Down
1 change: 1 addition & 0 deletions scripts/publish-wasm-assets.sh
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ FILES=(
wasm_exec.js
sqlite-bridge.js
sqlite-worker.js
sqlite-node-vfs.js
sqlite3.js
sqlite3.wasm
sqlite3-opfs-async-proxy.js
Expand Down
Loading
Loading