Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 23 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ configured zkApp's actions from the archive PostgreSQL database, follows the
confirmed best chain, stores indexed actions and cursor metadata in LevelDB,
and exposes read-only gRPC queries for the validator application.

The sidecar is local to the validator host. The wrapper enforces a literal
loopback gRPC listen address such as `127.0.0.1:9095` or `[::1]:9095`; hostnames,
unspecified addresses, and non-loopback IP addresses are rejected. Pulsar and
the wrapper must therefore share a network namespace. Deployments across
separate container networks require a separately designed Unix socket or
TLS/mTLS transport.
The sidecar defaults to a local-only gRPC transport. `loopback` accepts only a
literal loopback address such as `127.0.0.1:9095` or `[::1]:9095`. For a shared
Docker/private network, `trusted-network` must be explicitly selected; it may
bind to private or unspecified addresses and uses plaintext gRPC. This mode is
an operator-declared trust boundary, not a firewall or network-isolation check.
Deployments outside a controlled private network require a future TLS/mTLS
transport.

## Requirements

Expand All @@ -34,6 +35,8 @@ fields are:
| `block_height_database_key` | LevelDB key for the latest processed cursor. |
| `db_path` | Local LevelDB directory. |
| `grpc_listen_address` | TCP address for the local query server. |
| `grpc_transport_mode` | `loopback` by default, or explicit `trusted-network`. |
| `chain_home` | Optional Pulsar home; start/proceed require it from config, CLI, or environment. |
| `control_socket_path` | Unix socket used by the `stop` command. |
| `deployment_metadata_key` | LevelDB key used to store deployment identity. |
| `deployment_metadata.schema_version` | Stored deployment metadata schema version. |
Expand All @@ -58,12 +61,13 @@ Example:

```dotenv
POSTGRES_URI=postgres://user:password@127.0.0.1:5432/archive?sslmode=disable
CHAIN_HOME=/path/to/validator
ARCHIVE_WRAPPER_CHAIN_HOME=/path/to/validator
CONFIG=config.yaml
```

`CHAIN_HOME` is used by the Makefile. `CONFIG` is optional if you want to use
the default `config.yaml`.
`CHAIN_HOME` remains a Makefile convenience variable. The binary uses
`ARCHIVE_WRAPPER_CHAIN_HOME`; `CONFIG` is a Makefile convenience variable and
the binary requires `--config` or `ARCHIVE_WRAPPER_CONFIG`.

Build the pure-Go binary with:

Expand Down Expand Up @@ -117,9 +121,9 @@ make stop CONFIG=/path/to/config.yaml SOCKET_PATH=/tmp/archive-wrapper.sock

The control socket accepts `PING` (responding with `PONG`) and `STOP`. The
process also shuts down gracefully on `SIGINT` or `SIGTERM`. The `stop`
command can use `--socket-path` directly; otherwise it resolves the socket
from `--config`, `ARCHIVE_WRAPPER_CONFIG`, or
`ARCHIVE_WRAPPER_CONTROL_SOCKET_PATH`.
command can use `--control-socket-path` directly (or the legacy
`--socket-path` alias). Otherwise it resolves the socket from
`ARCHIVE_WRAPPER_CONTROL_SOCKET_PATH` and then the selected config file.

### Without Makefile

Expand All @@ -146,6 +150,10 @@ are:
and `proceed`.
- `ARCHIVE_WRAPPER_CONFIG` — default config path for `start`, `proceed`, and
`stop`.
- `ARCHIVE_WRAPPER_CHAIN_HOME` — Pulsar chain home for `start` and `proceed`.
- `ARCHIVE_WRAPPER_GRPC_LISTEN_ADDRESS` — effective gRPC listen address.
- `ARCHIVE_WRAPPER_GRPC_TRANSPORT_MODE` — effective gRPC transport mode.
- `ARCHIVE_WRAPPER_DB_PATH` — effective LevelDB path.
- `ARCHIVE_WRAPPER_CONTROL_SOCKET_PATH` — fallback socket path for `stop`.
- `ARCHIVE_WRAPPER_LOG_PATH` — append-only log path; defaults to
`archive-wrapper.log`.
Expand All @@ -164,7 +172,9 @@ The query service is defined in

