### Install stellar-core from SDF apt repository Source: https://github.com/stellar/stellar-rpc/blob/main/cmd/stellar-rpc/README.md Lists available stellar-core packages and installs a specific version. Requires adding the SDF apt repository first. ```bash apt-cache policy stellar-core sudo apt-get install stellar-core= ``` -------------------------------- ### Run RPC server with config file Source: https://github.com/stellar/stellar-rpc/blob/main/cmd/stellar-rpc/README.md Starts the RPC server using a specified configuration file path. ```bash ./stellar-rpc --config-path ``` -------------------------------- ### Example usage of SelectMode Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/api-reference/cli.md Example call to SelectMode with os.Args[1:] and os.LookupEnv. On error, prints the error to stderr and exits with status 1. ```go mode, err := cli.SelectMode(os.Args[1:], os.LookupEnv) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } ``` -------------------------------- ### startStreaming: backfill and serve/ingest loop Source: https://github.com/stellar/stellar-rpc/blob/main/design-docs/full-history-streaming-workflow.md Coordinates the streaming startup: backfills from the retention floor to the target chunk, then seeds the hot DB and starts the ingestion loop. Fails the run if the network tip is unreachable, so the daemon never serves behind an unknown frontier. Uses backfillTarget to compute the highest complete chunk to build. ```go func startStreaming(ctx context.Context, cfg Config) error { cat := openCatalog(cfg) cfg.Catalog = cat validateConfig(cfg) earliest := cat.EarliestLedger() lastCommitted := lastCommittedLedger(cat) // Step 1: backfill from the floor up to each pass's target chunk, leaving the // partial tip chunk to ingestion. Re-pass while the tip moves. backfilledThrough := int64(-1) for { tip, err := networkTip(cfg) if err != nil { return err // no tip, no pass: never serve behind an unknown frontier } target := backfillTarget(tip, lastCommitted) if target <= backfilledThrough { break // the tip stopped advancing the target: backfill is done } rangeStart := retentionFloorChunk(target, cfg.RetentionChunks, earliest) if rangeStart > target { break // floor pinned above the target (e.g. a first start with "now") } if err := executePlan(ctx, cfg, resolve(cfg, rangeStart, target)); err != nil { return err } lastCommitted = max(lastCommitted, chunkLastLedger(target)) backfilledThrough = target } resumeLedger := lastCommitted + 1 // Step 2: serve + ingest. Seed the lifecycle with the last complete chunk so // its first run clears crash/downtime leftovers while serving is already live. hotDB, err := openHotDBForChunk(cat, chunkID(resumeLedger)) if err != nil { return err } core := openCaptiveCore(cfg) // constructed here; starts on the loop's first pull if seed := lastCompleteChunkAt(resumeLedger - 1); seed >= 0 { notifyBoundary(seed) // no seed on a young network with no complete chunk } serveReads() go lifecycleLoop(ctx, cfg) return runIngestionLoop(ctx, cat, core, hotDB, resumeLedger) } // backfillTarget: the highest complete chunk a pass builds to — the last complete // chunk at max(tip, lastCommitted), except that a mid-chunk lastCommitted within // one chunk of the tip lowers it to the chunk below the resume point, leaving the // partial resume chunk to ingestion. The retention floor derives from this target, // so the floor never sits above what the pass actually builds. func backfillTarget(tip, lastCommitted uint32) int64 { target := lastCompleteChunkAt(max(tip, lastCommitted)) midChunk := lastCommitted != chunkLastLedger(chunkID(lastCommitted)) nearTip := int64(tip)-int64(lastCommitted) < LedgersPerChunk if nearTip && midChunk { target = lastCompleteChunkAt(lastCommitted) } return target } ``` -------------------------------- ### Usage example: rpcv2.ReadMethods with getLatestLedger Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/api-reference/methods.md Shows how to obtain a handler from rpcv2.ReadMethods and invoke it with a jrpc2.Request. The example retrieves the handler for protocol.GetLatestLedgerMethodName and calls it with a request context. ```go m := rpcv2.ReadMethods(cfg, registry, networkPassphrase, logger) rv := m[protocol.GetLatestLedgerMethodName] result, err := rv(ctx, &jrpc2.Request{Method: protocol.GetLatestLedgerMethodName}) ``` -------------------------------- ### Example bench.txt line for a scenario Source: https://github.com/stellar/stellar-rpc/blob/main/cmd/stellar-rpc/internal/rpcv2/bench/README.md Shows the Go benchmark format line written by `bench query` for each scenario. The name includes tier, type, and rps; fields include iterations, ns/op, percentiles, items/op, and dropped. The CPU profile for this scenario is cpu.ledgers.10rps.pprof. ```text BenchmarkQuery/tier=cold/type=ledgers/rps=10 600 812345 ns/op 790123 p50-ns 2345678 p99-ns 301234 handler-p50-ns 901234 handler-p99-ns 2400000 p99-from-due-ns 10 items/op 0 dropped ``` -------------------------------- ### startRPCv1Daemon: validate config and run rpcv1 daemon Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/api-reference/cli.md Validates the rpcv1 config and starts the daemon. Used by the root command of the rpcv1 mode. Requires a valid config; returns an error if validation fails. ```go func startRPCv1Daemon(cfg *v1config.Config) error { if err := cfg.Validate(); err != nil { return err } daemon.MustNew(cfg, supportlog.New()).Run() return nil } ``` -------------------------------- ### Install stellar-cli and stellar-xdr Source: https://github.com/stellar/stellar-rpc/blob/main/cmd/stellar-rpc/internal/integrationtest/infrastructure/docker/README.md Install the CLI and stellar-xdr to change limits in the upgrades/ directory. Uses pinned versions v23.0.0. ```bash cargo install --locked stellar-cli@v23.0.0; cargo install --locked stellar-xdr@v23.0.0; ``` -------------------------------- ### runRPCv2: require config path and optionally print runtime config Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/api-reference/cli.md Handles the rpcv2 root command. Requires --config-path or STELLAR_RPC_CONFIG_PATH; if --print-runtime-config is set, loads and prints the config as TOML instead of starting the daemon. ```go func (e *Entry) runRPCv2(cmd *cobra.Command, configPath string, printRuntimeConfig bool) error { if configPath == "" { return errors.New("rpcv2 mode needs a config file: pass --" + ConfigPathFlag + " or set " + ConfigPathEnv) } if printRuntimeConfig { cfg, err := v2config.LoadConfigWithFlags(configPath, cmd.Flags()) if err != nil { return err } return printTOML(cmd, cfg) } return e.startRPCv2(configPath, cmd.Flags()) } ``` -------------------------------- ### Packfile file layout diagram Source: https://github.com/stellar/stellar-rpc/blob/main/design-docs/packfile-library.md ASCII diagram showing the on-disk layout of a packfile: records, offset index (index groups, group directory, CRC32C), optional app data, and a 44-byte trailer. The indexBase marks the start of the offset index. ```text ┌──────────────────────────────────┐ offset 0 │ record 0 │ │ record 1 │ │ ... │ │ record N-1 │ ├──────────────────────────────────┤ indexBase │ offset index: index groups │ │ group directory │ │ CRC32C (4 bytes) │ ├──────────────────────────────────┤ (optional) │ app data │ ├──────────────────────────────────┤ │ trailer (44 bytes) │ └──────────────────────────────────┘ EOF ``` -------------------------------- ### Example: global gate in jsonrpc.NewHandler Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/api-reference/network.md Shows how to create an HTTP backlog queue limiter as a global gate when constructing a JSON-RPC handler. The limit comes from parameters and the logger is provided. ```go // Example: global gate in jsonrpc.NewHandler queueLimitedBridge := network.MakeHTTPBacklogQueueLimiter( rpc, globalQueueRequestBacklogLimiter, uint64(params.GlobalQueueLimit), params.Logger) ``` -------------------------------- ### Usage example: spec() with health and sendTransaction handlers Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/api-reference/methods.md Shows direct use of method constructors in specs.go. Pairs method names with their handlers: NewHealthCheck for getHealth and NewSendTransactionHandler for sendTransaction, including XDR decode options with MaxMemoryBytes. ```go spec(protocol.GetHealthMethodName, methods.NewHealthCheck(deps.RetentionWindow, deps.LedgerReader, deps.MaxHealthyLedgerLatency)), spec(protocol.SendTransactionMethodName, methods.NewSendTransactionHandler(deps.Daemon, deps.Logger, deps.LedgerReader, deps.NetworkPassphrase, xdr.DecodeOptions{MaxMemoryBytes: TransactionDecodeMaxMemory})), ``` -------------------------------- ### Optional storage split for ledgers on second NVMe Source: https://github.com/stellar/stellar-rpc/blob/main/docs/ARCHIVE-NODE-BETA-RUNBOOK.md Optional [storage] section that puts the 'ledgers' store on a second NVMe volume mounted at /data2, keeping events and everything else under /data. Set store paths before first start; changing them after data exists breaks data location. ```toml [storage] default_data_dir = "/data" ledgers = "/data2/ledgers" ``` -------------------------------- ### validateConfig: validate and pin earliest_ledger Source: https://github.com/stellar/stellar-rpc/blob/main/design-docs/full-history-streaming-workflow.md Validates configuration on startup, rejecting invalid workers, max_retries, or earliest_ledger values. On first start, resolves and pins earliest_ledger, requiring a reachable backend for 'now' and numeric floors. On restart, confirms the pinned value hasn't changed unless 'now' is used. ```go func validateConfig(cfg Config) { cat := cfg.Catalog if cfg.Workers < 1 { fail("workers must be > 0 (got %d)", cfg.Workers) } if cfg.MaxRetries < 0 { fail("max_retries must be >= 0 (got %d)", cfg.MaxRetries) } if cfg.EarliestLedger != "genesis" && cfg.EarliestLedger != "now" { n, err := parseUint32(cfg.EarliestLedger) if err != nil || n < GenesisLedger || n != chunkFirstLedger(chunkID(n)) { fail("earliest_ledger must be \"genesis\", \"now\", or a chunk-aligned "+ "ledger >= %d; got %q.", GenesisLedger, cfg.EarliestLedger) } } earliestStored, earliestPinned := cat.Get("config:earliest_ledger") if earliestPinned { // restart: confirm nothing changed, write nothing if cfg.EarliestLedger != "now" { // "now" on restart keeps the pinned floor want := uint32(GenesisLedger) if cfg.EarliestLedger != "genesis" { want = atoi(cfg.EarliestLedger) } if want != atoi(earliestStored) { fail("earliest_ledger changed: stored=%s, config=%s; wipe the data dir to change it.", earliestStored, cfg.EarliestLedger) } } return } // First start: resolve earliest_ledger, then pin it. "now" and a numeric // floor each need a reachable backend — "now" to resolve, a numeric floor to // reject one past the tip (it is pinned immutably, so it can't be checked later). var earliest uint32 switch cfg.EarliestLedger { case "genesis": earliest = GenesisLedger case "now": tip, err := networkTip(cfg) if err != nil { fail("earliest_ledger=now needs a reachable backend: %v", err) } earliest = chunkFirstLedger(chunkID(tip)) default: earliest = atoi(cfg.EarliestLedger) tip, err := networkTip(cfg) if err != nil { fail("a numeric earliest_ledger needs a reachable backend to validate against the tip: %v", err) } if earliest > tip { fail("earliest_ledger (%d) is past the network tip (%d)", earliest, tip) } } cat.Put("config:earliest_ledger", itoa(earliest)) } ``` -------------------------------- ### ReadRange Source: https://github.com/stellar/stellar-rpc/blob/main/design-docs/packfile-library.md Returns an iterator over count contiguous items starting at start. Each yielded []byte is valid only until the next iteration and only inside the for-range body. ```APIDOC ## ReadRange ### Description Returns an iterator over count contiguous items starting at start. Each yielded []byte is valid only until the next iteration and only inside the for-range body. ### Method ReadRange ### Signature func (r *Reader) ReadRange(start, count int) iter.Seq2[[]byte, error] ### Parameters - **start** (int) - Required - Starting position. - **count** (int) - Required - Number of items to read. ### Returns - **iter.Seq2[[]byte, error]** - Iterator yielding item data and error. Yields a single (nil, ErrPositionOutOfRange) and stops if start/count are invalid; count == 0 yields nothing. ### Notes Concurrent ReadRange calls on the same Reader are safe; the returned iterator is NOT safe for concurrent iteration. ``` -------------------------------- ### Create directories and pull archive node image Source: https://github.com/stellar/stellar-rpc/blob/main/docs/ARCHIVE-NODE-BETA-RUNBOOK.md Creates local host directories for configuration and data, then pulls the archive node container image. Put /srv/rpc-archive on the 7 TB NVMe volume. ```bash mkdir -p /srv/rpc-archive/config /srv/rpc-archive/data docker pull stellar/unsafe-stellar-rpc:archive-node-beta ``` -------------------------------- ### Startup helper commands for rpcv2 Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/configuration.md Commands to generate a config file, run the daemon, and print the resolved runtime config. Use --enable-rpcv2 to activate rpcv2 mode. ```bash ./stellar-rpc --enable-rpcv2 gen-config-file # print compiled defaults as TOML ./stellar-rpc --enable-rpcv2 --config-path cfg.toml # run the full-history daemon ./stellar-rpc --enable-rpcv2 --config-path cfg.toml --print-runtime-config # resolved config as TOML ``` -------------------------------- ### In-process read server usage Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/api-reference/rpcv2.md Shows how to set up an in-process read server using ReadMethods. It creates a registry, builds a handler map from the returned methods, and wraps it with jsonrpc.NewBridge. ```go import ( "github.com/creachadair/jrpc2/handler" "github.com/stellar/stellar-rpc/cmd/stellar-rpc/internal/jsonrpc" "github.com/stellar/stellar-rpc/cmd/stellar-rpc/internal/rpcv2" "github.com/stellar/stellar-rpc/cmd/stellar-rpc/internal/rpcv2/query" ) registry := query.NewRegistry(catalog, retention) m := handler.Map{} for name, h := range rpcv2.ReadMethods(cfg, registry, passphrase, logger) { m[name] = h } b := jsonrpc.NewBridge(m, logger) defer b.Close() ``` -------------------------------- ### Open Source: https://github.com/stellar/stellar-rpc/blob/main/design-docs/packfile-library.md Opens a packfile for reading. Returns immediately; file I/O runs in a background goroutine. The first read call blocks until the file is ready. ```APIDOC ## Open ### Description Opens a packfile for reading. Returns immediately; file I/O runs in a background goroutine. The first read call blocks until the file is ready. ### Method Open ### Endpoint packfile.Open(path string, options ReaderOptions) (*Reader, error) ### Parameters #### ReaderOptions - **RecordDecoder** (RecordDecoder) - Required - Decompressor; caller owns it; Reader.Close does not close it - **Concurrency** (int) - Optional - Parallel read goroutines ### Request Example ```go r := packfile.Open("output.pack", packfile.ReaderOptions{ RecordDecoder: decoder, }) ``` ### Response #### Success Response Returns a *Reader and nil error. #### Response Example ```go r := packfile.Open("output.pack", packfile.ReaderOptions{RecordDecoder: decoder}) ``` ``` -------------------------------- ### getLedgers Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/types.md Returns a list of ledgers, optionally filtered by start ledger, pagination cursor, and XDR format. Supports both base64 and JSON output formats. ```APIDOC ## getLedgers ### Description Returns a list of ledgers, optionally filtered by start ledger, pagination cursor, and XDR format. Supports both base64 and JSON output formats. ### Request #### Request Body - **startLedger** (uint32) - Required - First ledger, inclusive; must be within the node's range unless a cursor is given - **pagination.cursor** (string) - Optional - Resume token; mutually exclusive with startLedger - **pagination.limit** (uint) - Optional - Page size; `0` → the server default (v1 50, v2 5); over max (v1 200, v2 20) → error - **xdrFormat** (string) - Optional - `base64` (default) or `json` ### Response #### Success Response - **ledgers** (array of LedgerInfo) - Required - List of ledgers - **hash** (string) - Required - Ledger hash - **sequence** (uint32) - Required - Ledger sequence number - **ledgerCloseTime** (int64) - Required - Ledger close time (Unix timestamp) - **headerXdr** (string) - Required - Base64-encoded XDR ledger header - **headerJson** (object) - Optional - JSON representation of ledger header (when xdrFormat=json) - **metadataXdr** (string) - Required - Base64-encoded XDR ledger metadata - **metadataJson** (object) - Optional - JSON representation of ledger metadata (when xdrFormat=json) - **latestLedger** (uint32) - Required - Sequence of the latest ledger - **latestLedgerCloseTime** (int64) - Required - Close time of the latest ledger - **oldestLedger** (uint32) - Required - Sequence of the oldest ledger - **oldestLedgerCloseTime** (int64) - Required - Close time of the oldest ledger - **cursor** (string) - Required - Cursor for pagination ### Notes - Cursor semantics: next cursor = last served ledger's sequence; a caught-up poller's cursor is echoed back on an empty page; cursor below `oldestLedger - 1` → `-32602`. #### Response Example { "ledgers": [ { "hash": "abc123...", "sequence": 12345, "ledgerCloseTime": "1700000000", "headerXdr": "AAAA...", "metadataXdr": "AAAA..." } ], "latestLedger": 12345, "latestLedgerCloseTime": "1700000000", "oldestLedger": 12300, "oldestLedgerCloseTime": "1699990000", "cursor": "12345" } ``` -------------------------------- ### getTransactions Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/types.md Retrieves a list of transactions from the Stellar network. The request includes a starting ledger, optional pagination, and an optional XDR format. The response contains transaction details, ledger information, and a cursor for pagination. ```APIDOC ## getTransactions ### Description Retrieves a list of transactions from the Stellar network. The request includes a starting ledger, optional pagination, and an optional XDR format. The response contains transaction details, ledger information, and a cursor for pagination. ### Request - **startLedger** (uint32) - Required - The ledger sequence number to start scanning from. - **pagination** (LedgerPaginationOptions) - Optional - Pagination options. - **format** (string) - Optional - The XDR format for the response (e.g., 'json' or 'xdr'). ### Response - **transactions** (array of TransactionInfo) - List of transactions. - **latestLedger** (uint32) - The latest ledger sequence number. - **latestLedgerCloseTime** (int64) - The close time of the latest ledger. - **oldestLedger** (uint32) - The oldest ledger sequence number. - **oldestLedgerCloseTime** (int64) - The close time of the oldest ledger. - **cursor** (string) - Cursor for pagination (TOID value). ### Notes Cursors are TOID values (`ledger:transaction:operation` packed); the scan walks ledgers from the cursor onward, capping at `LedgerScanLimit` ledgers per page. ``` -------------------------------- ### Open Source: https://github.com/stellar/stellar-rpc/blob/main/design-docs/packfile-library.md Opens a packfile for reading. Returns a Reader immediately; validation runs synchronously, file I/O runs in background. Errors are deferred to the first method that needs the result. ```APIDOC ## Open ### Description Opens a packfile for reading. Returns a Reader immediately; validation runs synchronously, file I/O runs in background. Errors are deferred to the first method that needs the result. ### Method Open ### Signature func Open(path string, opts ReaderOptions) *Reader ### Parameters - **path** (string) - Required - Path to the packfile. - **opts** (ReaderOptions) - Required - Configuration options for the reader. ### ReaderOptions Fields - **RecordDecoder** (RecordDecoder) - Optional - Decodes record payloads. Must be safe for concurrent use. Caller-owned; not closed by Reader.Close. nil means passthrough. - **Concurrency** (int) - Optional - Most reads ReadItems keeps in flight. Zero means 1, on the calling goroutine. Negative value is an error, returned by the first read call. - **FirstRead** (func(fileSize int64) int) - Optional - Sizes Open's first read from the end of the file. nil means 256 KiB. Results clamped to [trailer size, file size]. ### Notes Close must always be called. ``` -------------------------------- ### runLifecycle: Execute plan, discard, and prune for a chunk Source: https://github.com/stellar/stellar-rpc/blob/main/design-docs/full-history-streaming-workflow.md Runs one lifecycle pass over the latest completed chunk. Computes the retention floor, executes the plan (freezing the chunk and folding it into the index), then performs discard and prune operations. Any error fails the run; startup is the recovery path. ```go func runLifecycle(ctx context.Context, cfg Config, lastChunk ChunkID) error { floor := retentionFloorChunk(lastChunk, cfg.RetentionChunks, cfg.Catalog.EarliestLedger()) if err := executePlan(ctx, cfg, resolve(cfg, floor, lastChunk)); err != nil { return err // fails the run; startup is the recovery path } for _, op := range eligibleDiscardOps(cfg, lastChunk, floor) { if err := op(); err != nil { return err } } for _, op := range eligiblePruneOps(cfg, floor) { if err := op(); err != nil { return err } } return nil } ``` -------------------------------- ### ReadRange Source: https://github.com/stellar/stellar-rpc/blob/main/design-docs/packfile-library.md Sequentially scans items from start to start+count-1. Safe to break early. The yielded slice is invalidated once the loop exits. Invalid start/count yields a single (nil, ErrPositionOutOfRange) pair and stops; count == 0 is valid and yields nothing. ```APIDOC ## ReadRange ### Description Sequentially scans items from start to start+count-1. Safe to break early. The yielded slice is invalidated once the loop exits. Invalid start/count yields a single (nil, ErrPositionOutOfRange) pair and stops; count == 0 is valid and yields nothing. ### Method ReadRange ### Endpoint (r *Reader) ReadRange(start int, count int) iterator ### Parameters - **start** (int) - Required - Starting position - **count** (int) - Required - Number of items to read ### Request Example ```go for data, err := range r.ReadRange(0, 1000) { if err != nil { return err } process(data) } ``` ### Response #### Success Response Yields (data []byte, err error) pairs. On error, yields (nil, error) and stops. ``` -------------------------------- ### Clone and build stellar-rpc Source: https://github.com/stellar/stellar-rpc/blob/main/cmd/stellar-rpc/README.md Clones the stellar-rpc repository and builds the binary using make build-stellar-rpc. ```bash git clone https://github.com/stellar/stellar-rpc.git cd stellar-rpc ``` ```bash make build-stellar-rpc ``` -------------------------------- ### openHotDBForChunk: Open or create a chunk's hot DB Source: https://github.com/stellar/stellar-rpc/blob/main/design-docs/full-history-streaming-workflow.md Opens the existing hot DB for a chunk if its catalog state is 'ready', otherwise wipes any leftover directory and creates a fresh one. The catalog key is set to 'transient' before creation and flipped to 'ready' only after fsync of the DB directory and its parent, ensuring durability before the key flips. ```go func openHotDBForChunk(cat Catalog, chunk ChunkID) (*HotDB, error) { hotKey, path := hotChunkKey(chunk), hotChunkPath(chunk) if state, _ := cat.Get(hotKey); state == "ready" { db, err := openExistingRocksDB(path) if err != nil { return nil, fmt.Errorf("hot DB for chunk %d is ready but won't open: %w", chunk, err) } return db, nil } // transient or absent: wipe any leftover dir and create fresh. deleteDirIfExists(path) cat.Put(hotKey, "transient") db := createChunkHotDB(path) fsyncDir(path) // durable before the key flips to "ready" fsyncParentDir(path) cat.Put(hotKey, "ready") return db, nil } ``` -------------------------------- ### rpcdatastore: LedgerBackendFactory, LedgerReader, and NewLedgerReader Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/api-reference/support.md Defines the datastore-backed ledger reader interfaces and constructor. GetLedgers returns a contiguous batch in [start, end] inclusive, erroring if any ledger is unavailable; GetAvailableLedgerRange assumes all history from genesis (FirstLedger: 2, no LastLedger). ```go type LedgerBackendFactory interface { NewBufferedBackend( config ledgerbackend.BufferedStorageBackendConfig, store datastore.DataStore, schema datastore.DataStoreSchema, ) (ledgerbackend.LedgerBackend, error) } // LedgerReader provides access to historical ledger data stored in a remote // object store (e.g., S3 or GCS) via buffered storage backend. type LedgerReader interface { GetLedgers(ctx context.Context, start, end uint32) ([]xdr.LedgerCloseMeta, error) GetAvailableLedgerRange(ctx context.Context) (protocol.LedgerSeqRange, error) } func NewLedgerReader(storageBackendConfig ledgerbackend.BufferedStorageBackendConfig, dataStore datastore.DataStore, dataStoreSchema datastore.DataStoreSchema, ) LedgerReader ``` -------------------------------- ### Launch stellar-rpc-v2 container with docker run Source: https://github.com/stellar/stellar-rpc/blob/main/docs/ARCHIVE-NODE-BETA-RUNBOOK.md Runs the archive node beta container with configuration and data volumes mounted, exposing ports 8000 and 6061. Preserve /srv/rpc-archive/data across restarts to avoid full backfill; the node exits non-zero on fatal errors and resumes backfill per 10,000-ledger chunk. ```bash docker run -d --name stellar-rpc-v2 \ -v /srv/rpc-archive/config:/config:ro \ -v /srv/rpc-archive/data:/data \ -p 8000:8000 \ -p 127.0.0.1:6061:6061 \ stellar/unsafe-stellar-rpc:archive-node-beta \ --config /config/rpc-archive.toml ``` -------------------------------- ### executePlan: run chunk and index builds concurrently Source: https://github.com/stellar/stellar-rpc/blob/main/design-docs/full-history-streaming-workflow.md Runs a plan from startup backfill or lifecycle run. Chunk builds run concurrently under a worker semaphore; each index build waits on the done-channels of its in-coverage chunk builds before running. The only concurrency knob is cfg.Workers (default GOMAXPROCS). Done-channels signal success; a chunk build that exhausts retries leaves its channel open and returns an error, cancelling gctx and failing the run. ```go func executePlan(ctx context.Context, cfg Config, plan Plan) error { slots := make(chan struct{}, cfg.Workers) // the only concurrency knob done := make(map[ChunkID]chan struct{}, len(plan.ChunkBuilds)) for _, cb := range plan.ChunkBuilds { done[cb.Chunk] = make(chan struct{}) } g, gctx := errgroup.WithContext(ctx) for _, cb := range plan.ChunkBuilds { g.Go(func() error { slots <- struct{}{} defer func() { <-slots }() if err := withRetries(gctx, cfg.MaxRetries, func() error { return processChunk(cfg, cb.Chunk, cb.Artifacts) }); err != nil { return err // leave done[cb.Chunk] open; the error cancels gctx, freeing waiters } close(done[cb.Chunk]) // success: dependents may now read this chunk's .bin return nil }) } for _, b := range plan.IndexBuilds { g.Go(func() error { for c := b.Lo; c <= b.Hi; c++ { // wait on the in-coverage chunk builds if ch, ok := done[c]; ok { select { case <-ch: // this chunk's .bin is frozen case <-gctx.Done(): // a build failed (or cancel) — bail return gctx.Err() } } } slots <- struct{}{} defer func() { <-slots }() return withRetries(gctx, cfg.MaxRetries, func() error { return buildThenSweep(cfg, b) }) }) } return g.Wait() } ``` -------------------------------- ### Writing a packfile with packfile.Create Source: https://github.com/stellar/stellar-rpc/blob/main/design-docs/packfile-library.md Creates a new packfile, appends items in order, and seals it with Finish. NewRecordEncoder is called once per worker; passing nil makes records passthrough. Close without Finish removes the incomplete file. ```go w, _ := packfile.Create("output.pack", packfile.WriterOptions{ ItemsPerRecord: 128, // items per record (default 128) Format: packfile.Format(1), // caller-assigned codec identifier NewRecordEncoder: func() packfile.RecordEncoder { // per-worker encoder return zstd.NewCompressor() }, Concurrency: 4, // parallel encode goroutines }) defer w.Close() // removes file if Finish was not called for _, item := range items { w.AppendItem(item) } w.Finish(nil) // seal the file (nil = no app data) ``` -------------------------------- ### version.NewCommand: return version subcommand Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/api-reference/cli.md Returns the `version` subcommand shared by both modes. Prints version information including commit hash and branch. ```go // NewCommand returns the `version` subcommand shared by both modes of the // stellar-rpc binary. func NewCommand() *cobra.Command // package cmd/stellar-rpc/internal/version ``` -------------------------------- ### buildThenSweep: build index and eagerly sweep demoted keys Source: https://github.com/stellar/stellar-rpc/blob/main/design-docs/full-history-streaming-workflow.md Runs an IndexBuild, then eagerly sweeps the keys its commit demoted (this window only), so freed disk returns without waiting for a run. It builds the txhash index, sweeps superseded coverage(s) in Pruning state, and for a terminal build sweeps the window's .bin inputs that are Pruning. ```go // buildThenSweep runs an IndexBuild, then eagerly sweeps the keys its commit // demoted (this window only), so freed disk returns without waiting for a run. func buildThenSweep(cfg Config, b IndexBuild) error { cat := cfg.Catalog if err := buildTxhashIndex(b.Window, b.Lo, b.Hi, cat); err != nil { return err } for _, key := range indexKeys(cat, b.Window) { // superseded coverage(s) if key.State == Pruning { sweepIndexKey(cat, key) } } var demoted []ArtifactRef // terminal build: the window's .bin inputs for c := windowFirstChunk(b.Window); c <= windowLastChunk(b.Window); c++ { if cat.State(c, TxHashBin) == Pruning { demoted = append(demoted, ArtifactRef{Chunk: c, Kind: TxHashBin}) } } if len(demoted) > 0 { sweepChunkArtifacts(cat, demoted) } return nil } ``` -------------------------------- ### Run unit tests with go test Source: https://github.com/stellar/stellar-rpc/blob/main/README.md Executes all unit tests in the repository with verbose output and stops at the first failure. ```bash go test -v -failfast ./... ``` -------------------------------- ### NoOpDaemon struct and constructor Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/api-reference/host.md Dummy daemon implementation supporting the Daemon interface, used only in testing. Returns empty responses and empty version. ```go // NoOpDaemon The noOpDeamon is a dummy daemon implementation, supporting the Daemon interface. // Used only in testing. type NoOpDaemon struct { ... } func MakeNoOpDaemon() *NoOpDaemon ``` -------------------------------- ### Create Source: https://github.com/stellar/stellar-rpc/blob/main/design-docs/packfile-library.md Creates a new packfile for writing. Items are appended in order, and Finish seals the file and fsyncs. Close after Finish is a no-op; Close without Finish removes the incomplete file. ```APIDOC ## Create ### Description Creates a new packfile for writing. Items are appended in order, and Finish seals the file and fsyncs. Close after Finish is a no-op; Close without Finish removes the incomplete file. ### Method Create ### Endpoint packfile.Create(outputPath string, options WriterOptions) (*Writer, error) ### Parameters #### WriterOptions - **ItemsPerRecord** (int) - Optional - Items per record (default 128) - **Format** (Format) - Required - Caller-assigned codec identifier - **NewRecordEncoder** (func() RecordEncoder) - Optional - Per-worker encoder; called once per worker; nil makes records passthrough (no encoding) - **Concurrency** (int) - Optional - Parallel encode goroutines ### Request Example ```go w, _ := packfile.Create("output.pack", packfile.WriterOptions{ ItemsPerRecord: 128, Format: packfile.Format(1), NewRecordEncoder: func() packfile.RecordEncoder { return zstd.NewCompressor() }, Concurrency: 4, }) ``` ### Response #### Success Response Returns a *Writer and nil error. #### Response Example ```go w, _ := packfile.Create("output.pack", packfile.WriterOptions{...}) ``` ``` -------------------------------- ### Registry.NewReadView: Acquire a ReadView with ordered loads Source: https://github.com/stellar/stellar-rpc/blob/main/design-docs/query-routing-design.md Loads latestLedger, handles, and snapshot in that order to ensure consistent range coverage. The floor anchor is derived from the snapshot's LastCompleteChunk. Returns an error if the snapshot has no ready hot chunk. The view must be released when done. ```go func (r *Registry) NewReadView() (*ReadView, error) { latest := r.latestLedger.Load() handles := r.handles.Load() snap, err := r.newSnapshot() // catalog.NewSnapshot, behind a test seam that pins this load order if err != nil { return nil, err } // The floor anchor is the highest ready hot chunk in the snapshot minus // one: the same last-complete-chunk anchor the lifecycle run uses // (Catalog.LastCompleteChunk live, Snapshot.LastCompleteChunk here). lastComplete, err := snap.LastCompleteChunk() if err != nil { snap.Release() return nil, err } return &ReadView{latestLedger: latest, floor: r.retention.FloorAt(lastComplete), handles: handles, snap: snap, catalog: r.catalog}, nil } ``` -------------------------------- ### Build and run bench ingest cold and query Source: https://github.com/stellar/stellar-rpc/blob/main/cmd/stellar-rpc/internal/rpcv2/bench/README.md Builds the stellar-rpc binary with RPCV2=true and runs the bench ingest cold and query commands. The ingest cold command backfills over a chunk range and writes a cold dataset; the query command calls read handlers at fixed request rates. Requires --enable-rpcv2 or STELLAR_RPC_ENABLE_RPCV2=true; release builds cannot run rpcv2. ```bash make build-stellar-rpc RPCV2=true ./stellar-rpc --enable-rpcv2 bench ingest cold --pack-dir PACKS \ --start-chunk 6000 --num-chunks 2 --cold-out-dir /data/cold --out out/ingest ./stellar-rpc --enable-rpcv2 bench query --data-dir /data/cold \ --types ledgers,txhash --target-rps 10,100 --out out/query ``` -------------------------------- ### Entry.Run method signature Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/api-reference/cli.md Runs the command line and returns the process exit code: 0 after a clean run or a signal, 1 on any failure. Fills defaults, calls SelectMode, builds the mode's root command, executes it via cobra, then runs the daemon. Returns 1 with "rpcv2 is not available in this build of stellar-rpc" if rpcv2 mode is selected but DisableRPCv2 is set. ```go // Run runs the command line and returns the process exit code: 0 after a // clean run or a signal, 1 on any failure. func (e *Entry) Run() int ``` -------------------------------- ### startRPCv2Daemon: run rpcv2 daemon with signal context Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/api-reference/cli.md Launches the rpcv2 daemon with a context that cancels on SIGINT or SIGTERM. Used after config validation in the rpcv2 mode. ```go func startRPCv2Daemon(configPath string, flags v2config.FlagOverrides) error { ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() return rpcv2.RunDaemon(ctx, configPath, flags) } ``` -------------------------------- ### Retention floor, last complete chunk, last committed ledger, and network tip computation Source: https://github.com/stellar/stellar-rpc/blob/main/design-docs/full-history-streaming-workflow.md Defines constants for ledger chunking and functions to compute the retention floor, last complete chunk, last committed ledger, and network tip. Used during daemon startup to determine backfill and resume points. Includes error handling for backend tips below genesis. ```go const ( GenesisLedger = 2 LedgersPerChunk = 10_000 ChunksPerTxhashIndex = 1_000 // window = 10M ledgers ) // retentionFloorChunk: the lowest chunk kept — retentionChunks back from // lastChunk, never below earliest's chunk. func retentionFloorChunk(lastChunk ChunkID, retentionChunks uint32, earliest uint32) ChunkID { floor := chunkID(earliest) if retentionChunks > 0 { floor = max(floor, lastChunk-ChunkID(retentionChunks)+1) } return floor } // lastCompleteChunkAt: the largest chunk whose last ledger is <= ledger. func lastCompleteChunkAt(ledger uint32) int64 { return (int64(ledger)-1)/LedgersPerChunk - 1 } // maxCommittedSeq: the highest ledger committed to a hot DB; an empty chunk-C DB // counts as chunkFirstLedger(C) - 1 (the watermark just below the chunk), so the // boundary-crash derivation is exact. // // lastCommittedLedger: the highest ledger in durable storage — the live hot DB's // last, the highest durable chunk's if it leads, or earliest-1 if neither exists. // A chunk is durable when its ledgers and events are "frozen" and its txhash is // "frozen" or covered by the window's frozen index (pendingArtifacts' test). func lastCommittedLedger(cat Catalog) uint32 { base := cat.EarliestLedger() - 1 cold := highestDurableChunk(cat) hot := highestReadyHotChunk(cat) switch { case hot > cold: db := openReadOnly(hot) defer db.Close() return max(base, maxCommittedSeq(db)) case cold >= 0: return max(base, chunkLastLedger(cold)) default: return base } } func networkTip(cfg Config) (uint32, error) { tip, err := withBackoff(func() (uint32, error) { return backendNetworkTip(cfg) }) if err != nil { return 0, err } if tip < GenesisLedger { return 0, fmt.Errorf("backend tip %d is below genesis — backend not ready", tip) } return tip, nil } ``` -------------------------------- ### Readiness Probe with getHealth Source: https://github.com/stellar/stellar-rpc/blob/main/docs/ARCHIVE-NODE-BETA-RUNBOOK.md Use this command as a readiness probe. It exits 0 only when the node is healthy, making it suitable for automated checks. ```bash curl -s localhost:8000 -H 'content-type: application/json' -d '{"jsonrpc":"2.0","id":1,"method":"getHealth"}' | grep -q '"status":"healthy"' ``` -------------------------------- ### Generate and use config file with gen-config-file Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/configuration.md Generates a TOML configuration file to stdout and then runs stellar-rpc with that config. The gen-config-file command accepts the same arguments as the root command's persistent flags. ```bash ./stellar-rpc gen-config-file > stellar-rpc.toml ``` ```bash ./stellar-rpc --config-path stellar-rpc.toml ``` -------------------------------- ### buildTxhashIndex: rebuild window index to cover chunks [lo, hi] Source: https://github.com/stellar/stellar-rpc/blob/main/design-docs/full-history-streaming-workflow.md Rebuilds window w's index to cover chunks [lo, hi] — lo the lowest in-floor chunk, hi the highest frozen chunk. Marks the index key as 'freezing' before writes, then 'frozen' after fsync. Demotes the predecessor index to 'pruning' and prunes terminal .bin inputs when hi is the window's last chunk. ```go func buildTxhashIndex(w WindowID, lo, hi ChunkID, cat Catalog) error { prev := frozenCoverage(cat, w) if prev != nil && prev.Lo == lo && prev.Hi == hi { return nil // already built (e.g. a buildThenSweep retry re-entering after the commit) } key := indexKey(w, lo, hi) cat.Put(key, "freezing") // mark before the writes sb := streamhash.NewSortedBuilder(indexFilePath(key)) for entry := range kWayMerge(binFiles(lo, hi)) { // sorted .bin files → one stream sb.Add(entry) } sb.Finish() fsyncFile(indexFilePath(key)) fsyncDirs(indexFilePath(key)) // the dirent chain — incl. a just-created window dir — durable before the key freezes batch := cat.NewBatch() // one atomic synced write — the whole finalization batch.Put(key, "frozen") if prev != nil { batch.Put(indexKey(w, prev.Lo, prev.Hi), "pruning") // demote predecessor } if hi == windowLastChunk(w) { // terminal: the merged .bin inputs are spent for c := lo; c <= hi; c++ { batch.Put(chunkKey(c, TxHashBin), "pruning") } } batch.Commit() return nil } ``` -------------------------------- ### cgo conversion helpers (FFI boundary) Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/api-reference/preflight.md Direct cgo helpers converting between Go []byte and the C types declared in cmd/stellar-rpc/lib/preflight.h/shared.h (xdr_t, xdr_vector_t, xdr_diff_vector_t). ```go func CXDR(xdr []byte) C.xdr_t func GoXDR(xdr C.xdr_t) []byte func GoXDRVector(xdrVector C.xdr_vector_t) [][]byte func GoXDRDiffVector(xdrDiffVector C.xdr_diff_vector_t) []XDRDiff ``` -------------------------------- ### GetPreflight free function Source: https://github.com/stellar/stellar-rpc/blob/main/_autodocs/api-reference/preflight.md Runs a preflight synchronously outside the pool, dispatching on OpBody.Type: InvokeHostFunction, or ExtendFootprintTtl/RestoreFootprint. Returns 'unsupported operation type: ' for any other operation type. ```go // GetPreflight runs a preflight synchronously (outside the pool), dispatching // on OpBody.Type: InvokeHostFunction, or ExtendFootprintTtl/RestoreFootprint. func GetPreflight(ctx context.Context, params Parameters) (Preflight, error) ``` -------------------------------- ### Rebuild window index over [lo, hi] with streamhash sorted builder Source: https://github.com/stellar/stellar-rpc/blob/main/design-docs/gettransaction-full-history-design.md Merges sorted .bin files for chunks in [lo, hi] into a new index file using streamhash's sorted builder, then swaps it in as the live index. The live index is never partially updated because the new file is written completely before replacement. A missing .bin file fails the merge; a coverage with no transactions builds a valid empty index. ```go // rebuild window w's index over [lo, hi] sb := streamhash.NewSortedBuilder(newIndexFile, sortedBuilderOpts) for entry := range kWayMerge(binFiles(lo, hi)) { // sorted .bin files → one stream sb.Add(entry) } sb.Finish() // then make newIndexFile the window's live index, replacing the old one ``` -------------------------------- ### Generate RPC config file Source: https://github.com/stellar/stellar-rpc/blob/main/cmd/stellar-rpc/README.md Generates a TOML configuration file for Stellar RPC. Outputs to stdout; save to a .toml file and update values for testnet. ```bash ./stellar-rpc gen-config-file ```