diff --git a/.github/workflows/cherry-pick.yml b/.github/workflows/cherry-pick.yml index 698d82818..6514a44e0 100644 --- a/.github/workflows/cherry-pick.yml +++ b/.github/workflows/cherry-pick.yml @@ -1,44 +1,52 @@ -on: - pull_request: - branches: - - main - types: ["closed"] - -permissions: - contents: write - pull-requests: write - -jobs: - cherry_pick_release_0_1_x: - runs-on: ubuntu-latest - name: Cherry pick into release/0.1.x - if: ${{ contains(github.event.pull_request.labels.*.name, 'release/0.1.x') && github.event.pull_request.merged == true }} - steps: - - name: Checkout - uses: actions/checkout@v2 - with: - fetch-depth: 0 - - name: Cherry pick into release/0.1.x - uses: carloscastrojumo/github-cherry-pick-action@v1.0.1 - with: - branch: release/0.1.x - labels: | - cherry-pick - - cherry_pick_release_0_2_x: - runs-on: ubuntu-latest - name: Cherry pick into release/0.2.x - if: ${{ contains(github.event.pull_request.labels.*.name, 'release/0.2.x') && github.event.pull_request.merged == true }} - steps: - - name: Checkout - uses: actions/checkout@v2 - with: - fetch-depth: 0 - - name: Cherry pick into release/0.2.x - uses: carloscastrojumo/github-cherry-pick-action@v1.0.1 - with: - branch: release/0.2.x - labels: | - cherry-pick -env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} +on: + pull_request: + branches: + - main + types: ["closed"] + +permissions: + contents: write + pull-requests: write + +jobs: + cherry_pick_release_0_1_x: + runs-on: ubuntu-latest + name: Cherry pick into release/0.1.x + if: ${{ contains(github.event.pull_request.labels.*.name, 'release/0.1.x') && github.event.pull_request.merged == true }} + steps: + - name: Checkout code + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 pinned commit SHA + with: + fetch-depth: 0 + # Removed persist-credentials: false so the cherry-pick action can authenticate git push + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Cherry pick into release/0.1.x + uses: carloscastrojumo/github-cherry-pick-action@09661c71f982ed876343b83dba9921b4b27a6679 # v1.0.1, pinned to commit SHA + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Scoped to this step only for least privilege + with: + branch: release/0.1.x + labels: | + cherry-pick + + cherry_pick_release_0_2_x: + runs-on: ubuntu-latest + name: Cherry pick into release/0.2.x + if: ${{ contains(github.event.pull_request.labels.*.name, 'release/0.2.x') && github.event.pull_request.merged == true }} + steps: + - name: Checkout code + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 pinned commit SHA + with: + fetch-depth: 0 + # Removed persist-credentials: false so the cherry-pick action can authenticate git push + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Cherry pick into release/0.2.x + uses: carloscastrojumo/github-cherry-pick-action@09661c71f982ed876343b83dba9921b4b27a6679 # v1.0.1, pinned to commit SHA + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Scoped to this step only for least privilege + with: + branch: release/0.2.x + labels: | + cherry-pick diff --git a/.github/workflows/docker_release.yml b/.github/workflows/docker_release.yml index 1e78da379..25ade6db0 100644 --- a/.github/workflows/docker_release.yml +++ b/.github/workflows/docker_release.yml @@ -1,66 +1,71 @@ -name: Push Docker Image - -on: - push: - tags: - - v* - workflow_dispatch: - inputs: - tag: - description: 'Tag name to build (e.g. v0.5.0)' - required: true - -permissions: - contents: read - packages: write - -env: - IMAGE_NAME: ghcr.io/morph-l2/node - -jobs: - push: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ inputs.tag || github.ref }} - - - name: Set up QEMU - uses: docker/setup-qemu-action@v4 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 - - - name: Log into registry - uses: docker/login-action@v3 - with: - registry: ghcr.io - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Extract version and commit - id: meta - run: | - TAG="${{ inputs.tag || github.ref_name }}" - if ! [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then - echo "Invalid release tag: $TAG (expected e.g. v0.5.0)" - exit 1 - fi - VERSION="${TAG#v}" - COMMIT=$(git rev-parse HEAD) - echo "version=${VERSION}" >> "$GITHUB_OUTPUT" - echo "commit=${COMMIT}" >> "$GITHUB_OUTPUT" - - - name: Build and push - uses: docker/build-push-action@v6 - with: - context: . - file: Dockerfile.l2-node - platforms: linux/amd64,linux/arm64 - push: true - tags: | - ${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }} - ${{ env.IMAGE_NAME }}:latest - cache-from: type=gha - cache-to: type=gha,mode=max +name: Push Docker Image + +on: + push: + tags: + - v* + workflow_dispatch: + inputs: + tag: + description: 'Tag name to build (e.g. v0.5.0)' + required: true + +permissions: + contents: read + packages: write + +env: + IMAGE_NAME: ghcr.io/morph-l2/node + +jobs: + push: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.tag || github.ref }} + + - name: Set up QEMU + uses: docker/setup-qemu-action@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log into registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract version and commit + id: meta + # Pass the tag through an env var: interpolating ${{ }} directly into + # run: would let a crafted tag name execute shell code BEFORE the + # regex gate below runs. + env: + TAG_INPUT: ${{ inputs.tag || github.ref_name }} + run: | + TAG="${TAG_INPUT}" + if ! [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then + echo "Invalid release tag: $TAG (expected e.g. v0.5.0)" + exit 1 + fi + VERSION="${TAG#v}" + COMMIT=$(git rev-parse HEAD) + echo "version=${VERSION}" >> "$GITHUB_OUTPUT" + echo "commit=${COMMIT}" >> "$GITHUB_OUTPUT" + + - name: Build and push + uses: docker/build-push-action@v6 + with: + context: . + file: Dockerfile.l2-node + platforms: linux/amd64,linux/arm64 + push: true + tags: | + ${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }} + ${{ env.IMAGE_NAME }}:latest + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/node/hakeeper/config.go b/node/hakeeper/config.go index 20e9b4779..8d2635134 100644 --- a/node/hakeeper/config.go +++ b/node/hakeeper/config.go @@ -1,278 +1,306 @@ -package hakeeper - -import ( - "fmt" - "math" - "net" - "os" - "path/filepath" - "strings" - "time" - - "github.com/pkg/errors" - "github.com/spf13/viper" - tmlog "github.com/tendermint/tendermint/libs/log" -) - -// Config defines the configuration for hakeeper. -type Config struct { - Enabled bool `mapstructure:"enabled"` - ServerID string `mapstructure:"server_id"` - StorageDir string `mapstructure:"storage_dir"` - Bootstrap bool `mapstructure:"bootstrap"` - JoinAddrs []string `mapstructure:"join_addrs"` - - // Debug enables verbose Raft internal logging. Set automatically when - // the node's log level is "debug". Not a config file / env option. - Debug bool `mapstructure:"-"` - - Consensus ConsensusConfig `mapstructure:"consensus"` - Snapshot SnapshotConfig `mapstructure:"snapshot"` - Timeout TimeoutConfig `mapstructure:"timeout"` - RPC RPCConfig `mapstructure:"rpc"` -} - -type ConsensusConfig struct { - ListenAddr string `mapstructure:"listen_addr"` - ListenPort int `mapstructure:"listen_port"` - AdvertisedAddr string `mapstructure:"advertised_addr"` -} - -type SnapshotConfig struct { - Interval time.Duration `mapstructure:"interval"` - Threshold uint64 `mapstructure:"threshold"` - TrailingLogs uint64 `mapstructure:"trailing_logs"` -} - -type TimeoutConfig struct { - Heartbeat time.Duration `mapstructure:"heartbeat"` - LeaderLease time.Duration `mapstructure:"leader_lease"` -} - -type RPCConfig struct { - ListenAddr string `mapstructure:"listen_addr"` - ListenPort int `mapstructure:"listen_port"` - Token string `mapstructure:"token"` -} - -// ── Step 1: Defaults ───────────────────────────────────────────────────────── - -// DefaultConfig returns the default configuration with sensible values -// for all common/generic settings. Node-specific fields (ServerID, StorageDir, -// AdvertisedAddr) are left empty for Resolve() to auto-detect. -func DefaultConfig() *Config { - return &Config{ - Consensus: ConsensusConfig{ - ListenAddr: "0.0.0.0", - ListenPort: 9400, - }, - Snapshot: SnapshotConfig{ - Interval: 30 * time.Second, - Threshold: 200, - TrailingLogs: 1200, - }, - Timeout: TimeoutConfig{ - Heartbeat: 1 * time.Second, - LeaderLease: 500 * time.Millisecond, - }, - RPC: RPCConfig{ - ListenAddr: "0.0.0.0", - ListenPort: 9401, - }, - } -} - -// ── Step 2: Config file overlay (optional) ─────────────────────────────────── - -// LoadFile reads a TOML config file and overlays values onto c. -// Only fields present in the file are overwritten; others keep their current value. -func (c *Config) LoadFile(path string) error { - dir := filepath.Dir(path) - filename := filepath.Base(path) - ext := filepath.Ext(filename) - name := filename[:len(filename)-len(ext)] - - v := viper.New() - v.AddConfigPath(dir) - v.SetConfigName(name) - v.SetConfigType("toml") - - if err := v.ReadInConfig(); err != nil { - return errors.Wrap(err, "failed to read HA config file") - } - if err := v.Unmarshal(c); err != nil { - return errors.Wrap(err, "failed to parse HA config file") - } - return nil -} - -// ── Step 3: Auto-resolve node-specific fields ──────────────────────────────── - -// Resolve fills in empty node-specific fields with auto-detected values: -// - ServerID → os.Hostname() -// - StorageDir → /raft -// - AdvertisedAddr → local non-loopback IP (if ListenAddr is 0.0.0.0) -// -// Call this AFTER flag overrides have been applied and BEFORE Validate(). -func (c *Config) Resolve(homeDir string) error { - // ServerID - if c.ServerID == "" { - hostname, err := os.Hostname() - if err != nil { - return fmt.Errorf("server_id not set and hostname detection failed: %w", err) - } - if hostname == "" { - return fmt.Errorf("server_id not set and hostname is empty") - } - c.ServerID = hostname - } - - // StorageDir - if c.StorageDir == "" { - c.StorageDir = filepath.Join(homeDir, "raft") - } - - // AdvertisedAddr - if c.Consensus.AdvertisedAddr == "" { - addr, err := resolveAdvertisedAddr(c.Consensus.ListenAddr, c.Consensus.ListenPort) - if err != nil { - return err - } - c.Consensus.AdvertisedAddr = addr - } - - return nil -} - -// resolveAdvertisedAddr derives the advertised address when not explicitly set. -func resolveAdvertisedAddr(listenAddr string, listenPort int) (string, error) { - port := fmt.Sprintf("%d", listenPort) - - // If ListenAddr is a specific IP, use it directly. - if listenAddr != "0.0.0.0" && listenAddr != "" { - return net.JoinHostPort(listenAddr, port), nil - } - - // Auto-detect: first non-loopback IPv4 on any active interface. - ip, err := localNonLoopbackIP() - if err != nil { - return "", fmt.Errorf("advertised_addr not set and auto-detect failed: %w", err) - } - return net.JoinHostPort(ip, port), nil -} - -func localNonLoopbackIP() (string, error) { - ifaces, err := net.Interfaces() - if err != nil { - return "", err - } - for _, iface := range ifaces { - if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 { - continue - } - addrs, err := iface.Addrs() - if err != nil { - continue - } - for _, addr := range addrs { - var ip net.IP - switch v := addr.(type) { - case *net.IPNet: - ip = v.IP - case *net.IPAddr: - ip = v.IP - } - if ip4 := ip.To4(); ip4 != nil && !ip4.IsLoopback() { - return ip4.String(), nil - } - } - } - return "", fmt.Errorf("no non-loopback IPv4 address found") -} - -// ── Step 4: Validate ───────────────────────────────────────────────────────── - -// Validate checks that all required fields are present. Call AFTER Resolve(). -func (c *Config) Validate() error { - if c.ServerID == "" { - return fmt.Errorf("server_id is required (set via config, --ha.server-id, or ensure hostname is available)") - } - if c.StorageDir == "" { - return fmt.Errorf("storage_dir is required") - } - if c.Consensus.ListenPort < 0 || c.Consensus.ListenPort > math.MaxUint16 { - return fmt.Errorf("invalid consensus.listen_port: %d", c.Consensus.ListenPort) - } - if c.RPC.ListenPort < 0 || c.RPC.ListenPort > math.MaxUint16 { - return fmt.Errorf("invalid rpc.listen_port: %d", c.RPC.ListenPort) - } - - // Raft timing sanity. A non-positive heartbeat disables liveness; a leader - // lease >= heartbeat destabilizes leadership (hashicorp/raft also requires - // LeaderLeaseTimeout <= HeartbeatTimeout). - if c.Timeout.Heartbeat <= 0 { - return fmt.Errorf("timeout.heartbeat must be > 0, got %s", c.Timeout.Heartbeat) - } - if c.Timeout.LeaderLease <= 0 { - return fmt.Errorf("timeout.leader_lease must be > 0, got %s", c.Timeout.LeaderLease) - } - if c.Timeout.LeaderLease >= c.Timeout.Heartbeat { - return fmt.Errorf("timeout.leader_lease (%s) must be less than timeout.heartbeat (%s)", - c.Timeout.LeaderLease, c.Timeout.Heartbeat) - } - - // TrailingLogs must be positive: snapshotting with 0 trailing logs truncates - // entries a lagging follower still needs, breaking catch-up. - if c.Snapshot.TrailingLogs == 0 { - return fmt.Errorf("snapshot.trailing_logs must be > 0") - } - - // AdvertisedAddr must be a routable address (IP or hostname) after Resolve(). - if c.Consensus.AdvertisedAddr != "" { - host, _, err := net.SplitHostPort(c.Consensus.AdvertisedAddr) - if err != nil { - return fmt.Errorf("invalid consensus.advertised_addr %q: %w", c.Consensus.AdvertisedAddr, err) - } - if host == "0.0.0.0" || host == "" { - return fmt.Errorf("consensus.advertised_addr must be a specific address, not %q", host) - } - } - - // Follower must have at least one address to join. - if !c.Bootstrap && len(c.JoinAddrs) == 0 { - return fmt.Errorf("join_addrs is required when bootstrap=false (set via config or --ha.join)") - } - - return nil -} - -// ── Print effective config ─────────────────────────────────────────────────── - -// LogEffectiveConfig prints the resolved HA configuration for operator visibility. -func (c *Config) LogEffectiveConfig(logger tmlog.Logger) { - role := "follower" - if c.Bootstrap { - role = "bootstrap-leader" - } - joinAddrs := "(none)" - if len(c.JoinAddrs) > 0 { - joinAddrs = strings.Join(c.JoinAddrs, ", ") - } - - logger.Info("========== HA Effective Config ==========") - logger.Info("ha config", - "role", role, - "server_id", c.ServerID, - "advertised_addr", c.Consensus.AdvertisedAddr, - "storage_dir", c.StorageDir, - "join_addrs", joinAddrs, - ) - logger.Info("ha config", - "raft_listen", fmt.Sprintf("%s:%d", c.Consensus.ListenAddr, c.Consensus.ListenPort), - "rpc_listen", fmt.Sprintf("%s:%d", c.RPC.ListenAddr, c.RPC.ListenPort), - "heartbeat", c.Timeout.Heartbeat, - "leader_lease", c.Timeout.LeaderLease, - "trailing_logs", c.Snapshot.TrailingLogs, - ) - logger.Info("=========================================") -} +package hakeeper + +import ( + "fmt" + "math" + "net" + "os" + "path/filepath" + "strings" + "time" + + "github.com/pkg/errors" + "github.com/spf13/viper" + tmlog "github.com/tendermint/tendermint/libs/log" +) + +// Config defines the configuration for hakeeper. +type Config struct { + Enabled bool `mapstructure:"enabled"` + ServerID string `mapstructure:"server_id"` + StorageDir string `mapstructure:"storage_dir"` + Bootstrap bool `mapstructure:"bootstrap"` + JoinAddrs []string `mapstructure:"join_addrs"` + + // Debug enables verbose Raft internal logging. Set automatically when + // the node's log level is "debug". Not a config file / env option. + Debug bool `mapstructure:"-"` + + Consensus ConsensusConfig `mapstructure:"consensus"` + Snapshot SnapshotConfig `mapstructure:"snapshot"` + Timeout TimeoutConfig `mapstructure:"timeout"` + RPC RPCConfig `mapstructure:"rpc"` +} + +type ConsensusConfig struct { + ListenAddr string `mapstructure:"listen_addr"` + ListenPort int `mapstructure:"listen_port"` + AdvertisedAddr string `mapstructure:"advertised_addr"` +} + +type SnapshotConfig struct { + Interval time.Duration `mapstructure:"interval"` + Threshold uint64 `mapstructure:"threshold"` + TrailingLogs uint64 `mapstructure:"trailing_logs"` +} + +type TimeoutConfig struct { + Heartbeat time.Duration `mapstructure:"heartbeat"` + LeaderLease time.Duration `mapstructure:"leader_lease"` +} + +type RPCConfig struct { + ListenAddr string `mapstructure:"listen_addr"` + ListenPort int `mapstructure:"listen_port"` + Token string `mapstructure:"token"` +} + +// ── Step 1: Defaults ───────────────────────────────────────────────────────── + +// DefaultConfig returns the default configuration with sensible values +// for all common/generic settings. Node-specific fields (ServerID, StorageDir, +// AdvertisedAddr) are left empty for Resolve() to auto-detect. +func DefaultConfig() *Config { + return &Config{ + Consensus: ConsensusConfig{ + ListenAddr: "0.0.0.0", + ListenPort: 9400, + }, + Snapshot: SnapshotConfig{ + Interval: 30 * time.Second, + Threshold: 200, + TrailingLogs: 1200, + }, + Timeout: TimeoutConfig{ + Heartbeat: 1 * time.Second, + LeaderLease: 500 * time.Millisecond, + }, + RPC: RPCConfig{ + ListenAddr: "0.0.0.0", + ListenPort: 9401, + }, + } +} + +// ── Step 2: Config file overlay (optional) ─────────────────────────────────── + +// LoadFile reads a TOML config file and overlays values onto c. +// Only fields present in the file are overwritten; others keep their current value. +func (c *Config) LoadFile(path string) error { + dir := filepath.Dir(path) + filename := filepath.Base(path) + ext := filepath.Ext(filename) + name := filename[:len(filename)-len(ext)] + + v := viper.New() + v.AddConfigPath(dir) + v.SetConfigName(name) + v.SetConfigType("toml") + + if err := v.ReadInConfig(); err != nil { + return errors.Wrap(err, "failed to read HA config file") + } + if err := v.Unmarshal(c); err != nil { + return errors.Wrap(err, "failed to parse HA config file") + } + return nil +} + +// ── Step 3: Auto-resolve node-specific fields ──────────────────────────────── + +// Resolve fills in empty node-specific fields with auto-detected values: +// - ServerID → os.Hostname() +// - StorageDir → /raft +// - AdvertisedAddr → local non-loopback IP (if ListenAddr is 0.0.0.0) +// +// Call this AFTER flag overrides have been applied and BEFORE Validate(). +func (c *Config) Resolve(homeDir string) error { + // ServerID + if c.ServerID == "" { + hostname, err := os.Hostname() + if err != nil { + return fmt.Errorf("server_id not set and hostname detection failed: %w", err) + } + if hostname == "" { + return fmt.Errorf("server_id not set and hostname is empty") + } + c.ServerID = hostname + } + + // StorageDir + if c.StorageDir == "" { + c.StorageDir = filepath.Join(homeDir, "raft") + } + + // AdvertisedAddr + if c.Consensus.AdvertisedAddr == "" { + addr, err := resolveAdvertisedAddr(c.Consensus.ListenAddr, c.Consensus.ListenPort) + if err != nil { + return err + } + c.Consensus.AdvertisedAddr = addr + } + + return nil +} + +// resolveAdvertisedAddr derives the advertised address when not explicitly set. +func resolveAdvertisedAddr(listenAddr string, listenPort int) (string, error) { + port := fmt.Sprintf("%d", listenPort) + + // If ListenAddr is a specific IP, use it directly. + if listenAddr != "0.0.0.0" && listenAddr != "" { + return net.JoinHostPort(listenAddr, port), nil + } + + // Auto-detect: first non-loopback IPv4 on any active interface. + ip, err := localNonLoopbackIP() + if err != nil { + return "", fmt.Errorf("advertised_addr not set and auto-detect failed: %w", err) + } + return net.JoinHostPort(ip, port), nil +} + +// isLoopbackListenAddr reports whether the given listen address only accepts +// connections from the local machine. An empty address or a wildcard cannot +// be proven loopback, so it is treated as remotely reachable (fail closed). +func isLoopbackListenAddr(listenAddr string) bool { + if listenAddr == "" { + return false + } + + // Normalize bracketed IPv6 addresses before loopback validation + if len(listenAddr) >= 2 && listenAddr[0] == '[' && listenAddr[len(listenAddr)-1] == ']' { + listenAddr = listenAddr[1 : len(listenAddr)-1] + } + + ip := net.ParseIP(listenAddr) + return ip != nil && ip.IsLoopback() +} + +// localNonLoopbackIP scans active network interfaces to find and return +// the first valid non-loopback IPv4 address. +func localNonLoopbackIP() (string, error) { + ifaces, err := net.Interfaces() + if err != nil { + return "", err + } + for _, iface := range ifaces { + if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 { + continue + } + addrs, err := iface.Addrs() + if err != nil { + continue + } + for _, addr := range addrs { + var ip net.IP + switch v := addr.(type) { + case *net.IPNet: + ip = v.IP + case *net.IPAddr: + ip = v.IP + } + if ip4 := ip.To4(); ip4 != nil && !ip4.IsLoopback() { + return ip4.String(), nil + } + } + } + return "", fmt.Errorf("no non-loopback IPv4 address found") +} + +// ── Step 4: Validate ───────────────────────────────────────────────────────── + +// Validate checks that all required fields are present and valid. Call AFTER Resolve(). +func (c *Config) Validate() error { + if c.ServerID == "" { + return fmt.Errorf("server_id is required (set via config, --ha.server-id, or ensure hostname is available)") + } + if c.StorageDir == "" { + return fmt.Errorf("storage_dir is required") + } + if c.Consensus.ListenPort < 0 || c.Consensus.ListenPort > math.MaxUint16 { + return fmt.Errorf("invalid consensus.listen_port: %d", c.Consensus.ListenPort) + } + if c.RPC.ListenPort < 0 || c.RPC.ListenPort > math.MaxUint16 { + return fmt.Errorf("invalid rpc.listen_port: %d", c.RPC.ListenPort) + } + + // The RPC write APIs (ha_addServerAsVoter, ha_removeServer, + // ha_transferLeaderToServer) mutate Raft membership and leadership. They + // must not be reachable unauthenticated from other hosts: previously an + // empty token only produced a log line and the server kept serving write + // APIs on 0.0.0.0. Fail closed at startup instead. + if c.RPC.Token == "" && !isLoopbackListenAddr(c.RPC.ListenAddr) { + return fmt.Errorf("rpc.token is required when rpc.listen_addr (%q) is not loopback: write APIs would be unauthenticated", c.RPC.ListenAddr) + } + + // Raft timing sanity. A non-positive heartbeat disables liveness; a leader + // lease >= heartbeat destabilizes leadership (hashicorp/raft also requires + // LeaderLeaseTimeout <= HeartbeatTimeout). + if c.Timeout.Heartbeat <= 0 { + return fmt.Errorf("timeout.heartbeat must be > 0, got %s", c.Timeout.Heartbeat) + } + if c.Timeout.LeaderLease <= 0 { + return fmt.Errorf("timeout.leader_lease must be > 0, got %s", c.Timeout.LeaderLease) + } + if c.Timeout.LeaderLease >= c.Timeout.Heartbeat { + return fmt.Errorf("timeout.leader_lease (%s) must be less than timeout.heartbeat (%s)", + c.Timeout.LeaderLease, c.Timeout.Heartbeat) + } + + // TrailingLogs must be positive: snapshotting with 0 trailing logs truncates + // entries a lagging follower still needs, breaking catch-up. + if c.Snapshot.TrailingLogs == 0 { + return fmt.Errorf("snapshot.trailing_logs must be > 0") + } + + // AdvertisedAddr must be a routable address (IP or hostname) after Resolve(). + if c.Consensus.AdvertisedAddr != "" { + host, _, err := net.SplitHostPort(c.Consensus.AdvertisedAddr) + if err != nil { + return fmt.Errorf("invalid consensus.advertised_addr %q: %w", c.Consensus.AdvertisedAddr, err) + } + if host == "0.0.0.0" || host == "" { + return fmt.Errorf("consensus.advertised_addr must be a specific address, not %q", host) + } + } + + // Follower must have at least one address to join. + if !c.Bootstrap && len(c.JoinAddrs) == 0 { + return fmt.Errorf("join_addrs is required when bootstrap=false (set via config or --ha.join)") + } + + return nil +} + +// ── Print effective config ─────────────────────────────────────────────────── + +// LogEffectiveConfig prints the resolved HA configuration for operator visibility. +func (c *Config) LogEffectiveConfig(logger tmlog.Logger) { + role := "follower" + if c.Bootstrap { + role = "bootstrap-leader" + } + joinAddrs := "(none)" + if len(c.JoinAddrs) > 0 { + joinAddrs = strings.Join(c.JoinAddrs, ", ") + } + + logger.Info("========== HA Effective Config ==========") + logger.Info("ha config", + "role", role, + "server_id", c.ServerID, + "advertised_addr", c.Consensus.AdvertisedAddr, + "storage_dir", c.StorageDir, + "join_addrs", joinAddrs, + ) + logger.Info("ha config", + "raft_listen", fmt.Sprintf("%s:%d", c.Consensus.ListenAddr, c.Consensus.ListenPort), + "rpc_listen", fmt.Sprintf("%s:%d", c.RPC.ListenAddr, c.RPC.ListenPort), + "heartbeat", c.Timeout.Heartbeat, + "leader_lease", c.Timeout.LeaderLease, + "trailing_logs", c.Snapshot.TrailingLogs, + ) + logger.Info("=========================================") +} diff --git a/node/hakeeper/rpc/server.go b/node/hakeeper/rpc/server.go index 90ad0216d..f2a00b7b2 100644 --- a/node/hakeeper/rpc/server.go +++ b/node/hakeeper/rpc/server.go @@ -1,8 +1,9 @@ package rpc import ( - "fmt" + "net" "net/http" + "strconv" "sync" "time" @@ -39,7 +40,14 @@ func New(log log.Logger, listenAddr string, listenPort int, cons ConsensusAdapte mux := http.NewServeMux() mux.Handle("/", authMiddleware(token, rpcSrv)) - addr := fmt.Sprintf("%s:%d", listenAddr, listenPort) + // Normalize bracketed IPv6 input before calling net.JoinHostPort + host := listenAddr + if len(host) >= 2 && host[0] == '[' && host[len(host)-1] == ']' { + host = host[1 : len(host)-1] + } + + // Build the RPC address safely for both IPv4 and IPv6 + addr := net.JoinHostPort(host, strconv.Itoa(listenPort)) httpSrv := &http.Server{ Addr: addr, Handler: mux, diff --git a/ops/devnet-morph/devnet/__init__.py b/ops/devnet-morph/devnet/__init__.py index ef4d056ad..549dd314d 100644 --- a/ops/devnet-morph/devnet/__init__.py +++ b/ops/devnet-morph/devnet/__init__.py @@ -44,11 +44,9 @@ '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80', ), help='Private key for the L1 contract deployer/owner') +# Removed the vulnerable Hardhat/Anvil fallback key. The key must be explicitly provided via environment. parser.add_argument('--batch-submitter-private-key', - default=os.environ.get( - 'BATCH_SUBMITTER_PRIVATE_KEY', - '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d', - ), + default=os.environ.get('BATCH_SUBMITTER_PRIVATE_KEY'), help='Private key for the devnet batch submitter; kept separate from the block sequencer') parser.add_argument('--cluster', action="store_true", default=os.environ.get('DEVNET_CLUSTER', '').lower() in ('1', 'true', 'yes'), @@ -95,6 +93,11 @@ def main(): """Entry point: parse CLI arguments and bring up the L1-only or full devnet.""" args = parser.parse_args() + # Fail early if the batch submitter private key is completely missing + if not args.batch_submitter_private_key: + log.error("BATCH_SUBMITTER_PRIVATE_KEY must be set in the environment or passed via --batch-submitter-private-key.") + exit(1) + polyrepo_dir = os.path.abspath(args.polyrepo_dir) L2_dir = pjoin(polyrepo_dir, 'ops', 'l2-genesis') devnet_dir = pjoin(polyrepo_dir, 'ops', 'l2-genesis', '.devnet') @@ -119,7 +122,7 @@ def main(): os.makedirs(devnet_dir, exist_ok=True) if args.only_l1: - devnet_l1(paths) + devnet_l1(paths, args.batch_submitter_private_key) return True # log.info(f'Building docker images') @@ -128,7 +131,7 @@ def main(): devnet_deploy(paths, args) -def devnet_l1(paths, result=None): +def devnet_l1(paths, batch_submitter_private_key, result=None): """Start the L1 execution/consensus/validator stack and fund sequencer accounts.""" log.info('Starting L1.') @@ -154,7 +157,8 @@ def devnet_l1(paths, result=None): log.info('Starting layer1 services (layer1-el, layer1-cl, layer1-vc)...') run_command(['docker', 'compose', '-f', 'docker-compose-devnet.yml', 'up', '-d', 'layer1-el', 'layer1-cl', 'layer1-vc'], cwd=paths.ops_dir, env={ - 'PWD': paths.ops_dir + 'PWD': paths.ops_dir, + 'BATCH_SUBMITTER_PRIVATE_KEY': batch_submitter_private_key, }) # Wait for EL node to be ready @@ -206,7 +210,7 @@ def devnet_build(paths): def devnet_deploy(paths, args): """Bring up the devnet where the contracts are deployed to L1.""" if not test_port(9545): - devnet_l1(paths) + devnet_l1(paths, args.batch_submitter_private_key) done_file = pjoin(paths.devnet_dir, 'done') log.info('Generating network config.') devnet_cfg_orig = pjoin(paths.deploy_config_dir, 'devnet-deploy-config.json') @@ -316,7 +320,6 @@ def devnet_deploy(paths, args): env_data['MORPH_SUBMITTER'] = addresses['Proxy__Submitter'] env_data['BATCH_BLOCK_INTERVAL'] = str(deploy_config['govBatchBlockInterval']) env_data['BATCH_TIMEOUT'] = str(deploy_config['govBatchTimeout']) - env_data['BATCH_SUBMITTER_PRIVATE_KEY'] = args.batch_submitter_private_key env_data['RUST_LOG'] = rust_log_level env_data.pop('Proxy__L1Staking', None) env_data.pop('MORPH_L1STAKING', None) diff --git a/ops/docker/.env b/ops/docker/.env index 9ca56d6cb..cfb2520d0 100644 --- a/ops/docker/.env +++ b/ops/docker/.env @@ -10,7 +10,10 @@ MORPH_ROLLUP=0xa513e6e4b8f2a923d98304ec87f64353c4d5c853 MORPH_SUBMITTER= BATCH_BLOCK_INTERVAL=200 BATCH_TIMEOUT=600 -BATCH_SUBMITTER_PRIVATE_KEY=0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d +# NOTE: the previous value was the well-known Hardhat/Anvil account #1 private +# key, committed in plain text. Provide the real submitter key via the +# environment; never commit funded keys to version control. +BATCH_SUBMITTER_PRIVATE_KEY=${BATCH_SUBMITTER_PRIVATE_KEY:?BATCH_SUBMITTER_PRIVATE_KEY must be set} BUILD_GETH=l2-geth RUST_LOG=info BATCH_UPGRADE_TIME=0