Blocks with no supported actions are still recorded by advancing the cursor.
The gRPC endpoint has no public authentication or authorization layer, so it
must stay bound to a trusted local interface.
must stay in the boundary selected by `grpc_transport_mode`. In
`trusted-network` mode, network isolation and access control are deployment
responsibilities.

### Health and diagnostics

Expand Down
12 changes: 10 additions & 2 deletions apperrors/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,16 @@ var (
var (
// ErrGRPCAddressRequired reports that grpc_listen_address is missing from config.
ErrGRPCAddressRequired = errors.New("grpc_listen_address is required")
// ErrInvalidGRPCListenAddress reports that grpc_listen_address is not a literal loopback TCP address.
ErrInvalidGRPCListenAddress = errors.New("grpc_listen_address must be a literal loopback TCP address")
// ErrInvalidGRPCListenAddress reports that grpc_listen_address violates the selected transport policy.
ErrInvalidGRPCListenAddress = errors.New("grpc_listen_address violates the selected transport policy")
// ErrUnsupportedGRPCTransportMode reports an unknown or intentionally unsupported transport mode.
ErrUnsupportedGRPCTransportMode = errors.New("unsupported grpc transport mode")
// ErrConfigPathRequired reports that no configuration file path was provided.
ErrConfigPathRequired = errors.New("archive-wrapper config path is required")
// ErrChainHomeRequired reports that the chain home was not provided for a runtime command.
ErrChainHomeRequired = errors.New("chain home is required")
// ErrPostgresConfigurationInvalid reports a malformed PostgreSQL pool configuration.
ErrPostgresConfigurationInvalid = errors.New("postgres query pool configuration is invalid")
// ErrContractAddressRequired reports that contract_address is missing from bridge params.
ErrContractAddressRequired = errors.New("contract_address is required")
// ErrBlockHeightDBKeyRequired reports that block_height_database_key is missing from config.
Expand Down
217 changes: 109 additions & 108 deletions cmd/archive-wrapper/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ import (
"os"
"strings"

"github.com/node101-io/archive-wrapper/apperrors"
"github.com/node101-io/archive-wrapper/config"
"github.com/syndtr/goleveldb/leveldb"
)

// run validates command-specific inputs before handing control to the runtime.
func run(args []string, ctx context.Context,
cancel context.CancelFunc, logger *slog.Logger) error {
func run(args []string, ctx context.Context, cancel context.CancelFunc, logger *slog.Logger) error {
cliLogger := logger.With("component", "cli")

if len(args) == 0 {
Expand All @@ -24,86 +24,44 @@ func run(args []string, ctx context.Context,

switch strings.ToLower(args[0]) {
case "start":
startCmd := flag.NewFlagSet("start", flag.ContinueOnError)

defaultConfigPath := os.Getenv("ARCHIVE_WRAPPER_CONFIG")
configPath := startCmd.String(
"config",
defaultConfigPath,
"path to configuration file",
)
homePath := startCmd.String(
"home",
"",
"path to chain home directory",
)

if err := startCmd.Parse(args[1:]); err != nil {
cmd := newRuntimeFlagSet("start")
if err := cmd.Parse(args[1:]); err != nil {
return err
}

if strings.TrimSpace(*configPath) == "" {
return fmt.Errorf("--config is required unless ARCHIVE_WRAPPER_CONFIG is set")
}
if strings.TrimSpace(*homePath) == "" {
return fmt.Errorf("--home is required")
configPath, err := resolveConfigPath(cmd.FlagSet, *cmd.configPath)
if err != nil {
return err
}

cliLogger.Info(
"start command received",
"config",
*configPath,
"home",
*homePath,
)

cfg, err := config.Load(*configPath)
cfg, err := config.Resolve(configPath, cmd.overrides())
if err != nil {
return err
}
// A fresh start must not silently reuse a persisted cursor.

cliLogger.Info("start command received", "config", configPath, "home", cfg.ChainHome)
if err := ensureDBPathDoesNotExist(cfg.DBPath); err != nil {
return err
}

bridgeParams, err := loadBridgeParamsFromHome(*homePath)
bridgeParams, err := loadBridgeParamsFromHome(cfg.ChainHome)
if err != nil {
return fmt.Errorf("load bridge params from genesis: %w", err)
}

return runStart(ctx, cfg, bridgeParams, cancel, logger)

case "proceed":
proceedCmd := flag.NewFlagSet("proceed", flag.ContinueOnError)

defaultConfigPath := os.Getenv("ARCHIVE_WRAPPER_CONFIG")
configPath := proceedCmd.String(
"config",
defaultConfigPath,
"path to configuration file",
)
homePath := proceedCmd.String(
"home",
"",
"path to chain home directory",
)

if err := proceedCmd.Parse(args[1:]); err != nil {
cmd := newRuntimeFlagSet("proceed")
if err := cmd.Parse(args[1:]); err != nil {
return err
}

if strings.TrimSpace(*configPath) == "" {
return fmt.Errorf("--config is required unless ARCHIVE_WRAPPER_CONFIG is set")
}
if strings.TrimSpace(*homePath) == "" {
return fmt.Errorf("--home is required")
configPath, err := resolveConfigPath(cmd.FlagSet, *cmd.configPath)
if err != nil {
return err
}

cfg, err := config.Load(*configPath)
cfg, err := config.Resolve(configPath, cmd.overrides())
if err != nil {
return err
}
// Proceed is valid only after start has initialized the local database.

if _, err := os.Stat(cfg.DBPath); err != nil {
if errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("db does not exist: %s; run start first", cfg.DBPath)
Expand All @@ -116,76 +74,46 @@ func run(args []string, ctx context.Context,
cfg.BlockHeightDatabaseKey,
logger,
)
// A missing cursor is valid when initialization finished before the first block.
if err != nil && !errors.Is(err, leveldb.ErrNotFound) {
return fmt.Errorf("load latest processed block height: %w", err)
}

cliLogger.Info(
"proceed command received",
"config",
*configPath,
"home",
*homePath,
)
cliLogger.Info("proceed command received", "config", configPath, "home", cfg.ChainHome)
if errors.Is(err, leveldb.ErrNotFound) {
cliLogger.Info("resuming before first cursor", "db_path", cfg.DBPath)
} else {
cliLogger.Info(
"resuming from persisted block height",
"block_height",
latestProcessedBlockHeight,
"db_path",
cfg.DBPath,
)
cliLogger.Info("resuming from persisted block height", "block_height", latestProcessedBlockHeight, "db_path", cfg.DBPath)
}

bridgeParams, err := loadBridgeParamsFromHome(*homePath)
bridgeParams, err := loadBridgeParamsFromHome(cfg.ChainHome)
if err != nil {
return fmt.Errorf("load bridge params from genesis: %w", err)
}

// Keep the genesis start height for bounds validation; the indexer
// resumes from the persisted cursor automatically when it exists.
return runStart(ctx, cfg, bridgeParams, cancel, logger)

case "stop":
stopCmd := flag.NewFlagSet("stop", flag.ContinueOnError)

defaultConfigPath := os.Getenv("ARCHIVE_WRAPPER_CONFIG")
configPath := stopCmd.String(
"config",
defaultConfigPath,
"path to configuration file",
)

socketPath := stopCmd.String(
"socket-path",
"",
"path to control socket",
)

if err := stopCmd.Parse(args[1:]); err != nil {
cmd := flag.NewFlagSet("stop", flag.ContinueOnError)
configPath := cmd.String("config", "", "path to configuration file")
legacySocketPath := cmd.String("socket-path", "", "legacy path to control socket")
controlSocketPath := cmd.String("control-socket-path", "", "path to control socket")
if err := cmd.Parse(args[1:]); err != nil {
return err
}
if flagWasSet(cmd, "socket-path") && flagWasSet(cmd, "control-socket-path") {
return fmt.Errorf("--socket-path and --control-socket-path cannot be used together")
}

resolvedSocketPath, err := resolveStopSocketPath(
*socketPath,
firstVisitedSocketPath(cmd, *legacySocketPath, *controlSocketPath),
flagWasSet(cmd, "socket-path") || flagWasSet(cmd, "control-socket-path"),
*configPath,
os.Getenv("ARCHIVE_WRAPPER_CONTROL_SOCKET_PATH"),
flagWasSet(cmd, "config"),
)
if err != nil {
return err
}

cliLogger.Info(
"stop command received",
"config",
strings.TrimSpace(*configPath),
"socket_path",
resolvedSocketPath,
)

cliLogger.Info("stop command received", "config", strings.TrimSpace(*configPath), "socket_path", resolvedSocketPath)
return runStop(resolvedSocketPath, logger)

case "help", "-h", "--help":
Expand All @@ -196,10 +124,83 @@ func run(args []string, ctx context.Context,
}
}

type runtimeFlagSet struct {
*flag.FlagSet
configPath *string
homePath *string
listenAddress *string
transportMode *string
dbPath *string
controlSocketPath *string
}

func newRuntimeFlagSet(name string) *runtimeFlagSet {
fs := flag.NewFlagSet(name, flag.ContinueOnError)
return &runtimeFlagSet{
FlagSet: fs,
configPath: fs.String("config", "", "path to configuration file"),
homePath: fs.String("home", "", "path to chain home directory"),
listenAddress: fs.String("grpc-listen-address", "", "gRPC listen address"),
transportMode: fs.String("grpc-transport-mode", "", "gRPC transport mode"),
dbPath: fs.String("db-path", "", "LevelDB path"),
controlSocketPath: fs.String("control-socket-path", "", "control socket path"),
}
}

func (f *runtimeFlagSet) overrides() config.Overrides {
Comment thread
korayakpinar marked this conversation as resolved.
Resolved
return config.Overrides{
ChainHome: visitedStringFlag(f.FlagSet, "home", f.homePath),
GRPCListenAddress: visitedStringFlag(f.FlagSet, "grpc-listen-address", f.listenAddress),
GRPCTransportMode: visitedStringFlag(f.FlagSet, "grpc-transport-mode", f.transportMode),
DBPath: visitedStringFlag(f.FlagSet, "db-path", f.dbPath),
ControlSocketPath: visitedStringFlag(f.FlagSet, "control-socket-path", f.controlSocketPath),
}
}

func usage() string {
return `usage:
archive-wrapper start --config <path> --home <path>
archive-wrapper proceed --config <path> --home <path>
archive-wrapper stop [--config <path>] [--socket-path <path>]
archive-wrapper start [--config <path>] [--home <path>] [runtime overrides]
archive-wrapper proceed [--config <path>] [--home <path>] [runtime overrides]
archive-wrapper stop [--config <path>] [--control-socket-path <path>]
`
}

func flagWasSet(fs *flag.FlagSet, name string) bool {
wasSet := false
fs.Visit(func(f *flag.Flag) {
if f.Name == name {
wasSet = true
}
})
return wasSet
}

func visitedStringFlag(fs *flag.FlagSet, name string, value *string) *string {
if !flagWasSet(fs, name) {
return nil
}
return value
}

func resolveConfigPath(fs *flag.FlagSet, flagValue string) (string, error) {
if flagWasSet(fs, "config") {
if strings.TrimSpace(flagValue) == "" {
return "", apperrors.ErrConfigPathRequired
}
return strings.TrimSpace(flagValue), nil
}
if value, ok := os.LookupEnv("ARCHIVE_WRAPPER_CONFIG"); ok {
if strings.TrimSpace(value) == "" {
return "", apperrors.ErrConfigPathRequired
}
return strings.TrimSpace(value), nil
}
return "", apperrors.ErrConfigPathRequired
}

func firstVisitedSocketPath(fs *flag.FlagSet, legacy, canonical string) string {
if flagWasSet(fs, "socket-path") {
return legacy
}
return canonical
}
Loading