rail402: <code>: <message>, naming the variable (see
Startup checks). Secrets are never echoed. An empty value is
treated as unset, and booleans are the literal strings true or false.
The Playground server has settings of its own, listed in
Run your own Playground.
Service
API keys are sent as
Authorization: Bearer <key> or X-API-Key: <key> (both, with different keys,
is refused). See Access keys for API_KEYS_FILE; API_KEY_SHA256 holds the SHA-256
digests of keys valid on every network (echo -n "$KEY" | sha256sum | cut -d' ' -f1) and is refused once
pubnet is enabled.
RATE_LIMIT_PER_MINUTE applies to every endpoint except /health, /ready, /metrics and the private
paths. A limited request gets HTTP 429 with a Retry-After header. Without TRUSTED_PROXY_HOPS, the
client address is the TCP peer; behind a proxy, set it to the number of proxies so each real client gets
its own limit. A /verify or /settle with a valid access key is limited per key instead
(on a host listed in PUBLIC_HOSTS, a key valid for that host’s network), so keyless traffic from the
same address or IPv6 /64 never uses up a key holder’s requests. A request for a network the key is not
valid for counts against its address’s limit as well, like any keyless request. That limit is what the key may send a
minute on all its networks together (requestsPerMinute, else KEY_DEFAULT_REQUESTS_PER_MINUTE, on
each), and never less than RATE_LIMIT_PER_MINUTE. When the shared limiter (Postgres) cannot answer, each
process limits on its own.
Metering. Every
/verify and /settle that reaches the facilitator is counted per caller
(key:<id> for access-key holders, where a key from API_KEY_SHA256 has the first 16 hex characters of
its digest as id, public otherwise), per day, network, operation, outcome and
asset, with the settled volume. A /settle answered from an earlier settlement of the same payment is
metered with the outcome repeat and no volume, so it never accrues a second service fee. Not metered: transport rejections (HTTP 400, 413, 415 and 429),
invalid_network and unsupported_scheme refusals, requests refused with HTTP 401 because a required
API key is missing or unknown, and requests the service answers with HTTP 500. With Postgres, rate limits
and metering are shared by every replica.
Each settlement also records its caller and the service fee priced when it was claimed, so a price
change never reprices history. Key holders read their usage at GET /usage: subject, days (31),
usage (the daily counts above) and serviceFee keep their meaning, with serviceFee.accruedUsd now the
sum of the prices recorded with each successful settlement Rail402 landed (basis: "per_settlement_recorded_price"). The body adds keyId, window and, per network the key may use,
settlements (succeeded, volume byAsset, sponsoredFeeStroops: the fees the sponsor was charged for
the key’s transactions whatever their outcome, serviceFeeUsd) and limits (requestsPerMinute,
sponsorBudgetStroopsPerHour, sponsorCommitted1hStroops, expiresAt). A failed settlement or a payment
another party’s transaction landed accrues no service fee.
node dist/usage.js export --from YYYY-MM-DD --to YYYY-MM-DD [--key <id>] [--format csv|json] prints one
row per caller × network × day (settlements, volume per asset, sponsored fee, service fee) for billing
off-chain. It reads DATABASE_URL (or DATABASE_URL_FILE; only the file with pubnet) and changes nothing.
Access keys
API_KEYS_FILE names a JSON file of access keys, each scoped to networks, with its own request limit,
hourly fee-sponsorship budget and expiry. It holds digests only, never a key:
node dist/keys.js new --id acme-prod-1 --networks stellar:pubnet --sponsor-budget-xlm-per-hour 2 [--requests-per-minute 120] [--days 90] prints a new key once, on the first line (r402_<id>_<43 random characters>; give it to its holder and do not store it), and the record to add on the second.
node dist/keys.js check <file> validates a file exactly as the service does, with the networks of
NETWORKS, and exits 0 or 78.
The service looks the file up by its path every 10 seconds and re-reads it when its inode, size or
modification time changed, and at once on SIGHUP, so issuing, expiring and revoking keys needs no
restart. Replace the file atomically (write a new file next to it, run keys check on it, rename it over
the old one). In a container, mount the directory that holds the file and set API_KEYS_DIR: a mount of
the single file keeps showing the file it was created with, so a file renamed over it on the host is never
seen inside, and a revoked key would stay valid until a restart. A changed file that fails validation
leaves the previous keys in force, logs the error, raises the critical /health warning
access_keys_reload_failed and counts rail402_access_keys_reload_failures_total. /health/private
shows the SHA-256 of the file in force (access.fileSha256), so a replacement can be confirmed on every
replica: compare it with the SHA-256 of the new file. A file replaced while the service starts is read
once more when the keys are built, so the digest always describes the keys in force; until a file has
been applied, access.fileSha256 is null. The file must not be writable by its group or others.
Internal discovery callers. A key with "scopes": ["discovery-internal"] and "networks": [] is the
identity of an internal discovery front end (for example a hosted discovery service that calls
/discovery/* for its own users). On the discovery routes its requests draw on a bucket of their own,
discoveryRequestsPerMinute (default DISCOVERY_INTERNAL_REQUESTS_PER_MINUTE), instead of the
per-address RATE_LIMIT_PER_MINUTE. With forwardedClientRequestsPerMinute set, the service also trusts
its X-Rail402-Client header (1–64 letters, digits, ., _, : or -; other values are ignored) and
gives each forwarded client that many discovery requests per minute, and its own share of concurrent
discovery requests (DISCOVERY_MAX_IN_FLIGHT_PER_CLIENT), so every remote user is limited on its own; the
header is ignored from anyone else. Such a key is refused with HTTP 403 on /verify and
/settle on every network.
How a request’s key is decided on one network:
Once the network and caller are known, each network applies its own limit: a key’s
requestsPerMinute,
or, for keyless callers, RATE_LIMIT_PER_MINUTE of the network per client address (unset: no network
limit), shared by every replica with Postgres and refused with HTTP 429 and Retry-After. When that
limiter cannot answer, pubnet requests are refused with HTTP 503 service_unavailable (“Rate limiting
is unavailable”), testnet requests are served. Each settlement records its caller, and the fee sponsor
admits it only within the network’s hourly budget and the caller’s own: the key’s
sponsorBudgetXlmPerHour, or for keyless callers KEYLESS_SPONSOR_BUDGET_XLM_PER_HOUR of the network,
shared by all of them. A spent caller budget is settle_exact_stellar_caller_budget_exhausted (or the
upto equivalent), retryable.
Keys through GitHub sign-in
WithKEY_SIGNUP=github the host that serves KEY_SIGNUP_NETWORK (a PUBLIC_HOSTS entry) issues access
keys to anyone with a GitHub account, without an operator in the loop:
GET /keys/newsends the browser to GitHub. No scope is asked for: only the public profile is read.- GitHub sends it back to
GET /keys/callback, which answers with JSON holding the key, shown once:
gh-<GitHub user id>, for KEY_SIGNUP_NETWORK only. Signing in again
issues a new key and the previous one stops working, at most once per KEY_SIGNUP_REISSUE_MINUTES. The
database keeps the key’s SHA-256 and the account’s id and login, never the key or the GitHub token. Every
replica reads the issued keys every 10 seconds; the replica that issued a key accepts it at once. Issued
keys are limited like file keys: their request limit and hourly fee budget apply per settlement. Metrics
count them under one key_id label, issued.
Sign-up requests are limited to 10 a minute per client address. The refusals are listed under
access-key sign-up on the error-code page.
Switches. The access-key file’s top-level
issuedKeys controls issued keys, and takes effect with the
file’s next reload (10 seconds, or at once on SIGHUP):
Keys in the file are never affected. To stop one holder, revoke the account:
node dist/keys.js issued revoke <gh-id or GitHub login>; it is refused within 10 seconds on every
replica and the account is issued no other key until node dist/keys.js issued restore <…>.
node dist/keys.js issued list prints every issued key without its secret. These commands connect with
DATABASE_URL (or DATABASE_URL_FILE). File key ids cannot start with gh-.
Secrets from files
Every secret can come from a file instead of the environment: set<NAME>_FILE to the file’s absolute
path, for DATABASE_URL, DATABASE_MIGRATION_URL, SEARCH_CURSOR_SECRET, TESTNET_SPONSOR_SECRET and
PUBNET_SPONSOR_SECRET.
An environment variable is visible to anyone who can inspect the container or the process; a file
mounted from a secret store is not. The file is read once at startup and its content, trimmed, is the
value. Setting both <NAME> and <NAME>_FILE is refused (config_secret_conflict).
A secret file must be a regular file of at most 4 KiB that neither its group nor others can write
(config_secret_file_insecure); a missing, unreadable, empty, oversized or relative path is
config_secret_file_unreadable. Errors name the variable and the path, never the content.
With pubnet enabled every secret comes from a file. PUBNET_SPONSOR_SECRET, DATABASE_URL,
DATABASE_MIGRATION_URL and SEARCH_CURSOR_SECRET in the environment are refused (config_secret_in_env), because one process then
also serves the public testnet. TESTNET_SPONSOR_SECRET may stay in the environment, though a file is
better. The pubnet sponsor key files (PUBNET_SPONSOR_SECRET_FILE, PUBNET_PREVIOUS_SPONSOR_SECRET_FILE)
must also be readable by their owner only (mode 0400 or 0600; group or others able to read is
config_secret_file_insecure), the database URL and cursor secret files by their owner and group only
(at most 0440; others able to read is config_secret_file_insecure), and the sponsor key files network-tagged: the first line is # rail402-key network=stellar:pubnet, followed by the seed.
config_secret_file_untagged), and a file tagged for
another network is refused on any network (config_secret_network_mismatch), so a seed generated and
handled as a testnet key cannot become the mainnet sponsor by mistake. Testnet sponsor files may be
untagged.
Per network
Variables are prefixedTESTNET_ or PUBNET_, for example TESTNET_RPC_URL. Only the networks listed
in NETWORKS are read.
The default asset is Circle USDC on each network:
CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA
on testnet and CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75 on pubnet, both with 7
decimals. INCLUSION_FEE_PERCENTILE is one of p50, p70, p80, p90, p95 or p99.
Validation rules beyond the formats:
NETWORKSmay not list a network twice, and each network needs its own sponsor account.- Whenever pubnet is enabled, every setting that decides what the fee sponsor pays for is explicit:
PUBNET_RPC_URLmust usehttps, and a provider URL with credentials in its user info, query or fragment must come fromPUBNET_RPC_URLS_FILE(config_secret_in_env; put a list whose URLs carry a key in their path there too);PUBNET_REQUIRE_API_KEYmust betrueorfalse;PUBNET_MAX_SPONSOR_SPEND_XLM_PER_HOUR,PUBNET_MAX_TX_FEE_STROOPS,PUBNET_INCLUSION_FEE_STROOPS(at least 200 unlessPUBNET_ALLOW_INCLUSION_FEE_BELOW_FLOOR=true),PUBNET_ASSETSand, unlessPUBNET_ALLOW_SINGLE_SIGNER_SPONSOR=true,PUBNET_SPONSOR_COLD_SIGNERmust be set, and everyPUBNET_ASSETSentry needs a minimum amount of at least 1 base unit, since a smaller payment costs the sponsor a full settlement fee. Withuptoon pubnet,PUBNET_UPTO_MAX_TX_FEE_STROOPSis required, and so isPUBNET_UPTO_TTL_MAX_FEE_STROOPSwhilePUBNET_UPTO_TTL_KEEPERis on (the default). None of these falls back to a testnet default. REQUIRE_API_KEY=trueneeds at least one digest inAPI_KEY_SHA256.TIMEOUT_MIN_SECONDSmay not exceedTIMEOUT_MAX_SECONDS,INCLUSION_FEE_STROOPSmay not exceedMAX_TX_FEE_STROOPS, andINCLUSION_FEE_CAP_STROOPSmust lie between the two.- With
uptoon,TIMEOUT_MAX_SECONDSmust be at least(EXPIRATION_MARGIN_LEDGERS + 1) × 5:uptorefuses a shortermaxTimeoutSeconds, whose authorization would expire before it can be settled. ASSETSentries need aC…contract address, a symbol of 1 to 12 letters or digits, decimals of 0 to 38, and a minimum no larger than the maximum; no contract may be listed twice.- At startup every
ASSETScontract is read from the network: a token whosedecimals()differs from the configured decimals, or a contract without adecimals()function, stops the service with exit code 78 andasset_decimals_mismatchorasset_not_a_tokenin the message. A contract that is not deployed yet, an RPC that does not answer, or adecimals()read that fails in any other way keeps/readyfailing until the check passes. See Accepted assets. PUBNET_UPTO_ENABLED=trueneedsPUBNET_UPTO_CONTRACTandPUBNET_UPTO_WASM_HASH; a non-canonicalUPTO_CONTRACTneedsUPTO_WASM_HASH, and a hash given for the canonical contract must be its hash.INCLUSION_FEE_STROOPSmay not exceedUPTO_MAX_TX_FEE_STROOPS, andUPTO_TTL_EXTEND_TO_LEDGERSmust exceedUPTO_TTL_EXTEND_BELOW_LEDGERS.UPTO_ZERO_SETTLEMENT=offchain(the pubnet default) needsSTORE=postgres: an off-chain zero exists only in the settlement ledger, which must survive restarts and be shared by every replica, or the same authorization could later be settled on-chain for more. A restore loses the records written after its restore point, so after one (recorded insettlement_rewinds) every network servingupto, whatever itsUPTO_ZERO_SETTLEMENTis now, settles nouptopayment that moves funds until the chain has passed the longest window rule 7 can accept,TIMEOUT_MAX_SECONDSin 1-second ledgers plus 7, about 25 minutes at the defaultTIMEOUT_MAX_SECONDSof 300 and 5-second ledgers (see Restoring a backup).- The
uptocontract is watched under the TTL aliasupto, so no asset symbol orTTL_CONTRACTSalias may beupto, and it may be neither an accepted asset nor listed inTTL_CONTRACTS.
Fee ceilings
The sponsor pays every settlement fee, so each network has a ceiling on the fee a settlement may cost:MAX_TX_FEE_STROOPS for exact and UPTO_MAX_TX_FEE_STROOPS for upto. Verification and settlement
compare the fee the simulation asks for (resource fee plus the inclusion bid; for upto, the bid counted twice,
for the settlement transaction and for its fee bump) with the ceiling and refuse a
payment above it before anything is signed, with invalid_exact_stellar_payload_fee_exceeds_maximum or
invalid_upto_stellar_payload_fee_exceeds_maximum.
The exact fee bump pays the inclusion bid a second time, so the most one exact settlement can cost the
sponsor is MAX_TX_FEE_STROOPS plus the highest bid (INCLUSION_FEE_CAP_STROOPS); for upto it is
UPTO_MAX_TX_FEE_STROOPS, which already counts both bids. Each settlement reserves that worst case against the
hourly budgets when it is claimed, and the sponsor refuses to sign a fee bump that would cost more than the
reservation (settle_exact_stellar_fee_bump_signing_failed), so the budgets cannot be overshot. Once a
settlement is finished it counts what the sponsor was charged instead: nothing when it expired or the network
refused its submission, and its maximum fee when the charge could not be read.
Most payments cost far less than the ceilings. The costly ones are first payments, which create ledger state
and pay its rent: a recipient’s first balance of a token, or a smart account’s first record in its
spending-limit policy. Fees observed, in stroops: the private-network rows while running the integration tests,
the testnet rows in rehearsals of the conformance harnesses. They are single observations that no test asserts;
the fee of every transaction of a recorded run is on the conformance evidence page,
and it varies with network conditions:
Testnet’s rent price follows the size of its ledger state and has kept rising: the smart-account TEST6
payment above carried a resource fee of 794,766 stroops nine days earlier, with the same instructions,
bytes and footprint. Testnet sponsors are funded by Friendbot, so the testnet defaults (2,000,000 and 5,000,000) leave
room for every payment above and for that drift. Pubnet has no defaults: set
PUBNET_MAX_TX_FEE_STROOPS and
PUBNET_UPTO_MAX_TX_FEE_STROOPS for the tokens and payers you choose to serve, since the sponsor pays every
stroop. 300,000 and 500,000 cover the Stellar Asset Contract payments above and refuse the costly first
payments. MAX_SPONSOR_SPEND_XLM_PER_HOUR bounds the total.
When the bid cannot follow the network, rail402_inclusion_fee_pinned_total counts it per network:
cause="cap" when the network asks for more than INCLUSION_FEE_CAP_STROOPS (settlements may wait under
surge pricing), cause="stats_unavailable" when fee stats could not be read and the floor was bid.
rail402_inclusion_fee_bid_stroops is the current bid.
Startup checks
Configuration problems stop the service before it serves anything, with exit code 78 andrail402: <code>: <message> on stderr. The codes are stable:
Any other failure that stops startup, such as missing embedding model files, exits with code 1 and
one line,
rail402: startup_failed: <what failed>, followed by the code locations of the failure. The
line never carries a URL or a secret seed, whatever was thrown.
Preflight. node dist/check-config.js (in the image: docker run --rm --env-file … <image> node dist/check-config.js) loads and validates the configuration exactly as the service does, with the same
environment, and with Postgres connects to check the database role and, with MIGRATE_ON_START=false,
that no migration is pending (it changes nothing), then exits 0 and prints one JSON line naming the networks and a SHA-256 digest of each
network’s effective settings (with Postgres also database: the connections the role may hold, the most one
process opens and how many replicas that holds), or exits 78 with the line the service would stop with. With
CHECK_CONFIG_PENDING_OK=true (preflight only) pending migrations are expected, for a deploy that applies them
with node dist/migrate.js next: it skips only the two pending-migration refusals (config_schema_outdated,
config_pubnet_migration_role_missing) and still checks the database role. It touches no
Stellar network. Run it before replacing a running service, so a configuration that cannot start never
replaces one that works. The service logs the same digest at startup (network settings loaded), so a
preflight and the service it guards, or two replicas, can be compared without printing any setting.
Bazaar and search
With embeddings on, the service refuses to start if the model files are missing or their SHA-256 hashes
do not match the pinned manifest.
pnpm models:fetch downloads and verifies them into .models/; the
container image already contains them.
Accounts
The sponsor pays every settlement fee through a fee-bump transaction and the base reserve of every channel account. It never holds or sends payment funds. Fund it with XLM only. Channel accounts are the source accounts of settlement transactions, one per in-flight settlement, so concurrent settlements never compete for a sequence number. They are derived from the sponsor secret (HKDF-SHA256), hold a zero balance, and need no separate secret or backup. Theupto settlement authority is the account every upto payment names in the terms the payer
signs (extra.facilitatorAddress in /supported). It is the operation source of each upto
settlement, and only it can choose the amount settled, up to the signed cap. It is derived from the
sponsor secret too and holds a zero balance with its reserve sponsored. A service that serves upto
creates it at startup when it is missing, whatever AUTO_PROVISION_CHANNELS says, and replicas starting
together take turns so only one creates it. If it cannot be created yet (for example, the sponsor is not
funded), the service still starts: exact works, upto payments are refused with
settle_upto_stellar_authority_unavailable, /health reports upto_authority_missing, and every poll
tries again. upto authority provision creates it by hand.
Examples
A testnet instance with the bundled Postgres needs only:channels provision first (see
Operations). The validation rules above are checked for pubnet at
startup, but pubnet itself has not been exercised end to end. The hosted Rail402 service serves testnet
only.