> ## Documentation Index
> Fetch the complete documentation index at: https://docs.canton.network/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> If you are building a Canton Network application, start from https://docs.canton.network/appdev/quickstart.md. To run only a local network for your own Daml code, without building the QuickStart demo, see https://docs.canton.network/sdks-tools/development-tools/localnet.md.

# LocalNet

> Run a multi-validator Canton Network locally with Docker Compose for development and integration testing.

LocalNet provides a straightforward topology comprising three participants, three validators, a PostgreSQL database, and several web applications (wallet, sv, scan) behind an NGINX gateway. Each validator plays a distinct role within the Splice ecosystem:

* **app-provider**: for the user operating their application
* **app-user**: for a user wanting to use the app from the App Provider
* **sv**: for providing the Global Synchronizer and handling AMT

Designed primarily for development and testing, LocalNet is not intended for production use.

LocalNet is provided as part of the [cn-quickstart](https://github.com/digital-asset/cn-quickstart) repository.

## What LocalNet Provides

* Three validators: Super Validator (SV), App Provider, and App User
* A local synchronizer with sequencer and mediator
* Canton Coin wallet services for each validator
* PQS (Participant Query Store) instances
* JSON API endpoints
* Keycloak for authentication (optional)
* Observability stack: Grafana, Prometheus, Loki (optional)

## Setup

From the cn-quickstart repository:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
git clone https://github.com/digital-asset/cn-quickstart
cd cn-quickstart
direnv allow
cd quickstart
make setup
make build
make start
```

`make setup` prompts you to select a deployment profile and generates the appropriate `.env.local` configuration. `make build` compiles the Daml contracts, Java backend, and React frontend. `make start` launches the Docker Compose stack.

Check the status of running containers:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
make status
```

Stop the environment:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
make stop
```

### Start LocalNet without the QuickStart application

If you only need the network, for example to deploy and test your own DAR, you can start LocalNet without `make setup` and `make build`. This needs Docker with the Compose plugin, but not Nix, direnv, a JDK or Node.js.

From the `quickstart/` directory of the cn-quickstart repository, point `LOCALNET_DIR` at the LocalNet module and set `IMAGE_TAG` to the Splice version that cn-quickstart pins in `.env`:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
export LOCALNET_DIR=$PWD/docker/modules/localnet
export IMAGE_TAG=$(grep '^SPLICE_VERSION=' .env | cut -d= -f2)

docker compose --env-file $LOCALNET_DIR/compose.env \
               --env-file $LOCALNET_DIR/env/common.env \
               -f $LOCALNET_DIR/compose.yaml \
               -f $LOCALNET_DIR/resource-constraints.yaml \
               --profile sv \
               --profile app-provider \
               --profile app-user up -d
```

Stop it and remove its data with the same command, replacing `up -d` with `down -v`. To check when the validators are ready, see [Health Checks](#health-checks).

If a host port is already taken, `docker compose up` exits with `address already in use`. LocalNet's PostgreSQL binds port 5432, which clashes with a local PostgreSQL server. Set `DB_PORT` to a free port before you run the command, for example `export DB_PORT=5440`. The web UIs need ports 2000, 3000 and 4000 for the `nginx` container. If one of those is taken, `nginx` doesn't start and the UIs are unavailable, but the validators and their Ledger APIs still run.

## Network Topology

```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}}
flowchart TB
    subgraph LocalNet
        SV[Super Validator<br>Port prefix: 4xxx]
        PROV[App Provider<br>Port prefix: 3xxx]
        USER[App User<br>Port prefix: 2xxx]
        SEQ[Sequencer]
        MED[Mediator]
    end

    SV --> SEQ
    PROV --> SEQ
    USER --> SEQ
    SEQ --> MED
```

Each validator runs a participant, wallet services, and supporting infrastructure. The Super Validator also runs the synchronizer components (sequencer and mediator) and the Splice SV app.

## Port Conventions

## Exposed Ports

The following section details the ports used by various services. The default database port is **DB\_PORT=5432**.

Other ports are generated using specific patterns based on the validator:

* For the Super Validator (sv), the port is specified as `4${PORT_SUFFIX}`.
* For the App Provider, the port is specified as `3${PORT_SUFFIX}`.
* For the App User, the port is specified as `2${PORT_SUFFIX}`.

These patterns apply to the following ports suffixes:

* **PARTICIPANT\_LEDGER\_API\_PORT\_SUFFIX**: 901
* **PARTICIPANT\_ADMIN\_API\_PORT\_SUFFIX**: 902
* **PARTICIPANT\_JSON\_API\_PORT\_SUFFIX**: 975
* **VALIDATOR\_ADMIN\_API\_PORT\_SUFFIX**: 903
* **CANTON\_HTTP\_HEALTHCHECK\_PORT\_SUFFIX**: 900
* **CANTON\_GRPC\_HEALTHCHECK\_PORT\_SUFFIX**: 961

UI Ports are defined as follows:

* **APP\_USER\_UI\_PORT**: 2000
* **APP\_PROVIDER\_UI\_PORT**: 3000
* **SV\_UI\_PORT**: 4000

## Application UIs

* **App User Wallet UI**

  > * **URL**: `http://wallet.localhost:2000`
  > * **Description**: Interface for managing user wallets.

* **App Provider Wallet UI**

  > * **URL**: `http://wallet.localhost:3000`
  > * **Description**: Interface for managing user wallets.

* **Super Validator Web UI**

  > * **URL**: `http://sv.localhost:4000`
  > * **Description**: Interface for super validator functionalities.

* **Scan Web UI**

  > * **URL**: `http://scan.localhost:4000`
  > * **Description**: Interface to monitor transactions.

> [!NOTE]
>
> LocalNet rounds may take up to 6 rounds (equivalent to one hour) to display in the scan UI.

In most scenarios, the `*.localhost` domains (e.g., `http://scan.localhost`) will resolve to your local host IP `127.0.0.1`. There are some situations where the resolution does not occur and the solution is to add entries to your `/etc/hosts` file. For example, to resolve `http://scan.localhost` and `http://wallet.localhost` add these entry to the file:

```
127.0.0.1   scan.localhost
127.0.0.1   wallet.localhost
```

## Default Wallet Users

* **App User**: app-user
* **App Provider**: app-provider
* **SV**: sv

For example, the App User's Ledger API is at `localhost:2901`, and the App Provider's JSON API is at `localhost:3975`.

> [!WARNING]
>
> The Admin API and PostgreSQL ports are exposed for development convenience. Do not expose these ports in non-local deployments.

## Authenticating to the Ledger API

Each validator's JSON Ledger API is at `http://localhost:<prefix>975`: `2975` for the App User, `3975` for the App Provider and `4975` for the Super Validator. The gRPC Ledger API is on `<prefix>901`.

The LocalNet started by the command above, and cn-quickstart with OAuth2 turned off in `make setup`, accept JWTs signed with a shared secret. Every Ledger API request needs a token with these values:

* **Algorithm**: HS256 (`unsafe-jwt-hmac-256`)
* **Secret**: `unsafe`
* **Audience (`aud`)**: `https://canton.network.global`
* **Subject (`sub`)**: `ledger-api-user`, which is an admin user on every validator

The env files in `docker/modules/localnet/env/` write the audience as `${AUTH_APP_PROVIDER_AUDIENCE:-https://canton.network.global}`. Use the resolved value; a token that carries the expression itself is rejected with HTTP 401. LocalNet sets no maximum token lifetime.

This creates a token valid for one hour, using only the Python standard library:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
TOKEN=$(python3 - <<'EOF'
import base64, hashlib, hmac, json, time
b64 = lambda b: base64.urlsafe_b64encode(b).rstrip(b"=").decode()
header = b64(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
claims = b64(json.dumps({"sub": "ledger-api-user", "aud": "https://canton.network.global", "exp": int(time.time()) + 3600}).encode())
signature = b64(hmac.new(b"unsafe", f"{header}.{claims}".encode(), hashlib.sha256).digest())
print(f"{header}.{claims}.{signature}")
EOF
)

curl http://localhost:3975/v2/parties -H "Authorization: Bearer $TOKEN"
```

`ledger-api-user` is an admin, so it can upload DARs, allocate parties and manage users. Admin rights don't let it submit commands as a party or read a party's contracts. Give it `CanActAs` or `CanReadAs` for each party first, for example by setting `"userId": "ledger-api-user"` when you allocate the party. See [Use the JSON Ledger API with authentication](https://docs.canton.network/appdev/modules/m4-json-api-tutorial.md#use-the-json-ledger-api-with-authentication).

With OAuth2 turned on, the App Provider and App User participants validate tokens issued by the bundled Keycloak instead, and the shared secret doesn't work on them. See [Keycloak in the QuickStart](https://docs.canton.network/appdev/quickstart/keycloak.md).

## Test Token Standard flows

LocalNet doesn't run registries for third-party tokens, such as the Digital Asset Registry. To test Token Standard workflows locally, use Canton Coin (Amulet) as the token. It implements both [CIP-0056](https://github.com/canton-foundation/cips/blob/main/cip-0056/cip-0056.md) (Token Standard V1) and [CIP-0112](https://github.com/canton-foundation/cips/blob/main/cip-0112/cip-0112.md) (V2), and LocalNet runs its registry and the Canton Coin faucet. Because every token goes through the same Token Standard interfaces, testing your workflows against Canton Coin in CI catches most integration problems before you test against a real registry. Test against other issuers' registries on DevNet or TestNet, through the test support those issuers provide.

The script below uses the [Wallet SDK](https://docs.canton.network/sdks-tools/sdks/wallet-sdk/overview.md) to run a two-step transfer on the App User validator. It creates two external parties, funds Alice from the faucet, lists her holdings, sends 100 CC to Bob and has Bob accept the pending transfer.

Before you run it, make sure that:

* LocalNet is running with the default ports. The SDK reaches the validator API on port 2000 and Scan on `scan.localhost:4000`, both through the `nginx` container.
* Node.js is installed.

Install the SDK and `tsx` in an empty directory:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
npm init -y
npm install @canton-network/wallet-sdk tsx
```

Save the script as `token-flows.mts`. The `.mts` extension makes Node treat it as an ES module, which the top-level `await` calls need.

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import {
    SDK,
    localNetStaticConfig,
    type TokenProviderConfig,
} from '@canton-network/wallet-sdk'

// LocalNet accepts self-signed tokens for the default ledger API user
const auth: TokenProviderConfig = {
    method: 'self_signed',
    issuer: 'unsafe-auth',
    credentials: {
        clientId: 'ledger-api-user',
        clientSecret: 'unsafe',
        audience: 'https://canton.network.global',
        scope: '',
    },
}

// On LocalNet, Canton Coin's registry is served through the validator's Scan Proxy
const registryUrl = localNetStaticConfig.LOCALNET_REGISTRY_API_URL

const sdk = await SDK.create({
    auth,
    ledgerClientUrl: localNetStaticConfig.LOCALNET_APP_USER_LEDGER_URL,
    // Pick the Global Synchronizer by its alias
    synchronizerId: (synchronizers) =>
        synchronizers.find((s) => s.synchronizerAlias === 'global')!
            .synchronizerId,
    token: { registries: [registryUrl], auth },
    amulet: {
        scanApiUrl: localNetStaticConfig.LOCALNET_SCAN_API_URL,
        registryUrl,
        auth,
    },
})

// 1. Create two external parties
const aliceKeys = sdk.keys.generate()
const alice = await sdk.party.external
    .create(aliceKeys.publicKey, { partyHint: 'alice' })
    .sign(aliceKeys.privateKey)
    .execute()

const bobKeys = sdk.keys.generate()
const bob = await sdk.party.external
    .create(bobKeys.publicKey, { partyHint: 'bob' })
    .sign(bobKeys.privateKey)
    .execute()

// 2. Fund Alice from the Canton Coin faucet (LocalNet and DevNet only)
const [tapCommand, tapDisclosedContracts] = await sdk.amulet.tap(
    alice.partyId,
    '2000'
)
await sdk.ledger
    .prepare({
        partyId: alice.partyId,
        commands: tapCommand,
        disclosedContracts: tapDisclosedContracts,
    })
    .sign(aliceKeys.privateKey)
    .execute({ partyId: alice.partyId })

// 3. List Alice's holdings
const aliceHoldings = await sdk.token.utxos.list({ partyId: alice.partyId })
console.log(
    'Alice holdings:',
    aliceHoldings.map((h) => h.interfaceViewValue.amount)
)

// 4. Alice sends 100 CC to Bob. Bob has no transfer preapproval,
//    so this creates a pending transfer instruction.
const [transferCommand, transferDisclosedContracts] =
    await sdk.token.transfer.create({
        sender: alice.partyId,
        recipient: bob.partyId,
        amount: '100',
        instrumentId: 'Amulet',
        registryUrl,
    })
await sdk.ledger
    .prepare({
        partyId: alice.partyId,
        commands: transferCommand,
        disclosedContracts: transferDisclosedContracts,
    })
    .sign(aliceKeys.privateKey)
    .execute({ partyId: alice.partyId })

// 5. Bob accepts the pending transfer
const pending = await sdk.token.transfer.pending(bob.partyId)
console.log('Bob pending transfers:', pending.length)

const [acceptCommand, acceptDisclosedContracts] =
    await sdk.token.transfer.accept({
        transferInstructionCid: pending[0].contractId,
        registryUrl,
    })
await sdk.ledger
    .prepare({
        partyId: bob.partyId,
        commands: acceptCommand,
        disclosedContracts: acceptDisclosedContracts,
    })
    .sign(bobKeys.privateKey)
    .execute({ partyId: bob.partyId })

// 6. Check both balances
for (const [name, party] of [
    ['Alice', alice.partyId],
    ['Bob', bob.partyId],
] as const) {
    const holdings = await sdk.token.utxos.list({ partyId: party })
    console.log(
        `${name} holdings:`,
        holdings.map((h) => h.interfaceViewValue.amount)
    )
}
process.exit(0)
```

Run it:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
npx tsx token-flows.mts
```

Besides the SDK's own log lines, the script prints the balances before and after the transfer:

```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
Alice holdings: [ '2000.0000000000' ]
Bob pending transfers: 1
Alice holdings: [ '1900.0000000000' ]
Bob holdings: [ '100.0000000000' ]
```

This was tested with Wallet SDK 1.7.0 on LocalNet with Splice 0.9.4. External parties sign each transaction with their own key, so the faucet tap, the transfer and the acceptance each go through `prepare`, `sign` and `execute`.

To test other transfer paths, see [Transfer types](https://docs.canton.network/sdks-tools/sdks/wallet-sdk/guides/transfer-types.md). It covers one-step transfers to a receiver with a transfer preapproval, and rejecting or withdrawing a pending transfer.

Allocations for delivery-versus-payment settle through an app that requests the allocations and then executes the trade, so testing them needs such an app. The `splice` container ships test trading apps for this in `/app/splice-node/dars`. Copy one out with `docker cp`, for example:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
docker cp splice:/app/splice-node/dars/splice-token-test-trading-app-1.0.2.dar .
```

For complete allocation flows that use these apps with the Wallet SDK, see the example scripts [04-token-standard-allocation.ts](https://github.com/hyperledger-labs/splice-wallet-kernel/blob/main/docs/wallet-integration-guide/examples/scripts/04-token-standard-allocation.ts) (V1) and [19-token-standard-allocation-v2.ts](https://github.com/hyperledger-labs/splice-wallet-kernel/blob/main/docs/wallet-integration-guide/examples/scripts/19-token-standard-allocation-v2.ts) (V2) in the Wallet SDK repository.

## Configuration Options

### Deployment Profiles

`make setup` offers deployment profiles that control which optional services are included:

* **Minimal** -- Core validators and synchronizer only
* **Standard** -- Adds PQS, JSON API, and authentication
* **Full** -- Adds observability (Grafana, Prometheus, Loki)

### Environment Variables

The `.env` file in the `quickstart/` directory contains version numbers, feature flags, and service configuration. Create a `.env.local` file (not tracked by git) to override settings locally.

### Docker Compose Modules

LocalNet is built from modular Docker Compose layers in `docker/modules/`:

* `localnet/` -- Base infrastructure (validators, synchronizer)
* `auth/` -- Keycloak authentication
* `observability/` -- Grafana, Prometheus, Loki
* `pqs/` -- Participant Query Store instances
* `app/` -- Application services (backend, frontend)

## Health Checks

Verify that validators are healthy:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -f http://localhost:2903/api/validator/readyz  # App User
curl -f http://localhost:3903/api/validator/readyz  # App Provider
curl -f http://localhost:4903/api/validator/readyz  # Super Validator
```

An empty response indicates a healthy service.

Each validator's JSON Ledger API also answers on `/livez` and `/readyz`. Both return HTTP 200 once the API accepts requests:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -f http://localhost:2975/readyz  # App User
curl -f http://localhost:3975/readyz  # App Provider
curl -f http://localhost:4975/readyz  # Super Validator
```

## Multiple Synchronizers

LocalNet supports running multiple synchronizers side by side.

By default, a single synchronizer controlled by the Super Validator (sv) is active. This synchronizer simulates the **Global Synchronizer**.

To enable a second synchronizer called `app-synchronizer`, start LocalNet with the `multi-sync` Docker Compose profile (`--profile multi-sync`). The additional synchronizer has the following characteristics:

* It is managed by the `app-sequencer` and `app-mediator` nodes.
* It simulates a **dedicated synchronizer**.
* Both the `app-provider` and `app-user` participants are cross-connected to the Global Synchronizer and the `app-synchronizer`.

## Using Non-Default Protocol Versions

The protocol version used in the LocalNet synchronizer and participants can be configured by setting the `CANTON_PROTOCOL_VERSION` environment variable to the required version prior to launching LocalNet. Non-stable protocol versions can be used for early testing, but require explicit opt-in. To enable that, export also an `ALPHA_PROTOCOL_VERSION_ENV=$LOCALNET_DIR/env/alpha-protocol-version.env` environment variable.

> [!WARNING]
>
> Non-stable protocol versions are unreleased versions that are under development, and are subject to announced breaking changes. One implication of this is that this environment usually cannot be upgraded, and will therefore require a full reset for every change. Use only for early testing and development purposes.

## When to Use LocalNet vs Sandbox

**Use LocalNet** when you need to test:

* Multi-party workflows across separate validators
* Canton Coin transfers and traffic purchases
* Wallet integration
* Splice API interactions (Scan, Validator APIs)
* End-to-end flows with backend, frontend, and ledger

**Use the [Sandbox](https://docs.canton.network/sdks-tools/development-tools/sandbox.md)** when you need:

* Fast iteration on contract logic
* Single-participant testing without Docker
* A lightweight environment for `dpm test` and Ledger API integration

## Related Pages

* [cn-quickstart](https://docs.canton.network/sdks-tools/reference-projects/cn-quickstart.md) -- Repository overview and project structure
* [Sandbox](https://docs.canton.network/sdks-tools/development-tools/sandbox.md) -- Lightweight single-node alternative
* [QuickStart walkthrough](https://docs.canton.network/appdev/quickstart/running-the-demo.md) -- Step-by-step guide to running the demo application
