About
Open Protocol Indexer, OPI, is the best-in-slot open-source indexing client for meta-protocols on Bitcoin.
Other ProjectsMeasured star growth
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- +2
- in 1 month
- Collecting history
Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.
README.md
OriginalOPI - Open Protocol Indexer
[!WARNING] Running OPI 2.x? Stay on the
legacybranch. OPI 3.0 is a new single-binary indexer with its own data layout and does not upgrade a 2.x installation in place. A 3.0 node starts fresh: it indexes from the start, or restores a snapshot from snap.opi.network. To keep a 2.x node running, pull fromlegacy, which holds the Python and per-module setup of 2.x. Set up 3.0 as a new installation alongside it and switch over once it has caught up.
Open Protocol Indexer, OPI, is the best-in-slot open-source indexing client for meta-protocols on Bitcoin. OPI links upstream ord 0.29.1 as a library and is built with modularity in mind. All modules in OPI have been built with reorg protection.
OPI has modules for BRC-20, Bitmap, SNS and Runes, which run together in the opi-indexer binary and are served by one API, opi-indexer api. Pull Requests are welcomed for other meta-protocols.
Repository layout
One root Cargo workspace holds every crate, the indexer and the API included.
| Path | Contents |
|---|---|
crates/opi-indexer |
the opi-indexer binary: run, api, validate and the brc20 subcommands |
crates/opi-source |
ord as a journal source: gate proxy, stager and the journal of finalized blocks |
crates/opi-runtime |
drives every module over the journal, one supervised task per module |
crates/opi-core |
the types shared by the source, the runtime and the modules |
crates/opi-brc20 |
the BRC-20 and BRC2.0 module, its database schema |
crates/opi-bitmap |
the Bitmap module |
crates/opi-sns |
the SNS module |
crates/opi-runes |
the Runes module |
crates/opi-utxos |
the UTXO set module |
crates/opi-api |
the HTTP API for every enabled module, served by opi-indexer api |
tools/parity |
Python reference implementations and comparison tests for the modules, and the API comparison script |
.env_sample |
every setting of opi-indexer and the API |
Main Meta-Protocol Indexer / opi-indexer
opi-indexer sits in the core of OPI. It runs ord as a journal source that records all json/text inscriptions and their first 2 transfers, and feeds the journal to the BRC-20, Bitmap and SNS modules, and ord's rune events to the Runes module, in one process. Each module keeps its own Postgres database. BRC-20 becomes invalid after 2 hops, bitmap and SNS validity is calculated at inscription time.
Modules
OPI_MODULES lists the modules to run: any subset of
brc20,bitmap,sns,runes,inscriptions,utxos.
Each module reads the journal and keeps its own Postgres database. The API serves the same list.
| Module | Indexes | Database variables |
|---|---|---|
brc20 |
BRC-20 and BRC2.0 | DB_* |
bitmap |
Bitmap | BITMAP_DB_* |
sns |
Sats Names, by the written spec (see SNS indexing rules) | SNS_DB_* |
runes |
Runes, from ord's rune events | RUNES_DB_* |
inscriptions |
Every bound inscription's number, content type, current outpoint and owner (see Inscriptions module) | INSCRIPTIONS_DB_* |
utxos |
Every unspent output, by outpoint and script (see UTXO module) | UTXOS_DB_* |
The *_DB_* variables are USER, HOST, PORT, DATABASE, PASSWD and
SSL, for example BITMAP_DB_DATABASE. The runes module reports event_hash_version 2 because it orders a
transaction's input and burn events canonically.
NETWORK_TYPE and REPORT_TO_INDEXER, REPORT_URL, REPORT_NAME,
REPORT_RETRIES are shared by all modules.
Running without runes
Rune indexing follows OPI_MODULES: ord runs with --index-runes and the
journal keeps rune records only when runes is in the list. A box that serves
BRC-20, Bitmap and SNS sets, for example:
OPI_MODULES=brc20,bitmap,sns
ord then builds no rune tables and does no rune work per block, and the journal has no rune rows, so both ord's index and the journal need less disk.
The choice is fixed per ord data dir and journal: ord records it in its index
when it creates the index, and the journal records it in its runes meta row.
A start whose OPI_MODULES disagrees with either is refused with a message
naming the dirs to rebuild. The journal is checked first, for example:
opening the journal of ord's data dir /data/ord: journal at /data/journal was built with rune indexing, but runes is disabled; start with runes enabled again, or delete the journal and ord's data dir and index again
To switch, either put OPI_MODULES back as it was, or delete OPI_ORD_DATA_DIR
and OPI_JOURNAL_DIR and index from the start with the new list. Adding runes
to an index built without them always takes a rebuild.
Every ord data dir and journal built by earlier versions has rune indexing. To
keep one, add runes to OPI_MODULES (this also starts the runes module and
needs RUNES_DB_DATABASE), or delete both dirs to run without runes.
Inscriptions module
The inscriptions module keeps one row per bound inscription in
inscriptions_entries: its id, number, sequence number, content type (as
inscribed, plus a lowercased media_type without parameters for filtering),
charms, outpoint (txid bytes and vout) and offset, raw pkscript, genesis
height, last moved height and latest event. Addresses derive from the
pkscript. Cursed inscriptions are included (negative number). Burned ones
stay at their OP_RETURN output, which has no address. Unbound inscriptions have
no location and are left out. Inscription content is not stored.
It reads every creation and transfer from the journal's inscription_moves
table, which the journal keeps only when inscriptions is in OPI_MODULES.
Like runes, the choice is fixed when the journal is created (its
inscriptions meta row): a start that disagrees is refused, and turning the
module on for an existing journal means deleting OPI_JOURNAL_DIR and
OPI_ORD_DATA_DIR and indexing from the start. Each block's moves apply in
ord's emission order, with one update per moved inscription.
inscriptions_events keeps one row per creation and transfer: the location
the inscription moved to, as txid bytes, vout, offset and raw pkScript, and
prev_id, the inscription's previous event, whose location a reorg rolls back
to. An event id holds its block height in the high 32 bits, so a block's
events are one primary-key range; addresses derive from the pkScript and the
network. The module reports no event hashes to the OPI network.
Text and JSON inscriptions (text/plain and application/json media
types: brc20, names, mints) keep their location, not their journey. Batch
spends move them by the billion, so each keeps its creation and latest
transfer, and an earlier transfer only until the transfer after it is 1,000
blocks deep, past any rollback. Every other inscription keeps all of its
transfers. On mainnet this holds the events table to a few percent of the
full history. A database of db_version 2, which holds every transfer,
migrates on the first start: the kept rows are copied to a new table that
replaces the old one in one transaction, then the history indexes are
built, so the migration needs disk for the kept rows and their indexes
only.
More than 10,000 blocks behind bitcoind's tip, the module catches up without
the four indexes only the API reads (the outpoint and wallet indexes of
inscriptions_entries and inscriptions_events): writes and rollbacks read
primary keys alone, so each move updates its entry in place and appends its
event. It builds them, which takes hours on a mainnet database, before it
writes the first block within 1,000 blocks of the tip. Until then the
inscriptions routes and the utxos wallet route scan these tables, so serve
them from a node that has caught up.
UTXO module
The utxos module keeps bitcoind's UTXO set in utxos: one row per unspent
output with its txid bytes, vout, value, creating height, coinbase flag and
raw pkscript, indexed by outpoint and by the pkscript's SHA-256. Addresses
derive from the pkscript. Like bitcoind, it leaves out the genesis coinbase
and unspendable outputs (an OP_RETURN script, or one over 10,000 bytes), and a
repeated coinbase txid replaces the earlier outputs. Spent outputs are
deleted.
The journal carries no outputs, so the module reads blocks from bitcoind
(getblock <hash> 0, outside the gate proxy) and resolves each spend against
its own table. It runs in two modes:
- Catch-up, while it is more than
MAX_ROLLBACK_DEPTH(1000) blocks below the journal's tip: it reads blocks by height, writes many per transaction and keeps no undo data. This is how a new module indexes from genesis, on a pruned journal too, and how one that fell behind gets back. - Following, within the window: it reads each block by the journal's hash
and writes it with its undo data,
utxos_createdandutxos_spent, which a rollback uses to delete the block's outputs and put back the ones it spent. Every 100 blocks it drops the undo data older than the window, whetherOPI_PRUNEis set or not.
A block that spends an output the table does not hold fails, and the module
restarts from its cursor. A rollback below the oldest undo data
(utxos_undo.undo_from) fails too; the database must then be recreated. The
module reports no event hashes to the OPI network.
The API serves the set as GET /v1/utxos/wallet?address=|pkscript=&type=,
which needs the inscriptions and runes modules too: each of the wallet's
outputs with the inscriptions and rune balances it carries, and for each
inscription whether it is a used BRC-20 or BRC2.0 transfer inscription.
type=cardinal (which also needs brc20) keeps the outputs a wallet may spend
as plain bitcoin: no runes, no inscriptions other than used transfer
inscriptions, and created at or below indexed_height, the lowest height of
the modules read. inscribed and runic keep the outputs with inscriptions
or runes. A wallet with more than 10,000 unspent outputs answers 413.
With MEMPOOL_ENABLED=true (and BITCOIN_RPC_URL with
BITCOIN_RPC_COOKIE or BITCOIN_RPC_USER/BITCOIN_RPC_PASSWD), the API
keeps a mempool view in memory: it reads getrawmempool every
MEMPOOL_POLL_MS (default 2000) and fetches each new transaction with
getrawtransaction and getmempoolentry. mempool=true on the route then
leaves out the outputs a mempool transaction spends and adds the wallet's
mempool outputs, with height null, the transaction's fee and vsize,
and pending when their contents are unknown until they confirm: the
transaction or an in-mempool ancestor opens an inscription envelope or
holds a runestone, or a confirmed output they spend carries an inscription
or a rune or lies above indexed_height. Only mempool outputs that are not
pending count as cardinal; inscribed and runic list none. A transaction
that leaves the mempool stays in the view until the utxos module reaches
the bitcoind tip it left at, so a block's outputs never vanish between
bitcoind and the module, and at most until the tip is 3 blocks past it, so
a module catching up from far behind does not grow the view. Before the
view's first poll, mempool=true
answers 503.
Prerequisites
- bitcoind with
-txindex, not pruned. Finalize may fetchgetblock <hash> 3, which needs undo data. - One Postgres database per enabled module.
- A writable directory for the brc20-prog engine (
BRC20_PROG_DB_PATH) whenbrc20is enabled. The engine runs inside the indexer process, and the brc20 module always runs BRC2.0.
Configuration
Copy .env_sample to .env in the repository root (loaded from the working
directory or an ancestor, so run opi-indexer from inside the repository) or export the variables.
| Variable | Meaning |
|---|---|
OPI_CHAIN |
mainnet, signet, testnet4 or regtest |
OPI_ORD_DATA_DIR |
directory of ord's index database |
OPI_JOURNAL_DIR |
directory of the journal (see Journal) |
OPI_JOURNAL_CACHE_MB |
the redb page cache of the journal's tracked.redb, in MiB, 64 to 65536, default 1024. The process's memory grows by up to that amount; the journal's height files are read through the kernel's page cache |
OPI_JOURNAL_SEGMENT |
heights per journal segment directory, 100 to 100000, default 1000; fixed when the journal is created |
OPI_MIN_FREE_DISK_GB |
free disk space, in GiB, the journal keeps on its file system, 1 to 10000, default 20. A journal write that would leave less fails, and run stops; free space and start again to resume |
OPI_ORD_CACHE_MB |
the redb page cache of ord's index in MiB, 64 to 65536, default 1024. ord reads its index through the kernel's page cache, which holds the pages redb's cache would copy, so the RAM serves ord best left to the page cache; raise it only on a host whose page cache already holds the whole index |
MALLOC_ARENA_MAX |
glibc's malloc arenas, 1 to 1024, default 2. glibc otherwise opens up to 8 arenas per core, and each keeps the memory freed into it: on a signet catch-up 90 arenas held 3.6 of the process's 4.6 GiB, and 2 arenas brought its peak to 3.1 GiB. Read from the .env too |
BITCOIN_RPC_URL |
bitcoind RPC URL |
BITCOIN_RPC_USER, BITCOIN_RPC_PASSWD |
bitcoind RPC credentials |
BITCOIN_RPC_COOKIE |
bitcoind cookie file, instead of user and password |
OPI_CHUNK |
blocks per ord update, default 1000 |
OPI_MODULES |
comma-separated modules (brc20, bitmap, sns, runes, inscriptions, utxos), default brc20; runes also switches on ord's rune indexing (see Running without runes) and inscriptions the journal's inscription moves (see Inscriptions module) |
OPI_PRUNE |
blocks of history to keep, at least 1000; unset keeps everything (see Pruning) |
BRC20_HISTORY, RUNES_HISTORY, INSCRIPTIONS_HISTORY |
full (default) or window: the module keeps its current state and only the last 1000 blocks of history (see History windows) |
DB_*, BITMAP_DB_*, SNS_DB_*, RUNES_DB_*, INSCRIPTIONS_DB_*, UTXOS_DB_* |
the module databases (see Modules); DB_DATABASE, BITMAP_DB_DATABASE, SNS_DB_DATABASE, RUNES_DB_DATABASE, INSCRIPTIONS_DB_DATABASE and UTXOS_DB_DATABASE have no default and are required when the module is enabled |
NETWORK_TYPE |
network every module indexes; must match OPI_CHAIN |
REPORT_* |
block reporting, shared by all modules; one REPORT_NAME names the node for all of them, and each report's payload carries its module type |
RUST_LOG |
log filter, default info |
opi-indexer reads one .env, from its working directory or an ancestor. brc20's own
variables (DB_*, OPERATION_MODE, BRC20_PROG_*, BITCOIN_RPC_CACHE_ENABLED, ...)
live in that same file; .env_sample lists them. Set DB_DATABASE to brc20's
own database, not postgres. brc20 runs in full mode (OPERATION_MODE=full).
All enabled modules' settings are read and checked before the source starts, so
a missing or invalid one fails the start.
BITCOIN_RPC_URL and the bitcoind credentials are shared by the source and
brc20's engine lookups; set them once.
Build
cargo build --release --locked -p opi-indexer
Run
target/release/opi-indexer run
run is the default subcommand. SIGINT and SIGTERM close the source gate, stop
the modules, join the source and exit 0. A source error is logged and exits
non-zero. Each module indexes a block once the journal finalizes it, and rolls
back when its stored hashes differ from the journal's. A module error or panic
restarts that module, with a freshly built instance and database state, after a
backoff of 5 seconds, doubling to 5 minutes; the other modules and the source
keep running. A panic in brc20 stops the process instead (see BRC2.0 engine).
On shutdown run waits up to 150 seconds for brc20 to finish the block in
flight. Log verbosity follows RUST_LOG. Logs go to stderr for every
command.
Journal
The journal holds ord's raw events and the records finalize makes of them, for the blocks the modules have yet to read and those a reorg may roll back. It keeps no state of its own: ord's index holds the chain and inscription state, and each module's database holds the module's.
OPI_JOURNAL_DIR holds:
| File | Holds |
|---|---|
raw/<segment>/<height> |
the raw events ord emitted for a block it has indexed and the journal has yet to finalize, under the block's hash |
rec/<segment>/<height> |
a finalized block's header, transfer records, inscription infos, rune events and inscription moves |
meta.json |
chain, schema, the runes, inscriptions and segment settings, the gate limit and the pruned floor |
tracked.redb |
the bound text and JSON inscriptions whose first transfer the journal has yet to record |
lock |
held while a process has the journal open |
<segment> is the first height of the OPI_JOURNAL_SEGMENT heights its
directory groups. A height file is a 28-byte header (magic, format version,
stream, flags, height, lengths and CRC-32 checksums), a head (the block hash
of a raw file, the block header of a record file), and a body holding the
height's rows table by table, zstd-compressed when that makes it smaller.
The layout is documented in crates/opi-source/src/journal/files.rs.
The fork records a bound text or JSON inscription's creation and its first
transfer, and that choice numbers every record of the block after it. ord's
index keeps no content type, so tracked.redb keeps one small row per such
inscription until its first transfer. Only brc20 reads a transfer's content,
and only for a BRC-20 transfer, a brc20-module withdraw or a BRC2.0
deploy, call or transact, so the row of such an inscription also keeps
the info its creation recorded, which its first transfer's record carries
again; the first transfer of any other inscription carries none. Most of
these are BRC-20 transfer inscriptions, moved within a few blocks, so the
kept infos stay few. A rune transaction's records list the outpoints it spends:
the runes module, which keeps every unspent rune outpoint and every rune's
totals, makes the input events and the counter rows from them, so the block
event hashes are those the journal reported before.
A height file is written to <height>.tmp, synced, renamed into place and
its directory synced, so it exists whole or not at all; an open deletes the
.tmp files a crash leaves. Finalize writes record files in height order and
a rollback deletes them from the top down, so the final tip is the highest
height with a record file, after a crash at any point. Finalize deletes a
height's raw file once its record file is written: modules read records, and
a reorg makes ord emit the replacing block's events again. Raw files on disk
are those of the blocks ord has indexed ahead of finalize, at most
OPI_CHUNK of them.
Before every write the journal checks the free space of its file system, and
refuses a write that would leave less than OPI_MIN_FREE_DISK_GB; run logs
the refusal and stops, and a start after space is freed resumes where it
stopped.
A journal built in a redb layout (journal.redb, or meta.redb with
seg-<height>.redb files) is refused with a message: delete it and the ord
data dir and index again.
History windows
BRC20_HISTORY=window, RUNES_HISTORY=window and INSCRIPTIONS_HISTORY=window
keep a module's current state and only the history a rollback reads: the last
1000 blocks (MAX_ROLLBACK_DEPTH). They are independent of OPI_PRUNE, which
prunes the journal: a node can keep its full journal, to add or reindex modules
from it, while chosen modules keep windows.
| Module | Kept | Deleted once 1000 blocks deep |
|---|---|---|
| brc20 | tickers, current balances and holders, each wallet and ticker's latest brc20_historic_balances row, the inscribe events of transfer and BRC2.0 inscriptions not yet spent, predeploy events, the inscription of each deleted transfer event (brc20_used_transfers), cumulative event hashes, block hashes, BRC2.0 tables |
the other events and their brc20_event_parties rows; balance rows but each wallet and ticker's latest |
| runes | entries, unspent outpoints, current balances, holders, cumulative event hashes, block hashes | events; outpoints spent at that height; entry changes but each rune's latest |
| inscriptions | inscriptions_entries, each inscription's creation and latest event, block hashes |
the event a transfer moved the inscription from |
Wallet balances, unspent rune outpoints, inscription locations and the
cardinal rule of /v1/utxos/wallet read current state and answer as on a
full node. The routes that read history (brc20 and rune activity and balances
at a past height, event feeds, etchings, inscription and wallet history)
answer from what the window keeps. The brc20 event hashes reported to an OPI
network are computed per block as it is indexed, so a windowed brc20 node
reports like a full one.
A module switches from full history to a window on its next start, in one
transaction that deletes the history below the window. A database that keeps a
window refuses full: its history below the window is gone, so going back
means recreating the database and indexing again.
Pruning
With OPI_PRUNE=<blocks>, run deletes the data that only indexing and
rollbacks read once it is more than <blocks> deep. Every API route keeps
answering as on a full node, for every height. OPI_PRUNE is at least 1000,
the deepest rollback the scheduler walks.
| Store | Pruned | Kept |
|---|---|---|
| journal | record segments whose heights are all below both the final tip and the lowest module height minus <blocks>; raw files a crash left below the window; tracked inscriptions transferred below the window |
the window's record segments; the tracked inscriptions not yet transferred |
| brc20 | brc20_logs, which nothing reads |
every table the API, the light clients and validate read |
| bitmap, sns | *_block_hashes below the window |
names, bitmaps, cumulative event hashes |
| runes | runes_block_hashes below the window; runes_id_to_entry_changes below it except each rune's latest |
outpoints with their spends, events, entries, cumulative event hashes |
| inscriptions | inscriptions_block_hashes below the window |
inscriptions_entries and the inscriptions_events rows the module keeps, which the history routes read |
Each module prunes its tables every 100 blocks. ord's index has no history to
prune: run builds it without sat, address or transaction indexes.
The journal prunes by deleting whole directories of height files, and each
file takes the bytes it holds, so its disk use is its data: at most
<blocks> / OPI_JOURNAL_SEGMENT + 2 record segments (the window's, the one
being written, and the one the window starts in), the raw files of the blocks
ord has indexed ahead of finalize, tracked.redb and meta.json. A
background task deletes the segments below the window every minute, while
every enabled module is running and has reported its height; a deletion takes
milliseconds. A module or API read with a file open keeps reading it, and the
file system frees its space when the read ends.
On mainnet in 2025 a height's records hold about 0.5 MB of transfer records
and inscription infos, which compress about 3 to 1, so a window of 2000
blocks takes well under 1 GB. Its raw events hold 2 to 65 MB, almost all of
them transfers of inscriptions the journal does not track; they compress
about 2.5 to 1 and live only until finalize, so a catch-up of OPI_CHUNK
blocks holds a few GB of them at its peak.
tracked.redb holds one row per tracked inscription not yet transferred,
about 48 million rows and 2.2 GB of data at height 890,000; it is compacted
when the journal opens.
A pruned journal no longer holds the blocks a module needs to start from
scratch. A module whose next block is below the journal's pruned floor (a new
database, a module enabled later, or a brc20 reorg below the floor) fails with
"below the journal's pruned floor" and keeps restarting; rebuilding it needs a
new journal and ord data dir indexed from the start. brc20-prog's database is
not pruned.
BRC2.0 engine
When brc20 is enabled, the brc20-prog engine (Brc20Prog, brc20-prog 0.17)
runs inside the opi-indexer process as a library. There is no separate
brc20-prog server, and the engine needs no RPC credentials: brc20 calls the
indexer methods in process.
| Variable | Meaning |
|---|---|
BRC20_PROG_DB_PATH |
directory of the engine's database; required |
BRC20_PROG_RPC_SERVER_URL |
address of the public JSON-RPC server, default 127.0.0.1:18545 |
BRC20_PROG_RPC_SERVER_ENABLED |
the public JSON-RPC server runs when this is unset or exactly true; any other value turns it off |
EVM_RECORD_TRACES |
the engine records transaction traces when this is unset or exactly true; any other value turns it off. The block trace hash that OPI nodes compare is built from these traces, so with traces off every block's trace hash is the hash of the empty string and differs from the network's. Traces also serve debug_traceTransaction. The engine fixes the setting in its database when it creates it, so changing it takes a fresh BRC20_PROG_DB_PATH and a brc20 reindex |
run and brc20 light serve brc20-prog's public JSON-RPC on
BRC20_PROG_RPC_SERVER_URL, under the same settings. Blockscout, the swap
sequencer and other clients connect there. Both start serving it before their
start-up work. run serves it until brc20 finishes its last block after
SIGINT or SIGTERM; brc20 light serves it until the light client stops.
brc20 light stops on SIGINT or SIGTERM after its current block, or between
its start-up steps and BRC2.0 balance fill batches, with the engine's blocks
committed; a second signal exits (status 130) once the engine's current
commit has finished, or after 30 seconds. It answers the indexer methods
(brc20_mine and the like) with a 401 error for every caller and takes no
credentials, so bind it to loopback or firewall it. brc20-prog's
BRC20_PROG_RPC_SERVER_ENABLE_AUTH, BRC20_PROG_RPC_SERVER_USER and
BRC20_PROG_RPC_SERVER_PASSWORD apply only to brc20-prog's standalone server
and have no effect here. The engine reads its remaining settings from
brc20-prog's own variables (EVM_CALL_GAS_LIMIT, request limits; see
brc20-prog's configuration docs).
The engine gets its Bitcoin data in process, through the indexer. A lookup reads the Bitcoin RPC cache first
when BITCOIN_RPC_CACHE_ENABLED=true (an in-memory buffer, then the Postgres
table; the code default is false, .env_sample sets true). A "not yet"
answer (an unknown transaction, or a transaction not yet in a block) is reused
only within the block that looked it up: in full mode a later block asks
bitcoind again, while light mode replays the rows full nodes published. A
stored getrawtransaction answer is likewise served in full mode only when
the block it names is indexed; otherwise bitcoind is asked again. In
full mode a miss goes to bitcoind at BITCOIN_RPC_URL, authenticated with
BITCOIN_RPC_USER and BITCOIN_RPC_PASSWD, or with BITCOIN_RPC_COOKIE, which
is re-read on every request. Full mode requires one of the two credentials; the
config check fails otherwise. Light mode needs no bitcoind and no Bitcoin
credentials: it answers from the cache alone, so it requires
BITCOIN_RPC_CACHE_ENABLED=true (the config check fails otherwise), and the
network comes from NETWORK_TYPE.
The cache stores successful answers and getrawtransaction "not found" (-5)
answers. Only the indexer's own lookups write it; public eth_calls read it,
in light mode too. In light mode, a public call that needs a Bitcoin
transaction the cache does not hold fails (reverts). Each process that serves
engine lookups (run with brc20, and brc20 light) holds 2 Postgres
connections for the indexer's cache reads and 2 for public calls, outside
DB_MAX_CONNECTIONS. A lookup gives up after 20 seconds (a request to
bitcoind after 15, a wait for a Postgres connection after 5), and the engine
retries a failed lookup 5 times before it panics, which stops the process
(see below).
The network and chain id follow NETWORK_TYPE. brc20-prog's own
BITCOIN_RPC_PASSWORD and BITCOIN_RPC_NETWORK have no effect;
BITCOIN_RPC_URL and BITCOIN_RPC_USER are opi-indexer's settings, as
described above. An .env that still sets BITCOIN_RPC_PROXY_SERVER_ENABLED or
BITCOIN_RPC_PROXY_SERVER_ADDR has them ignored; remove them.
A panic on the brc20 thread or in the engine's public JSON-RPC server stops the
whole process, since the engine may be left mid-write. Run opi-indexer under a
supervisor such as systemd that restarts it.
To move a node that ran the standalone brc20-prog server, stop that server and
point BRC20_PROG_DB_PATH at its database; the on-disk format is the same.
When the engine's height is below brc20's at start, as with a fresh or lagging
BRC20_PROG_DB_PATH, brc20 rolls back to the engine's height (or to the block
before BRC2.0's activation, 229999 on signet, when the engine is below it) the
way brc20 reorg does, logs the engine dir and both heights (a warning,
except for an engine at most 10 blocks behind from the block before
activation on, which is uncommitted blocks), and replays the BRC2.0 blocks
from there. Between blocks of a running light client, an engine below the
block before activation is an error instead.
A database whose extra tables were built only partly can carry an incomplete
current-balances table. Once per database, before indexing resumes, brc20
checks brc20_current_balances against the newest brc20_historic_balances
row per pkScript and ticker, and rebuilds the extra tables as
brc20 reindex-extras does when they differ; a difference the rebuild leaves
stops the start. On mainnet the check scans both tables once.
brc20_extras_verified records that it passed. db_init.sql creates the
record, so a new database skips the check.
Docker
One image holds the opi-indexer binary. It runs as uid 10001, its entrypoint
is opi-indexer and its default command is run. State lives under /data
(journal, ord and brc20-prog), which the image's OPI_JOURNAL_DIR,
OPI_ORD_DATA_DIR and BRC20_PROG_DB_PATH defaults point at.
docker build -t opi-indexer .
docker run --rm opi-indexer --help
docker/compose.yml runs three services from that image, plus an optional
fourth:
| Service | Runs |
|---|---|
postgres |
Postgres 16; creates one database per module from DB_DATABASE, BITMAP_DB_DATABASE, SNS_DB_DATABASE, RUNES_DB_DATABASE and INSCRIPTIONS_DB_DATABASE when its volume is empty |
indexer |
opi-indexer run |
api |
opi-indexer api, published on 127.0.0.1:8000 |
bitcoind |
optional, under the bitcoind profile |
The API port is bound to localhost. To serve it more widely, change the api
port mapping in the compose file (for example "8000:8000") or put a reverse
proxy in front. The engine's public JSON-RPC (indexer in compose.yml,
light in compose.light.yml) listens on 0.0.0.0:18545 inside the
container and is published on 127.0.0.1:18545.
Compose reads .env from the repository root and overrides the settings that
differ in the compose network: DB_HOST and the other module hosts point at
postgres, DB_SSL is false, and the data dirs point at /data. postgres
takes its user and password from DB_USER and DB_PASSWD.
Signet
cp .env_sample .env
# set BITCOIN_RPC_URL and the bitcoind credentials, and DB_PASSWD
docker compose -f docker/compose.yml up -d --build
curl http://127.0.0.1:8000/v1/status
.env_sample already names signet (OPI_CHAIN and NETWORK_TYPE).
Mainnet
Set OPI_CHAIN="mainnet" and NETWORK_TYPE="mainnet" in .env, then run the
same commands. The journal, the ord dir and the brc20-prog database grow with
the chain, so size the Docker volume for mainnet.
bitcoind
bitcoind is external by default: BITCOIN_RPC_URL points at a node with
-txindex that is not pruned, and the credentials are either
BITCOIN_RPC_USER with BITCOIN_RPC_PASSWD, or BITCOIN_RPC_COOKIE. Inside
the container 127.0.0.1 is the container itself, so for a bitcoind on the
host set BITCOIN_RPC_URL to http://host.docker.internal:<port> (the
indexer service maps that name to the host). A cookie file has to be
readable inside the container: mount it into indexer through a
docker/compose.override.yml, pass both files
(docker compose -f docker/compose.yml -f docker/compose.override.yml up -d;
compose loads an override file automatically only when no -f is given), and
set BITCOIN_RPC_COOKIE to the mounted path.
docker compose -f docker/compose.yml --profile bitcoind up -d also starts a
bitcoind (image BITCOIND_IMAGE, default bitcoin/bitcoin:29.4) with
-txindex on the chain named by OPI_CHAIN, authenticated with
BITCOIN_RPC_USER and BITCOIN_RPC_PASSWD. Set BITCOIN_RPC_URL to
http://bitcoind:<port> (RPC port 8332 mainnet, 38332 signet).
Volumes
| Volume | Holds | Must persist |
|---|---|---|
opi-data (/data) |
the journal, ord's index and the brc20-prog database | yes; losing it forces a full reindex |
postgres-data |
the module databases | yes |
bitcoind-data |
bitcoind's chain data (bitcoind profile) |
yes |
The opi-indexer brc20 maintenance commands open brc20-prog's database, so
stop indexer before them:
docker compose -f docker/compose.yml run --rm indexer brc20 reorg <HEIGHT>.
Restarting
api only reads the module databases and holds no state of its own, so
docker compose -f docker/compose.yml restart api leaves indexer running,
and the reverse. indexer gets a three-minute stop grace period to finish the
block in flight.
Light client
docker/compose.light.yml runs postgres, light (opi-indexer brc20 light)
and api. It has no bitcoind, journal or ord dir; it sets
OPERATION_MODE=light and BITCOIN_RPC_CACHE_ENABLED=true, and uses its own
opi-light project name and volumes.
docker compose -f docker/compose.light.yml up -d --build
CI
.github/workflows/docker.yml builds the image on pushes to main and on
pull requests, and checks that both compose files resolve. It does not publish the image.
.github/workflows/rust.yml runs on the same events: cargo fmt --all --check, cargo clippy --workspace --all-targets --locked -- -D warnings
and cargo test --workspace --locked, with SQLX_OFFLINE=true. No
database is set, so the Postgres tests skip; the OpenAPI tests run.
Subcommands
opi-indexer [run | api | validate | brc20 <COMMAND>]
api serves the HTTP API (see API); it needs neither the journal nor ord.
opi-indexer brc20 holds the BRC-20 light client and maintenance commands. It
reads only brc20's environment, so it runs on light-client hosts.
event-str runs alongside run. Every other command opens brc20-prog's
database, which run holds, so stop run first; they fail with "brc20-prog's
database at is in use; stop opi-indexer run first" otherwise. In full
mode these commands read Bitcoin data like run does, so the .env carries the
same bitcoind credentials (BITCOIN_RPC_USER and BITCOIN_RPC_PASSWD, or
BITCOIN_RPC_COOKIE).
| Command | Does |
|---|---|
brc20 light |
runs the BRC-20 light client until SIGINT or SIGTERM, serving the engine's public JSON-RPC as run does; needs OPERATION_MODE=light |
brc20 reset [--yes] |
deletes all BRC-20 data and starts fresh |
brc20 reorg [--yes] <HEIGHT> |
rolls the BRC-20 state back to a block height |
brc20 recalculate-hashes <FROM> |
recomputes the cumulative event hashes from a height to the latest indexed block |
brc20 reindex-extras [--yes] |
rebuilds the extra tables from the indexed data; may take a long time |
brc20 event-str <HEIGHT> |
prints the block event string at a height |
brc20 trace-str <HEIGHT> |
prints the block trace string at a height |
The destructive commands (reset, reorg, reindex-extras) ask for a y/N confirmation; --yes
skips it. opi-indexer <command> --help prints each command's usage.
Metrics and health
run, brc20 light and api each serve Prometheus metrics and health checks
on a listener of their own, apart from the public API and the engine's
JSON-RPC, so the metrics stay off the public port. Bind it to loopback or a
private network.
| Variable | Meaning |
|---|---|
METRICS_ADDR |
listen address of the metrics listener of run and brc20 light, for example 127.0.0.1:9100; empty or unset runs none |
API_METRICS_ADDR |
listen address of the metrics listener of api; empty or unset runs none |
READY_MAX_LAG_BLOCKS |
the most blocks a module may be behind the chain tip while run or brc20 light is ready, default 2 |
READY_MAX_TIP_AGE_SECS |
the most seconds since the last chain tip read while run or brc20 light is ready, default 600 |
READY_NETWORK_CHECK_SECS |
how often run compares brc20's cumulative hashes with the OPI network's for readiness, for example 60; 0 (the default) or unset runs no comparison. Needs brc20 enabled |
A start fails when its metrics address is taken. run and brc20 light
serve the listener from the start of the process, on a thread of their own, so
liveness answers during start-up, such as while the engine opens or a fill
runs. Each listener serves:
| Route | Answers |
|---|---|
GET /health/live |
200 while the listener serves |
GET /health/ready |
200 when ready, else 503 with the reason in the body |
GET /metrics |
every metric below, in the OpenMetrics text format |
run is ready when no start-up fill runs, bitcoind's best block was read
within READY_MAX_TIP_AGE_SECS (the source reads it before each ord update),
and every enabled module's indexed height is at most READY_MAX_LAG_BLOCKS
below it. With READY_NETWORK_CHECK_SECS set, run is also not ready while
brc20 disagrees with the OPI network: every that many seconds it compares
brc20's cumulative event and trace hashes with the network's at the lower of
brc20's height and the network's best verified block, the newest height both
sides have, as validate does. A comparison that cannot complete, such as
while the network is unreachable, is logged and leaves the last answer
standing, so an outage of the network does not take a node out of service.
brc20 light compares brc20's height with the OPI network's best
verified block instead, which it reads while it waits for a new block. A module
that has not read its height yet, or whose run failed and waits to restart,
and an unknown tip, are not ready. api is ready when every enabled module's
database answers its latest block height; the databases are asked together and
have 2 seconds, and the 503 body names the database that does not answer.
Before run or brc20 light has finished its start-up, ready answers 503
starting. Once shutdown begins (SIGINT or SIGTERM for run and api, the
end of the light client), ready answers 503 shutting down, and the listener
stops after the process's work has stopped.
Every metric name starts with opi_. Metrics a process does not record have
no samples: api records only the api_* and stream_* metrics and its pools, run
everything else, and brc20 light the chain tip metrics and the brc20
module's.
| Metric | Type | Labels | Meaning |
|---|---|---|---|
opi_chain_tip_height |
gauge | the chain tip the modules follow: bitcoind's best block, or the OPI network's best verified block in light mode | |
opi_chain_tip_age_seconds |
gauge | seconds since that tip was last read | |
opi_indexed_height |
gauge | module |
last block the module has applied; no sample while the module is down |
opi_lag_blocks |
gauge | module |
blocks the module is behind the chain tip, 0 when at or above it |
opi_network_check_height |
gauge | the height of the last completed comparison of brc20 with the OPI network (READY_NETWORK_CHECK_SECS); no sample before the first |
|
opi_network_agrees |
gauge | 1 when brc20's hashes agreed with the network's at that comparison, 0 when they differed | |
opi_network_check_age_seconds |
gauge | seconds since that comparison completed | |
opi_block_seconds |
histogram | module |
seconds the module takes to apply one block |
opi_engine_seconds |
histogram | module (brc20) |
seconds of one brc20 block spent in the BRC2.0 engine; blocks that make no engine call, such as those below BRC2.0's first height, are not observed |
opi_fill_running |
gauge | module, fill |
runs of the start-up fill in progress, 0 once it has finished; fill is block_time, evm_addresses, prog_balances or prog_transfers |
opi_fill_progress |
gauge | module, fill |
last block filled (block_time, prog_balances, prog_transfers), or events read (evm_addresses) |
opi_fill_target |
gauge | module, fill |
the block the fill ends at (prog_balances, prog_transfers) |
opi_db_pool_connections |
gauge | module |
open connections of the module's database pool |
opi_db_pool_idle_connections |
gauge | module |
idle connections of the module's database pool |
opi_api_requests_total |
counter | module, route, status |
API requests answered |
opi_api_request_seconds |
histogram | module, route |
seconds the API takes to answer a request |
opi_api_rate_limited_total |
counter | module |
API requests the rate limiter rejected with 429 |
opi_stream_subscribers |
gauge | open streams of the push feed (/v1/stream); no sample before the first |
|
opi_stream_messages_total |
counter | event |
push feed messages sent, by event: block, rollback, heartbeat, error |
route is the route pattern, such as /v1/brc20/explorer/balances/{evm_address},
never the requested path; a request no route matches has route="unmatched".
module of an API metric is the module whose /v1/<module> prefix the path is
under, or api for other paths such as /v1/status. A request whose handler
panics counts with status="500". Rate-limited requests count only in
opi_api_rate_limited_total. Block histograms have buckets from
5 ms to 300 s, the request histogram from 1 ms to 10 s.
Validation runbook
Cut a deployment over to opi-indexer only after validate passes on signet and
on mainnet.
validate
opi-indexer validate [--from <height>] [--to <height>]
A BRC-20 node is correct when its cumulative event hash (and, from BRC2.0 on, its cumulative trace hash) equals the OPI network's at the same height. Each block's hash folds into the next, so a match at height N vouches for every height up to N.
validate reads brc20's hashes from its Postgres database and the network's
from the OPI API, with the same DB_* and NETWORK_TYPE variables, API URL
and event hash version as run. It never opens the journal, so it runs
while opi-indexer run is running.
--fromdefaults to brc20's first BRC-20 height for the network.--todefaults to the lower of brc20's latest height and the network's best verified block.
It compares the hashes at --to. When the event hashes match, and the trace
hashes match or the network has none, it prints OK <from>..<to> and exits 0.
Otherwise it bisects <from>..<to> for the first height whose event or trace
hash differs, prints that height with brc20's and the network's values for both
hashes, and exits 1. A height missing on either side, an unreachable API or
database, or an empty range prints the cause and exits 2.
Cut-over check
Run signet first, then mainnet. With opi-indexer run synced to the network's
best verified block, run opi-indexer validate. Expected: OK <first>..<tip>.
On a mismatch, the printed height is the first one where brc20 and the network
differ. Rerun with --from <h> --to <h> to confirm it is deterministic, then
compare that block's events with the network's. Fix the cause in the owning
component with a regression test, then rebuild brc20's hashes from that height
(opi-indexer brc20 recalculate-hashes <h>) and run validate again.
Signet smoke run
Run opi-indexer on signet with a fresh brc20 database for at least 1,000
blocks past the first BRC-20 height. Expected: brc20's current block height
advances and no errors are logged.
BRC-20 Indexer
BRC-20 Indexer is the first module of OPI. It follows the official protocol rules hosted here. BRC-20 Indexer saves all historical balance changes and all BRC-20 events.
In addition to indexing all events, it also calculates a block hash and cumulative hash of all events for easier db comparison.
It also calculates a hash of all BRC-20 programmable module traces in the current block, and a cumulative hash of the traces.
Here's the pseudocode for hash calculation:
## Calculation starts at block 767430 which is the first inscription block
EVENT_SEPARATOR = '|'
## max_supply, limit_per_mint, amount decimal count is the same as ticker's decimals (no trailing dot if decimals is 0)
## ticker_lowercase = lower(ticker)
## ticker_original is the ticker on inscription
## PRAGUE_ACTIVATION_HEIGHT marks support for PRAGUE EVM on BRC2.0 and it's 923369 on Mainnet and 275000 on Signet
for event in block_events:
if event is 'predeploy-inscribe':
block_str += 'predeploy-inscribe;<inscr_id>;<predeployer_pkscript>;<hash>;<block_height>' + EVENT_SEPARATOR
if event is 'deploy-inscribe':
block_str += 'deploy-inscribe;<inscr_id>;<deployer_pkscript>;<ticker_lowercase>;<ticker_original>;<max_supply>;<decimals>;<limit_per_mint>;<is_self_mint("true" or "false")>' + EVENT_SEPARATOR
if event is 'mint-inscribe':
block_str += 'mint-inscribe;<inscr_id>;<minter_pkscript>;<ticker_lowercase>;<ticker_original>;<amount>;<parent_id("" if null)>' + EVENT_SEPARATOR
if event is 'transfer-inscribe':
block_str += 'transfer-inscribe;<inscr_id>;<source_pkscript>;<ticker_lowercase>;<ticker_original>;<amount>' + EVENT_SEPARATOR
if event is 'transfer-transfer':
## if sent as fee, sent_pkscript is empty
block_str += 'transfer-transfer;<inscr_id>;<source_pkscript>;<sent_pkscript>;<ticker_lowercase>;<ticker_original>;<amount>' + EVENT_SEPARATOR
if event is 'brc20prog-deploy-inscribe':
block_str += 'brc20prog-deploy-inscribe;<inscr_id>;<source_pkscript>;<data>;<base64_data>' + EVENT_SEPARATOR
if event is 'brc20prog-deploy-transfer':
if block_height >= PRAGUE_ACTIVATION_HEIGHT:
block_str += 'brc20prog-deploy-transfer;<inscr_id>;<source_pkscript>;<spent_pkscript>;<data>;<base64_data>;<byte_len>;<op_return_tx_id>' + EVENT_SEPARATOR
else:
block_str += 'brc20prog-deploy-transfer;<inscr_id>;<source_pkscript>;<spent_pkscript>;<data>;<base64_data>;<byte_len>' + EVENT_SEPARATOR
if event is 'brc20prog-call-inscribe':
block_str += '<inscr_id>;<source_pkscript>;<contract_address>;<contract_inscription_id>;<data>;<base64_data>' + EVENT_SEPARATOR
if event is 'brc20prog-call-transfer':
if block_height >= PRAGUE_ACTIVATION_HEIGHT:
block_str += '<inscr_id>;<source_pkscript>;<spent_pkscript>;<contract_address>;<contract_inscription_id>;<data>;<base64_data>;<byte_len>;<op_return_tx_id>' + EVENT_SEPARATOR
else:
block_str += '<inscr_id>;<source_pkscript>;<spent_pkscript>;<contract_address>;<contract_inscription_id>;<data>;<base64_data>' + EVENT_SEPARATOR
if event is 'brc20prog-transact-inscribe':
block_str += '<inscr_id>;<source_pkscript>;<data>;<base64_data>' + EVENT_SEPARATOR
if event is 'brc20prog-transact-transfer':
if block_height >= PRAGUE_ACTIVATION_HEIGHT:
block_str += '<inscr_id>;<source_pkscript>;<spent_pkscript>;<data>;<base64_data>;<byte_len>;<op_return_tx_id>' + EVENT_SEPARATOR
else:
block_str += '<inscr_id>;<source_pkscript>;<spent_pkscript>;<data>;<base64_data>;<byte_len>' + EVENT_SEPARATOR
if event is 'brc20prog-withdraw-inscribe':
block_str += '<inscr_id>;<source_pkscript>;<ticker_lowercase>;<ticker_original>;<amount>' + EVENT_SEPARATOR
if event is 'brc20prog-withdraw-transfer':
block_str += '<inscr_id>;<source_pkscript>;<spent_pkscript>;<ticker_lowercase>;<ticker_original>;<amount>' + EVENT_SEPARATOR
if block_str.last is EVENT_SEPARATOR: block_str.remove_last()
block_hash = sha256_hex(block_str)
## for first block last_cumulative_hash is empty
cumulative_hash = sha256_hex(last_cumulative_hash + block_hash)
To calculate the trace hashes in a stable way, the JSON string representation of an EVM trace uses the suggested schema at RFC 8785, which has implementations in both Rust and Python:
### Calculation starts at block 912690, which is the first BRC2.0 block
traces_str = ""
for tx in block_txes:
trace_str = rfc8785.dumps(brc20_prog_client.debug_traceTransaction(tx).result)
traces_str += trace_str + EVENT_SEPARATOR
if traces_str.last is EVENT_SEPARATOR: traces_str.remove_last()
traces_hash = sha256_hex(traces_str)
cumulative_traces_hash = sha256_hex(last_cumulative_traces_hash + traces_hash)
There is an optional block event hash reporting system pointed at https://api.opi.network/report_block. If you want to exclude your node from this, just change the REPORT_TO_INDEXER variable in .env.
Also change REPORT_NAME to differentiate your node from others.
Bitmap Indexer
Bitmap Indexer is the second module of OPI. It follows the official protocol rules hosted here. Bitmap Indexer saves all bitmap-number inscription-id pairs.
In addition to indexing all pairs, it also calculates a block hash and cumulative hash of all events for easier db comparison. Here's the pseudocode for hash calculation:
## Calculation starts at block 767430 which is the first inscription block
EVENT_SEPARATOR = '|'
for bitmap in new_bitmaps_in_block:
block_str += 'inscribe;<inscr_id>;<bitmap_number>' + EVENT_SEPARATOR
if block_str.last is EVENT_SEPARATOR: block_str.remove_last()
block_hash = sha256_hex(block_str)
## for first block last_cumulative_hash is empty
cumulative_hash = sha256_hex(last_cumulative_hash + block_hash)
SNS Indexer
SNS Indexer is the third module of OPI. It follows the official protocol rules hosted here. SNS Indexer saves all name, domain, inscription-id and namespace, inscription-id tuples.
In addition to indexing all tuples, it also calculates a block hash and cumulative hash of all events for easier db comparison. Here's the pseudocode for hash calculation:
## Calculation starts at block 767430 which is the first inscription block
EVENT_SEPARATOR = '|'
for event in new_events_in_block:
if event is 'name-registration':
## name is the full name, domain is the part afler dot
block_str += 'register;<inscr_id>;<name>;<domain>' + EVENT_SEPARATOR
elif event is 'namespace-registration':
block_str += 'ns_register;<inscr_id>;<namespace>' + EVENT_SEPARATOR
if block_str.last is EVENT_SEPARATOR: block_str.remove_last()
block_hash = sha256_hex(block_str)
## for first block last_cumulative_hash is empty
cumulative_hash = sha256_hex(last_cumulative_hash + block_hash)
Runes Indexer
The runes module (crates/opi-runes) turns ord's rune events into the runes
Postgres schema in crates/opi-runes/src/db_init.sql. It saves every event (input to a tx, transfer, mint,
initial allocation and burn), the rune entries and the outpoint to balance
entries, and calculates a block hash and a cumulative hash of all events. State
starts at ord's first rune height; event hashes start at height 840000 on
mainnet, 2520000 on testnet, 173831 on signet and 0 elsewhere.
Event order. A transaction's events are, in this order:
input: for each input in input order that spends a rune outpoint, one event per stored(rune_id, amount)in rune id order;new_rune_allocation: when the transaction etches a rune through a runestone, with the premine as amount;mint: each mint, in emission order;output: each transfer, by output index and rune id;burn: each burn, by rune id, zero amounts included.
Reports carry event_hash_version 2 for this order.
Event hash. Each event is the string
<type>;<outpoint>;<pkscript>;<rune_id>;<amount>, with type one of input,
new_rune_allocation, mint, output, burn. outpoint and pkscript are
set for input and output events and empty for new_rune_allocation,
mint and burn. The block string is the events joined with |,
block_event_hash = sha256_hex(block_string) (an empty block hashes ""), and
cumulative_hash = sha256_hex(previous_cumulative_hash + block_event_hash).
The first hashed block uses its block_event_hash as the cumulative hash.
Storage. runes_events and runes_outpoint_to_balances store txids and
pkScripts as bytea and an outpoint as its txid (bytea) and vout
(int4); runes_current_balances keys its rows by the pkScript's bytes.
No table stores an address: the API derives it from the pkScript on the
database's network (runes_network_type), and resolves an address
parameter to the pkScript it encodes. An outpoint is unspent while its
spent_block_height is null, and runes_outpoint_to_balances is keyed by
(txid, vout). The API prints every txid and pkScript as lowercase hex and
every outpoint as <txid>:<vout>, the text the event hash reads.
runes_events is indexed by block_height, txid, (rune_id, id) and
(pkscript, id); runes_outpoint_to_balances by (txid, vout),
block_height and pkscript.
API tables. For the API's rune routes the module keeps
runes_current_balances (per rune and pkScript, the sum of its unspent
outpoints' balances) and runes_holders (the pkScripts with a positive
balance per rune) in each block's transaction and on every rollback, from
that block's balance changes alone; they feed no event, hash or report. A
database without them gets them filled from the unspent outpoints at start,
and the indexes the routes read are created at start when missing (they
include runes_id_to_entry_number_idx, which orders runes by number).
Until the tables and indexes exist, the API's rune routes and
/v1/runes/holders answer 503.
Versions. Reports send opi-runes-full-node v1.0.0 with db_version 7. A
database with another db_version is refused and must be indexed from scratch.
RUNES_DB_DATABASE names a new database: one that holds blocks written by
another indexer is refused.
API
opi-indexer api serves every module in OPI_MODULES on one port, from its own
process. It reads the same .env as run.
- BRC-20 exposes activity on block (block events), balance of a wallet at the start of a given height, current balance of a wallet, block hash and cumulative hash at a given block and hash of all current balances, and tickers, holders, wallet balances and event feeds that merge BRC-20 and BRC2.0 (see Ticker, wallet and lookup routes).
- Bitmap exposes block hash and cumulative hash at a given block, hash of all bitmaps and inscription_id of a given bitmap.
- SNS exposes block hash and cumulative hash at a given block, hash of all registered names, id number and domain of a given name, id number and name tuples of a domain, and all registered namespaces endpoints.
- Runes exposes activity on a block (
/v1/runes/activity_on_block), the balance of a wallet at the start of a height (/v1/runes/balance_on_block), the current balance of a wallet (/v1/runes/get_current_balance_of_wallet), the unspent rune outpoints of a wallet (/v1/runes/get_unspent_rune_outpoints_of_wallet), the holders of a rune (/v1/runes/holders), and the block hash and cumulative hash at a height (/v1/runes/get_hash_of_all_activity), plus paged rune, holder, wallet balance and event feed routes (see Rune, holder and wallet routes). - Inscriptions exposes an inscription's metadata and current location, a wallet's inscriptions filtered by content type, genesis height or curse, and the inscriptions on one or many outputs; with runes also enabled,
/v1/outputsanswers the inscriptions and runes on many outputs at once (see Inscription and output routes).
Each module's routes live under /v1/<module>/. A module outside OPI_MODULES
answers 404 {"error":"<module> is not enabled on this node"}. /v1/status
lists the enabled modules; a module entry is {"block_height":N}, or
{"error":"unavailable"} when its database query fails (the cause is logged).
A failing handler answers
500 {"error":"internal error","result":null}.
The server speaks HTTP/1 only and closes a connection that has not sent its
request headers within 60 seconds. On SIGINT or SIGTERM it stops accepting
connections, ends every push feed stream, lets requests in flight finish for
at most 10 seconds and exits.
Responses carry no X-Powered-By and no ETag.
The API needs Postgres 12 or newer: every connection starts with the startup
option plan_cache_mode=force_custom_plan, which keeps the row order of
queries without a full ORDER BY. A pooler that drops startup options (some
PgBouncer setups) loses it; the API logs a warning at startup when a database
runs another mode. <MODULE>_SSL=true encrypts the database connection
without verifying the server certificate. An idle keep-alive connection closes
at the same 60 second header-read timeout.
The API only reads from the module databases, so give it a read-only database
role (see OPI_ENV_FILE below for pointing it at its own env file).
The brc20 explorer routes read evm_addresses, which the brc20 module creates
and keeps current: each block's events add their addresses, and a database
without the table gets it filled from the indexed events on the next start
(an existing table is adopted as it is). When opi-indexer takes over a
database whose evm_addresses the Python sidecar
brc20_update_evm_addresses_custom.py maintains, stop the sidecar; no wait is
needed. The next start adds the rows for the blocks above the sidecar's
progress table brc20_block_hashes_evm_addresses and drops that table. The
sidecar's DDL makes postgres the table owner, so the indexer's database role
needs INSERT and DELETE on evm_addresses and USAGE on
evm_addresses_id_seq, or ownership
(ALTER TABLE evm_addresses OWNER TO <role>), and the right to drop the
progress table (its owner or a superuser).
The unused-transaction routes read brc20_unused_txes, which the indexer
keeps. /v1/brc20/extras_block_height reads brc20_extras_block_hashes,
which neither the indexer nor brc20 reindex-extras creates; it answers -1
until that table exists in the brc20 database.
OpenAPI document and routes
GET /v1/openapi.json serves the API's OpenAPI 3.1 document: every route of
the modules in OPI_MODULES, with its parameters (bounds and defaults), its
answers' schemas and content types, and its error bodies. Use it to browse
the API or to generate a client. It counts against the rate limit as any
route does.
The document comes from the route code: each handler carries a
#[utoipa::path] annotation, and its module registers it with
.routes(routes!(handler)), which adds the route and its operation together.
A module registers its routes through ModuleRoutes, which takes nothing
but routes!, so a route without an operation does not compile. Unit tests
fail when the document does not validate against the OpenAPI 3.1 schema and
when the tables below differ from it, and every route test checks its
answer's status, content type and JSON body against the document. The
tables are generated from the document; after a route change, rewrite them
with
OPI_UPDATE_README=1 cargo test -p opi-api readme. A parameter in bold is
required: the route needs it for a useful answer, and the document says
what the route answers without it.
The Node API's routes answer byte for byte as the Node API does, so their schemas describe node-pg's value forms: an int8 count or a numeric amount is a string, a missing column value is null, and a route that echoes a query parameter echoes it as given (a string, or an array or object for a repeated or bracketed parameter).
api: The node's status and this document.
| Route | Query parameters | Answers |
|---|---|---|
GET /v1/openapi.json |
This OpenAPI document. | |
GET /v1/status |
Each enabled module's latest indexed height. |
brc20: BRC-20 and BRC2.0.
| Route | Query parameters | Answers |
|---|---|---|
GET /v1/brc20/activity_on_block |
block_height |
Every brc20 event of a block height. |
GET /v1/brc20/balance_on_block |
block_height, pkscript, ticker |
A ticker's balance of a pkscript at the start of a block height. |
GET /v1/brc20/bitcoin_rpc_results_on_block |
block_height |
Every cached bitcoin RPC result of a block height. |
GET /v1/brc20/block_height |
The latest indexed block height. | |
GET /v1/brc20/db_version |
The database's schema version. | |
GET /v1/brc20/deploys |
type, category, before_id, limit |
A page of the network's events of some categories, newest first. |
GET /v1/brc20/event |
inscription_id |
Every event of an inscription id. |
GET /v1/brc20/event_hash_version |
The version of the event hash format. | |
POST /v1/brc20/events_by_inscriptions |
Every event of up to 500 inscription ids. | |
GET /v1/brc20/explorer/address_tabs_counters/{evm_address} |
The address tab counters of an EVM address, for the BRC2.0 explorer. | |
GET /v1/brc20/explorer/balances/{evm_address} |
The BRC-20 balances of an EVM address's BTC address, for the BRC2.0 explorer. | |
GET /v1/brc20/explorer/btc_address/{evm_address} |
The BTC address an EVM address maps to, for the BRC2.0 explorer. | |
GET /v1/brc20/explorer/tokens |
q, items_count, order |
A page of tickers by holder count, for the BRC2.0 explorer. |
GET /v1/brc20/extras_block_height |
The latest block height of brc20_extras_block_hashes. |
|
GET /v1/brc20/get_current_balance_of_wallet |
address, pkscript, ticker |
A wallet's current balance of a ticker. |
GET /v1/brc20/get_hash_of_all_activity |
block_height |
A block's event and trace hashes, cumulative and its own. |
GET /v1/brc20/get_hash_of_all_current_balances |
The hash of every current balance, BRC-20 and BRC2.0. | |
GET /v1/brc20/get_valid_tx_notes_of_ticker |
ticker |
A ticker's unused transfer inscriptions. |
GET /v1/brc20/get_valid_tx_notes_of_wallet |
address, pkscript |
A wallet's unused transfer inscriptions. |
GET /v1/brc20/holders |
ticker |
A ticker's holders and their current balances. |
GET /v1/brc20/ip |
The client's IP address, as the API sees it through API_TRUSTED_PROXY_CNT proxies. | |
GET /v1/brc20/ticker |
ticker |
A ticker's supply, mint progress, holder counts and BRC2.0 token contract. |
GET /v1/brc20/ticker/by_contract |
contract_address |
The ticker a BRC2.0 token contract carries. |
GET /v1/brc20/ticker/events |
ticker, type, category, before_id, limit |
A page of a ticker's events, newest first. |
GET /v1/brc20/ticker/holders |
ticker, offset, limit |
A page of a ticker's holders, BRC-20 and BRC2.0 balances merged. |
GET /v1/brc20/ticker/holders/snapshot |
ticker, block_height, format |
Every holder of a ticker at the end of a block, streamed. |
GET /v1/brc20/tickers |
sort, order, search, offset, limit |
A page of tickers, by holders or another order. |
GET /v1/brc20/wallet/balance_history |
address, pkscript, ticker, before_id, limit |
A wallet's balance of one ticker after each change, newest first. |
GET /v1/brc20/wallet/balances |
address, offset, limit |
A page of a wallet's tickers, BRC-20 and BRC2.0 balances side by side. |
GET /v1/brc20/wallet/events |
address, pkscript, type, category, include_prog_transfers, before_id, before, limit |
A page of the events a wallet takes part in, newest first, with its BRC2.0 token transfers when asked for. |
bitmap: Bitmap.
| Route | Query parameters | Answers |
|---|---|---|
GET /v1/bitmap/block_height |
The latest indexed block height. | |
GET /v1/bitmap/by_inscription |
inscription_id |
The bitmap an inscription registered. |
GET /v1/bitmap/get_hash_of_all_activity |
block_height |
A block's event hashes, cumulative and its own. |
GET /v1/bitmap/get_hash_of_all_bitmaps |
The hash of every bitmap; the route always fails. | |
GET /v1/bitmap/get_inscription_id_of_bitmap |
bitmap_number |
The inscription id of a bitmap number. |
GET /v1/bitmap/ip |
The client's IP address, as the API sees it through API_TRUSTED_PROXY_CNT proxies. | |
GET /v1/bitmap/search |
prefix, after, limit |
A page of the bitmaps whose number starts with a prefix. |
sns: SNS names and namespaces.
| Route | Query parameters | Answers |
|---|---|---|
GET /v1/sns/block_height |
The latest indexed block height. | |
GET /v1/sns/by_inscription |
inscription_id |
The name an inscription registered. |
POST /v1/sns/by_inscriptions |
The names up to 500 inscriptions registered. | |
GET /v1/sns/get_hash_of_all_activity |
block_height |
A block's event hashes, cumulative and its own. |
GET /v1/sns/get_hash_of_all_registered_names |
The hash of every registered name. | |
GET /v1/sns/get_info_of_sns |
name |
The inscription and namespace of a registered name. |
GET /v1/sns/get_inscriptions_of_domain |
domain |
Every name of a namespace, with its inscription. |
GET /v1/sns/get_registered_namespaces |
Every registered namespace, with its inscription. | |
GET /v1/sns/ip |
The client's IP address, as the API sees it through API_TRUSTED_PROXY_CNT proxies. | |
GET /v1/sns/search |
prefix, namespace, after, limit |
A page of the names that start with a prefix. |
runes: Runes.
| Route | Query parameters | Answers |
|---|---|---|
GET /v1/runes/activity_on_block |
block_height |
Every runes event of a block height. |
GET /v1/runes/balance_on_block |
block_height, pkscript, address |
Every rune balance of a pkscript or address at the start of a block height. |
GET /v1/runes/block_height |
The latest indexed block height. | |
GET /v1/runes/etchings |
before_number, limit |
A page of etched runes, newest first. |
GET /v1/runes/event |
transaction_id |
Every runes event of a transaction id. |
GET /v1/runes/get_current_balance_of_wallet |
address, pkscript |
Every current rune balance of a wallet. |
GET /v1/runes/get_hash_of_all_activity |
block_height |
A block's event hashes, cumulative and its own. |
GET /v1/runes/get_unspent_rune_outpoints_of_wallet |
address, pkscript |
Every unspent outpoint of a wallet that holds runes. |
GET /v1/runes/holders |
rune_name, rune_id |
Every holder of a rune, largest balance first. |
GET /v1/runes/ip |
The client's IP address, as the API sees it through API_TRUSTED_PROXY_CNT proxies. | |
GET /v1/runes/rune |
rune |
A rune's etching, supply, mint terms and progress, and holder count. |
GET /v1/runes/rune/events |
rune, type, category, before_id, limit |
A page of a rune's events, newest first. |
GET /v1/runes/rune/holders |
rune, after, limit |
A page of a rune's holders, largest balance first. |
GET /v1/runes/runes |
sort, order, search, after, limit |
A page of runes, by holders or another order. |
GET /v1/runes/wallet/balances |
address, pkscript, after, limit |
A page of the runes a wallet holds, with its balances. |
GET /v1/runes/wallet/events |
address, pkscript, rune, type, category, before_id, limit |
The input and output events of the outpoints the wallet owns, named by address or pkscript; rune keeps those of one rune. The feed pages by key, as the rune feed does. |
inscriptions: Inscriptions and their current locations.
| Route | Query parameters | Answers |
|---|---|---|
GET /v1/inscriptions/inscription |
id, number |
One inscription's metadata and current location. |
GET /v1/inscriptions/inscription/history |
id, number, before_id, limit |
A page of an inscription's creation and transfers, newest first. |
GET /v1/inscriptions/outpoint |
outpoint |
The inscriptions an output holds, with their offsets. |
POST /v1/inscriptions/outpoints |
The inscriptions on up to 500 outputs, with their offsets. | |
GET /v1/inscriptions/wallet |
address, pkscript, content_type, from_height, to_height, cursed, after, limit |
A page of the inscriptions a wallet holds, newest first. |
GET /v1/inscriptions/wallet/history |
address, pkscript, before_id, limit |
A page of the inscriptions a wallet received, newest first, each with the transfer that moved it on. |
outputs: The inscriptions and runes on outputs.
| Route | Query parameters | Answers |
|---|---|---|
POST /v1/outputs |
The inscriptions and runes on up to 500 outputs. |
utxos: A wallet's unspent outputs and what they carry.
| Route | Query parameters | Answers |
|---|---|---|
GET /v1/utxos/wallet |
address, pkscript, type, mempool |
A wallet's unspent outputs, with their inscriptions and runes. |
stream: The push feed of each block's events.
| Route | Query parameters | Answers |
|---|---|---|
GET /v1/stream |
modules, confirmations, from_height |
Server-sent events of each block's events, with rollbacks on reorgs. |
Ticker, wallet and lookup routes
These routes answer {"error":null,"result":...}. A missing or invalid
parameter answers 400 {"error":"<reason>","result":null}, and an unknown
ticker or inscription answers 404 with "ticker not found",
"bitmap not found" or "sns name not found" as the error. Lists take
limit (default 100, at most 500). A list result echoes the request's
resolved filters (sort and order, ticker, address, pkscript,
event_type, prefix, namespace), as the route applied them: a lowercased
ticker, an EVM address answered as its mapped Bitcoin address, the lowercase
SNS prefix and namespace. Parameters are bounded: offset is at most
1000000000, before_id at most 999999999999999999, the bitmap after at
most 2147483647, address and inscription_id at most 128 bytes,
pkscript at most 20000 hex digits, ticker, search and type at most 256
bytes, and the SNS prefix, namespace and after at most 2048 bytes. A
text parameter holds no NUL byte. The route tables
list each route's parameters.
Amounts. Amounts are raw integers as strings. Every BRC-20 and BRC2.0
amount carries 18 fractional digits (1 token is 1000000000000000000), so
decimals is always 18: divide by 10^decimals for tokens.
ticker_decimals is the ticker's deploy precision, the most fractional digits
an amount of it may have; it is null for a BRC2.0 balance of a ticker brc20
does not list and for an event without a ticker. Tickers match in lowercase,
as brc20 stores them, so ticker=ORDI finds ordi. Each answer of the brc20
routes carries the database's block_height.
BRC2.0 balances. The brc20 module keeps every wallet's BRC2.0 token balance
in its own database (brc20_prog_tickers, brc20_prog_current_balances and
brc20_prog_historical_balances), read from the engine's logs in the same
transaction as each block. A BRC20Created log of the BRC20 controller
registers a token contract under its name(), and the contract's ERC-20
Transfer logs move balances between lowercase EVM addresses. The historical
table holds one row per wallet, ticker and block, the balance at the end of
that block. A database without these tables gets them filled from the engine's
logs, from the BRC2.0 activation height up, on the next start before indexing
resumes (a few seconds on signet). The fill needs the engine and brc20 at the
same height and refuses to start otherwise.
A database also carries brc20_prog_transfers, one row per ERC-20 Transfer
log of a BRC2.0 token. A database without it creates it and fills it from the
BRC2.0 activation height on the next start: indexing pauses, /health/ready
answers 503 meanwhile, and a stop resumes the fill later. Before running an
image that predates the table, stop the indexer and run
DROP TABLE IF EXISTS brc20_prog_transfers, brc20_prog_transfers_fill;. An
older image neither writes nor rolls back the table, and a later upgrade
does not refill a table that already exists.
Tickers. /v1/brc20/ticker answers the ticker's tick, original_tick,
decimals, ticker_decimals, max_supply, minted_supply,
remaining_supply, burned_supply, limit_per_mint, is_self_mint,
deploy_inscription_id, deploy_block_height, holders, prog_holders and
prog_contract_address (the BRC2.0 token contract, null before the ticker's
first deposit). holders counts the pkScripts with a positive BRC-20
balance, and prog_holders the EVM addresses with a positive BRC2.0 balance;
a Bitcoin address holding both counts in both. Neither counts the BRC2.0
module's pkScript 6a09425243323050524f47 (OP_RETURN "BRC20PROG"), which
holds the BRC-20 side of every deposit: that balance is listed per EVM
address on the BRC2.0 side.
/v1/brc20/ticker/by_contract answers the same object for the ticker a BRC2.0
token contract carries, with prog_contract_address the queried contract and
prog_ticker_hash the ticker hash its BRC20Created log registered.
contract_address is 0x and 40 hex digits in any case; an unknown contract
answers 404 {"error":"contract not found","result":null}.
/v1/brc20/tickers lists the same objects without prog_contract_address.
sort is holders (default), prog_holders, max_supply, mint_progress
(minted over max supply) or deploy_height; order is desc (default) or
asc; ties order by ticker. search keeps the tickers that start with it.
Holders and wallet balances. A holder is a Bitcoin address: its BRC-20
balance and the BRC2.0 balance of its EVM address (from evm_addresses) form
one row, {"address","pkscript","evm_address","balance","available_balance", "prog_balance","total_balance"}, where total_balance is balance plus
prog_balance. A BRC-20 balance whose pkScript has no address is listed by
its pkscript, and an EVM address without a Bitcoin address (a contract, for
example) by its evm_address with a null address. /v1/brc20/ticker/holders
orders by total_balance, largest first, then by holder. The module pkScript
is left out of holders and wallet balances.
/v1/brc20/wallet/balances takes a Bitcoin address, whose EVM address comes
from evm_addresses, or an EVM address (0x and 40 hex digits, any case),
whose Bitcoin address comes from the same table when it has one. It answers
address, evm_address and balances, one row per ticker with a positive
balance on either side, by ticker: {"tick","decimals","ticker_decimals", "balance","available_balance","prog_balance","total_balance"}. Both lists
page with offset (default 0) and limit, and report offset, limit
and has_more. A wallet the database does not know answers 200 with an
empty list, here and on /v1/brc20/wallet/events.
Holders snapshot. /v1/brc20/ticker/holders/snapshot lists every holder
of a ticker at the end of block block_height (default: the indexed tip),
for airdrop and snapshot tooling. A holder's balance at that height is its
latest row at or below it in brc20_historic_balances and
brc20_prog_historical_balances; the rows merge, filter and order as
/v1/brc20/ticker/holders lists them, so the snapshot at the tip is that
route's full list. EVM addresses map through the current evm_addresses
table; a mapping depends only on the pkScript. The tip and the rows come
from one database snapshot (a REPEATABLE READ READ ONLY transaction). A
block_height above the indexed tip or below the ticker's deploy height
answers 400. At most 4 snapshots, and at most half the pool
(DB_MAX_CONNECTIONS), stream at once; another answers 503. Each holds a
pool connection while it streams, for at most API_SNAPSHOT_TIMEOUT_MS; one
that cannot start within that limit answers 503 "snapshot timed out".
format=json (default) answers
{"error":null,"result":{"ticker","block_height","decimals", "ticker_decimals","holders":[...]}} with the holders route's row objects
and no paging. format=csv answers text/csv; charset=utf-8 as the
attachment <ticker>-<block_height>.csv: a header row, then one row per
holder with the columns address,evm_address,pkscript,brc20_balance, brc20_available_balance,prog_balance,total_balance (the row object's
balance and available_balance are brc20_balance and
brc20_available_balance; a null is an empty field), CRLF line ends and RFC
4180 quoting. Both formats stream from Postgres as the rows arrive. A
failure partway through, or the time limit passing, aborts the transfer, so
a complete download is a complete snapshot. A snapshot at least 1000 blocks
below the tip (the indexer's deepest rollback) never changes, and its answer
carries Cache-Control: public, max-age=86400, immutable, so a shared cache
in front of the API can serve repeats; every other answer, refusals
included, carries Cache-Control: no-store. Each holder's latest row comes
from an index-only scan of (tick, pkscript, block_height DESC, id DESC) on
brc20_historic_balances and (ticker, wallet, block_height DESC) on
brc20_prog_historical_balances, which a start builds concurrently on a
database from before them while indexing goes on.
Whole-table hashes. /v1/brc20/get_hash_of_all_current_balances and
/v1/sns/get_hash_of_all_registered_names read and hash a whole table, so
each is computed once per indexed block (its height and block hash) and
served from memory until the tip moves. Requests that arrive while it is
computed wait for that one computation.
get_hash_of_all_current_balances covers BRC-20 and BRC2.0 balances, both
read in one snapshot. Its string is the nonzero brc20_current_balances rows
as pkscript;tick;overall;available, ordered by pkscript then tick in
JavaScript string order, then the nonzero brc20_prog_current_balances rows
as prog;wallet;ticker;balance (a plain decimal integer), ordered by wallet
then ticker the same way, all joined by |. A database without a BRC2.0
balance hashes the BRC-20 part alone. The hash is a drift check between OPI
hosts; opi.network does not read it.
Event feeds. An event is {"id","block_height","block_time", "inscription_id","event_type","ticker_decimals","event"}: block_time is the
block's time in seconds and is null when the block's time is unknown (a block
indexed before block times were stored that the journal did not hold at a
start, or any such block in light mode), event_type is the name from
brc20_event_types and event is the stored event object. type keeps one
event type by that name. category keeps the events of one or more
categories, comma-separated; every event type has exactly one:
| Category | Events |
|---|---|
deploy |
deploy-inscribe, predeploy-inscribe |
mint |
mint-inscribe |
transfer |
transfer-inscribe, and transfer-transfer not spent to the BRC2.0 module pkScript |
wrap |
transfer-transfer spent to the BRC2.0 module pkScript (6a09425243323050524f47 on every network): a deposit into BRC2.0 |
unwrap |
brc20prog-withdraw-inscribe and brc20prog-withdraw-transfer, the two steps of a withdrawal (add type=brc20prog-withdraw-transfer for the withdrawals alone) |
brc20prog |
the BRC2.0 deploy, call and transact inscriptions and transfers |
prog_transfer |
/v1/brc20/wallet/events only: the wallet's BRC2.0 token transfers (below) |
With both type and category, an event passes both. A ticker's events are
those whose tick is the ticker. A wallet's events are those where it is a
party (deployer, minted, source, spent, predeployer): for
pkscript, the party's *_pkScript field is that pkScript; for address,
the party's *_wallet field is that address. address is a Bitcoin address
or an EVM address that answers as its mapped Bitcoin address (an unmapped one
has no inscription events; with transfers asked for, it lists its BRC2.0
transfers), and pkscript is hex. /v1/brc20/deploys lists the whole
network's deploy and predeploy events, or with category the events of those
categories (every wrap, say). The feeds page by key: before_id is the
previous page's next_before_id, and a page holds the events with a lower
id, so pages neither repeat nor skip events as new ones arrive. has_more
tells whether older events exist; next_before_id is null on the last page.
BRC2.0 transfers in the wallet feed. With include_prog_transfers=true,
or category listing prog_transfer, /v1/brc20/wallet/events also lists
the wallet's BRC2.0 token transfers: the rows of brc20_prog_transfers from
or to its EVM address, the one evm_addresses maps its Bitcoin address to
(for pkscript, the address the pkScript encodes), or the EVM address asked
for. A Bitcoin address without an EVM address lists its events alone. A
transfer is
{"id": null, "block_height": 840000, "block_time": 1713571767,
"inscription_id": null, "event_type": "brc20prog-token-transfer",
"ticker_decimals": 18,
"event": {"tick": "ordi", "amount": "1000000000000000000",
"tx_hash": "0x…", "log_index": 3, "contract_address": "0x…",
"from": "0x…", "to": "0x…", "direction": "out",
"counterparty": {"evm_address": "0x…", "address": "bc1q…"}}}
with lowercase hex addresses, tick the ticker as brc20_prog_transfers
stores it and amount in the token's raw units. direction is out when
the wallet sends (a transfer to itself is one out row) and in when it
receives; the counterparty's address is its Bitcoin address from
evm_addresses, null for an unmapped one. A type filter keeps events of
that type, so it leaves the transfers out. Without either parameter the
answer lists events alone, as above. The transfers are complete once the
BRC2.0 transfers fill finishes: while brc20_prog_transfers_fill exists,
older transfers may be missing.
The wallet feed also pages by block, which a page with transfers needs (it
refuses before_id): before=<block_height>:<rows> is the previous page's
next_before, and a page holds the rows below that block plus the rows of
that block after its first rows. The rows run newest block first, and in a
block in one fixed order: its events by id descending, then its transfers by
(tx_hash, log_index) descending. next_before is the page's last row's
block and the count of that block's rows given so far over all pages (null
on the last page), so the same cursor names the same position on every
database with the same blocks, whatever its event ids. before and
before_id together answer 400, and a page that lists transfers has a null
next_before_id.
Each page costs the same at any depth, an index range scan from the cursor.
A ticker's events come from the (event ->> 'tick', id) index, with a
partial copy per rare category (deploy, wrap, unwrap); the network's
from partial (id) indexes per rare category (deploy, wrap, unwrap,
brc20prog); a wallet's from brc20_event_parties, one row per party
pkScript of each event (bytea, primary key (pkscript, event_id)), which the
indexer writes in the transaction that writes the events and deletes with
them on a reorg, in both modes. An address is read as the pkScript it
encodes, and an event of that pkScript passes when one of its *_wallet
fields is the address as given; the indexer writes each wallet field from its
party's pkScript, so this names the events the wallet fields name, and the
same pkScript in another network's form names none. A category is
brc20_event_category(event_type, event) and a party list
brc20_event_party_pkscripts(event), SQL functions db_init.sql creates. A
filter without its own index (a ticker's mint page, say) reads the rows
until the page fills. A before page reads the wallet's rows of the
cursor's block (the parties key within the block's id range, and the
transfers of that one block), skips the first rows of them, then reads
below the block: the parties key below the last event id under the block,
and the transfers from the (from_address, block_height, tx_hash, log_index)
and (to_address, …) indexes, merged newest block first.
Balance history. /v1/brc20/wallet/balance_history lists a wallet's
balance of one ticker after each change, newest first: one row
{"id","block_height","block_time","overall_balance","available_balance"}
per row of brc20_historic_balances, with the result's decimals (18) and
ticker_decimals. address and pkscript name the wallet as on
/v1/brc20/wallet/events (by address, a row passes when its wallet is the
address as given). It pages by key with before_id as the feeds do, and
each page is a backward range scan of the (pkscript, tick, block_height)
index from the cursor's block. An unknown ticker answers 404.
Events by inscription. POST /v1/brc20/events_by_inscriptions takes the
body {"inscription_ids":["<txid>i<index>",...]} with 1 to 500 inscription
ids (64 hex digits, any case, i and a 32-bit index) and answers
{"inscriptions":[{"inscription_id","events"}],"block_height"}, one entry
per requested id in the request's order (a repeated id answers each time).
Each events list is what /v1/brc20/event?inscription_id= answers for that
id: its rows of brc20_events and brc20_light_events by id, each the
stored event object with event_type and inscription_id set, empty for an
id without events. block_height is the module's height, read in one
snapshot with the events. Answers name ids in lowercase.
Bitmap and SNS lookups. A bitmap is {"inscription_id", "inscription_number","bitmap_number","block_height"} and a name is
{"inscription_id","inscription_number","name","namespace","block_height"},
where block_height is the registering block and namespace is the part of
the name after its dot. /v1/bitmap/search lists the bitmaps whose decimal
number starts with prefix (1 to 10 digits), ascending by number.
/v1/sns/search lists the names that start with prefix, bytewise ascending,
optionally within one namespace; the prefix and namespace are lowercased as
SNS stores names (the result's prefix and namespace are those lowercase
forms), and %, _ and \ match themselves. Both page by key:
after is the previous page's next_after, has_more tells whether more
follow and next_after is null on the last page. POST /v1/sns/by_inscriptions
takes the same body as /v1/brc20/events_by_inscriptions and answers
{"names":[{"inscription_id","name"}],"block_height"}, one entry per
requested id in the request's order, name being what
/v1/sns/by_inscription answers for the id or null for one that registered
no name; block_height is the module's height, read in one snapshot with the
names.
Rune, holder and wallet routes
The generic runes routes (/v1/runes/rune, /v1/runes/runes,
/v1/runes/etchings, /v1/runes/rune/holders, /v1/runes/wallet/balances,
/v1/runes/rune/events and /v1/runes/wallet/events) answer
{"error":null,"result":...} with the database's block_height, as the
brc20 ticker routes do. A missing or invalid parameter answers
400 {"error":"<reason>","result":null}, and an unknown rune answers
404 {"error":"rune not found","result":null}. On a database the runes
module has not built its API tables and indexes in (it builds them when
opi-indexer run starts), they answer
503 {"error":"the runes API tables are not built yet; start opi-indexer run once","result":null},
as does the parity route /v1/runes/holders, which reads runes_current_balances; the other
parity routes do not need these tables. An address is read as the pkScript it
encodes on the database's network: one that does not parse, belongs to another
network or encodes a script type without an address form answers no rows.
Lists take limit (default
100, at most 500). rune and search are at most 128 bytes and after
at most 256; the other bounds are those of the ticker routes.
Runes. rune names a rune by its id (block:tx) or its name, spaced
(• or .) or not, in any case, read with ord's own parsers: uncommongoods,
UNCOMMON•GOODS and uncommon.goods find the same rune. A rune's identity
is its unspaced name, so any spacing of its letters finds it, and every
answer carries the rune's own spaced_rune_name. /v1/runes/rune answers rune_id, rune_name
(the letters), spaced_rune_name, number, divisibility, symbol,
spacers, etching, etching_block_height, timestamp, turbo,
premine, mints, burned, supply (the premine plus mints times the
mint amount), max_supply (the premine plus the mint cap times the mint
amount), terms (amount, cap, height_start, height_end,
offset_start, offset_end; null without mint terms), mint_progress
(mints over the cap, null without a cap) and holders. Amounts are raw
integers as strings with divisibility fractional digits.
/v1/runes/runes lists the same objects. sort is holders (default),
supply, mint_progress (a rune without a mint cap sorts as -1: last in
desc, first in asc) or
etching_height; order is desc (default) or asc; ties order by rune
number in the same direction. search keeps the runes whose name starts
with it: written without spacers it matches the letters (UNCOMMONG finds
UNCOMMON•GOODS), with spacers the spaced name (UNCOMMON•G finds
UNCOMMON•GOODS, not UNCOMMONG•OODS). /v1/runes/etchings lists the
same objects newest first, by rune number descending (a rune's number is its
place in etching order), and pages by before_number, the previous page's
next_before_number, as the event feeds page by before_id.
Holders and wallet balances. A holder is a pkScript with a positive
balance of the rune over its unspent outpoints, as
{"address","pkscript","balance"} (address is null for a script without
one). The runes module keeps these balances in runes_current_balances and
their count per rune in runes_holders, in each block's transaction and on
every rollback (see Runes Indexer). /v1/runes/rune/holders orders by balance, largest first,
then by pkScript, descending. /v1/runes/wallet/balances takes address or
pkscript (hex) and answers one row per rune the wallet holds, by rune
number: {"rune_id","rune_name","spaced_rune_name","number","divisibility", "symbol","balance"}. A wallet the database does not know answers an empty
list. These lists and /v1/runes/runes page by key: after is the previous
page's next_after, an opaque cursor, and a page holds the rows after it.
Event feeds. An event is {"id","block_height","block_time", "event_type","txid","outpoint","pkscript","address","rune_id","rune_name", "spaced_rune_name","divisibility","amount"}. block_time is the block's
time in seconds, null for a height whose block hash row pruning removed.
event_type is the name from runes_event_types (input,
new-allocation, mint, output, burn), and type keeps one of them.
category keeps one or more categories, comma-separated: etch
(new-allocation), mint, transfer (input and output) and burn;
with type too, an event must pass both. The answer echoes the filters as
event_type and category.
outpoint, pkscript and address are set for input and output
events. A rune's feed lists the events of its id; a wallet's feed, by
address or pkscript, lists the input and output events of its
outpoints, and rune keeps those of one rune (echoed as rune_id; an
unknown rune answers 404). Both page by before_id, as the brc20 feeds do.
A filter applies to the rows the feed's index walks (a rune's events, or a
wallet's), so a filter that keeps few of them reads more rows per page.
Inscription and output routes
The inscriptions routes (/v1/inscriptions/inscription,
/v1/inscriptions/wallet, /v1/inscriptions/outpoint and
POST /v1/inscriptions/outpoints) and POST /v1/outputs answer
{"error":null,"result":...}. A missing or invalid parameter or body
answers 400 {"error":"<reason>","result":null}, and an unknown inscription
answers 404 {"error":"inscription not found","result":null}. They read
the inscriptions module's current-state table: one row per bound
inscription at its current location, kept per block and on every rollback.
Unbound inscriptions have no location and are not listed; a burned one stays
on its OP_RETURN output with a null address; cursed ones are listed with a
negative number.
Indexed height. Every answer carries indexed_height, the highest block
the answer covers: the rows and the height come from one database snapshot.
An output confirmed above indexed_height is unknown, not clean, so a
wallet treats it as unsafe to spend until the node catches up.
Inscriptions. An inscription is {"inscription_id","number", "sequence_number","content_type","media_type","charms","cursed","outpoint", "offset","pkscript","address","genesis_height","last_moved_height"}.
content_type is the envelope's content type as inscribed and media_type
the same lowercased without parameters (both null without one), charms is
ord's charm bitfield, cursed tells whether number is negative, offset
is the inscribed sat's offset in the output and pkscript the output's
script in hex. /v1/inscriptions/inscription takes id (<txid>i<index>,
any case) or number, exactly one.
Wallet inscriptions. /v1/inscriptions/wallet takes address or
pkscript (hex) and lists the inscriptions on the wallet's outputs, newest
first by sequence number. content_type keeps one media type, compared
lowercased and without parameters: exactly (text/plain), or by prefix when
it ends with / (image/). from_height and to_height bound the genesis
height, both inclusive, and cursed=true or cursed=false keeps the cursed
inscriptions or the others. The result echoes the filters as applied. The
list pages by key: limit (default 100, at most 500) and after, the
previous page's next_after; has_more tells whether more follow and
next_after is null on the last page. A wallet the database does not know
answers an empty list.
Addresses. An address derives from the output's pkScript and the
database's network, for P2PKH, P2SH, P2WPKH, P2WSH and P2TR scripts (null
for any other). An address parameter resolves to the pkScript it encodes,
in any case; one that does not parse, belongs to another network or encodes
another script type matches nothing.
History. /v1/inscriptions/inscription/history takes id or number
and lists the inscription's creation and transfers, newest first.
/v1/inscriptions/wallet/history takes address or pkscript and lists
the wallet's stays, newest receipt first: each is
{"inscription","received","sent"}, the event that put an inscription on
the wallet and the inscription's next transfer (null while the wallet holds
it). An event is {"id","block_height","block_time","event_type", "old_outpoint","old_offset","old_pkscript","old_address","new_outpoint", "new_offset","new_pkscript","new_address"}, event_type creation or
transfer, the old_ fields null for a creation and for a transfer whose
previous event the node no longer keeps. A text/plain or application/json
inscription's history holds its creation, its latest transfer, and each
earlier transfer until the transfer after it is 1,000 blocks deep, so a
wallet's history lists such an inscription only while it holds it or for
1,000 blocks after it moved on; every other inscription's history is
complete. Both page by key: limit (default 100, at most 500) and
before_id, the previous page's next_before_id. A node pruned with
OPI_PRUNE keeps the same events, so both answer as on a full node;
block_time is null below the pruned window.
Outputs. An outpoint is <txid>:<vout>: 64 hex digits, any case, and a
32-bit output index. /v1/inscriptions/outpoint?outpoint= answers
{"outpoint","inscriptions","indexed_height"}, the inscriptions by offset.
POST /v1/inscriptions/outpoints takes the body
{"outpoints":["<txid>:<vout>",...]} with 1 to 500 outpoints and answers
{"outpoints":[{"outpoint","inscriptions"}],"indexed_height"}, one entry
per requested outpoint in the request's order; an output without
inscriptions has an empty list. Answers name outpoints in lowercase.
POST /v1/outputs takes the same body and answers, per outpoint, its
inscriptions and its runes: {"outputs":[{"outpoint","inscriptions", "runes"}],"indexed_height","heights":{"inscriptions","runes"}}. A rune is
{"rune_id","rune_name","spaced_rune_name","divisibility","symbol", "amount"}, from the runes module's unspent outpoints, amount a raw
integer as a string with divisibility fractional digits. indexed_height
is the lower of the two modules' heights and null while either has no
block. The route needs both inscriptions and runes in OPI_MODULES:
without one it answers
404 {"error":"runes is not enabled on this node","result":null} (or
inscriptions), since an output holding what the missing module tracks
would look clean. A wallet that builds transactions from its own node's
listunspent sends its candidate outputs here and spends only those with
two empty lists, confirmed at or below indexed_height.
Push feed
GET /v1/stream pushes each block's events as server-sent events
(text/event-stream), once the block has the confirmations the subscriber
asks for, and rolls the subscriber back when a reorg replaces a block it has
received. It carries brc20 (the block's events, in the event feeds' form),
bitmap (the bitmaps the block registered) and sns (the names the block
registered), each in its lookup route's form, and inscriptions (the block's
creations and transfers). runes is not on the stream yet.
| Parameter | Meaning |
|---|---|
modules |
comma-separated brc20, bitmap, sns, inscriptions; left out, every enabled one. A module that is unknown, disabled or runes answers 400 |
confirmations |
block H is sent once its module's indexed tip reaches H + confirmations - 1, so 1 sends each block as soon as it is indexed; from 1 to STREAM_MAX_CONFIRMATIONS, default STREAM_DEFAULT_CONFIRMATIONS |
from_height |
replay the stored blocks from this height on, in order; below a module's oldest kept block it answers 400 with that height. Left out, each module starts with its first block not yet due |
| Event | id |
Data |
|---|---|---|
block |
the stream's position | {"module","height","hash","block_time","events":[...]}; brc20's block adds "decimals":18, the fractional digits of its raw amounts, and bitmap's and sns's block_time is null. An inscriptions event is {"id","block_height","event_type","sequence_number","inscription_id","number","cursed","content_type","media_type","old_outpoint","old_offset","old_pkscript","old_address","new_outpoint","new_offset","new_pkscript","new_address"}: event_type is creation (the old_ fields null) or transfer, in the order ord applied them |
rollback |
the stream's position | {"module","height"}: the module's blocks above height, the last block kept, were replaced; the replacement blocks follow |
heartbeat |
{"tips":{"<module>":<height>}}, each module's indexed tip, every STREAM_HEARTBEAT_SECS while no block is due |
|
error |
{"error"}, the last event of a stream that ends early, sent between events |
A block or rollback event's id is the client's position after it in every
module of the stream: <module>:<height>:<hash> per module, comma-separated
in module name order, such as bitmap:328270:00…ab,brc20:328270:00…ab,sns:328269:00…cd.
The height is the last one the client holds; the hash is empty for a module
that has sent no block at or below it yet (a stream that started above it).
The header Last-Event-ID (which an EventSource sends when it reconnects)
resumes each module it names after its position, checked against that
module's own database: a module whose block there was replaced gets a
rollback first, and one whose database has not reached that height yet (a
node further behind) waits for it. A position still waited for after
STREAM_RESUME_WAIT_SECS, for its block or for its module's poller to read
the reorg that replaced it, is taken as stale: the module rolls back 1000
blocks, as for a reorg the process did not see, and the API logs it. A module of the stream the id leaves
out starts at from_height, or with its first block not yet due. The id
takes precedence over from_height; a position below a module's oldest
kept block answers 400. One module's <module>:<height>:<hash> is a valid
id of its own. A frame's id line comes last, so a block cut off by a
dropped connection carries no id, and a resume sends that block again.
One block event comes per block and module, with every event of the block,
however many; it is read and sent in pages. The blocks of a stream's modules
come by height, then by module name, so a module whose tip is behind holds
the others back; subscribe to it on a stream of its own to let the others go
on. Each module's blocks wait for that module's own tip.
A reorg shows as a replaced hash in a module's block-hash table. When the
last block the stream sent is no longer stored, the stream sends rollback
to the newest block it sent that still is, found among the last 1000 it
sent, then the new blocks. A block is due once the block-hash row
confirmations - 1 above it is stored, read with the block itself. Each
poller remembers the hashes reorgs replaced, so a rollback below the
blocks a stream sent, such as one for a Last-Event-ID taken before a
reorg, names the fork exactly when this process saw the reorg; while the
module's poller has not read a reorg yet, the stream waits for it. Past
what the poller saw (the process started after the reorg), the stream rolls
back 1000 blocks, the deepest rollback the indexer walks, and replays from
there.
The API learns of new blocks by polling: one poller per module and process,
whatever the number of subscribers, reads the module's highest block-hash row
every STREAM_POLL_MS, and the new rows when it changes. A subscriber holds
no database connection while it waits for a block. The streams read a module
database with at most as many connections at once as the holders snapshots
may take (4, and at most half of DB_MAX_CONNECTIONS), so replaying streams
leave connections to the other routes. A stream that cannot queue a message
for its client for STREAM_HEARTBEAT_SECS ends with an error event; the
client resumes with its Last-Event-ID. Beyond STREAM_MAX_SUBSCRIBERS
open streams, a request answers
503 {"error":"too many stream subscribers","result":null}; the cap counts
every client together, so one client can take every place the rate limit
lets it open. A stream's buffer holds STREAM_BUFFER chunks, a brc20 page
of 100 events being about 60 KB, so at most about 1 MB per stream with the
default. On
shutdown every stream ends at once, so its connection closes within the
10 second grace; the header-read timeout applies only until a request's
headers have arrived, so it never cuts a stream.
STREAM_MAX_CONFIRMATIONS is at most 1000, the smallest OPI_PRUNE: a
pruned bitmap, sns or inscriptions database keeps the block hashes of at least the last
1000 blocks, so every block a subscriber may wait for is still stored.
$ curl -N 'http://127.0.0.1:8000/v1/stream?modules=brc20,sns&confirmations=3&from_height=328270'
event: block
data: {"module":"brc20","height":328270,"hash":"000000b1…","block_time":1761700000,"decimals":18,"events":[{"id":5120001,"block_height":328270,"block_time":1761700000,"inscription_id":"…i0","event_type":"mint-inscribe","ticker_decimals":18,"event":{…}}]}
id: brc20:328270:000000b1…,sns:328269:
event: block
data: {"module":"sns","height":328270,"hash":"000000b1…","block_time":null,"events":[]}
id: brc20:328270:000000b1…,sns:328270:000000b1…
event: heartbeat
data: {"tips":{"brc20":328275,"sns":328275}}
event: rollback
data: {"module":"brc20","height":328272}
id: brc20:328272:000000a7…,sns:328273:000000d2…
event: block
data: {"module":"brc20","height":328273,"hash":"000000c4…","block_time":1761701800,"decimals":18,"events":[]}
id: brc20:328273:000000c4…,sns:328273:000000d2…
API configuration
opi-indexer api reads the .env of its working directory (or an ancestor), or
the file OPI_ENV_FILE names (set it as a process environment variable, since
it is read before the file is loaded); variables already in the environment
win, and a missing file is ignored.
| Variable | Meaning |
|---|---|
OPI_MODULES |
the modules to serve, as for opi-indexer, default brc20 |
OPI_ENV_FILE |
alternative .env path; only works as a process environment variable |
DB_*, BITMAP_DB_*, SNS_DB_*, RUNES_DB_*, INSCRIPTIONS_DB_* |
the module databases; the database name is required for each enabled module |
DB_MAX_CONNECTIONS |
maximum connections per module database pool, default 10 |
API_HOST |
listen address, default 127.0.0.1 |
API_PORT |
listen port, default 8000 |
API_TRUSTED_PROXY_CNT |
number of trusted proxies (such as nginx) in front of the API, default 0 |
RATE_LIMIT_ENABLE |
true turns the rate limiter on, default false |
RATE_LIMIT_WINDOW_MS |
rate limit window in milliseconds, default 900000 |
RATE_LIMIT_MAX |
requests per client per window, default 100 |
API_SNAPSHOT_TIMEOUT_MS |
how long a holders snapshot may stream, in milliseconds, default 600000 |
STREAM_POLL_MS |
how often each module's block hashes are read for the push feed, in milliseconds, from 10, default 1000 |
STREAM_DEFAULT_CONFIRMATIONS |
the confirmations of a stream that names none, default 1 |
STREAM_MAX_CONFIRMATIONS |
the most confirmations a stream may ask for, at most 1000, default 100 |
STREAM_MAX_SUBSCRIBERS |
the most streams open at once, default 100; 0 refuses every stream |
STREAM_HEARTBEAT_SECS |
the heartbeat interval, and how long a stream may be unable to queue a message before it ends, default 15 |
STREAM_RESUME_WAIT_SECS |
how long a resumed module's position may wait for its block to be stored or its reorg to be read before it is taken as stale and rolled back 1000 blocks, from 1 to 86400, default 300 |
STREAM_BUFFER |
the chunks (a block's head, a page of 100 events of up to about 60 KB, or a small event) a stream queues for its client, default 16, about 1 MB at most |
The DB_*, BITMAP_DB_*, SNS_DB_*, RUNES_DB_* and INSCRIPTIONS_DB_*
variables are the same ones opi-indexer run reads (USER and HOST default to postgres and
localhost, PORT to 5432, SSL is on only when exactly true).
Run opi-indexer api in place of the Node API or the four per-module API
processes (ports 8000-8003) and point reverse proxies at API_PORT. Route
paths are unchanged.
Setup
For detailed installation guides:
- Ubuntu: installation guide
Modules use PostgreSQL as DB. Before running the indexer, setup a PostgreSQL DB (all modules can write into different databases as well as use a single database).
Build opi-indexer:
cargo build --release --locked -p opi-indexer
Setup the .env file and DBs
Copy .env_sample to .env in the repository root and fill it in, as described in Configuration and API configuration. The BRC-20, Bitmap, SNS and Runes databases are created from the schema on first start, and OPI_MODULES selects the modules to run. opi-indexer brc20 reset deletes all BRC-20 data and starts fresh.
Run
Main Meta-Protocol Indexer / BRC-20, Bitmap, SNS and Runes Indexers
With the brc20 module, set BRC20_PROG_DB_PATH; the brc20-prog engine runs inside opi-indexer and needs no separate server.
target/release/opi-indexer run
API
target/release/opi-indexer api
Tests
SQLX_OFFLINE=true cargo test --workspace
The opi-api crate's database tests run when OPI_API_TEST_DATABASE_URL
(brc20) and OPI_API_TEST_BITMAP_URL, OPI_API_TEST_SNS_URL and
OPI_API_TEST_RUNES_URL name indexed databases, and are skipped otherwise.
Developer note: sqlx offline data
opi-api and opi-brc20 check their SQL at compile time with sqlx macros. The
committed .sqlx directory of each crate lets SQLX_OFFLINE=true cargo build
work without a database. After changing a query, regenerate that crate's data
with cargo sqlx prepare (sqlx-cli 0.9) against a database that holds the
schema, then verify it with cargo sqlx prepare --check. The DATABASE_URL
needs an explicit user.
For opi-api, build a throwaway database from the six schemas plus the one
table the API reads that no db_init.sql creates (brc20_extras_block_hashes),
whose DDL goes in a local file api_extra_tables.sql:
CREATE TABLE public.brc20_extras_block_hashes (
id bigserial NOT NULL, block_height int4 NOT NULL, block_hash text NOT NULL,
CONSTRAINT brc20_extras_block_hashes_pk PRIMARY KEY (id));
createdb -h /tmp opi_api_sqlx_prepare
for f in crates/opi-brc20/src/database/sql/db_init.sql crates/opi-bitmap/src/db_init.sql \
crates/opi-sns/src/db_init.sql crates/opi-runes/src/db_init.sql \
crates/opi-inscriptions/src/db_init.sql crates/opi-utxos/src/db_init.sql \
api_extra_tables.sql; do
psql -h /tmp -d opi_api_sqlx_prepare -X -q -v ON_ERROR_STOP=1 -f "$f"
done
cd crates/opi-api
export DATABASE_URL='postgres://<user>@localhost/opi_api_sqlx_prepare?host=/tmp'
cargo sqlx prepare
cargo sqlx prepare --check
cd ../.. && dropdb -h /tmp opi_api_sqlx_prepare
For opi-brc20, create a database from crates/opi-brc20/src/database/sql/db_init.sql the same way and run cargo sqlx prepare and cargo sqlx prepare --check in crates/opi-brc20.
The parity tests in tools/parity/tests compare the modules with the Python reference implementations. They need a local Postgres:
OPI_TEST_PG=1 uv run --with 'psycopg[binary]' --with pytest --with json5 python -m pytest tools/parity/tests
tools/parity/api_compare.py replays every API route, bad-parameter cases and request quirks against two running APIs by base URL, for example a release of the API and a new build, and diffs status, headers and body (any difference gives exit code 1). It needs only the Python standard library. Run it on databases nobody is writing to:
python3 tools/parity/api_compare.py --pair js-rust \
--js http://127.0.0.1:18200 --rust http://127.0.0.1:18201
--js names the reference and --rust the candidate. --rate-limit replays the rate-limit sequence on two freshly started servers; the script's docstring lists the remaining options.
tools/parity/brc20_hash_compare.py --a <postgres url> --b <postgres url> compares the event hash, cumulative event hash, trace hash and cumulative trace hash of two brc20 databases at every common height (exit 0 equal, 1 difference, 2 usage or database error).
Update
- Stop all indexers and apis (preferably starting from main indexer but actually the order shouldn't matter)
- Update the repo (
git pull) - Recompile opi-indexer (
cargo build --release --locked -p opi-indexer) - Re-run the indexer and the api
ord dependency
ord (=0.29.1) and ordinals (=0.0.17) come from crates.io. The tests'
mock bitcoind, mockcore, is not published, so it is a git dev-dependency on
the matching ord tag (https://github.com/ordinals/ord, tag 0.29.1). mockcore
depends on ord by path inside that repository; the workspace's
[patch."https://github.com/ordinals/ord"] resolves that ord to the crates.io
release, so the tree holds one ord. An ord bump moves the crates.io versions,
the mockcore tag and the patch together.
redb is pinned to =3.1.3, the version ord 0.29.1's own lockfile holds, so
the journal and ord's index use the redb release ord is tested with. bitcoin
resolves to 0.32.102, also ord's locked version. cargo tree -d shows one copy
of each of ord, ordinals, bitcoin and redb.
An ord index has a schema version: ord 0.29.1 (schema 34) refuses an index written by an older ord, and redb 3 refuses a file written in redb 2's format. An ord data dir or journal written by ord 0.23.2 (schema 30) or by redb 2 does not open; delete both and index again. A new ord release with a new schema likewise needs a fresh ord data dir and journal.
Dependency notes
Dependencies track their latest releases, except:
brc20-prog(incrates/opi-brc20) stays withinBRC20_PROG_VERSION_REQUIREMENT(~0.17.0);opi-indexerlinks brc20-prog as a library (crates/opi-indexerpins the same release).redbstays at=3.1.3, ord's locked version (see above), although redb 4 is released.bitcoinfollows ord's lock (0.32.102) rather than a 0.33 pre-release.
reqwest 0.13 uses rustls (aws-lc-rs with the platform certificate verifier)
as its default TLS backend; ord pulls the same reqwest with
default features. opi-brc20's sqlx also uses rustls (tls-rustls), so
neither binary links native-tls.
Upstream assumptions
The crash-safety design rests on four properties of ord. Each ord bump re-checks them against the new release's source; ord 0.29.1 holds all four.
A1: every commit follows a getblockchaininfo barrier. In
Updater::update_index (src/index/updater.rs), each block is followed by:
uncommitted += 1;
if uncommitted == self.index.settings.commit_interval()
|| (!self.index.settings.integration_test()
&& Reorg::is_savepoint_required(self.index, self.height)?)
{
self.commit(wtx, utxo_cache)?;
--commit-interval 4294967295 makes the first term false, so
Reorg::is_savepoint_required runs, and it calls
index.client.get_blockchain_info() (src/index/reorg.rs) on the updater
thread before any commit decision. It returns early without the call only when
the index durability is Durability::None. The only other commit is if uncommitted > 0 { self.commit(wtx, utxo_cache)?; } after the loop, which
follows the last block's barrier. The gate proxy (opi-source/src/proxy.rs)
holds that call until the stager (opi-source/src/stager.rs) has synced the
raw log.
A2: getblockhash error -8 ends the block stream. The fetcher thread's
get_block_with_retries maps client.get_block_hash(height).into_option()
through BitcoinCoreRpcResultExt::into_option (src/index.rs), which turns
RpcError { code: -8, .. } into Ok(None), and Ok(None) => break ends the
stream. The proxy answers -8 above the chunk end.
A3: event shapes and order. src/index/event.rs defines the Event enum
that RawEvent's exhaustive From<Event> (opi-source/src/raw_event.rs)
mirrors, so a changed variant fails to compile. Finalize
(opi-source/src/journal/finalize.rs) relies on emission order within a block
(transactions in block order, coinbase last; fee-bound inscriptions emitted at
coinbase time) and on InscriptionCreated.parent_inscription_ids holding the
parents ord accepted. In 0.29.1 that list skips a purported parent that has no
inscription entry yet; 0.23.2 panics on such a parent, so no block indexed by
the fork carries one.
A4: durable, non-test settings. ord opens its index with
Durability::Immediate outside its own unit tests, and integration_test
defaults to false. ord_settings passes --commit-interval 4294967295,
passes --index-runes when runes is enabled, and never sets
--integration-test. ORD_* environment variables and an ord.yaml in the
data dir are merged by Settings::load, so spawn_source checks the merged
settings (check_ord_settings in opi-source/src/ord_settings.rs) and refuses
to start when integration_test is on, the commit interval differs, or rune
indexing differs from the runes switch. ord stores its rune setting in the
index's statistics when it creates the index and reads it back on every open,
ignoring the flag, so check_ord_index compares Index::has_rune_index with
the switch after the open.
Inscription rules. The journal reproduces the fork's numbering and transfer
rules, which are built on ord 0.23.2. Between 0.23.2 and 0.29.1 ord changes no
curse, charm, numbering, pointer or fee rule. Envelope parsing recognizes tag
19 (property_encoding, odd, so it never curses), and inscription creation
adds gallery and collection bookkeeping that emits no events.
SNS indexing rules
The sns module (crates/opi-sns) indexes Sats Names by the written spec,
index-names and
mint-names. Where
the spec leaves a choice open, the rule below states the one opi-sns makes
(marked decision).
Inscriptions. Creations only, in ascending inscription number. An inscription counts when it is blessed (number >= 0, decision) and its content type is
text/plainorapplication/json, alone or followed by;parameters (decision). The content type is matched byte for byte and is case-sensitive (decision).UTF-8. Content that is not valid UTF-8 registers nothing.
Names. The content is parsed as JSON5.
- If it does not parse, the whole text is the candidate name.
- If it parses, the value must be an object with
p == "sns",op == "reg"and a stringname, which is the candidate. Any other value registers nothing, so1.5,"x.sats"andtrueregister nothing (decision: no raw-text fallback for parsed values). - The candidate is lowercased and reduced to its first whitespace-separated
token: leading whitespace is trimmed, then the text is cut at the next
whitespace, so
" alice.sats"registersalice.sats(decision: the spec's trim step only does anything if the cut skips leading whitespace). - An escaped line break or other whitespace inside a JSON
name("\nalice.sats") is whitespace, and is trimmed or cuts like any other (decision). A raw line break inside a string fails JSON5 parsing (rule 7). - It must contain exactly one
., with text on both sides (decision: both parts non-empty). The part after the.is the namespace, stored asdomain.
Namespaces. Only a JSON5 object with
p == "sns",op == "ns"and a stringns. It is lowercased and must be non-empty, without.and without whitespace (decision). When one inscription yields both a name and a namespace, the name wins.Whitespace is the Unicode
White_Spaceproperty (decision: the spec says "whitespace or newline").Unicode version. Lowercasing (the full mapping, with final sigma) and
White_Spacecome from committed Unicode 17.0.0 tables (crates/opi-sns/src/unicode_tables.rs), so results do not depend on the Rust toolchain (decision).tools/parity/unicode_tables.pyregenerates them with Python 3.15.JSON5 grammar. JSON5 1.0 as Python's json5 0.12.0 implements it (decision), with these details:
- nesting deeper than 128 arrays or objects is a parse failure; the depth counts every value in the text, including one a repeated key later replaces;
- raw line breaks inside strings are a parse failure;
- trailing commas are allowed;
- a repeated key keeps its first position and its last value;
- a number that does not convert is a parse failure: a sign before hex, a fraction or exponent without digits, or an integer of more than 4300 digits.
crates/opi-sns/src/json5.rslists the full grammar.Surrogates. JSON5 strings are ES5 strings, so a
\uhigh surrogate directly followed by a\ulow surrogate is one character (\uD83Dfollowed by\uDE00is 😀); a\line continuation between the two halves does not break the pair. A name or namespace that holds any other surrogate (unpaired, reversed, or followed by a non-surrogate) is skipped (decision).Storage limits. A name or namespace that holds
\0, or is longer than 2048 UTF-8 bytes after lowercasing, is skipped (decision: Postgrestextcannot store\0).First is first. The first inscription of a name or namespace registers it. Later ones insert nothing and emit no event. Events are
register;<inscription_id>;<name>;<namespace>andns_register;<inscription_id>;<namespace>, joined with|. Each block hashes them with sha256 and chains the hash onto the previous block's cumulative hash.Versions. Reports send
opi-sns-names-full-node v3.0.0withdb_version5. A database with anotherdb_versionis refused and must be indexed from scratch.
tools/parity/sns_spec_vectors.py implements these rules independently in
Python, and crates/opi-sns/tests/spec_vectors.json holds its results. The
module's tests require the Rust rules to match every vector.
Explore related projects
Loading…