# Run a wallet backend

> For the complete documentation index, see [llms.txt](https://bsvblockchain.com/docs/llms.txt).

Run the two backend services a BRC-100 wallet can use: Wallet Infra for remote wallet storage and the Wallet Authentication Backend (WAB) for phone sign-in and recovery.

import BlueTable from '/snippets/BlueTable.jsx';
import WalletBackendFlow from '/snippets/WalletBackendFlow.jsx';

Run Wallet Infra and the WAB (Wallet Authentication Backend) on your machine, on testnet, and connect a wallet to each of them. Wallet Infra keeps a wallet's records on a server instead of on the device, and the WAB lets a user sign in with a phone number and get the same wallet back on a new device. Run them standalone when your BRC-100 (BSV Request for Comments 100, the standard interface between apps and wallets) wallet offers remote storage or phone sign-in, so you can test them before you deploy them. At the end, a test wallet keeps its records on your storage server, and a test sign-in through your WAB returns a presentation key (A 256-bit key the WAB gives back after the phone check. It is one of three factors, with the password and a recovery key, and any two of them unlock the wallet).

## Before you begin

You need Node.js 24 (not 25) and npm 11, which both services require, and a MySQL 8 server that you can reach from your machine. This page was written against Wallet Infra 2.0.55, the WAB server 1.8.16, `@bsv/wallet-toolbox` 2.15.1, `@bsv/sdk` 4.0.1 and MySQL 8.4.

## How it works

Both services live in the `infra/` folder of the [ts-stack repository](https://github.com/bsv-blockchain/ts-stack), and your wallet reaches each one through a client class of `@bsv/wallet-toolbox`:

<BlueTable>

| Service | What it does | Database | Client class | Run it when |
| --- | --- | --- | --- | --- |
| Wallet Infra | Serves the toolbox storage over JSON-RPC (A protocol that sends requests and replies as JSON): outputs, spent state, baskets, labels and certificates | MySQL | `StorageClient` | Your wallet keeps its records on a server, for one user or many |
| WAB | Verifies a phone number with a one-time code and returns the user's presentation key. It also stores optional recovery shares and pays a one-time faucet to new users | SQLite for development, MySQL for production | `WABClient` | Your wallet offers phone sign-in and recovery |

</BlueTable>

A wallet that uses both goes through three steps:

<WalletBackendFlow />

A wallet that uses both services goes through three steps. 1. Sign in, with WABClient: the wallet sends the phone number, then the code the user received, with a presentation key it generated. The WAB verifies the code. A new user keeps the key the wallet sent, and a returning user gets back the key stored on the first sign-in. 2. Unlock, with WalletAuthenticationManager: the wallet combines the presentation key with the password to decrypt the root key from the user's UMP token. There is no backend call, and the WAB never receives the password or the root key. 3. Store, with StorageClient: the wallet signs every storage call with its identity key and posts it as JSON-RPC. Wallet Infra checks the signature and reads or writes only the records of that identity key in MySQL.

The UMP (User Management Protocol) token that holds the encrypted root key is published on chain, not kept on the WAB.

Wallet Relay, which lets a phone wallet connect to a web app, is not part of this backend: the web app's own server runs it with `@bsv/wallet-relay`.

## Get the source

The first step is to download the two service folders from ts-stack. Run this where you keep your projects:

```bash
git clone --depth 1 --filter=blob:none --sparse https://github.com/bsv-blockchain/ts-stack.git
cd ts-stack
git sparse-checkout set infra/wab infra/wallet-infra
```

The sparse checkout downloads only these two folders and the files at the root of `infra/`. Both folders already ignore `.env`, where the next sections put the keys.

## Run the storage server

With the source in place, set up the database and start Wallet Infra:

**1. Create the database**

Connect to your MySQL server with a user that can create databases, and create an empty one:

```bash
mysql -h 127.0.0.1 -u DB_USER -p -e "CREATE DATABASE wallet_storage;"
```

Replace `DB_USER` with your MySQL user. The command prints nothing when it succeeds. Wallet Infra creates its tables in this database the first time it starts.

**2. Configure the server**

> `SERVER_PRIVATE_KEY` is the private key of the storage server's identity. Keep it in `.env` only, never commit it, and use a new key for each environment.

Generate the server key in the `infra/wallet-infra` folder:

```bash
openssl rand -hex 32
```

Then create `.env` in the same folder:

```bash infra/wallet-infra/.env
NODE_ENV=development
BSV_NETWORK=test
ENABLE_NGINX=false
HTTP_PORT=8081
SERVER_PRIVATE_KEY=STORAGE_SERVER_PRIVATE_KEY
KNEX_DB_CONNECTION={"host":"127.0.0.1","port":3306,"user":"DB_USER","password":"DB_PASSWORD","database":"wallet_storage"}
```

Replace `STORAGE_SERVER_PRIVATE_KEY` with the key you generated, and `DB_USER` and `DB_PASSWORD` with your MySQL credentials. The values that matter:

- `BSV_NETWORK=test` points the server at testnet. The default is `main`.
- `ENABLE_NGINX=false` serves the app directly on `HTTP_PORT`. The default starts an nginx proxy on port 8080, which the Docker image includes and a local setup does not.
- `KNEX_DB_CONNECTION` is the Knex connection to MySQL, as JSON.

**3. Install and build**

Install the dependencies and compile the TypeScript in the same folder:

```bash
npm ci --ignore-scripts
npm run build
```

```text
added 303 packages, and audited 304 packages in 22s
> @bsv/wallet-infra@2.0.55 build
> tsc --build
```

`--ignore-scripts` skips the native build of a SQLite driver that `@bsv/wallet-toolbox` bundles. Wallet Infra uses MySQL, so it does not need that driver.

**4. Start the server**

Start Wallet Infra and keep this terminal open:

```bash
npm start
```

The log ends with:

```text
WalletStorageServer listening at http://0.0.0.0:8081
{"level":"info",...,"operation":"storage_server.start","outcome":"ok","msg":"StorageServer started"}
{"level":"info",...,"operation":"monitor.start","outcome":"ok","msg":"Monitor started"}
{"level":"info",...,"operation":"bootstrap","outcome":"ok","duration_ms":4787,"msg":"wallet-infra started"}
```

On startup, the server runs the database migrations and starts the Monitor (The toolbox component that broadcasts queued transactions, gathers proofs and repairs wallet state in the background) in the same process.

**5. Check the server**

Ask for its health and its description from a second terminal:

```bash
curl http://localhost:8081/healthz
curl http://localhost:8081/
```

```text
{"status":"ok"}
BRC-100 testNet Storage Provider.
```

These two routes are public. Every storage call goes to `POST /` and needs mutual authentication, so a plain `curl` there gets a `401`.

## Connect a wallet to the storage server

Now that the server answers, point a test wallet at it. The script below builds a wallet with `@bsv/wallet-toolbox` whose only storage is your server:

**1. Create the client project**

> `ROOT_KEY_HEX` is the root private key of the test wallet. Keep it in `.env`, never commit it, and use this wallet only on testnet.

Create a folder named `wallet-backend-client` outside `ts-stack`, install the packages there, and write a new root key to `.env`:

```bash
mkdir wallet-backend-client
cd wallet-backend-client
npm init -y
npm pkg set type=module
npm install --ignore-scripts @bsv/wallet-toolbox @bsv/sdk dotenv
echo "ROOT_KEY_HEX=$(openssl rand -hex 32)" > .env
echo ".env" >> .gitignore
```

The install ends with:

```text
added 118 packages, and audited 119 packages in 14s
```

The client keeps no records of its own, so it skips the SQLite driver build too. The last two commands write the key and keep `.env` out of git.

**2. Write the script**

Save this as `connect-storage.mjs` in `wallet-backend-client`:

```javascript connect-storage.mjs
import 'dotenv/config'
import { PrivateKey, KeyDeriver } from '@bsv/sdk'
import { Wallet, WalletStorageManager, Services, StorageClient } from '@bsv/wallet-toolbox'

const chain = 'test'
const storageUrl = 'http://localhost:8081'

const keyDeriver = new KeyDeriver(PrivateKey.fromHex(process.env.ROOT_KEY_HEX))
const storage = new WalletStorageManager(keyDeriver.identityKey)
const wallet = new Wallet({ chain, keyDeriver, storage, services: new Services(chain) })

const client = new StorageClient(wallet, storageUrl)
await storage.addWalletStorageProvider(client)
const settings = await storage.makeAvailable()

console.log('Storage server identity:', settings.storageIdentityKey)
console.log('Storage chain:', settings.chain)
console.log('Wallet identity key:', keyDeriver.identityKey)
const { totalOutputs } = await wallet.listOutputs({ basket: 'default' })
console.log('Outputs in the default basket:', totalOutputs)
```

The lines that connect the wallet to your server:

- `new StorageClient(wallet, storageUrl)` creates a storage provider that sends each call to your server. It takes the wallet itself, because it signs the requests with the wallet's identity key.
- `addWalletStorageProvider` makes the server the wallet's active storage, and `makeAvailable` opens it and returns the server's settings.
- `listOutputs` is an ordinary BRC-100 call. The wallet answers it from the records on your server.

**3. Run the script**

Run it from `wallet-backend-client` with the storage server still running:

```bash
node connect-storage.mjs
```

```text
Storage server identity: 03305a…6283
Storage chain: test
Wallet identity key: 03b0a7…d5de
Outputs in the default basket: 0
```

The keys above are shortened, and yours differ. The storage server identity is the public key of the server's `SERVER_PRIVATE_KEY`. The first call from a new identity key creates a user on the server with an empty `default` basket, so the wallet starts with no outputs.

## Run the WAB

The WAB comes next. For a local test, it uses SQLite and a development sign-in method that writes the one-time code to its log instead of sending an SMS:

**1. Configure the WAB**

> `SERVER_PRIVATE_KEY` is the private key of the WAB's faucet wallet, and `SHARE_ENCRYPTION_KEY` encrypts the recovery shares. Keep both in `.env` only and never commit them. Losing `SHARE_ENCRYPTION_KEY` makes every stored share unreadable.

Generate two keys in the `infra/wab` folder, running the command once for each:

```bash
openssl rand -hex 32
```

Then create `.env` in the same folder:

```bash infra/wab/.env
NODE_ENV=development
PORT=8080
BSV_NETWORK=test
SERVER_PRIVATE_KEY=WAB_SERVER_PRIVATE_KEY
STORAGE_URL=http://localhost:8081
SHARE_ENCRYPTION_KEY=SHARE_ENCRYPTION_KEY_HEX
DEV_CONSOLE_AUTH_METHOD_ENABLED=true
```

Replace `WAB_SERVER_PRIVATE_KEY` and `SHARE_ENCRYPTION_KEY_HEX` with the two keys. The values that matter:

- `NODE_ENV=development` selects SQLite, in a `dev.sqlite3` file in the folder.
- `STORAGE_URL` is your Wallet Infra server, where the WAB's faucet wallet keeps its records, so the WAB needs it to start. The WAB accepts plain HTTP only for a loopback address, and HTTPS everywhere else.
- `DEV_CONSOLE_AUTH_METHOD_ENABLED=true` turns on the `DevConsole` sign-in method. The WAB accepts it only when `NODE_ENV` is `development` or `test`.

The WAB stores its users and their presentation keys in `dev.sqlite3`, and the folder does not ignore that file yet. Add it to `.gitignore`:

```bash
echo "dev.sqlite3" >> .gitignore
```

**2. Install and build**

Install the dependencies, build the SQLite driver the WAB uses, and compile:

```bash
npm ci --ignore-scripts
npm rebuild sqlite3
npm run build
```

```text
npm warn rebuild 6 packages have install scripts not yet covered by allowScripts. Run `npm approve-scripts --allow-scripts-pending` to review.
rebuilt dependencies successfully
> @bsv/wab-server@1.8.16 build
> tsc
```

`npm rebuild sqlite3` downloads a prebuilt binary of the `sqlite3` driver. The warning lists the install scripts that `--ignore-scripts` skipped, and the WAB does not need them.

**3. Start the WAB**

Start the server with the variables from `.env`, and keep this terminal open:

```bash
node --env-file=.env --require ./dist/telemetry.js dist/server.js
```

```text
{"level":"info",...,"operation":"db.migrate","msg":"Checking for pending database migrations"}
{"level":"info",...,"operation":"db.migrate","migration_count":10,"batch":1,...,"msg":"Ran database migrations"}
{"level":"info",...,"operation":"migrate","outcome":"ok","msg":"migrations applied"}
{"level":"info",...,"operation":"presentation-key-vault","outcome":"ok","mode":"legacy",...,"msg":"presentation-key vault reconciled"}
{"level":"info",...,"operation":"listen","outcome":"ok","port":"8080","duration_ms":79,"msg":"WAB server running"}
```

The WAB does not read `.env` by itself, so `--env-file` passes it to Node.js. It checks its keys and the storage URL, runs its migrations, then listens.

**4. Check the WAB**

Ask for its health and the sign-in methods it offers from another terminal:

```bash
curl http://localhost:8080/healthz
curl http://localhost:8080/info
```

```text
{"ok":true,"status":"ok","service":"wab-server","network":"test","profile":"standard"}
{"supportedAuthMethods":["DevConsole"],"faucetEnabled":true,"faucetAmount":1000}
```

`supportedAuthMethods` lists the methods a wallet can offer its users. `faucetAmount` is the one-time payment to a new user in satoshis, 1,000 by default. One BitcoinSV (BSV) is 100,000,000 satoshis.

## Sign in through the WAB

The WAB is ready for a sign-in. The script below plays the part of the wallet with `WABClient` and the `DevConsole` method:

**1. Write the sign-in script**

> The presentation key is one of the factors that unlock a wallet. The script creates a new one, and the WAB keeps it in plain text in `dev.sqlite3`. Use it only on testnet, and keep that file out of git.

Save this as `wab-login.mjs` in `wallet-backend-client`:

```javascript wab-login.mjs
import { createInterface } from 'node:readline/promises'
import { WABClient, DevConsoleInteractor } from '@bsv/wallet-toolbox'

const wab = new WABClient('http://localhost:8080')
const method = new DevConsoleInteractor()
const phoneNumber = '+15555550100'

console.log('WAB info:', await wab.getInfo())

const presentationKey = wab.generateRandomPresentationKey()
const started = await wab.startAuthMethod(method, presentationKey, { phoneNumber })
console.log('Start:', started.message)

const rl = createInterface({ input: process.stdin, output: process.stdout })
const otp = await rl.question('Code from the WAB log: ')
rl.close()

const result = await wab.completeAuthMethod(method, presentationKey, { phoneNumber, otp })
console.log('Complete:', {
  success: result.success,
  accountStatus: result.accountStatus,
  registrationStatus: result.registrationStatus,
  presentationKeyReturned: result.presentationKey === presentationKey
})
```

How the script uses the WAB:

- `generateRandomPresentationKey` creates the key the wallet proposes. The WAB keeps it only if the phone number is new.
- `startAuthMethod` asks the WAB to send a code. With `DevConsole`, the code goes to the WAB log, and the phone number is only an identifier. A production wallet uses `TwilioPhoneInteractor`, and the user gets an SMS.
- `completeAuthMethod` sends the code back and gets the presentation key that belongs to this phone number. The script compares it with the proposed key instead of printing it, because the presentation key is a secret.

**2. Run the script**

Run it from `wallet-backend-client`, and leave it waiting at the prompt:

```bash
node wab-login.mjs
```

```text
WAB info: {
  supportedAuthMethods: [ 'DevConsole' ],
  faucetEnabled: true,
  faucetAmount: 1000
}
Start: Development OTP sent for +15555550100. Check console logs.
Code from the WAB log:
```

**3. Enter the code**

Find the code in the terminal that runs the WAB, in the `otp` field of this line:

```text
{"level":"info",...,"operation":"auth.dev_console.start","identifier":"[redacted]","expires_at":1793223814677,"otp":"642234","msg":"Development OTP code generated"}
```

Type it at the prompt and press Enter. The script prints the result:

```text
Complete: {
  success: true,
  accountStatus: 'new-user',
  registrationStatus: 'pending',
  presentationKeyReturned: true
}
```

A new phone number creates a user with the proposed key. The registration stays `pending` until a wallet publishes the user's UMP token and confirms it with `finalizeRegistration`, which `WalletAuthenticationManager` does in a full wallet.

Run the script a second time with the same phone number. The result shows `accountStatus: 'existing-user'` and `presentationKeyReturned: false`, because the WAB returns the key it stored on the first sign-in, not the new one the script proposed. That stored key is what lets the user unlock the same wallet on another device.

## Move the services to production

Each folder has a `Dockerfile`, a `docker-compose.yml` and an `.env.example` with the main variables. Before you deploy, change what the local setup relaxed:

- To move to Mainnet, follow [Go to Mainnet](https://bsvblockchain.com/docs/guides/go-to-mainnet/) and use new keys for both services.
- Run the WAB with `NODE_ENV=production` and MySQL, through the `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER` and `DB_PASS` variables. `DB_CLIENT` is optional, since `mysql2` is the default.
- Set `TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN` and `TWILIO_VERIFY_SERVICE_SID` to send SMS codes. With all three empty, the WAB offers no phone method, and `DevConsole` never runs in production.
- Serve both services over HTTPS, and point `STORAGE_URL` at the HTTPS address of Wallet Infra.
- The WAB's faucet wallet pays each new user from its own balance, and on Mainnet every payment is real and cannot be undone. In the WAB, `COMMISSION_FEE` sets the faucet amount in satoshis, and leaving it unset or at `0` keeps 1,000.
- In Wallet Infra, `COMMISSION_FEE` is a different setting: a commission in satoshis that the storage server adds to each transaction its wallets create. Above `0`, it needs `COMMISSION_PUBLIC_KEY`, the key that receives the commission.
- By default, in legacy mode, the WAB stores presentation keys in plain text in its database. To encrypt them at rest, set `WAB_PRESENTATION_KEY_ENCRYPTION_MODE` and `WAB_PRESENTATION_KEY_ENCRYPTION_KEY`, and follow the staged rollout in the WAB README.
- Back up the MySQL databases, and keep `SHARE_ENCRYPTION_KEY` and the presentation key encryption key backed up apart from them.

The [WAB](https://github.com/bsv-blockchain/ts-stack/tree/main/infra/wab) and [Wallet Infra](https://github.com/bsv-blockchain/ts-stack/tree/main/infra/wallet-infra) READMEs cover the rest: rate limits, CORS, the admin routes and the monitor operator listener. Kubernetes samples are in [`infra/wab/deploy/`](https://github.com/bsv-blockchain/ts-stack/tree/main/infra/wab/deploy) and [`infra/wallet-infra/guides/kube_samples/`](https://github.com/bsv-blockchain/ts-stack/tree/main/infra/wallet-infra/guides/kube_samples).

## Troubleshooting

**Install stops on a native build**

A plain `npm ci` fails on a machine without Python and a C++ compiler, with `gyp ERR! find Python` from `better-sqlite3`. The toolbox bundles that SQLite driver, and neither service uses it. Install with `npm ci --ignore-scripts`, then run `npm rebuild sqlite3` in the WAB folder only.

## Related articles

To learn more about building a BRC-100 wallet, review these articles:

- [How the toolbox tracks UTXOs](https://bsvblockchain.com/docs/wallet-dev/wallet-toolbox/utxo-lifecycle/)
- [BRC-100 Wallet Interface](https://bsvblockchain.com/docs/concepts/wallet-model/)
- [Build a wallet](https://bsvblockchain.com/docs/wallet-dev/)