diff --git a/.github/workflows/mobile-bindings.yml b/.github/workflows/mobile-bindings.yml index 48058e053..e855f54ad 100644 --- a/.github/workflows/mobile-bindings.yml +++ b/.github/workflows/mobile-bindings.yml @@ -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 diff --git a/Makefile b/Makefile index f05a23c31..d2db2607c 100644 --- a/Makefile +++ b/Makefile @@ -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" \ @@ -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)/ # 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. diff --git a/cmd/wavewalletdk-wasm/AGENTS.md b/cmd/wavewalletdk-wasm/AGENTS.md index fd190bf75..7dbc5893b 100644 --- a/cmd/wavewalletdk-wasm/AGENTS.md +++ b/cmd/wavewalletdk-wasm/AGENTS.md @@ -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. diff --git a/cmd/wavewalletdk-wasm/CLAUDE.md b/cmd/wavewalletdk-wasm/CLAUDE.md index fd190bf75..7dbc5893b 100644 --- a/cmd/wavewalletdk-wasm/CLAUDE.md +++ b/cmd/wavewalletdk-wasm/CLAUDE.md @@ -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. diff --git a/cmd/wavewalletdk-wasm/main.go b/cmd/wavewalletdk-wasm/main.go index fa7805e5d..d663921db 100644 --- a/cmd/wavewalletdk-wasm/main.go +++ b/cmd/wavewalletdk-wasm/main.go @@ -18,6 +18,7 @@ import ( "io" "syscall/js" + "github.com/lightninglabs/wavelength/internal/wasmhost" "github.com/lightninglabs/wavelength/sdk/wavewalletdk/mobile" ) @@ -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) @@ -269,19 +273,38 @@ 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() } @@ -289,10 +312,14 @@ func startConfig(req js.Value) string { 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. diff --git a/db/sqlite_open_wasm.go b/db/sqlite_open_wasm.go index 38e97de3b..ff98c3d60 100644 --- a/db/sqlite_open_wasm.go +++ b/db/sqlite_open_wasm.go @@ -12,21 +12,32 @@ 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()) + 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) { @@ -34,11 +45,17 @@ func openSQLiteDatabase(cfg SQLiteOpenConfig) (*SQLiteOpenResult, error) { 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( @@ -47,6 +64,16 @@ func openSQLiteDatabase(cfg SQLiteOpenConfig) (*SQLiteOpenResult, error) { } } + // Exclusive locking is not merely an optimization for a + // 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, ";")) @@ -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) @@ -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) diff --git a/go.mod b/go.mod index 43221fcc1..38f0e3d6a 100644 --- a/go.mod +++ b/go.mod @@ -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 ( diff --git a/go.sum b/go.sum index c967a803a..7115439e2 100644 --- a/go.sum +++ b/go.sum @@ -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= diff --git a/internal/wasmhost/host.go b/internal/wasmhost/host.go new file mode 100644 index 000000000..9d10032e4 --- /dev/null +++ b/internal/wasmhost/host.go @@ -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" + } + + return "opfs" +} diff --git a/lwwallet/walletdb_wasm.go b/lwwallet/walletdb_wasm.go index 987ab09dc..3a8bd5ca2 100644 --- a/lwwallet/walletdb_wasm.go +++ b/lwwallet/walletdb_wasm.go @@ -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" ) @@ -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 @@ -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 + // 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( @@ -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) diff --git a/scripts/publish-wasm-assets.sh b/scripts/publish-wasm-assets.sh index 0a17e67f2..af805a392 100755 --- a/scripts/publish-wasm-assets.sh +++ b/scripts/publish-wasm-assets.sh @@ -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 diff --git a/swapclientserver/fs_wasm.go b/swapclientserver/fs_wasm.go index 93a38c601..e8507ae9d 100644 --- a/swapclientserver/fs_wasm.go +++ b/swapclientserver/fs_wasm.go @@ -2,8 +2,28 @@ package swapclientserver -// ensureSwapDBDir is a no-op in browser builds. The SQLite driver maps the -// configured database filename to OPFS, where host directories do not exist. -func ensureSwapDBDir(string) error { - return nil +import ( + "errors" + "os" + "path/filepath" + "syscall" +) + +// ensureSwapDBDir creates the directory holding the swap database when the +// js/wasm host has a filesystem, and does nothing when it does not. +// +// See waved.ensureDataDir for why ENOSYS is the browser's way of saying it has +// no host filesystem, while any other error is a real failure a Node host +// should hear about before it tries to open the database. +func ensureSwapDBDir(dbPath string) error { + if dbPath == "" { + return nil + } + + err := os.MkdirAll(filepath.Dir(dbPath), 0o700) + if err == nil || errors.Is(err, syscall.ENOSYS) { + return nil + } + + return err } diff --git a/waved/fs_wasm.go b/waved/fs_wasm.go index 8e55cfe6e..11121a3ea 100644 --- a/waved/fs_wasm.go +++ b/waved/fs_wasm.go @@ -2,9 +2,36 @@ package waved -// ensureDataDir is a no-op in browser builds. Persistent state uses -// OPFS-backed SQLite and browser storage instead of host filesystem -// directories, and os.MkdirAll is not implemented under js/wasm. -func ensureDataDir(string) error { - return nil +import ( + "errors" + "os" + "syscall" +) + +// ensureDataDir creates the daemon's data directory when the js/wasm host has +// a filesystem, and does nothing when it does not. +// +// The two hosts genuinely differ here. Go's wasm_exec.js installs a stub fs +// whose calls all fail with ENOSYS unless the host wires a real one in, so in +// a browser there is no directory to create and persistent state lives in OPFS +// instead. A Node host assigns globalThis.fs from node:fs before instantiating +// the module, and os.MkdirAll then reaches the host filesystem exactly as it +// would natively, which is where the node:fs SQLite VFS expects to find this +// directory. +// +// Rather than sniff the host, this asks for the directory and reads ENOSYS as +// the browser answering that it has no filesystem. Every other failure is +// real and is returned, so a Node host given an unwritable path fails at +// startup rather than at the first database open. +func ensureDataDir(dir string) error { + if dir == "" { + return nil + } + + err := os.MkdirAll(dir, 0o700) + if err == nil || errors.Is(err, syscall.ENOSYS) { + return nil + } + + return err }