diff --git a/Makefile b/Makefile index 294b9f15f..2bc8ad774 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ ################## update dependencies #################### ETHEREUM_SUBMODULE_COMMIT_OR_TAG := morph-v2.2.8 ETHEREUM_TARGET_VERSION := morph-v2.2.8 -TENDERMINT_TARGET_VERSION := v0.3.11 +TENDERMINT_TARGET_VERSION := v0.3.12-0.20261117072417-04bdb93cdbfe ETHEREUM_MODULE_NAME := github.com/morph-l2/go-ethereum TENDERMINT_MODULE_NAME := github.com/morph-l2/tendermint @@ -11,11 +11,11 @@ update_mod: @echo "Updating go.mod in $(MODULE)..." @if grep -q '$(ETHEREUM_MODULE_NAME)' $(MODULE)/go.mod; then \ - sed -i '' -e "s|$(ETHEREUM_MODULE_NAME) v[0-9][^[:space:]]*|$(ETHEREUM_MODULE_NAME) $(ETHEREUM_TARGET_VERSION)|" $(MODULE)/go.mod; \ + sed -i.bak -e "s|$(ETHEREUM_MODULE_NAME) v[0-9][^[:space:]]*|$(ETHEREUM_MODULE_NAME) $(ETHEREUM_TARGET_VERSION)|" $(MODULE)/go.mod && rm -f $(MODULE)/go.mod.bak; \ fi @if grep -q '$(TENDERMINT_MODULE_NAME)' $(MODULE)/go.mod; then \ - sed -i '' -e "s|$(TENDERMINT_MODULE_NAME) v[0-9][^[:space:]]*|$(TENDERMINT_MODULE_NAME) $(TENDERMINT_TARGET_VERSION)|" $(MODULE)/go.mod; \ + sed -i.bak -e "s|$(TENDERMINT_MODULE_NAME) v[0-9][^[:space:]]*|$(TENDERMINT_MODULE_NAME) $(TENDERMINT_TARGET_VERSION)|" $(MODULE)/go.mod && rm -f $(MODULE)/go.mod.bak; \ fi @cd $(MODULE) && go mod tidy diff --git a/bindings/go.mod b/bindings/go.mod index f75b8d29c..ca252ee0c 100644 --- a/bindings/go.mod +++ b/bindings/go.mod @@ -2,7 +2,7 @@ module morph-l2/bindings go 1.24.0 -replace github.com/tendermint/tendermint => github.com/morph-l2/tendermint v0.3.11 +replace github.com/tendermint/tendermint => github.com/morph-l2/tendermint v0.3.12-0.20261117072417-04bdb93cdbfe require github.com/morph-l2/go-ethereum v1.10.14-0.20261109063348-1c528b351da0 diff --git a/common/go.mod b/common/go.mod index ac13298fa..9cdc89a67 100644 --- a/common/go.mod +++ b/common/go.mod @@ -2,7 +2,7 @@ module morph-l2/common go 1.24.0 -replace github.com/tendermint/tendermint => github.com/morph-l2/tendermint v0.3.11 +replace github.com/tendermint/tendermint => github.com/morph-l2/tendermint v0.3.12-0.20261117072417-04bdb93cdbfe require ( github.com/holiman/uint256 v1.2.4 diff --git a/contracts/go.mod b/contracts/go.mod index 6a9db130f..f3bf46d10 100644 --- a/contracts/go.mod +++ b/contracts/go.mod @@ -2,7 +2,7 @@ module morph-l2/contract go 1.24.0 -replace github.com/tendermint/tendermint => github.com/morph-l2/tendermint v0.3.11 +replace github.com/tendermint/tendermint => github.com/morph-l2/tendermint v0.3.12-0.20261117072417-04bdb93cdbfe require ( github.com/iden3/go-iden3-crypto v0.0.16 diff --git a/node/cmd/node/main.go b/node/cmd/node/main.go index de0d7b47f..7f3167397 100644 --- a/node/cmd/node/main.go +++ b/node/cmd/node/main.go @@ -9,12 +9,10 @@ import ( "os/signal" "path/filepath" "strconv" - "strings" "syscall" "time" "github.com/morph-l2/go-ethereum/common" - "github.com/morph-l2/go-ethereum/crypto" "github.com/morph-l2/go-ethereum/ethclient" "github.com/prometheus/client_golang/prometheus/promhttp" tmcrypto "github.com/tendermint/tendermint/crypto" @@ -208,6 +206,10 @@ func L2NodeMain(ctx *cli.Context) error { if err != nil { return err } + // Report this node's signer addresses in HAKeeper NodeInfo. + if haService != nil && signer != nil { + haService.SetSignerAddrs(signer.Addresses) + } switch { case isMockSequencer: @@ -457,27 +459,36 @@ func initL1SequencerComponents( return nil, nil, nil, fmt.Errorf( "sequencer.privateKey and sequencer.enclaveSignerAddr are mutually exclusive; pick one") case seqPrivKeyHex != "": - seqPrivKeyHex = strings.TrimPrefix(seqPrivKeyHex, "0x") - privKey, err := crypto.HexToECDSA(seqPrivKeyHex) + // Comma-separated list: several keys let the node switch to a new + // sequencer key at its L1 activation height (devnet / testing). + privKeys, err := l1sequencer.ParsePrivateKeys(seqPrivKeyHex) if err != nil { return nil, nil, nil, fmt.Errorf("invalid sequencer private key: %w", err) } - signer, err = l1sequencer.NewLocalSigner(privKey, logger) + signer, err = l1sequencer.NewLocalSigner(logger, privKeys...) if err != nil { return nil, nil, nil, err } - logger.Info("Sequencer signer initialized (local)", "address", signer.Address().Hex()) + logger.Info("Sequencer signer initialized (local)", "addresses", l1sequencer.AddrHexes(signer.Addresses())) case enclaveSignerAddr != "": - var err error - signer, err = l1sequencer.NewEnclaveSigner(enclaveSignerAddr, logger) + // Which keys the enclave loads (KMS key id + SM secret id each) + // comes from MORPH_NODE_SEQUENCER_ENCLAVE_{KMS_KEY_ID,SECRET_ID}_. + keys, err := l1sequencer.ParseEnclaveKeys(os.Environ()) + if err != nil { + return nil, nil, nil, fmt.Errorf("enclave key config: %w", err) + } + signer, err = l1sequencer.NewEnclaveSigner(enclaveSignerAddr, keys, logger) if err != nil { return nil, nil, nil, fmt.Errorf("init enclave signer: %w", err) } logger.Info("Sequencer signer initialized (enclave)", - "addr", enclaveSignerAddr, "address", signer.Address().Hex()) + "addr", enclaveSignerAddr, "addresses", l1sequencer.AddrHexes(signer.Addresses())) default: logger.Info("Sequencer signer not configured (no privateKey, no enclaveSignerAddr)") } + if signer != nil { + l1sequencer.ExposeSignerAddresses("morphnode", signer.Addresses()) + } return tracker, verifier, signer, nil } diff --git a/node/flags/flags.go b/node/flags/flags.go index e6ed45f78..0685b4a11 100644 --- a/node/flags/flags.go +++ b/node/flags/flags.go @@ -238,10 +238,12 @@ var ( Value: 5 * time.Minute, } - // Sequencer private key for block signing (hex encoded, without 0x prefix) + // Sequencer private key(s) for block signing (hex encoded, optional 0x + // prefix). Comma-separated for several keys: before each block the node + // signs with whichever key the L1 contract designates for that height. SequencerPrivateKey = cli.StringFlag{ Name: "sequencer.privateKey", - Usage: "Sequencer private key for block signing (hex encoded)", + Usage: "Sequencer private key(s) for block signing (hex encoded; comma-separated for multiple keys)", EnvVar: prefixEnvVar("SEQUENCER_PRIVATE_KEY"), } @@ -250,8 +252,10 @@ var ( // --addr convention so the same string works in either tool). // Mutually exclusive with sequencer.privateKey — with this set, // the node never sees the plaintext key, signing happens via the - // enclave. The signer's EVM address is fetched at startup via - // GetPubkey. + // enclave. Which keys the enclave loads is configured with env pairs + // MORPH_NODE_SEQUENCER_ENCLAVE_KMS_KEY_ID_ / + // MORPH_NODE_SEQUENCER_ENCLAVE_SECRET_ID_ (one pair per key, any + // number of keys); see l1sequencer.ParseEnclaveKeys. SequencerEnclaveSignerAddr = cli.StringFlag{ Name: "sequencer.enclaveSignerAddr", Usage: "Vsock address of the enclave signer: `CID:port` or `vsock:CID:port`. Mutually exclusive with sequencer.privateKey.", diff --git a/node/go.mod b/node/go.mod index 6e08efd6b..f11a98b3d 100644 --- a/node/go.mod +++ b/node/go.mod @@ -2,7 +2,7 @@ module morph-l2/node go 1.24.0 -replace github.com/tendermint/tendermint => github.com/morph-l2/tendermint v0.3.11 +replace github.com/tendermint/tendermint => github.com/morph-l2/tendermint v0.3.12-0.20261117072417-04bdb93cdbfe require ( github.com/cenkalti/backoff/v4 v4.1.3 diff --git a/node/go.sum b/node/go.sum index 9256eeaeb..c9b341117 100644 --- a/node/go.sum +++ b/node/go.sum @@ -416,8 +416,8 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lN github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/morph-l2/go-ethereum v1.10.14-0.20261109063348-1c528b351da0 h1:NnyyOHfGo/mKSTyQfNhwBiVWwsxxqGFkMI8OR9vIJHY= github.com/morph-l2/go-ethereum v1.10.14-0.20261109063348-1c528b351da0/go.mod h1:qNV1ziCmoLzpIKrAF0c8LUmVuKG3zMiLOA6c8xXkfic= -github.com/morph-l2/tendermint v0.3.11 h1:PTA6TEjbvlRqFYQMrkv8YSSOGwB0e3hdBlqJyyzMWSc= -github.com/morph-l2/tendermint v0.3.11/go.mod h1:qpiwqfcCB89dBYfqVJOc/HjGxDp3OdDlthgttJJYyRs= +github.com/morph-l2/tendermint v0.3.12-0.20261117072417-04bdb93cdbfe h1:w4733oyO9bbsckdOlnc45FqqE2YPNWTzDxJ7dqijiLY= +github.com/morph-l2/tendermint v0.3.12-0.20261117072417-04bdb93cdbfe/go.mod h1:qpiwqfcCB89dBYfqVJOc/HjGxDp3OdDlthgttJJYyRs= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= diff --git a/node/hakeeper/config.go b/node/hakeeper/config.go index 20e9b4779..a87f8a649 100644 --- a/node/hakeeper/config.go +++ b/node/hakeeper/config.go @@ -6,6 +6,7 @@ import ( "net" "os" "path/filepath" + "strconv" "strings" "time" @@ -53,6 +54,28 @@ type RPCConfig struct { ListenAddr string `mapstructure:"listen_addr"` ListenPort int `mapstructure:"listen_port"` Token string `mapstructure:"token"` + + // Peers overrides where other cluster members' HAKeeper RPC is reached, + // as server id -> "host:port". By default a member's RPC is assumed to + // be on its Raft host at this node's own ListenPort, which holds when + // every member uses the same ports; list a member here when that does + // not (several nodes on one host, port mapping). Config file only. + Peers map[string]string `mapstructure:"peers"` +} + +// PeerAddr returns the HAKeeper RPC address of the member with the given +// server id and Raft address: its Peers entry if there is one, otherwise +// the Raft host with this node's own RPC port. +func (c *RPCConfig) PeerAddr(id, raftAddr string) (string, error) { + // The config loader lower-cases keys, so ids are matched case-insensitively. + if addr, ok := c.Peers[strings.ToLower(id)]; ok { + return addr, nil + } + host, _, err := net.SplitHostPort(raftAddr) + if err != nil { + return "", err + } + return net.JoinHostPort(host, strconv.Itoa(c.ListenPort)), nil } // ── Step 1: Defaults ───────────────────────────────────────────────────────── @@ -92,7 +115,9 @@ func (c *Config) LoadFile(path string) error { ext := filepath.Ext(filename) name := filename[:len(filename)-len(ext)] - v := viper.New() + // "::" instead of the default "." key delimiter: server ids are keys of + // rpc.peers and may contain dots (host names). + v := viper.NewWithOptions(viper.KeyDelimiter("::")) v.AddConfigPath(dir) v.SetConfigName(name) v.SetConfigType("toml") @@ -206,6 +231,11 @@ func (c *Config) Validate() error { if c.RPC.ListenPort < 0 || c.RPC.ListenPort > math.MaxUint16 { return fmt.Errorf("invalid rpc.listen_port: %d", c.RPC.ListenPort) } + for id, addr := range c.RPC.Peers { + if _, _, err := net.SplitHostPort(addr); err != nil { + return fmt.Errorf("invalid rpc.peers entry %s = %q: %w", id, addr, err) + } + } // Raft timing sanity. A non-positive heartbeat disables liveness; a leader // lease >= heartbeat destabilizes leadership (hashicorp/raft also requires diff --git a/node/hakeeper/ha.toml.example b/node/hakeeper/ha.toml.example index e9f48afd5..0e30bcebc 100644 --- a/node/hakeeper/ha.toml.example +++ b/node/hakeeper/ha.toml.example @@ -16,6 +16,8 @@ enabled = true bootstrap = false # Addresses of existing cluster nodes to join (follower only). +# Only used while storage_dir is empty: a node that already has Raft state +# reconnects to the cluster recorded there and ignores this list. # Override: --ha.join addr1,addr2 # join_addrs = ["10.0.0.1:9401", "10.0.0.2:9401"] @@ -45,3 +47,11 @@ listen_port = 9401 # If empty, auth is disabled (not recommended for production). # Override: --ha.rpc-token or MORPH_NODE_HA_RPC_TOKEN env var # token = "" + +# Where to reach other members' admin RPC, as server id = "host:port". +# Not needed when every member uses the same ports: a member's RPC is then +# found on its Raft host at this node's own rpc.listen_port. List a member +# only when that does not hold (several nodes on one host, port mapping). +# [rpc.peers] +# node-1 = "127.0.0.1:9501" +# node-2 = "127.0.0.1:9601" diff --git a/node/hakeeper/ha_service.go b/node/hakeeper/ha_service.go index b5c03a8b8..e07a1c7f3 100644 --- a/node/hakeeper/ha_service.go +++ b/node/hakeeper/ha_service.go @@ -7,6 +7,7 @@ import ( "net" "os" "path/filepath" + "slices" "sync" "sync/atomic" "time" @@ -14,6 +15,7 @@ import ( hclog "github.com/hashicorp/go-hclog" "github.com/hashicorp/raft" boltdb "github.com/hashicorp/raft-boltdb/v2" + "github.com/morph-l2/go-ethereum/common" tmlog "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/types" @@ -48,6 +50,15 @@ type HAService struct { transport *raft.NetworkTransport raftObserver *raft.Observer + // hasExistingState is true when the Raft stores already held state (a + // term, log entries or a snapshot) at startup, i.e. this node has taken + // part in a cluster before. Set by initRaft. + hasExistingState bool + + // signerAddrs returns this node's sequencer signer addresses, reported in + // NodeInfo. Nil for a node without a signer. Set before Start(). + signerAddrs func() []common.Address + leaderReady int32 // atomic: 1 = can produce blocks stopCh chan struct{} wg sync.WaitGroup @@ -73,6 +84,12 @@ func New(cfg *Config, logger tmlog.Logger) (*HAService, error) { }, nil } +// SetSignerAddrs registers the source of this node's signer addresses for +// NodeInfo (e.g. signer.Addresses). Must be called before Start(). +func (h *HAService) SetSignerAddrs(fn func() []common.Address) { + h.signerAddrs = fn +} + // SetOnBlockApplied registers the business callback invoked by the FSM on every // committed log entry. Must be called before Start(). func (h *HAService) SetOnBlockApplied(fn func(*types.BlockV2) error) { @@ -109,15 +126,33 @@ func (h *HAService) Start() error { h.wg.Add(1) go h.leaderMonitor() - if !h.cfg.Bootstrap { + if h.shouldJoin() { h.wg.Add(1) go h.joinLoop() + } else if !h.cfg.Bootstrap { + h.logger.Info("hakeeper: raft state found on disk, not joining via join_addrs", + "storage_dir", h.cfg.StorageDir) } h.logger.Info("hakeeper: started", "server_id", h.cfg.ServerID, "bootstrap", h.cfg.Bootstrap) return nil } +// shouldJoin reports whether this node asks join_addrs to add it to a cluster. +// Like bootstrap, that is only for a node with empty Raft storage. A node that +// has state already knows its cluster's members from it and reconnects on its +// own; sending it to join_addrs again would add it to whatever cluster those +// addresses belong to by now. Raft messages carry no cluster identity, so if +// that is a different cluster (a join address that was wiped and bootstrapped +// anew), its leader would overwrite the log kept here and this node would drop +// out of its own cluster. +// +// Consequently a node removed from the cluster does not add itself back on +// restart: wipe its storage_dir, or add it with ha_addServerAsVoter. +func (h *HAService) shouldJoin() bool { + return !h.cfg.Bootstrap && !h.hasExistingState +} + // Stop gracefully shuts down the HAService. // Order: close stopCh → shutdown Raft (unblocks Barrier) → wg.Wait → stop RPC. func (h *HAService) Stop() { @@ -171,7 +206,9 @@ func (h *HAService) tryJoin(addr string) error { return fmt.Errorf("get membership from %s: %w", addr, err) } - // If this node is already a member (e.g. after a restart), skip AddServerAsVoter. + // If this node is already a member (its storage was wiped without removing + // it, or an earlier attempt timed out after the leader had added it), skip + // AddServerAsVoter. for _, srv := range membership.Servers { if srv.ID == h.cfg.ServerID { h.logger.Info("hakeeper: already a cluster member, skipping join", "id", h.cfg.ServerID) @@ -290,6 +327,69 @@ func (h *HAService) TransferLeaderTo(id, addr string) error { return h.r.LeadershipTransferToServer(raft.ServerID(id), raft.ServerAddress(addr)).Error() } +// TransferLeaderToEligible hands leadership to an eligible voter: one whose +// signer holds a key for addr, the address the L1 contract designates as +// sequencer for the next block. Used by a leader that holds no key for it. +func (h *HAService) TransferLeaderToEligible(addr common.Address) error { + future := h.r.GetConfiguration() + if err := future.Error(); err != nil { + return err + } + target, ok := h.findSignerHolder(future.Configuration().Servers, addr) + if !ok { + return fmt.Errorf("no other voter holds a key for %s", addr.Hex()) + } + h.logger.Info("hakeeper: handing leadership to the holder of the designated key", + "to", target.ID, "signer", addr.Hex()) + return h.r.LeadershipTransferToServer(target.ID, target.Address).Error() +} + +// findSignerHolder returns the first voter other than this node whose +// signer holds a key for addr, asking each for its NodeInfo. A member that +// cannot be reached is skipped: it could not take over anyway. +func (h *HAService) findSignerHolder(servers []raft.Server, addr common.Address) (raft.Server, bool) { + for _, srv := range servers { + if srv.Suffrage != raft.Voter || string(srv.ID) == h.cfg.ServerID { + continue + } + info, err := h.peerNodeInfo(srv) + if err != nil { + h.logger.Error("hakeeper: cannot query member's signer addresses", "id", srv.ID, "err", err) + continue + } + if slices.Contains(info.SignerAddrs, addr) { + return srv, true + } + } + return raft.Server{}, false +} + +// peerNodeInfo fetches a member's NodeInfo over its HAKeeper RPC (see +// RPCConfig.PeerAddr for where that is). The answer must come from the +// member that was asked for: a wrong address is an error, never another +// node's signer addresses. +func (h *HAService) peerNodeInfo(srv raft.Server) (*hakeeperrpc.NodeInfo, error) { + rpcAddr, err := h.cfg.RPC.PeerAddr(string(srv.ID), string(srv.Address)) + if err != nil { + return nil, err + } + ctx, cancel := context.WithTimeout(context.Background(), raftTimeout) + defer cancel() + client, err := hakeeperrpc.DialAPIClient(ctx, rpcAddr, "") + if err != nil { + return nil, err + } + defer client.Close() + info, err := client.NodeInfo(ctx) + if err != nil { + return nil, err + } + if info.ServerID != string(srv.ID) { + return nil, fmt.Errorf("%s answered as %q", rpcAddr, info.ServerID) + } + return info, nil +} + func (h *HAService) ClusterMembership() (*hakeeperrpc.ClusterMembership, error) { future := h.r.GetConfiguration() if err := future.Error(); err != nil { @@ -315,6 +415,19 @@ func (h *HAService) ServerID() string { return h.cfg.ServerID } func (h *HAService) Addr() string { return h.advertisedAddr } +func (h *HAService) NodeInfo() *hakeeperrpc.NodeInfo { + info := &hakeeperrpc.NodeInfo{ + ServerID: h.cfg.ServerID, + Addr: h.advertisedAddr, + Leader: h.Leader(), + SignerAddrs: []common.Address{}, + } + if h.signerAddrs != nil { + info.SignerAddrs = append(info.SignerAddrs, h.signerAddrs()...) + } + return info +} + // ── internal ───────────────────────────────────────────────────────────────── // initRaft creates the Raft instance. Called once from Start(). @@ -409,6 +522,12 @@ func (h *HAService) initRaft() (retErr error) { return fmt.Errorf("TCP transport: %w", err) } + // Checked before Raft runs, since it may write to the stores once it does. + hasExistingState, err := raft.HasExistingState(logStore, stableStore, snapshotStore) + if err != nil { + return fmt.Errorf("check existing raft state: %w", err) + } + r, err = raft.NewRaft(rc, h.fsm, logStore, stableStore, snapshotStore, transport) if err != nil { return fmt.Errorf("raft.NewRaft: %w", err) @@ -425,6 +544,7 @@ func (h *HAService) initRaft() (retErr error) { h.r = r h.transport = transport + h.hasExistingState = hasExistingState h.logger.Info("hakeeper: raft initialized", "bind", bindAddr) return nil diff --git a/node/hakeeper/ha_service_test.go b/node/hakeeper/ha_service_test.go index ca1150bc1..a4ea63073 100644 --- a/node/hakeeper/ha_service_test.go +++ b/node/hakeeper/ha_service_test.go @@ -1,10 +1,21 @@ package hakeeper import ( + "net" + "net/http/httptest" + "os" + "path/filepath" + "strconv" "testing" "github.com/go-kit/kit/metrics" "github.com/hashicorp/raft" + boltdb "github.com/hashicorp/raft-boltdb/v2" + "github.com/morph-l2/go-ethereum/common" + ethrpc "github.com/morph-l2/go-ethereum/rpc" + tmlog "github.com/tendermint/tendermint/libs/log" + + hakeeperrpc "morph-l2/node/hakeeper/rpc" ) type recordingGauge struct { @@ -44,3 +55,178 @@ func TestHandleRaftObservationUpdatesRaftStateImmediately(t *testing.T) { t.Fatalf("raft_state metric = %v, want %v", stateGauge.value, raft.Leader) } } + +func TestNodeInfoReportsSignerAddrs(t *testing.T) { + h := &HAService{cfg: &Config{ServerID: "node-1"}, advertisedAddr: "10.0.0.1:9400"} + + // No signer configured: empty (not nil) list. + info := h.NodeInfo() + if info.ServerID != "node-1" || info.Addr != "10.0.0.1:9400" || info.Leader { + t.Fatalf("unexpected identity: %+v", info) + } + if info.SignerAddrs == nil || len(info.SignerAddrs) != 0 { + t.Fatalf("SignerAddrs = %v, want empty", info.SignerAddrs) + } + + // Read on every call, so a changed signer key set is reflected. + addrs := []common.Address{common.HexToAddress("0xa1"), common.HexToAddress("0xb2")} + h.SetSignerAddrs(func() []common.Address { return addrs }) + if got := h.NodeInfo().SignerAddrs; len(got) != 2 || got[0] != addrs[0] || got[1] != addrs[1] { + t.Fatalf("SignerAddrs = %v, want %v", got, addrs) + } + addrs = addrs[1:] + if got := h.NodeInfo().SignerAddrs; len(got) != 1 || got[0] != addrs[0] { + t.Fatalf("SignerAddrs after change = %v, want %v", got, addrs) + } +} + +// A leader without the designated key looks for a voter that holds it, by +// asking each member's HAKeeper RPC for its signer addresses. +func TestFindSignerHolder(t *testing.T) { + oldKey, newKey := common.HexToAddress("0xa1"), common.HexToAddress("0xb2") + + // The peer: holds both keys and serves ha_nodeInfo. + peer := &HAService{cfg: &Config{ServerID: "node-2"}} + peer.SetSignerAddrs(func() []common.Address { return []common.Address{oldKey, newKey} }) + srv := ethrpc.NewServer() + if err := srv.RegisterName(hakeeperrpc.RPCNamespace, hakeeperrpc.NewAPIBackend(tmlog.NewNopLogger(), peer)); err != nil { + t.Fatal(err) + } + ts := httptest.NewServer(srv) + defer ts.Close() + _, port, _ := net.SplitHostPort(ts.Listener.Addr().String()) + rpcPort, _ := strconv.Atoi(port) + + // The leader uses the same RPC port as the peer, so by default every + // member's RPC is expected on that port of its Raft host. + h := &HAService{ + logger: tmlog.NewNopLogger(), + cfg: &Config{ServerID: "node-1", RPC: RPCConfig{ListenPort: rpcPort}}, + } + self := raft.Server{ID: "node-1", Address: "127.0.0.1:9400", Suffrage: raft.Voter} + voter := raft.Server{ID: "node-2", Address: "127.0.0.1:9400", Suffrage: raft.Voter} + nonvoter := raft.Server{ID: "node-3", Address: "127.0.0.1:9400", Suffrage: raft.Nonvoter} + unreachable := raft.Server{ID: "node-4", Address: "no-port", Suffrage: raft.Voter} + // Its default RPC address is answered by node-2: not node-5's keys. + impostor := raft.Server{ID: "node-5", Address: "127.0.0.1:9400", Suffrage: raft.Voter} + + // Itself, non-voters, unreachable members and answers from another + // node are passed over. + got, ok := h.findSignerHolder([]raft.Server{self, nonvoter, unreachable, impostor, voter}, newKey) + if !ok || got.ID != voter.ID { + t.Fatalf("holder = %v,%v; want %s", got.ID, ok, voter.ID) + } + if _, ok := h.findSignerHolder([]raft.Server{self, nonvoter, unreachable, impostor}, newKey); ok { + t.Fatal("no eligible member holds the key: want none") + } + if _, ok := h.findSignerHolder([]raft.Server{self, voter}, common.HexToAddress("0xc3")); ok { + t.Fatal("nobody holds this key: want none") + } + + // A leader on another RPC port (several nodes on one host) cannot guess + // the peer's address and needs it spelled out in rpc.peers. + h.cfg.RPC.ListenPort = rpcPort + 1 + if _, ok := h.findSignerHolder([]raft.Server{self, voter}, newKey); ok { + t.Fatal("peer is not on the leader's RPC port: want none without rpc.peers") + } + h.cfg.RPC.Peers = map[string]string{"node-2": ts.Listener.Addr().String()} + if got, ok := h.findSignerHolder([]raft.Server{self, voter}, newKey); !ok || got.ID != voter.ID { + t.Fatalf("with rpc.peers: holder = %v,%v; want %s", got.ID, ok, voter.ID) + } +} + +// Only a node with empty Raft storage asks join_addrs to add it to a cluster. +// One that already has state belongs to the cluster recorded there, and must +// not be added to whichever cluster a join address is part of by now. +func TestJoinOnlyWithEmptyRaftStorage(t *testing.T) { + start := func(t *testing.T, dir string, bootstrap bool) *HAService { + cfg := DefaultConfig() + cfg.ServerID = "node-1" + cfg.StorageDir = dir + cfg.Bootstrap = bootstrap + cfg.JoinAddrs = []string{"127.0.0.1:9401"} + cfg.Consensus.ListenAddr = "127.0.0.1" + cfg.Consensus.ListenPort = 0 // any free port + h := &HAService{ + logger: tmlog.NewNopLogger(), + cfg: cfg, + advertisedAddr: "127.0.0.1:9400", + fsm: NewBlockFSM(tmlog.NewNopLogger(), NopMetrics()), + metrics: NopMetrics(), + } + if err := h.initRaft(); err != nil { + t.Fatal(err) + } + t.Cleanup(h.shutdownRaft) + return h + } + + // Raft storage as a node that has taken part in a cluster leaves it. + usedDir := func(t *testing.T) string { + dir := t.TempDir() + logs, err := boltdb.NewBoltStore(filepath.Join(dir, "raft-log.db")) + if err != nil { + t.Fatal(err) + } + if err := logs.StoreLog(&raft.Log{Index: 1, Term: 1, Type: raft.LogNoop}); err != nil { + t.Fatal(err) + } + if err := logs.Close(); err != nil { + t.Fatal(err) + } + return dir + } + + if h := start(t, t.TempDir(), false); !h.shouldJoin() { + t.Error("empty storage: a follower must join") + } + if h := start(t, usedDir(t), false); h.shouldJoin() { + t.Error("existing raft state: a follower must not join again") + } + if h := start(t, t.TempDir(), true); h.shouldJoin() { + t.Error("a bootstrap node never joins") + } +} + +// rpc.peers comes from the config file; ids are matched case-insensitively +// because the loader lower-cases keys, and may contain dots. +func TestConfigRPCPeers(t *testing.T) { + path := filepath.Join(t.TempDir(), "ha.toml") + toml := ` +[consensus] +listen_port = 9500 + +[rpc] +listen_port = 9401 + +[rpc.peers] +ha1 = "127.0.0.1:9701" +Node-B = "10.0.0.2:9501" +"node-c.example" = "10.0.0.3:9501" +` + if err := os.WriteFile(path, []byte(toml), 0o600); err != nil { + t.Fatal(err) + } + cfg := DefaultConfig() + if err := cfg.LoadFile(path); err != nil { + t.Fatal(err) + } + if cfg.Consensus.ListenPort != 9500 || cfg.RPC.ListenPort != 9401 || cfg.RPC.ListenAddr != "0.0.0.0" { + t.Fatalf("file values / defaults not applied: %+v %+v", cfg.Consensus, cfg.RPC) + } + for _, tc := range []struct{ id, raftAddr, want string }{ + {"node-c.example", "10.0.0.3:9400", "10.0.0.3:9501"}, // listed, dotted id + {"ha1", "127.0.0.1:9700", "127.0.0.1:9701"}, // listed + {"Node-B", "10.0.0.2:9400", "10.0.0.2:9501"}, // listed, mixed case + {"ha2", "ha-node-2:9400", "ha-node-2:9401"}, // not listed: raft host + own RPC port + {"ha3", "[fd00::3]:9400", "[fd00::3]:9401"}, // IPv6 + } { + got, err := cfg.RPC.PeerAddr(tc.id, tc.raftAddr) + if err != nil || got != tc.want { + t.Errorf("PeerAddr(%s, %s) = %q, %v; want %q", tc.id, tc.raftAddr, got, err, tc.want) + } + } + if _, err := cfg.RPC.PeerAddr("ha4", "no-port"); err == nil { + t.Error("a Raft address without a port must be an error") + } +} diff --git a/node/hakeeper/rpc/api.go b/node/hakeeper/rpc/api.go index 3f4585513..305e2a1f5 100644 --- a/node/hakeeper/rpc/api.go +++ b/node/hakeeper/rpc/api.go @@ -20,4 +20,7 @@ type API interface { TransferLeaderToServer(ctx context.Context, id string, addr string) error // ClusterMembership returns the current cluster membership configuration. ClusterMembership(ctx context.Context) (*ClusterMembership, error) + // NodeInfo returns this node's identity and the sequencer signer + // addresses it holds. Read-only, public information (no auth). + NodeInfo(ctx context.Context) (*NodeInfo, error) } diff --git a/node/hakeeper/rpc/auth_test.go b/node/hakeeper/rpc/auth_test.go index 4775df114..bbb4df863 100644 --- a/node/hakeeper/rpc/auth_test.go +++ b/node/hakeeper/rpc/auth_test.go @@ -161,3 +161,15 @@ func TestAuthMiddleware_UnparseableBody_NoToken_Returns401(t *testing.T) { } } } + +func TestAuthMiddleware_NodeInfo_NoToken_Passes(t *testing.T) { + h := authMiddleware("secret", okHandler) + body := `{"jsonrpc":"2.0","method":"ha_nodeInfo","params":[],"id":1}` + req := httptest.NewRequest(http.MethodPost, "/", bytes.NewBufferString(body)) + req.Header.Set("Content-Type", "application/json") + rr := httptest.NewRecorder() + h.ServeHTTP(rr, req) + if rr.Code != http.StatusOK { + t.Fatalf("expected 200 for read-only ha_nodeInfo without token, got %d", rr.Code) + } +} diff --git a/node/hakeeper/rpc/backend.go b/node/hakeeper/rpc/backend.go index bb1be40b8..ee0f5facc 100644 --- a/node/hakeeper/rpc/backend.go +++ b/node/hakeeper/rpc/backend.go @@ -58,3 +58,7 @@ func (api *APIBackend) TransferLeaderToServer(ctx context.Context, id string, ad func (api *APIBackend) ClusterMembership(ctx context.Context) (*ClusterMembership, error) { return api.cons.ClusterMembership() } + +func (api *APIBackend) NodeInfo(ctx context.Context) (*NodeInfo, error) { + return api.cons.NodeInfo(), nil +} diff --git a/node/hakeeper/rpc/client.go b/node/hakeeper/rpc/client.go index 0aa832c26..0281bcfef 100644 --- a/node/hakeeper/rpc/client.go +++ b/node/hakeeper/rpc/client.go @@ -82,3 +82,9 @@ func (c *APIClient) ClusterMembership(ctx context.Context) (*ClusterMembership, err := c.c.CallContext(ctx, &membership, prefixRPC("clusterMembership")) return &membership, err } + +func (c *APIClient) NodeInfo(ctx context.Context) (*NodeInfo, error) { + var info NodeInfo + err := c.c.CallContext(ctx, &info, prefixRPC("nodeInfo")) + return &info, err +} diff --git a/node/hakeeper/rpc/types.go b/node/hakeeper/rpc/types.go index fbc0bfeaf..539d3ed57 100644 --- a/node/hakeeper/rpc/types.go +++ b/node/hakeeper/rpc/types.go @@ -1,5 +1,7 @@ package rpc +import "github.com/morph-l2/go-ethereum/common" + // ServerSuffrage determines whether a Server in a Configuration gets a vote. type ServerSuffrage int @@ -44,6 +46,17 @@ type ServerInfo struct { Suffrage ServerSuffrage `json:"suffrage"` } +// NodeInfo describes one HA node: its Raft identity and the sequencer +// signer addresses it can sign blocks with (empty for a node without a +// signer). Exchanged between raft members so a leader can tell which +// member holds the key the L1 contract designates. +type NodeInfo struct { + ServerID string `json:"serverId"` + Addr string `json:"addr"` + Leader bool `json:"leader"` + SignerAddrs []common.Address `json:"signerAddrs"` +} + // ConsensusAdapter is the interface the RPC backend requires. // It is implemented directly by HAService in ha_service.go. type ConsensusAdapter interface { @@ -58,4 +71,5 @@ type ConsensusAdapter interface { ClusterMembership() (*ClusterMembership, error) ServerID() string Addr() string + NodeInfo() *NodeInfo } diff --git a/node/l1sequencer/enclave_creds.go b/node/l1sequencer/enclave_creds.go index f36ce824d..82601551a 100644 --- a/node/l1sequencer/enclave_creds.go +++ b/node/l1sequencer/enclave_creds.go @@ -5,7 +5,6 @@ import ( "encoding/xml" "fmt" "io" - "net" "net/http" "net/url" "os" @@ -14,7 +13,7 @@ import ( ) // awsCreds are the temporary AWS credentials the node injects into the -// enclave over vsock (op=ProvideCredentials). The enclave reads no IMDS, +// enclave over vsock with each LoadKeys request. The enclave reads no IMDS, // so the host resolves credentials and pushes them in. type awsCreds struct { accessKeyID string @@ -23,36 +22,18 @@ type awsCreds struct { expiryUnixSecs uint64 } -// injectCredentials resolves credentials from the pod's IRSA environment -// and pushes them into the enclave on a one-shot connection, so the -// signer can run its deferred one-time key load (SM Get + KMS Decrypt). -// -// No IRSA env (local/dev) → skip; the following probe() then surfaces the -// enclave's own error if it actually needed credentials. Idempotent -// enclave-side: re-injecting after the key is loaded is a no-op Ack, so -// this runs safely on every node (re)start. -func (s *EnclaveSigner) injectCredentials() error { +// resolveCreds returns the pod's IRSA credentials, or nil when no IRSA env +// is present (local/dev: the enclave's file backend needs none). Resolved +// fresh for every LoadKeys, so expiry is never an issue. +func resolveCreds() (*awsCreds, error) { creds, available, err := irsaCreds() if err != nil { - return fmt.Errorf("resolve IRSA credentials: %w", err) + return nil, fmt.Errorf("resolve IRSA credentials: %w", err) } if !available { - s.logger.Info("no IRSA env; skipping enclave credential injection") - return nil - } - conn, err := s.dial() - if err != nil { - return err - } - defer func() { _ = conn.Close() }() - if err := conn.SetDeadline(time.Now().Add(credLoadTimeout)); err != nil { - return fmt.Errorf("set deadline: %w", err) + return nil, nil } - if err := writeProvideCredentials(conn, creds); err != nil { - return fmt.Errorf("provide credentials: %w", err) - } - s.logger.Info("enclave credentials injected via IRSA", "role", os.Getenv("AWS_ROLE_ARN")) - return nil + return &creds, nil } // irsaCreds resolves temporary credentials from the EKS IRSA environment @@ -146,7 +127,7 @@ func assumeRoleWithWebIdentity(region, roleARN, session, jwt string) (awsCreds, return out, nil } -// ProvideCredentials field caps — must match crates/protocol in the +// Credential field caps — must match crates/protocol in the // morph-enclave-signer repo. Bounding each field keeps the u16 length // prefix from overflowing (STS credential fields are opaque and, per AWS, // carry no documented max size). @@ -156,38 +137,36 @@ const ( maxSessionTokenLen = 8192 ) -// writeProvideCredentials sends op=ProvideCredentials on an established -// conn and reads the Ack. Field layout mirrors crates/protocol (and -// ops-cli's client.go): +// appendCreds appends the credential block shared by Init / LoadKeys +// (mirrors crates/protocol and ops-cli's client.go): // -// [op=0x04][akid_lp][sak_lp][token_lp][expiry:u64] +// [akid_lp][sak_lp][token_lp][expiry:u64] // -// where each _lp is [len:u16][bytes]; all integers are big-endian. -func writeProvideCredentials(conn net.Conn, c awsCreds) error { +// where each _lp is [len:u16][bytes]; nil creds = empty akid (none). +func appendCreds(buf []byte, creds *awsCreds) ([]byte, error) { + var c awsCreds + if creds != nil { + c = *creds + } if len(c.accessKeyID) > maxAccessKeyIDLen { - return fmt.Errorf("access key id len %d exceeds max %d", len(c.accessKeyID), maxAccessKeyIDLen) + return nil, fmt.Errorf("access key id len %d exceeds max %d", len(c.accessKeyID), maxAccessKeyIDLen) } if len(c.secretAccessKey) > maxSecretAccessKeyLen { - return fmt.Errorf("secret access key len %d exceeds max %d", len(c.secretAccessKey), maxSecretAccessKeyLen) + return nil, fmt.Errorf("secret access key len %d exceeds max %d", len(c.secretAccessKey), maxSecretAccessKeyLen) } if len(c.sessionToken) > maxSessionTokenLen { - return fmt.Errorf("session token len %d exceeds max %d", len(c.sessionToken), maxSessionTokenLen) + return nil, fmt.Errorf("session token len %d exceeds max %d", len(c.sessionToken), maxSessionTokenLen) } - buf := []byte{opProvideCredentials} buf = appendLPString(buf, c.accessKeyID) buf = appendLPString(buf, c.secretAccessKey) buf = appendLPString(buf, c.sessionToken) var exp [8]byte binary.BigEndian.PutUint64(exp[:], c.expiryUnixSecs) - buf = append(buf, exp[:]...) - if _, err := conn.Write(buf); err != nil { - return fmt.Errorf("write ProvideCredentials: %w", err) - } - return readOkStatus(conn) + return append(buf, exp[:]...), nil } // appendLPString appends a [len:u16][bytes] field (big-endian length). -// Callers bound each field below the u16 max (see writeProvideCredentials), +// Callers bound each field below the u16 max (see appendCreds), // so the length conversion cannot overflow. func appendLPString(buf []byte, s string) []byte { var l [2]byte diff --git a/node/l1sequencer/enclave_signer.go b/node/l1sequencer/enclave_signer.go index be84be6de..dfe9a1954 100644 --- a/node/l1sequencer/enclave_signer.go +++ b/node/l1sequencer/enclave_signer.go @@ -2,10 +2,11 @@ package l1sequencer import ( "encoding/binary" - "errors" "fmt" "io" "net" + "slices" + "sort" "strconv" "strings" "sync" @@ -20,116 +21,281 @@ import ( // Wire protocol constants — must match crates/protocol/src/lib.rs in // the morph-enclave-signer repo. Big-endian throughout. // -// Init (op=0x01) is the key-creation flow handled by ops-cli on a -// throwaway EC2; the morph node never sends it. ProvideCredentials -// (op=0x04) is sent once at startup to inject IRSA credentials so the -// AWS-backed signer can load its key (see injectCredentials). +// The enclave image carries no key configuration: the node names every +// key (KMS key id + SM secret id) in LoadKeys (op=0x04), together with +// the AWS credentials, and signs with Sign(address, hash) (op=0x02). +// Init (op=0x01) is the key-creation flow run by ops-cli; ListKeys +// (op=0x03) is for operators. The node never sends either. const ( - opSign byte = 0x02 - opGetPubkey byte = 0x03 - opProvideCredentials byte = 0x04 + opSign byte = 0x02 // [address:20][hash:32] + opLoadKeys byte = 0x04 // [creds][n:u8] + n × [kms_lp][sid_lp] statusOk byte = 0x00 - // statusKeyNotInitialized (Status::KeyNotInitialized in crates/protocol) - // means the enclave has no key loaded — its in-memory keystore is empty, - // e.g. because the enclave restarted and lost the key. Sign recovers by - // re-injecting credentials (idempotent enclave-side) and retrying. - statusKeyNotInitialized byte = 0x02 hashLen = 32 sigLen = 65 pubkeyLen = 33 addressLen = 20 maxErrMsg = 1024 + // maxIDLen caps a KMS key id / SM secret id (crates/protocol + // MAX_SECRET_ID_LEN). + maxIDLen = 512 // dialTimeout bounds vsock connect. mdlayher/vsock has no // context/timeout-aware Dial, so we wrap it in a goroutine and // race against a timer; without this the constructor and any - // reconnect on the Sign hot path could block forever if the + // reconnect on the sign hot path could block forever if the // enclave accepted the FD but never sends. dialTimeout = 3 * time.Second - // requestTimeout bounds one round-trip on an established conn. - // Applied via SetDeadline at the start of probe/signOnce, cleared - // on exit so the persistent conn can be reused for the next call. + // requestTimeout bounds one Sign round-trip on an established conn. + // Applied via SetDeadline at the start of each RPC, cleared on + // exit so the persistent conn can be reused for the next call. requestTimeout = 1 * time.Second - // credLoadTimeout bounds the one-shot ProvideCredentials round-trip. - // Unlike a normal RPC, the enclave's Ack returns only after its - // one-time SM Get + KMS Decrypt + key load, so this is far larger - // than requestTimeout. - credLoadTimeout = 5 * time.Second + // perKeyLoadTimeout budgets one key's SM Get + KMS Decrypt inside + // LoadKeys; the whole request gets this times the key count. Keys the + // enclave already holds answer from memory and cost nothing. + perKeyLoadTimeout = 5 * time.Second ) +// Env var names for the enclave key config: one KMS key id / SM secret id +// pair per key, numbered by , e.g. +// +// MORPH_NODE_SEQUENCER_ENCLAVE_KMS_KEY_ID_0=arn:aws:kms:... +// MORPH_NODE_SEQUENCER_ENCLAVE_SECRET_ID_0=arn:aws:secretsmanager:... +const ( + EnclaveKMSKeyIDEnvPrefix = "MORPH_NODE_SEQUENCER_ENCLAVE_KMS_KEY_ID_" + EnclaveSecretIDEnvPrefix = "MORPH_NODE_SEQUENCER_ENCLAVE_SECRET_ID_" + enclaveKeyEnvPrefixSummary = "MORPH_NODE_SEQUENCER_ENCLAVE_{KMS_KEY_ID,SECRET_ID}_" +) + +// EnclaveKey names one key the enclave should load. +type EnclaveKey struct { + KMSKeyID string + SecretID string +} + +// ParseEnclaveKeys collects the enclave key config from environment +// entries ("K=V", as from os.Environ). Every that appears is one key; +// keys are ordered by , which need not be contiguous. must be a +// plain decimal number ("0", "1", "10"; not "01"). An with only one +// half of the pair (or an empty value) is an error, as is having no key +// at all. +func ParseEnclaveKeys(environ []string) ([]EnclaveKey, error) { + type pair struct{ kms, sid string } + pairs := map[uint64]*pair{} + for _, kv := range environ { + k, v, _ := strings.Cut(kv, "=") + var suffix string + var isKMS bool + switch { + case strings.HasPrefix(k, EnclaveKMSKeyIDEnvPrefix): + suffix, isKMS = strings.TrimPrefix(k, EnclaveKMSKeyIDEnvPrefix), true + case strings.HasPrefix(k, EnclaveSecretIDEnvPrefix): + suffix = strings.TrimPrefix(k, EnclaveSecretIDEnvPrefix) + default: + continue + } + // Canonical decimal only: "01" and "1" would otherwise both parse + // to 1 and one pair would silently overwrite the other. + n, err := strconv.ParseUint(suffix, 10, 32) + if err != nil || strconv.FormatUint(n, 10) != suffix { + return nil, fmt.Errorf("%s: suffix must be a decimal number without leading zeros", k) + } + p := pairs[n] + if p == nil { + p = &pair{} + pairs[n] = p + } + if isKMS { + p.kms = v + } else { + p.sid = v + } + } + if len(pairs) == 0 { + return nil, fmt.Errorf("no enclave key configured: set %s", enclaveKeyEnvPrefixSummary) + } + ns := make([]uint64, 0, len(pairs)) + for n := range pairs { + ns = append(ns, n) + } + sort.Slice(ns, func(i, j int) bool { return ns[i] < ns[j] }) + keys := make([]EnclaveKey, 0, len(ns)) + for _, n := range ns { + p := pairs[n] + if p.kms == "" || p.sid == "" { + return nil, fmt.Errorf("%s%d and %s%d must both be set", EnclaveKMSKeyIDEnvPrefix, n, EnclaveSecretIDEnvPrefix, n) + } + keys = append(keys, EnclaveKey{KMSKeyID: p.kms, SecretID: p.sid}) + } + return keys, nil +} + // EnclaveSigner implements Signer by talking to a Nitro Enclave signer -// over vsock. One persistent connection is reused across all Sign -// calls; on any wire error the next call transparently reconnects. +// over vsock. One persistent connection is reused across all sign calls; +// on any wire error the next call transparently reconnects. +// +// The node owns the key config (which KMS key / SM secret backs each +// key) and pushes it on every new connection with LoadKeys, so a +// restarted enclave — which has lost its in-memory keys — is reloaded +// without a node restart. // -// Address format: "CID:port" (e.g. "16:5000"). The enclave's EVM -// address is fetched at startup via GetPubkey and cached. +// The signer's identity — the address of every configured key — is fixed +// by the first connection and never changes afterwards: every later +// connection must load exactly the same addresses or it is refused. +// Changing keys means changing the config and restarting the node. type EnclaveSigner struct { - cid uint32 - port uint32 - address common.Address - logger tmlog.Logger + cid uint32 + port uint32 + logger tmlog.Logger + keys []EnclaveKey + // dialFn opens a fresh connection to the enclave (vsock in production); + // credsFn resolves the AWS credentials sent with LoadKeys (IRSA, nil + // when absent). Both replaceable in tests. + dialFn func() (net.Conn, error) + credsFn func() (*awsCreds, error) + + // addrs[i] is the address of keys[i]. Set once by the first connection + // and read-only from then on, so it needs no lock. + addrs []common.Address + // mu guards conn and is held for a whole sign (including a reconnect). mu sync.Mutex conn net.Conn } -// NewEnclaveSigner dials the enclave, fetches the loaded EVM address -// via GetPubkey, then runs a signature self-test (sign a zero hash, -// recover the address from the resulting signature, assert it matches). -// The self-test catches misconfig where the enclave reports one -// address but signs with a key for a different one — wrong SECRET_ID -// baked into the .eif, vsock-proxy MITM swap, etc. -// -// Failure here is fatal: the caller (node startup in cmd/node/main.go) -// propagates the error and the process exits before tendermint comes -// up. The self-test mismatch case panics with the recovered vs. -// reported addresses; other init errors return through the caller. -func NewEnclaveSigner(addr string, logger tmlog.Logger) (*EnclaveSigner, error) { +// NewEnclaveSigner connects to the enclave and has it load every key in +// keys (see connect). Any failure is fatal: the caller (node startup in +// cmd/node/main.go) exits before tendermint comes up. Starting with only +// some keys could make this node leader with no valid key at a rotation +// height. +func NewEnclaveSigner(addr string, keys []EnclaveKey, logger tmlog.Logger) (*EnclaveSigner, error) { cid, port, err := parseAddr(addr) if err != nil { return nil, err } s := &EnclaveSigner{ - cid: cid, - port: port, - logger: logger.With("module", "signer", "kind", "enclave", "addr", addr), - } - // Inject AWS credentials (resolved from the pod's IRSA env) before the - // probe: an AWS-backed signer loads its key lazily on ProvideCredentials - // and would otherwise reject GetPubkey/Sign. No-op when no IRSA env is - // present (local/dev); idempotent enclave-side, so safe on every restart. - if err := s.injectCredentials(); err != nil { - s.logger.Error("enclave credential injection failed; node cannot start", "err", err) - return nil, fmt.Errorf("enclave signer credentials %s: %w", addr, err) - } - if err := s.probe(); err != nil { - s.logger.Error("enclave signer init failed; node cannot start", "err", err) - return nil, fmt.Errorf("enclave signer probe %s: %w", addr, err) - } - if err := s.verifySigningIdentity(); err != nil { - s.logger.Error("enclave signer self-test failed; node cannot start", "err", err) - _ = s.Close() - return nil, fmt.Errorf("enclave signer self-test: %w", err) + cid: cid, + port: port, + keys: keys, + logger: logger.With("module", "signer", "kind", "enclave", "addr", addr), + credsFn: resolveCreds, + } + s.dialFn = s.dialVsock + if err := s.connect(); err != nil { + return nil, fmt.Errorf("enclave signer %s: %w", addr, err) } return s, nil } -// Sign signs a 32-byte prehash. Returns the 65-byte [r||s||v] signature. +// connect opens a connection on which the enclave holds every configured +// key: dial, LoadKeys (idempotent enclave-side: a key still in memory is +// answered from there, a restarted enclave loads it again), then a +// signature self-test per key. +// +// It is all-or-nothing: a key that fails to load, two keys with the same +// address or a failed self-test fail the whole connection, on startup and +// on every reconnect alike. The first connection fixes the signer's +// identity (s.addrs); a later one that loads different addresses is +// refused, so a reconnect can only ever restore the startup state. +// +// Caller holds s.mu, or is the constructor. +func (s *EnclaveSigner) connect() (err error) { + creds, err := s.credsFn() + if err != nil { + return err + } + conn, err := s.dialFn() + if err != nil { + return err + } + defer func() { + if err != nil { + _ = conn.Close() + } + }() + + results, err := loadKeysOnce(conn, creds, s.keys) + if err != nil { + return fmt.Errorf("LoadKeys: %w", err) + } + if len(results) != len(s.keys) { + return fmt.Errorf("LoadKeys: %d results for %d keys", len(results), len(s.keys)) + } + addrs := make([]common.Address, len(results)) + for i, r := range results { + if !r.ok() { + return fmt.Errorf("key %d (%s) failed to load: status=0x%02X %s", i, s.keys[i].SecretID, r.status, r.msg) + } + if j := slices.Index(addrs[:i], r.address); j >= 0 { + return fmt.Errorf("keys %d and %d resolve to the same address %s", j, i, r.address.Hex()) + } + addrs[i] = r.address + } + if s.addrs != nil && !slices.Equal(addrs, s.addrs) { + return fmt.Errorf("enclave keys changed since startup: loaded %v, expected %v", AddrHexes(addrs), AddrHexes(s.addrs)) + } + if err := verifySigningIdentity(conn, addrs); err != nil { + return fmt.Errorf("self-test: %w", err) + } + + s.conn = conn + if s.addrs == nil { + s.addrs = addrs + } + return nil +} + +// verifySigningIdentity asks the enclave to sign a 32-byte zero hash with +// every key in addrs, recovers the public key from each signature, derives +// the EVM address, and returns an error if any doesn't match. This catches +// a keystore whose claimed address disagrees with what its signature +// actually recovers to, and any layer between the SDK and the wire +// (vsock-proxy, in-enclave stub) tampering with payloads. +func verifySigningIdentity(conn net.Conn, addrs []common.Address) error { + var zero [hashLen]byte + for _, addr := range addrs { + sig, err := signOnce(conn, addr, zero[:]) + if err != nil { + return fmt.Errorf("self-test sign with %s: %w", addr.Hex(), err) + } + pub, err := crypto.SigToPub(zero[:], sig) + if err != nil { + return fmt.Errorf("self-test recover pubkey for %s: %w", addr.Hex(), err) + } + if derived := crypto.PubkeyToAddress(*pub); derived != addr { + return fmt.Errorf("address mismatch: enclave reported %s but its signature recovers to %s", + addr.Hex(), derived.Hex()) + } + } + return nil +} + +// Addresses returns the address of every configured key, in config order. +func (s *EnclaveSigner) Addresses() []common.Address { + return slices.Clone(s.addrs) +} + +// HasAddress reports whether addr is one of the signer's keys. +func (s *EnclaveSigner) HasAddress(addr common.Address) bool { + return slices.Contains(s.addrs, addr) +} + +// SignWith signs a 32-byte prehash with the key of addr — the address the +// L1 contract designates for the block being produced. Returns the +// 65-byte [r||s||v] signature. // -// Up to 3 attempts: each tries the cached conn (or dials fresh if -// none), and on any wire error drops the conn and retries. If the -// enclave reports KeyNotInitialized (it restarted and lost its -// in-memory key), the credentials are re-injected between attempts so -// the signer reloads the key without waiting for a full node restart. -// After 3 failures returns an error wrapping the last cause; the caller -// is expected to treat that as fatal (block production can't proceed -// without a signer, so tendermint will halt consensus). -func (s *EnclaveSigner) Sign(data []byte) ([]byte, error) { +// Up to 3 attempts: each uses the cached conn or reconnects (see connect), +// and drops the conn on any error so the next attempt starts fresh. After +// 3 failures returns an error wrapping the last cause; the caller abandons +// this block round, and the next sign starts over with a reconnect. +func (s *EnclaveSigner) SignWith(addr common.Address, data []byte) ([]byte, error) { if len(data) != hashLen { return nil, fmt.Errorf("enclave signer: hash must be %d bytes, got %d", hashLen, len(data)) } + if !s.HasAddress(addr) { + return nil, fmt.Errorf("enclave signer has no key for %s", addr.Hex()) + } s.mu.Lock() defer s.mu.Unlock() @@ -137,41 +303,32 @@ func (s *EnclaveSigner) Sign(data []byte) ([]byte, error) { var lastErr error for attempt := 1; attempt <= maxAttempts; attempt++ { if s.conn == nil { - conn, err := s.dial() - if err != nil { - lastErr = err - s.logger.Info("sign attempt failed at dial", - "attempt", attempt, "max", maxAttempts, "err", err) + if lastErr = s.connect(); lastErr != nil { + s.logger.Error("enclave reconnect failed", "attempt", attempt, "max", maxAttempts, "err", lastErr) continue } - s.conn = conn + s.logger.Info("enclave signer reconnected", "addresses", AddrHexes(s.addrs)) } - sig, err := s.signOnce(s.conn, data) + sig, err := signOnce(s.conn, addr, data) if err == nil { return sig, nil } lastErr = err s.logger.Info("sign attempt failed", - "attempt", attempt, "max", maxAttempts, "err", err) + "attempt", attempt, "max", maxAttempts, "signer", addr.Hex(), "err", err) + s.dropConn() + } + s.logger.Error("sign exhausted all retries", "attempts", maxAttempts, "signer", addr.Hex(), "err", lastErr) + return nil, fmt.Errorf("enclave sign with %s failed after %d attempts: %w", addr.Hex(), maxAttempts, lastErr) +} + +func (s *EnclaveSigner) dropConn() { + if s.conn != nil { _ = s.conn.Close() s.conn = nil - // KeyNotInitialized means the enclave lost its key (it restarted): - // its keystore is empty until credentials are pushed again. Re-inject - // (a no-op Ack enclave-side once loaded) so the next attempt can sign, - // instead of failing every Sign until the whole node is restarted. - if isKeyNotInitialized(err) { - if ierr := s.injectCredentials(); ierr != nil { - s.logger.Error("re-inject credentials after key-not-loaded failed", "err", ierr) - } - } } - s.logger.Error("sign exhausted all retries", "attempts", maxAttempts, "err", lastErr) - return nil, fmt.Errorf("enclave sign failed after %d attempts: %w", maxAttempts, lastErr) } -// Address returns the enclave's EVM address (fetched at construction). -func (s *EnclaveSigner) Address() common.Address { return s.address } - // Close releases the persistent connection. Safe to call multiple times. func (s *EnclaveSigner) Close() error { s.mu.Lock() @@ -184,80 +341,78 @@ func (s *EnclaveSigner) Close() error { return err } -func (s *EnclaveSigner) probe() error { - conn, err := s.dial() - if err != nil { - return err +// keyResult is one LoadKeys outcome, in request order. +type keyResult struct { + status byte + address common.Address + msg string +} + +func (r keyResult) ok() bool { return r.status == statusOk } + +// loadKeysOnce sends LoadKeys(creds, keys) on conn and decodes the +// per-key results. +func loadKeysOnce(conn net.Conn, creds *awsCreds, keys []EnclaveKey) ([]keyResult, error) { + if len(keys) > 255 { + return nil, fmt.Errorf("too many enclave keys: %d", len(keys)) } - success := false - defer func() { - if !success { - _ = conn.Close() - } - }() - if err := conn.SetDeadline(time.Now().Add(requestTimeout)); err != nil { - return fmt.Errorf("set deadline: %w", err) + if err := conn.SetDeadline(time.Now().Add(time.Duration(len(keys)) * perKeyLoadTimeout)); err != nil { + return nil, fmt.Errorf("set deadline: %w", err) } - defer func() { _ = conn.SetDeadline(time.Time{}) }() // clear on exit so signOnce can manage its own deadline + defer func() { _ = conn.SetDeadline(time.Time{}) }() - if _, err := conn.Write([]byte{opGetPubkey}); err != nil { - return fmt.Errorf("write GetPubkey: %w", err) + req, err := appendCreds([]byte{opLoadKeys}, creds) + if err != nil { + return nil, err } - if err := readOkStatus(conn); err != nil { - return err + req = append(req, byte(len(keys))) + for _, k := range keys { + if len(k.KMSKeyID) > maxIDLen || len(k.SecretID) > maxIDLen { + return nil, fmt.Errorf("kms key id / secret id longer than %d bytes", maxIDLen) + } + req = appendLPString(req, k.KMSKeyID) + req = appendLPString(req, k.SecretID) } - body := make([]byte, pubkeyLen+addressLen) - if _, err := io.ReadFull(conn, body); err != nil { - return fmt.Errorf("read pubkey+address: %w", err) + if _, err := conn.Write(req); err != nil { + return nil, fmt.Errorf("write LoadKeys: %w", err) } - copy(s.address[:], body[pubkeyLen:]) - s.conn = conn - success = true - return nil -} - -// verifySigningIdentity asks the enclave to sign a 32-byte zero hash, -// recovers the public key from the signature using secp256k1 ECDSA -// recovery, derives the EVM address, and returns an error if it -// doesn't match the address GetPubkey reported. This catches: -// - SECRET_ID baked into the .eif points at a different bundle than -// the operator believes -// - keystore loaded a key whose claimed address disagrees with what -// the signature actually recovers to -// - any layer between the SDK and the wire (vsock-proxy, in-enclave -// stub) tampering with payloads -// -// Called only from NewEnclaveSigner. A non-nil return aborts node -// startup via main.go's error path; tendermint never sees the bad -// signer, so we don't need to panic for runtime safety. -func (s *EnclaveSigner) verifySigningIdentity() error { - var zero [hashLen]byte - sig, err := s.signOnce(s.conn, zero[:]) - if err != nil { - return fmt.Errorf("self-test sign: %w", err) + if err := readOkStatus(conn); err != nil { + return nil, err } - pub, err := crypto.SigToPub(zero[:], sig) - if err != nil { - return fmt.Errorf("self-test recover pubkey: %w", err) + var n [1]byte + if _, err := io.ReadFull(conn, n[:]); err != nil { + return nil, fmt.Errorf("read result count: %w", err) } - derived := crypto.PubkeyToAddress(*pub) - if derived != s.address { - return fmt.Errorf( - "address mismatch: GetPubkey reported %s but Sign recovers to %s", - s.address.Hex(), derived.Hex()) + results := make([]keyResult, n[0]) + body := make([]byte, 1+pubkeyLen+addressLen) + for i := range results { + if _, err := io.ReadFull(conn, body); err != nil { + return nil, fmt.Errorf("read result %d: %w", i, err) + } + msg, err := readLPString(conn, maxErrMsg) + if err != nil { + return nil, fmt.Errorf("read result %d msg: %w", i, err) + } + results[i] = keyResult{ + status: body[0], + address: common.BytesToAddress(body[1+pubkeyLen:]), + msg: msg, + } } - return nil + return results, nil } -func (s *EnclaveSigner) signOnce(conn net.Conn, data []byte) ([]byte, error) { +// signOnce sends one Sign(addr, data) round-trip on conn. +func signOnce(conn net.Conn, addr common.Address, data []byte) ([]byte, error) { if err := conn.SetDeadline(time.Now().Add(requestTimeout)); err != nil { return nil, err } defer func() { _ = conn.SetDeadline(time.Time{}) }() - req := make([]byte, 1+hashLen) - req[0] = opSign - copy(req[1:], data) + req := make([]byte, 0, 1+addressLen+hashLen) + req = append(req, opSign) + req = append(req, addr.Bytes()...) + req = append(req, data...) if _, err := conn.Write(req); err != nil { return nil, fmt.Errorf("write Sign: %w", err) } @@ -271,11 +426,11 @@ func (s *EnclaveSigner) signOnce(conn net.Conn, data []byte) ([]byte, error) { return sig, nil } -// dial wraps vsock.Dial with dialTimeout. mdlayher/vsock has no +// dialVsock wraps vsock.Dial with dialTimeout. mdlayher/vsock has no // context-aware Dial, so we run it in a goroutine and race against a // timer; if Dial returns after we've given up, the late conn is // closed in a background goroutine to avoid an FD leak. -func (s *EnclaveSigner) dial() (net.Conn, error) { +func (s *EnclaveSigner) dialVsock() (net.Conn, error) { type result struct { conn net.Conn err error @@ -306,8 +461,6 @@ func parseAddr(addr string) (uint32, uint32, error) { // Accept both "vsock:CID:port" (matches ops-cli's --addr convention) // and bare "CID:port" (legacy — kept so existing systemd Environment // / k8s ConfigMap entries keep working through the format unification). - // TrimPrefix is a no-op when the prefix isn't there, so one parse - // path covers both. s := strings.TrimPrefix(addr, "vsock:") parts := strings.SplitN(s, ":", 2) if len(parts) != 2 { @@ -324,6 +477,23 @@ func parseAddr(addr string) (uint32, uint32, error) { return uint32(cid), uint32(port), nil } +// readLPString reads a [len:u16][utf8] field capped at max. +func readLPString(conn net.Conn, max int) (string, error) { + var l [2]byte + if _, err := io.ReadFull(conn, l[:]); err != nil { + return "", err + } + n := int(binary.BigEndian.Uint16(l[:])) + if n > max { + return "", fmt.Errorf("field len %d exceeds max %d", n, max) + } + b := make([]byte, n) + if _, err := io.ReadFull(conn, b); err != nil { + return "", err + } + return string(b), nil +} + func readOkStatus(conn net.Conn) error { var statusBuf [1]byte if _, err := io.ReadFull(conn, statusBuf[:]); err != nil { @@ -332,26 +502,15 @@ func readOkStatus(conn net.Conn) error { if statusBuf[0] == statusOk { return nil } - var lenBuf [2]byte - if _, err := io.ReadFull(conn, lenBuf[:]); err != nil { - return fmt.Errorf("enclave signer status=0x%02X (read msg len: %w)", statusBuf[0], err) - } - msgLen := binary.BigEndian.Uint16(lenBuf[:]) - if msgLen > maxErrMsg { - return fmt.Errorf("enclave signer status=0x%02X (msg len %d exceeds max %d)", - statusBuf[0], msgLen, maxErrMsg) - } - msg := make([]byte, msgLen) - if _, err := io.ReadFull(conn, msg); err != nil { + msg, err := readLPString(conn, maxErrMsg) + if err != nil { return fmt.Errorf("enclave signer status=0x%02X (read msg: %w)", statusBuf[0], err) } - return &enclaveError{status: statusBuf[0], msg: string(msg)} + return &enclaveError{status: statusBuf[0], msg: msg} } // enclaveError is a well-formed non-OK status frame from the enclave -// (status byte + message). It is returned by readOkStatus so callers can -// branch on the status code — notably statusKeyNotInitialized, which Sign -// recovers from by re-injecting credentials. +// (status byte + message). type enclaveError struct { status byte msg string @@ -360,10 +519,3 @@ type enclaveError struct { func (e *enclaveError) Error() string { return fmt.Sprintf("enclave signer error: status=0x%02X msg=%q", e.status, e.msg) } - -// isKeyNotInitialized reports whether err is an enclave status frame with -// KeyNotInitialized (0x02) anywhere in its chain. -func isKeyNotInitialized(err error) bool { - var e *enclaveError - return errors.As(err, &e) && e.status == statusKeyNotInitialized -} diff --git a/node/l1sequencer/enclave_signer_test.go b/node/l1sequencer/enclave_signer_test.go index 0fb5793fa..703f6d7cf 100644 --- a/node/l1sequencer/enclave_signer_test.go +++ b/node/l1sequencer/enclave_signer_test.go @@ -1,16 +1,24 @@ package l1sequencer import ( + "crypto/ecdsa" + "encoding/binary" + "io" + "net" + "os" + "strings" + "sync" "testing" + "github.com/morph-l2/go-ethereum/common" + "github.com/morph-l2/go-ethereum/crypto" "github.com/stretchr/testify/require" + tmlog "github.com/tendermint/tendermint/libs/log" ) -// Wire-protocol tests are deliberately omitted: the client is -// vsock-only, and there is no portable way to stand up a vsock -// listener from a test (mdlayher/vsock is Linux-only and CI usually -// lacks vsock support). The wire protocol is exercised end-to-end on -// real Nitro instances; here we only test the pure-Go addr parsing. +// The production transport is vsock, which CI usually lacks, so the +// wire-protocol tests below run over TCP against fakeEnclave +// (EnclaveSigner's dialFn makes the transport swappable). func TestParseAddr(t *testing.T) { cases := []struct { @@ -48,3 +56,388 @@ func TestParseAddr(t *testing.T) { }) } } + +// fakeEnclave speaks the signer wire protocol over TCP so EnclaveSigner can +// be exercised without vsock. "Secrets" are a map secret_id → key; LoadKeys +// loads named secrets into memory (additive), Sign signs with a loaded key. +type fakeEnclave struct { + t *testing.T + ln net.Listener + + mu sync.Mutex + secrets map[string]*ecdsa.PrivateKey // what SM would return + loaded map[string]*ecdsa.PrivateKey // enclave memory + loads int // LoadKeys requests served + // lie, if set, makes that address sign with a different key. + lie common.Address +} + +func newFakeEnclave(t *testing.T, secrets map[string]*ecdsa.PrivateKey) *fakeEnclave { + ln, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + f := &fakeEnclave{t: t, ln: ln, secrets: secrets, loaded: map[string]*ecdsa.PrivateKey{}} + go f.serve() + t.Cleanup(func() { _ = ln.Close() }) + return f +} + +// restart models an enclave restart: in-memory keys are lost. +func (f *fakeEnclave) restart() { + f.mu.Lock() + defer f.mu.Unlock() + f.loaded = map[string]*ecdsa.PrivateKey{} +} + +func (f *fakeEnclave) setSecret(id string, k *ecdsa.PrivateKey) { + f.mu.Lock() + defer f.mu.Unlock() + if k == nil { + delete(f.secrets, id) + } else { + f.secrets[id] = k + } +} + +// setLie makes addr sign with a key other than its own (zero address: none). +func (f *fakeEnclave) setLie(addr common.Address) { + f.mu.Lock() + defer f.mu.Unlock() + f.lie = addr +} + +func (f *fakeEnclave) dial() (net.Conn, error) { return net.Dial("tcp", f.ln.Addr().String()) } + +func (f *fakeEnclave) serve() { + for { + c, err := f.ln.Accept() + if err != nil { + return + } + go f.handle(c) + } +} + +func readLP(c net.Conn) string { + var l [2]byte + if _, err := io.ReadFull(c, l[:]); err != nil { + return "" + } + b := make([]byte, binary.BigEndian.Uint16(l[:])) + _, _ = io.ReadFull(c, b) + return string(b) +} + +func writeErr(c net.Conn, status byte, msg string) { + _, _ = c.Write(appendLPString([]byte{status}, msg)) +} + +func (f *fakeEnclave) handle(c net.Conn) { + defer c.Close() + for { + var op [1]byte + if _, err := io.ReadFull(c, op[:]); err != nil { + return + } + switch op[0] { + case opLoadKeys: + readLP(c) // akid + readLP(c) // secret key + readLP(c) // token + var exp [8]byte + var n [1]byte + if _, err := io.ReadFull(c, exp[:]); err != nil { + return + } + if _, err := io.ReadFull(c, n[:]); err != nil { + return + } + resp := []byte{statusOk, n[0]} + f.mu.Lock() + f.loads++ + for i := 0; i < int(n[0]); i++ { + readLP(c) // kms key id + sid := readLP(c) + k := f.loaded[sid] + if k == nil { + k = f.secrets[sid] + if k != nil { + f.loaded[sid] = k + } + } + if k == nil { + resp = append(resp, 0x02) + resp = append(resp, make([]byte, pubkeyLen+addressLen)...) + resp = appendLPString(resp, "secret not found: "+sid) + continue + } + resp = append(resp, statusOk) + resp = append(resp, crypto.CompressPubkey(&k.PublicKey)...) + resp = append(resp, crypto.PubkeyToAddress(k.PublicKey).Bytes()...) + resp = appendLPString(resp, "") + } + f.mu.Unlock() + _, _ = c.Write(resp) + case opSign: + buf := make([]byte, addressLen+hashLen) + if _, err := io.ReadFull(c, buf); err != nil { + return + } + addr := common.BytesToAddress(buf[:addressLen]) + f.mu.Lock() + var key *ecdsa.PrivateKey + for _, k := range f.loaded { + if crypto.PubkeyToAddress(k.PublicKey) == addr { + key = k + } + } + empty, lie := len(f.loaded) == 0, f.lie + f.mu.Unlock() + switch { + case empty: + writeErr(c, 0x02, "no key loaded") + continue + case key == nil: + writeErr(c, 0x06, "no such key") + continue + case addr == lie: + key, _ = crypto.GenerateKey() + } + sig, err := crypto.Sign(buf[addressLen:], key) + require.NoError(f.t, err) + _, _ = c.Write(append([]byte{statusOk}, sig...)) + default: + return + } + } +} + +func newTestEnclaveSigner(t *testing.T, f *fakeEnclave, secretIDs ...string) (*EnclaveSigner, error) { + keys := make([]EnclaveKey, len(secretIDs)) + for i, id := range secretIDs { + keys[i] = EnclaveKey{KMSKeyID: "alias/k", SecretID: id} + } + s := &EnclaveSigner{ + logger: tmlog.NewNopLogger(), + keys: keys, + dialFn: f.dial, + credsFn: func() (*awsCreds, error) { return &awsCreds{accessKeyID: "AKIA", secretAccessKey: "s"}, nil }, + } + if err := s.connect(); err != nil { + return nil, err + } + t.Cleanup(func() { _ = s.Close() }) + return s, nil +} + +func mustKey(t *testing.T) *ecdsa.PrivateKey { + k, err := crypto.GenerateKey() + require.NoError(t, err) + return k +} + +func addrOf(k *ecdsa.PrivateKey) common.Address { return crypto.PubkeyToAddress(k.PublicKey) } + +func assertSignsAs(t *testing.T, s Signer, addr common.Address) { + t.Helper() + hash := crypto.Keccak256([]byte("block")) + sig, err := s.SignWith(addr, hash) + require.NoError(t, err) + pub, err := crypto.SigToPub(hash, sig) + require.NoError(t, err) + require.Equal(t, addr, crypto.PubkeyToAddress(*pub)) +} + +func TestParseEnclaveKeys(t *testing.T) { + kms, sid := EnclaveKMSKeyIDEnvPrefix, EnclaveSecretIDEnvPrefix + keys, err := ParseEnclaveKeys([]string{ + sid + "1=s1", "PATH=/bin", kms + "0=k0", kms + "1=k1", sid + "0=s0", + kms + "10=k10", sid + "10=arn:aws:secretsmanager:r:1:secret:a=b", + }) + require.NoError(t, err) + require.Equal(t, []EnclaveKey{ + {KMSKeyID: "k0", SecretID: "s0"}, + {KMSKeyID: "k1", SecretID: "s1"}, + {KMSKeyID: "k10", SecretID: "arn:aws:secretsmanager:r:1:secret:a=b"}, + }, keys) + + for _, bad := range [][]string{ + {}, + {"PATH=/bin"}, + {kms + "0=k0"}, + {kms + "0=k0", sid + "0="}, + {kms + "x=k", sid + "x=s"}, + {kms + "=k", sid + "=s"}, + // Non-canonical suffixes: "01" would collide with "1". + {kms + "01=k", sid + "01=s"}, + {kms + "1=k1", sid + "1=s1", kms + "01=k01", sid + "01=s01"}, + {kms + "00=k", sid + "00=s"}, + {kms + "+1=k", sid + "+1=s"}, + } { + _, err := ParseEnclaveKeys(bad) + require.Error(t, err, "%v", bad) + } +} + +func TestEnclaveSigner_MultiKey(t *testing.T) { + a, b := mustKey(t), mustKey(t) + f := newFakeEnclave(t, map[string]*ecdsa.PrivateKey{"sa": a, "sb": b}) + s, err := newTestEnclaveSigner(t, f, "sa", "sb") + require.NoError(t, err) + require.Equal(t, []common.Address{addrOf(a), addrOf(b)}, s.Addresses()) + + assertSignsAs(t, s, addrOf(a)) + assertSignsAs(t, s, addrOf(b)) + + require.True(t, s.HasAddress(addrOf(b))) + other := addrOf(mustKey(t)) + require.False(t, s.HasAddress(other)) + _, err = s.SignWith(other, make([]byte, hashLen)) + require.ErrorContains(t, err, "has no key for") + _, err = s.SignWith(addrOf(a), []byte{1, 2, 3}) + require.ErrorContains(t, err, "hash must be") +} + +func TestEnclaveSigner_AnyKeyFailingFailsStartup(t *testing.T) { + f := newFakeEnclave(t, map[string]*ecdsa.PrivateKey{"sa": mustKey(t)}) + _, err := newTestEnclaveSigner(t, f, "sa", "missing") + require.ErrorContains(t, err, "key 1 (missing) failed to load") + require.ErrorContains(t, err, "secret not found: missing") +} + +func TestEnclaveSigner_DuplicateAddressFailsStartup(t *testing.T) { + a := mustKey(t) + f := newFakeEnclave(t, map[string]*ecdsa.PrivateKey{"s1": a, "s2": a}) + _, err := newTestEnclaveSigner(t, f, "s1", "s2") + require.ErrorContains(t, err, "same address") +} + +func TestEnclaveSigner_SelfTestCatchesWrongKey(t *testing.T) { + a, b := mustKey(t), mustKey(t) + f := newFakeEnclave(t, map[string]*ecdsa.PrivateKey{"sa": a, "sb": b}) + f.lie = addrOf(b) + _, err := newTestEnclaveSigner(t, f, "sa", "sb") + require.ErrorContains(t, err, "address mismatch") +} + +func TestEnclaveSigner_ReconnectReloadsKeys(t *testing.T) { + a, b := mustKey(t), mustKey(t) + f := newFakeEnclave(t, map[string]*ecdsa.PrivateKey{"sa": a, "sb": b}) + s, err := newTestEnclaveSigner(t, f, "sa", "sb") + require.NoError(t, err) + + // Enclave restarted (memory lost): the next sign reconnects, LoadKeys + // reloads both keys, signing continues — no node restart needed. + require.NoError(t, s.Close()) + f.restart() + assertSignsAs(t, s, addrOf(b)) + require.Equal(t, 2, f.loads) +} + +// A reconnect must restore exactly the startup state. If the restarted +// enclave cannot — a key no longer loads, a secret now holds another key, +// a self-test fails — no key signs (not even the healthy one), the signer's +// identity stays what it was, and signing resumes by itself once the +// enclave is back to the startup state. +func TestEnclaveSigner_ReconnectIsAllOrNothing(t *testing.T) { + a, b := mustKey(t), mustKey(t) + for _, tc := range []struct { + name string + breakIt func(f *fakeEnclave) + wantErr string + }{ + {"key no longer loads", func(f *fakeEnclave) { f.setSecret("sa", nil) }, "failed to load"}, + {"secret holds another key", func(f *fakeEnclave) { f.setSecret("sa", mustKey(t)) }, "keys changed since startup"}, + {"self-test fails", func(f *fakeEnclave) { f.setLie(addrOf(a)) }, "self-test"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newFakeEnclave(t, map[string]*ecdsa.PrivateKey{"sa": a, "sb": b}) + s, err := newTestEnclaveSigner(t, f, "sa", "sb") + require.NoError(t, err) + + require.NoError(t, s.Close()) + f.restart() + tc.breakIt(f) + _, err = s.SignWith(addrOf(b), make([]byte, hashLen)) + require.ErrorContains(t, err, tc.wantErr) + require.Equal(t, []common.Address{addrOf(a), addrOf(b)}, s.Addresses()) + + // Fixed and the enclave restarted: no node restart needed. + f.restart() + f.setSecret("sa", a) + f.setLie(common.Address{}) + assertSignsAs(t, s, addrOf(a)) + assertSignsAs(t, s, addrOf(b)) + }) + } +} + +func TestLocalSigner_MultiKey(t *testing.T) { + a, b := mustKey(t), mustKey(t) + s, err := NewLocalSigner(tmlog.NewNopLogger(), a, b) + require.NoError(t, err) + require.Equal(t, []common.Address{addrOf(a), addrOf(b)}, s.Addresses()) + require.True(t, s.HasAddress(addrOf(a))) + require.True(t, s.HasAddress(addrOf(b))) + assertSignsAs(t, s, addrOf(a)) + assertSignsAs(t, s, addrOf(b)) + other := addrOf(mustKey(t)) + require.False(t, s.HasAddress(other)) + _, err = s.SignWith(other, make([]byte, hashLen)) + require.Error(t, err) + + _, err = NewLocalSigner(tmlog.NewNopLogger(), a, a) + require.ErrorContains(t, err, "duplicates") + _, err = NewLocalSigner(tmlog.NewNopLogger()) + require.Error(t, err) +} + +func TestParsePrivateKeys(t *testing.T) { + a, b := mustKey(t), mustKey(t) + ha := common.Bytes2Hex(crypto.FromECDSA(a)) + hb := common.Bytes2Hex(crypto.FromECDSA(b)) + + keys, err := ParsePrivateKeys(ha) + require.NoError(t, err) + require.Len(t, keys, 1) + + keys, err = ParsePrivateKeys("0x" + ha + " , " + hb) + require.NoError(t, err) + require.Len(t, keys, 2) + require.Equal(t, addrOf(b), addrOf(keys[1])) + + _, err = ParsePrivateKeys(ha + ",") + require.ErrorContains(t, err, "#1 is empty") + _, err = ParsePrivateKeys("zz") + require.Error(t, err) + require.NotContains(t, err.Error(), "zz") +} + +// TestEnclaveSigner_RealEnclave runs against a real morph-signer built +// without the vsock feature (TCP, file backend). Skipped unless +// ENCLAVE_TCP_ADDR (host:port) and ENCLAVE_TEST_SECRETS (comma-separated +// bundle paths, as written by morph-key-init) are set. +func TestEnclaveSigner_RealEnclave(t *testing.T) { + addr, secrets := os.Getenv("ENCLAVE_TCP_ADDR"), os.Getenv("ENCLAVE_TEST_SECRETS") + if addr == "" || secrets == "" { + t.Skip("ENCLAVE_TCP_ADDR / ENCLAVE_TEST_SECRETS not set") + } + var keys []EnclaveKey + for _, sid := range strings.Split(secrets, ",") { + keys = append(keys, EnclaveKey{KMSKeyID: "local", SecretID: sid}) + } + s := &EnclaveSigner{ + logger: tmlog.NewNopLogger(), + keys: keys, + dialFn: func() (net.Conn, error) { return net.Dial("tcp", addr) }, + credsFn: func() (*awsCreds, error) { return nil, nil }, + } + require.NoError(t, s.connect()) + defer s.Close() + require.Len(t, s.Addresses(), len(keys)) + for _, a := range s.Addresses() { + assertSignsAs(t, s, a) + } + // Reconnect path: drop the conn, sign again (LoadKeys answered from memory). + require.NoError(t, s.Close()) + assertSignsAs(t, s, s.Addresses()[0]) +} diff --git a/node/l1sequencer/metrics.go b/node/l1sequencer/metrics.go index 7b2ca112d..2bda72719 100644 --- a/node/l1sequencer/metrics.go +++ b/node/l1sequencer/metrics.go @@ -6,6 +6,7 @@ import ( "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/discard" "github.com/go-kit/kit/metrics/prometheus" + "github.com/morph-l2/go-ethereum/common" stdprometheus "github.com/prometheus/client_golang/prometheus" ) @@ -50,3 +51,20 @@ func NopMetrics() *Metrics { // SetLag records the L1 lag, truncated to whole seconds. func (m *Metrics) SetLag(d time.Duration) { m.LagSeconds.Set(float64(d / time.Second)) } + +// ExposeSignerAddresses publishes the addresses the sequencer signer holds +// as _sequencer_signer_address{address="0x…"} 1 — an info-style +// gauge: the value is always 1, the label carries the information (e.g. a +// Grafana table of the keys every node holds). The addresses are fixed for +// the life of the process, so this is called once at startup. +func ExposeSignerAddresses(namespace string, addrs []common.Address) { + g := prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: "sequencer", + Name: "signer_address", + Help: "Addresses the sequencer signer holds a key for (always 1; see the address label).", + }, []string{"address"}) + for _, a := range addrs { + g.With("address", a.Hex()).Set(1) + } +} diff --git a/node/l1sequencer/signer.go b/node/l1sequencer/signer.go index e99726e7a..d7f8bc3e1 100644 --- a/node/l1sequencer/signer.go +++ b/node/l1sequencer/signer.go @@ -3,53 +3,114 @@ package l1sequencer import ( "crypto/ecdsa" "fmt" + "strings" "github.com/morph-l2/go-ethereum/common" "github.com/morph-l2/go-ethereum/crypto" tmlog "github.com/tendermint/tendermint/libs/log" ) -// Signer manages sequencer identity and signing capabilities. -// It abstracts the private key management, allowing for local key storage -// or remote signing services (e.g., HSM, KMS) in the future. +// Signer manages the sequencer's signing identity. It may hold several keys +// (e.g. the current and the next sequencer key during a planned rotation); +// the block producer picks, per height, the one address the L1 contract +// designates and signs with exactly that key. +// +// Method set matches tendermint's sequencer.Signer. type Signer interface { - // Sign signs data with the sequencer's private key - Sign(data []byte) ([]byte, error) + // Addresses returns every address this signer can currently sign as, + // in configuration order. For logging / reporting; block production + // uses HasAddress. + Addresses() []common.Address - // Address returns the sequencer's address - Address() common.Address + // HasAddress reports whether the signer currently holds a key for addr. + HasAddress(addr common.Address) bool + + // SignWith signs data with the private key of addr. Returns an error + // if the signer holds no key for addr. + SignWith(addr common.Address, data []byte) ([]byte, error) } -// LocalSigner implements Signer with a local private key +// LocalSigner implements Signer with one or more in-memory private keys. +// Intended for devnet / testing; production uses EnclaveSigner. type LocalSigner struct { - privKey *ecdsa.PrivateKey - address common.Address - logger tmlog.Logger + addrs []common.Address + keys map[common.Address]*ecdsa.PrivateKey + logger tmlog.Logger +} + +// NewLocalSigner creates a LocalSigner holding privKeys, in that order. +// At least one key is required; the same key twice is rejected. +func NewLocalSigner(logger tmlog.Logger, privKeys ...*ecdsa.PrivateKey) (*LocalSigner, error) { + if len(privKeys) == 0 { + return nil, fmt.Errorf("at least one private key is required") + } + s := &LocalSigner{ + keys: make(map[common.Address]*ecdsa.PrivateKey, len(privKeys)), + logger: logger.With("module", "signer"), + } + for i, k := range privKeys { + if k == nil { + return nil, fmt.Errorf("private key #%d is nil", i) + } + addr := crypto.PubkeyToAddress(k.PublicKey) + if _, dup := s.keys[addr]; dup { + return nil, fmt.Errorf("private key #%d duplicates address %s", i, addr.Hex()) + } + s.keys[addr] = k + s.addrs = append(s.addrs, addr) + } + return s, nil } -// NewLocalSigner creates a new LocalSigner with a local private key -func NewLocalSigner(privKey *ecdsa.PrivateKey, logger tmlog.Logger) (*LocalSigner, error) { - if privKey == nil { - return nil, fmt.Errorf("private key is required") +// ParsePrivateKeys parses a comma-separated list of hex private keys +// (optional 0x prefix, surrounding whitespace ignored), e.g. the value of +// --sequencer.privateKey. +func ParsePrivateKeys(csv string) ([]*ecdsa.PrivateKey, error) { + var keys []*ecdsa.PrivateKey + for i, part := range strings.Split(csv, ",") { + h := strings.TrimPrefix(strings.TrimSpace(part), "0x") + if h == "" { + return nil, fmt.Errorf("private key #%d is empty", i) + } + k, err := crypto.HexToECDSA(h) + if err != nil { + // Never echo the key material itself. + return nil, fmt.Errorf("private key #%d is invalid: %w", i, err) + } + keys = append(keys, k) } + return keys, nil +} - return &LocalSigner{ - privKey: privKey, - address: crypto.PubkeyToAddress(privKey.PublicKey), - logger: logger.With("module", "signer"), - }, nil +// AddrHexes renders addrs as hex strings, for logging. +func AddrHexes(addrs []common.Address) []string { + hexes := make([]string, len(addrs)) + for i, a := range addrs { + hexes[i] = a.Hex() + } + return hexes } -// Sign signs data with the sequencer's private key -func (s *LocalSigner) Sign(data []byte) ([]byte, error) { - signature, err := crypto.Sign(data, s.privKey) +// Addresses returns the signer's addresses in configuration order. +func (s *LocalSigner) Addresses() []common.Address { + return append([]common.Address(nil), s.addrs...) +} + +// HasAddress reports whether the signer holds a key for addr. +func (s *LocalSigner) HasAddress(addr common.Address) bool { + _, ok := s.keys[addr] + return ok +} + +// SignWith signs data with the key of addr. +func (s *LocalSigner) SignWith(addr common.Address, data []byte) ([]byte, error) { + k, ok := s.keys[addr] + if !ok { + return nil, fmt.Errorf("local signer has no key for %s", addr.Hex()) + } + signature, err := crypto.Sign(data, k) if err != nil { return nil, fmt.Errorf("failed to sign: %w", err) } return signature, nil } - -// Address returns the sequencer's address -func (s *LocalSigner) Address() common.Address { - return s.address -} diff --git a/node/l1sequencer/verifier.go b/node/l1sequencer/verifier.go index 3f9f76877..e870480f2 100644 --- a/node/l1sequencer/verifier.go +++ b/node/l1sequencer/verifier.go @@ -179,24 +179,29 @@ func (c *SequencerVerifier) refreshLoop(ctx context.Context) { } } -// SequencerAtHeight returns the sequencer address at the given L2 height. -func (c *SequencerVerifier) SequencerAtHeight(l2Height uint64) (common.Address, bool) { +// ============================================================================ +// Interface implementation +// ============================================================================ + +// SequencerAtHeight returns the sequencer address the L1 contract designates +// for the given L2 height. It errors when no record covers that height. +func (c *SequencerVerifier) SequencerAtHeight(l2Height uint64) (common.Address, error) { c.mu.Lock() defer c.mu.Unlock() if len(c.history) == 0 { - return common.Address{}, false + return common.Address{}, fmt.Errorf("no sequencer record for height %d", l2Height) } if c.cursor.valid && l2Height >= c.cursor.from && l2Height < c.cursor.to { - return c.cursor.addr, true + return c.cursor.addr, nil } idx := sort.Search(len(c.history), func(i int) bool { return c.history[i].StartL2Block > l2Height }) - 1 if idx < 0 { - return common.Address{}, false + return common.Address{}, fmt.Errorf("no sequencer record for height %d", l2Height) } c.cursor.from = c.history[idx].StartL2Block @@ -207,18 +212,14 @@ func (c *SequencerVerifier) SequencerAtHeight(l2Height uint64) (common.Address, } c.cursor.addr = c.history[idx].SequencerAddr c.cursor.valid = true - return c.cursor.addr, true + return c.cursor.addr, nil } -// ============================================================================ -// Interface implementation -// ============================================================================ - // IsSequencerAt checks if addr was the sequencer at the given L2 height. func (c *SequencerVerifier) IsSequencerAt(addr common.Address, l2Height uint64) (bool, error) { - histAddr, found := c.SequencerAtHeight(l2Height) - if !found { - return false, fmt.Errorf("no sequencer record for height %d", l2Height) + histAddr, err := c.SequencerAtHeight(l2Height) + if err != nil { + return false, err } return addr == histAddr, nil } diff --git a/ops/l2-genesis/go.mod b/ops/l2-genesis/go.mod index db15793f7..791b65d05 100644 --- a/ops/l2-genesis/go.mod +++ b/ops/l2-genesis/go.mod @@ -2,7 +2,7 @@ module morph-l2/morph-deployer go 1.24.0 -replace github.com/tendermint/tendermint => github.com/morph-l2/tendermint v0.3.11 +replace github.com/tendermint/tendermint => github.com/morph-l2/tendermint v0.3.12-0.20261117072417-04bdb93cdbfe require ( github.com/holiman/uint256 v1.2.4 diff --git a/ops/tools/go.mod b/ops/tools/go.mod index c2c5eaafc..80b323409 100644 --- a/ops/tools/go.mod +++ b/ops/tools/go.mod @@ -2,7 +2,7 @@ module morph-l2/tools go 1.24.0 -replace github.com/tendermint/tendermint => github.com/morph-l2/tendermint v0.3.11 +replace github.com/tendermint/tendermint => github.com/morph-l2/tendermint v0.3.12-0.20261117072417-04bdb93cdbfe require ( github.com/morph-l2/go-ethereum v1.10.14-0.20261109063348-1c528b351da0 diff --git a/ops/tools/go.sum b/ops/tools/go.sum index bd9345b9a..05358245f 100644 --- a/ops/tools/go.sum +++ b/ops/tools/go.sum @@ -163,8 +163,8 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJ github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/morph-l2/go-ethereum v1.10.14-0.20261109063348-1c528b351da0 h1:NnyyOHfGo/mKSTyQfNhwBiVWwsxxqGFkMI8OR9vIJHY= github.com/morph-l2/go-ethereum v1.10.14-0.20261109063348-1c528b351da0/go.mod h1:qNV1ziCmoLzpIKrAF0c8LUmVuKG3zMiLOA6c8xXkfic= -github.com/morph-l2/tendermint v0.3.11 h1:PTA6TEjbvlRqFYQMrkv8YSSOGwB0e3hdBlqJyyzMWSc= -github.com/morph-l2/tendermint v0.3.11/go.mod h1:qpiwqfcCB89dBYfqVJOc/HjGxDp3OdDlthgttJJYyRs= +github.com/morph-l2/tendermint v0.3.12-0.20261117072417-04bdb93cdbfe h1:w4733oyO9bbsckdOlnc45FqqE2YPNWTzDxJ7dqijiLY= +github.com/morph-l2/tendermint v0.3.12-0.20261117072417-04bdb93cdbfe/go.mod h1:qpiwqfcCB89dBYfqVJOc/HjGxDp3OdDlthgttJJYyRs= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= diff --git a/tx-submitter/go.mod b/tx-submitter/go.mod index 1e67f98fd..a636700f8 100644 --- a/tx-submitter/go.mod +++ b/tx-submitter/go.mod @@ -2,7 +2,7 @@ module morph-l2/tx-submitter go 1.24.0 -replace github.com/tendermint/tendermint => github.com/morph-l2/tendermint v0.3.11 +replace github.com/tendermint/tendermint => github.com/morph-l2/tendermint v0.3.12-0.20261117072417-04bdb93cdbfe require ( github.com/consensys/gnark-crypto v0.16.0