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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions pkg/rpc/core/blocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -447,11 +447,11 @@ func getAttesterSignatures(ctx context.Context, height int64) (map[string][]byte
Data: signaturesReq,
})
if err != nil {
return make(map[string][]byte), nil
return nil, fmt.Errorf("query attester signatures: %w", err)
}

if result.Code != 0 {
return make(map[string][]byte), nil
return nil, fmt.Errorf("attester signatures query failed: code %d, log: %s", result.Code, result.Log)
}

var signaturesResp networktypes.QueryAttesterSignaturesResponse
Expand Down
55 changes: 55 additions & 0 deletions pkg/rpc/core/blocks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package core

import (
"context"
"errors"
"testing"
"time"

abci "github.com/cometbft/cometbft/abci/types"
"github.com/cometbft/cometbft/crypto/ed25519"
cmtlog "github.com/cometbft/cometbft/libs/log"
"github.com/cometbft/cometbft/libs/math"
Expand Down Expand Up @@ -260,6 +262,59 @@ func TestCommit_VerifyCometBFTLightClientCompatibility_MultipleBlocks(t *testing
}
}

func TestGetAttesterSignaturesReturnsQueryError(t *testing.T) {
require := require.New(t)

mockApp := new(MockApp)
previousEnv := env
t.Cleanup(func() {
env = previousEnv
mockApp.AssertExpectations(t)
})

env = &Environment{
Adapter: &adapter.Adapter{App: mockApp},
Logger: cmtlog.NewNopLogger(),
}

mockApp.On("Query", mock.Anything, mock.MatchedBy(func(req *abci.RequestQuery) bool {
return req.Path == "/evabci.network.v1.Query/AttesterSignatures"
})).Return(nil, errors.New("query unavailable")).Once()

signatures, err := getAttesterSignatures(context.Background(), 10)

require.Nil(signatures)
require.ErrorContains(err, "query attester signatures")
require.ErrorContains(err, "query unavailable")
}

func TestGetAttesterSignaturesReturnsNonOKQueryCode(t *testing.T) {
require := require.New(t)

mockApp := new(MockApp)
previousEnv := env
t.Cleanup(func() {
env = previousEnv
mockApp.AssertExpectations(t)
})

env = &Environment{
Adapter: &adapter.Adapter{App: mockApp},
Logger: cmtlog.NewNopLogger(),
}

mockApp.On("Query", mock.Anything, mock.MatchedBy(func(req *abci.RequestQuery) bool {
return req.Path == "/evabci.network.v1.Query/AttesterSignatures"
})).Return(&abci.ResponseQuery{Code: 7, Log: "signature store unavailable"}, nil).Once()

signatures, err := getAttesterSignatures(context.Background(), 10)

require.Nil(signatures)
require.ErrorContains(err, "attester signatures query failed")
require.ErrorContains(err, "code 7")
require.ErrorContains(err, "signature store unavailable")
}

