Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add startup check to verify existing DB data matches the algod network. #833

Merged
merged 6 commits into from
Jan 25, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 17 additions & 0 deletions idb/postgres/internal/encoding/encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package encoding

import (
"encoding/base64"
"fmt"

"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/data/basics"
Expand Down Expand Up @@ -666,3 +667,19 @@ func DecodeAccountTotals(data []byte) (ledgercore.AccountTotals, error) {

return res, nil
}

// EncodeNetworkState encodes network metastate into json.
func EncodeNetworkState(state *types.NetworkState) []byte {
return encodeJSON(state)
}

// DecodeNetworkState decodes network metastate from json.
func DecodeNetworkState(data []byte) (types.NetworkState, error) {
var state types.NetworkState
err := DecodeJSON(data, &state)
if err != nil {
return types.NetworkState{}, fmt.Errorf("DecodeNetworkState() err: %w", err)
}

return state, nil
}
19 changes: 19 additions & 0 deletions idb/postgres/internal/encoding/encoding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ import (
"math/rand"
"testing"

"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/data/basics"
"github.com/algorand/go-algorand/data/bookkeeping"
"github.com/algorand/go-algorand/data/transactions"
"github.com/algorand/go-algorand/ledger/ledgercore"
"github.com/algorand/go-algorand/protocol"
"github.com/algorand/indexer/idb/postgres/internal/types"
shiqizng marked this conversation as resolved.
Show resolved Hide resolved
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

Expand Down Expand Up @@ -527,3 +529,20 @@ func TestTxnExtra(t *testing.T) {
})
}
}

// Test that encoding of NetworkState is as expected and that decoding results in the
// same object.
func TestNetworkStateEncoding(t *testing.T) {
network := types.NetworkState{
GenesisHash: crypto.Digest{77},
}

buf := EncodeNetworkState(&network)

expectedString := `{"genesis-hash":"TQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="}`
assert.Equal(t, expectedString, string(buf))

decodedNetwork, err := DecodeNetworkState(buf)
require.NoError(t, err)
assert.Equal(t, network, decodedNetwork)
}
1 change: 1 addition & 0 deletions idb/postgres/internal/schema/metastate.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ const (
MigrationMetastateKey = "migration"
SpecialAccountsMetastateKey = "accounts"
AccountTotals = "totals"
NetworkMetaStateKey = "network"
)
7 changes: 7 additions & 0 deletions idb/postgres/internal/types/types.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package types

import "github.com/algorand/go-algorand/crypto"

// ImportState encodes an import round counter.
type ImportState struct {
NextRoundToAccount uint64 `codec:"next_account_round"`
Expand All @@ -19,3 +21,8 @@ type MigrationState struct {
// It would require a mechanism to clear the data field between migrations to avoid using migration data
// from the previous migration.
}

// NetworkState encodes network metastate.
type NetworkState struct {
GenesisHash crypto.Digest `codec:"genesis-hash"`
}
46 changes: 45 additions & 1 deletion idb/postgres/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"time"

"github.com/algorand/go-algorand/config"
"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/data/basics"
"github.com/algorand/go-algorand/data/bookkeeping"
"github.com/algorand/go-algorand/data/transactions"
Expand Down Expand Up @@ -397,9 +398,26 @@ func (db *IndexerDb) AddBlock(block *bookkeeping.Block) error {
// LoadGenesis is part of idb.IndexerDB
func (db *IndexerDb) LoadGenesis(genesis bookkeeping.Genesis) error {
f := func(tx pgx.Tx) error {
// check genesis hash
network, err := db.getNetworkState(context.Background(), nil)
shiqizng marked this conversation as resolved.
Show resolved Hide resolved
if err == idb.ErrorNotInitialized {
networkState := types.NetworkState{
GenesisHash: crypto.HashObj(genesis),
}
err = db.setNetworkState(nil, &networkState)
shiqizng marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return fmt.Errorf("LoadGenesis() err: %w", err)
}
} else if err != nil {
return fmt.Errorf("LoadGenesis() err: %w", err)
} else {
if network.GenesisHash != crypto.HashObj(genesis) {
return fmt.Errorf("LoadGenesis() genesis hash not matching")
}
}
setAccountStatementName := "set_account"
query := `INSERT INTO account (addr, microalgos, rewardsbase, account_data, rewards_total, created_at, deleted) VALUES ($1, $2, 0, $3, $4, 0, false)`
_, err := tx.Prepare(context.Background(), setAccountStatementName, query)
_, err = tx.Prepare(context.Background(), setAccountStatementName, query)
if err != nil {
return fmt.Errorf("LoadGenesis() prepare tx err: %w", err)
}
Expand Down Expand Up @@ -491,6 +509,32 @@ func (db *IndexerDb) setImportState(tx pgx.Tx, state *types.ImportState) error {
tx, schema.StateMetastateKey, string(encoding.EncodeImportState(state)))
}

// Returns idb.ErrorNotInitialized if uninitialized.
// If `tx` is nil, use a normal query.
func (db *IndexerDb) getNetworkState(ctx context.Context, tx pgx.Tx) (types.NetworkState, error) {
networkStateJSON, err := db.getMetastate(ctx, tx, schema.NetworkMetaStateKey)
if err == idb.ErrorNotInitialized {
return types.NetworkState{}, idb.ErrorNotInitialized
}
if err != nil {
return types.NetworkState{}, fmt.Errorf("unable to get network state err: %w", err)
}

state, err := encoding.DecodeNetworkState([]byte(networkStateJSON))
if err != nil {
return types.NetworkState{},
fmt.Errorf("unable to parse network state v: \"%s\" err: %w", networkStateJSON, err)
}

return state, nil
}

// If `tx` is nil, use a normal query.
func (db *IndexerDb) setNetworkState(tx pgx.Tx, state *types.NetworkState) error {
return db.setMetastate(
tx, schema.NetworkMetaStateKey, string(encoding.EncodeNetworkState(state)))
}

// Returns ErrorNotInitialized if genesis is not loaded.
// If `tx` is nil, use a normal query.
func (db *IndexerDb) getNextRoundToAccount(ctx context.Context, tx pgx.Tx) (uint64, error) {
Expand Down
25 changes: 25 additions & 0 deletions idb/postgres/postgres_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1876,3 +1876,28 @@ func TestTransactionsTxnAhead(t *testing.T) {
require.NoError(t, row.Error)
}
}

// Test that if genesis hash is different from what is in db metastate
// indexer does not start.
func TestGenesisHashCheckAtDBStartup(t *testing.T) {
_, connStr, shutdownFunc := pgtest.SetupPostgres(t)
defer shutdownFunc()
genesis := test.MakeGenesis()
db := setupIdbWithConnectionString(
t, connStr, genesis, test.MakeGenesisBlock())
defer db.Close()
genesisHash := crypto.HashObj(genesis)
network, err := db.getMetastate(context.Background(), nil, schema.NetworkMetaStateKey)
assert.NoError(t, err)
networkState, err := encoding.DecodeNetworkState([]byte(network))
assert.NoError(t, err)
assert.Equal(t, genesisHash, networkState.GenesisHash)
// connect with different genesis configs
genesis.Network = "testnest"
// different genesisHash, should fail
idb, _, err := OpenPostgres(connStr, idb.IndexerDbOptions{}, nil)
assert.NoError(t, err)
err = idb.LoadGenesis(genesis)
assert.Error(t, err)
assert.Contains(t, err.Error(), "genesis hash not matching")
}