func createTestBlock(height uint64, chainID string, baseTime time.Time, validatorAddress []byte, validatorHash []byte, offset int) (*types.Data, types.Header) {
blockTime := uint64(baseTime.UnixNano() + int64(offset-1)*int64(time.Second))

Expand Down
66 changes: 47 additions & 19 deletions server/attester_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ func pullBlocksAndAttest(
return err
}

var nextHeight int64 = 1
var nextHeight int64
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()

Expand All @@ -191,6 +191,12 @@ func pullBlocksAndAttest(
fmt.Printf("⚠️ status poll failed: %v\n", err)
continue
}
if nextHeight == 0 {
nextHeight = initialAttestationHeight(currentHeight)
}
if currentHeight < nextHeight {
continue
}
for h := nextHeight; h <= currentHeight; h++ {
if err := submitAttestation(ctx, config, h, valAddr, operatorPrivKey, consensusPrivKey, clientCtx); err != nil {
// duplicate or transient — log and move on
Expand All @@ -201,6 +207,13 @@ func pullBlocksAndAttest(
}
}

func initialAttestationHeight(latestHeight int64) int64 {
if latestHeight < 2 {
return 2
}
return latestHeight
}

var accSeq uint64 = 0

func broadcastTx(
Expand Down Expand Up @@ -432,28 +445,13 @@ func submitAttestation(
return fmt.Errorf("getting original block ID: %w", err)
}

vote := cmtproto.Vote{
Type: cmtproto.PrecommitType,
Height: height,
Round: 0,
BlockID: blockID,
Timestamp: header.Time(),
ValidatorAddress: pv.Key.PubKey.Address(),
ValidatorIndex: 0,
}
signBytes := cmttypes.VoteSignBytes(config.ChainID, &vote)
sig, err := pv.Key.PrivKey.Sign(signBytes)
voteBytes, err := buildAttesterVoteBytes(config.ChainID, height, blockID, header.Time(), pv)
if err != nil {
return fmt.Errorf("sign vote: %w", err)
}
vote.Signature = sig
voteBytes, err := proto.Marshal(&vote)
if err != nil {
return fmt.Errorf("marshal vote: %w", err)
return err
}

authorityAddr := sdk.AccAddress(senderKey.PubKey().Address()).String()
consensusAddr := sdk.ConsAddress(pv.Key.PubKey.Address()).String()
consensusAddr := sdk.ConsAddress(pv.Key.Address).String()
msg := networktypes.NewMsgAttest(authorityAddr, consensusAddr, height, voteBytes)

txHash, err := broadcastTx(ctx, config, msg, senderKey, clientCtx)
Expand All @@ -466,6 +464,36 @@ func submitAttestation(
return nil
}

func buildAttesterVoteBytes(
chainID string,
height int64,
blockID cmtproto.BlockID,
timestamp time.Time,
pv *pvm.FilePV,
) ([]byte, error) {
validatorAddress := pv.Key.Address
vote := cmtproto.Vote{
Type: cmtproto.PrecommitType,
Height: height,
Round: 0,
BlockID: blockID,
Timestamp: timestamp,
ValidatorAddress: validatorAddress,
ValidatorIndex: 0,
}
signBytes := cmttypes.VoteSignBytes(chainID, &vote)
sig, err := pv.Key.PrivKey.Sign(signBytes)
if err != nil {
return nil, fmt.Errorf("sign vote: %w", err)
}
vote.Signature = sig
voteBytes, err := proto.Marshal(&vote)
if err != nil {
return nil, fmt.Errorf("marshal vote: %w", err)
}
return voteBytes, nil
}

// getLatestHeight returns the latest raw block height the sequencer has
// produced. It cannot use /status in attester mode because /status reports
// the last-attested height there (which is 0 before any attestation is made,
Expand Down
49 changes: 49 additions & 0 deletions server/attester_cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@ import (
"net/http/httptest"
"strings"
"testing"
"time"

"github.com/cometbft/cometbft/crypto/ed25519"
pvm "github.com/cometbft/cometbft/privval"
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
cmttypes "github.com/cometbft/cometbft/types"
"github.com/cosmos/gogoproto/proto"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -220,6 +226,13 @@ func TestGetLatestHeight(t *testing.T) {
})
}

func TestInitialAttestationHeight(t *testing.T) {
require.Equal(t, int64(2), initialAttestationHeight(0))
require.Equal(t, int64(2), initialAttestationHeight(1))
require.Equal(t, int64(2), initialAttestationHeight(2))
require.Equal(t, int64(42), initialAttestationHeight(42))
}

func TestGetEvolveHeader(t *testing.T) {
t.Run("valid response builds Evolve header", func(t *testing.T) {
nodeURL := newAttesterRPCTestServer(t, `{
Expand Down Expand Up @@ -311,6 +324,42 @@ func TestGetEvolveHeader(t *testing.T) {
})
}

func TestBuildAttesterVoteBytesSignsSerializedValidatorAddress(t *testing.T) {
privKey := ed25519.GenPrivKey()
validatorAddress := cmttypes.Address(bytesOf(0xAB, 20))
pv := &pvm.FilePV{
Key: pvm.FilePVKey{
Address: validatorAddress,
PubKey: privKey.PubKey(),
PrivKey: privKey,
},
}
blockID := cmtproto.BlockID{
Hash: bytesOf(0xCD, 32),
PartSetHeader: cmtproto.PartSetHeader{
Total: 1,
Hash: bytesOf(0xEF, 32),
},
}
timestamp := time.Date(2026, 6, 19, 12, 0, 0, 0, time.UTC)

voteBytes, err := buildAttesterVoteBytes("test-chain", 7, blockID, timestamp, pv)
require.NoError(t, err)

var vote cmtproto.Vote
require.NoError(t, proto.Unmarshal(voteBytes, &vote))
require.Equal(t, validatorAddress, cmttypes.Address(vote.ValidatorAddress))
require.True(t, privKey.PubKey().VerifySignature(cmttypes.VoteSignBytes("test-chain", &vote), vote.Signature))
}

func bytesOf(value byte, length int) []byte {
bytes := make([]byte, length)
for i := range bytes {
bytes[i] = value
}
return bytes
}

func newAttesterRPCTestServer(t *testing.T, response string) string {
t.Helper()

Expand Down
77 changes: 77 additions & 0 deletions tests/integration/gm_gaia_health_multi_attester_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package integration_test

import (
"encoding/base64"
"encoding/json"
"testing"

"github.com/stretchr/testify/require"
)

func TestGenerateAttesterIdentitiesCreatesDistinctOperatorsAndConsensusKeys(t *testing.T) {
identities, err := generateAttesterIdentities(4)
require.NoError(t, err)
require.Len(t, identities, 4)

operatorAddresses := map[string]struct{}{}
consensusAddresses := map[string]struct{}{}
for _, identity := range identities {
require.NotEmpty(t, identity.OperatorArmor)
require.NotEmpty(t, identity.OperatorAddress.String())
require.NotEmpty(t, identity.ConsensusAddress)
require.NotEmpty(t, identity.PrivValidatorKeyJSON)
require.NotEmpty(t, identity.PrivValidatorStateJSON)

operatorAddresses[identity.OperatorAddress.String()] = struct{}{}
consensusAddresses[identity.ConsensusAddress] = struct{}{}
}
require.Len(t, operatorAddresses, 4)
require.Len(t, consensusAddresses, 4)
}

func TestSetGenesisAttestersWritesAllGeneratedAttesters(t *testing.T) {
identities, err := generateAttesterIdentities(4)
require.NoError(t, err)

genesis := []byte(`{"app_state":{"network":{"params":{}}}}`)
updated, err := setGenesisAttesters(genesis, identities)
require.NoError(t, err)

var genDoc map[string]interface{}
require.NoError(t, json.Unmarshal(updated, &genDoc))
appState := genDoc["app_state"].(map[string]interface{})
network := appState["network"].(map[string]interface{})
attesterInfos := network["attester_infos"].([]interface{})
require.Len(t, attesterInfos, 4)

for i, rawInfo := range attesterInfos {
info := rawInfo.(map[string]interface{})
require.Equal(t, identities[i].OperatorAddress.String(), info["authority"])
require.Equal(t, identities[i].ConsensusAddress, info["consensus_address"])
require.Equal(t, float64(0), info["joined_height"])

pubkey := info["pubkey"].(map[string]interface{})
require.Equal(t, "/cosmos.crypto.ed25519.PubKey", pubkey["@type"])
pubKeyBytes, err := base64.StdEncoding.DecodeString(pubkey["key"].(string))
require.NoError(t, err)
require.Equal(t, identities[i].ConsensusPubKey.Bytes(), pubKeyBytes)
}
}

func TestValidatorSetFromAttestersUsesGeneratedConsensusKeys(t *testing.T) {
identities, err := generateAttesterIdentities(4)
require.NoError(t, err)

valSet := validatorSetFromAttesters(identities)
require.Len(t, valSet.Validators, 4)
require.Equal(t, int64(4), valSet.TotalVotingPower())

expectedAddresses := map[string]struct{}{}
for _, identity := range identities {
expectedAddresses[identity.ConsensusPubKey.Address().String()] = struct{}{}
}
for _, validator := range valSet.Validators {
_, ok := expectedAddresses[validator.Address.String()]
require.True(t, ok, "validator %s is not one of the generated attesters", validator.Address.String())
}
}
Loading
Loading