diff --git a/docs/giga-storage/StakingStorage.sol b/docs/giga-storage/StakingStorage.sol index dda9dc012e..a7c83a84d4 100644 --- a/docs/giga-storage/StakingStorage.sol +++ b/docs/giga-storage/StakingStorage.sol @@ -51,6 +51,13 @@ contract StakingStorage { uint64 power; } + /// @dev A member of an epoch snapshot. + struct EpochValidator { + address operator; + uint64 power; + bytes32 consensusPubkey; // ed25519 + } + struct Delegation { uint256 shares; } @@ -97,6 +104,11 @@ contract StakingStorage { ValidatorPower[] internal lastValidators; // 0x11: the bonded set, as last sent to consensus uint256 internal lastTotalPower; // 0x12 + /// @dev The bonded set at the end of each epoch's last block, with each + /// member's consensus key. Consensus derives an epoch's committee from the + /// set two epochs before it, so the latest three are kept. + mapping(uint64 => EpochValidator[]) internal epochValidators; // epoch => + uint64 internal nextSnapshotEpoch; // the epoch after the latest in epochValidators, 0 before any mapping(address => Validator) internal validators; // 0x21: operator => AddressSet internal validatorSet; // every operator in validators diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index 9a470371d4..ee475c4b83 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -203,6 +203,7 @@ Staking: |---|---|---| | `0x11` | last validator power | `lastValidators` (array, one slot per bonded validator) | | `0x12` | last total power | `lastTotalPower` | +| none | the bonded set at each epoch end | `epochValidators` (see *The epoch snapshot*) | | `0x21` | validators | `validators` (+ set) | | `0x22` | validator by consensus address | `validatorsByConsensusPubkey`, keyed by the key itself | | `0x23` | validators by power | `validatorsByPower` (sorted array) | @@ -289,6 +290,26 @@ that cost is small. every node, follow tx reverts and snapshots, and be rebuilt after state sync. - **Ordered flatkv keys**, V2's approach exactly. See *Prefix walks*. +### The epoch snapshot + +V2 hands CometBFT a new validator set every block. Autobahn changes its +committee once per epoch: it reads the bonded set after an epoch's last block, +derives the committee two epochs ahead from it, and keeps that committee in +consensus-owned state the precompiles do not read. Rewards need the committee +that served a block. + +So at the end of an epoch's last block, EndBlock copies `lastValidators`, with +each member's consensus key, into `epochValidators[epoch]`, and the committee +that served a block in epoch E is the snapshot of epoch E−2. The snapshot is +committed state, so every node reads the same one, and a node that state-syncs +gets it too. Consensus marks the block that closes an epoch, so the app never +repeats the epoch length. The keys are copied because a member can leave the +bonded set, finish unbonding with no shares and be removed while its snapshot +is still read. + +Three are kept, E−2 to E, and EndBlock deletes the one before them when it +takes a new one: about 150 slot writes once an epoch at 35 validators. + ### Where the structures don't carry over Each of these is a place where slot storage, or a deliberate simplification, @@ -501,7 +522,8 @@ of a million state writes per epoch. - The fee pot is for the rewards design to define. Giga's coinbase and base fee are zero today. - Minting belongs to the rewards design. pacific-1's release schedule is empty. -- Power and the bonded set are read from staking, not copied. +- Power and the bonded set are read from staking, not copied: the committee + that served a block from staking's epoch snapshot. - `communityTax` and the proposer reward params stay in distribution's params (all zero on pacific-1). diff --git a/giga/evmonly/custom_precompile.go b/giga/evmonly/custom_precompile.go index 5a3ca176de..ab23348824 100644 --- a/giga/evmonly/custom_precompile.go +++ b/giga/evmonly/custom_precompile.go @@ -14,6 +14,7 @@ import ( "github.com/holiman/uint256" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + gigatypes "github.com/sei-protocol/sei-chain/sei-db/state_db/giga/types" ) var ( @@ -167,6 +168,12 @@ var ( _ precompiles.LogSink = (*precompileState)(nil) ) +// ReadOnlyState returns view as a custom precompile's State under a static +// call: a write is dropped and fails the state, and nothing is charged. +func ReadOnlyState(view gigatypes.EVMStateView) precompiles.State { + return &precompileState{db: newNativeStateDB(gigaSnapshotStateReader{snapshot: view}), readOnly: true} +} + func (s *precompileState) GetBalance(addr common.Address) *big.Int { return s.db.GetBalance(addr).ToBig() } diff --git a/giga/evmonly/custom_precompile_execution_test.go b/giga/evmonly/custom_precompile_execution_test.go index 2ebee208da..5903b44e21 100644 --- a/giga/evmonly/custom_precompile_execution_test.go +++ b/giga/evmonly/custom_precompile_execution_test.go @@ -270,3 +270,19 @@ func TestPrecompileStateMetersLogs(t *testing.T) { require.ErrorIs(t, s.err, vm.ErrOutOfGas) require.Empty(t, db.logs, "the log is dropped") } + +func TestReadOnlyStateReadsTheViewAndFailsOnAWrite(t *testing.T) { + slot, value := testHash(0x01), testHash(0x02) + source := NewMemoryState() + source.SetState(registeredPrecompileAddress, slot, value) + view := NewMemoryStore(source).OpenView() + defer view.Close() + + state := ReadOnlyState(view) + require.Equal(t, value, state.GetState(registeredPrecompileAddress, slot)) + require.False(t, state.Failed()) + + state.SetState(registeredPrecompileAddress, slot, common.Hash{}) + require.True(t, state.Failed()) + require.Equal(t, value, view.GetStorage(registeredPrecompileAddress, slot), "the view is unchanged") +} diff --git a/giga/evmonly/end_block.go b/giga/evmonly/end_block.go index 3a3576a751..b7828bfa1a 100644 --- a/giga/evmonly/end_block.go +++ b/giga/evmonly/end_block.go @@ -114,13 +114,14 @@ func truncateUTF8(s string, n int) string { func endBlockContext(block BlockContext, chainID *big.Int) precompiles.BlockContext { return precompiles.BlockContext{ - Number: block.Number, - UnixNano: unixNano(block.Time), - ChainID: cloneOptionalBig(chainID), - BaseFee: cloneOptionalBig(block.BaseFee), - BlobBaseFee: cloneOptionalBig(block.BlobBaseFee), - Coinbase: block.Coinbase, - PrevRandao: block.PrevRandao, + Number: block.Number, + UnixNano: unixNano(block.Time), + ChainID: cloneOptionalBig(chainID), + BaseFee: cloneOptionalBig(block.BaseFee), + BlobBaseFee: cloneOptionalBig(block.BlobBaseFee), + Coinbase: block.Coinbase, + PrevRandao: block.PrevRandao, + ClosingEpoch: block.ClosingEpoch, } } diff --git a/giga/evmonly/giga_store.go b/giga/evmonly/giga_store.go index bffa20369e..1a4fc76226 100644 --- a/giga/evmonly/giga_store.go +++ b/giga/evmonly/giga_store.go @@ -9,6 +9,7 @@ import ( "github.com/ethereum/go-ethereum/common" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" gigametrics "github.com/sei-protocol/sei-chain/giga/metrics" gigatypes "github.com/sei-protocol/sei-chain/sei-db/state_db/giga/types" ) @@ -168,6 +169,52 @@ func (e *Executor) AwaitCommits() error { return e.awaitPipelineCommit() } +// ReadLatest calls read with read-only state holding every block this executor has run, without +// waiting for the commit in flight. It fails once a commit is known to have failed. +func (e *Executor) ReadLatest(read func(precompiles.State) error) error { + if e.stateStore == nil { + return errMissingStateStore + } + // Held so that no block starts its commit between taking the overlay and opening the view, + // which would pair the view with an overlay older than it. + e.storeMu.Lock() + defer e.storeMu.Unlock() + // Taken before the view, never after, as in executePreparedBlockWithStore. + pending := e.pipelinePending() + snapshot := e.stateStore.OpenView() + if snapshot == nil { + return errors.New("giga store returned a nil snapshot") + } + defer snapshot.Close() + source := pending.overlay(gigaSnapshotStateReader{snapshot: snapshot, missingState: e.missingState}) + if err := read(&precompileState{db: newNativeStateDB(source), readOnly: true}); err != nil { + return err + } + // Checked after the read: a failed commit retired before the overlay was taken leaves the view + // short of that block and nothing to supply it. + return e.commitFailure() +} + +// commitFailure reports a commit known to have failed, without waiting for the one in flight. +func (e *Executor) commitFailure() error { + e.pipelineMu.Lock() + defer e.pipelineMu.Unlock() + if e.pipelineFailure != nil { + return e.pipelineFailure + } + if e.pipelineDone == nil { + return nil + } + select { + case <-e.pipelineDone: + if e.pipelineErr != nil { + return fmt.Errorf("commit state changes: %w", e.pipelineErr) + } + default: + } + return nil +} + // pipelinePending returns the indexed changes of a block whose commit has not been waited on yet, or // nil when the store is caught up. func (e *Executor) pipelinePending() *pendingIndex { diff --git a/giga/evmonly/pipeline_store_test.go b/giga/evmonly/pipeline_store_test.go index 0def74e9cd..cf697cf37e 100644 --- a/giga/evmonly/pipeline_store_test.go +++ b/giga/evmonly/pipeline_store_test.go @@ -3,6 +3,7 @@ package evmonly import ( "errors" "math/big" + "sync" "testing" "time" @@ -10,6 +11,7 @@ import ( "github.com/holiman/uint256" "github.com/stretchr/testify/require" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" gigatypes "github.com/sei-protocol/sei-chain/sei-db/state_db/giga/types" ) @@ -307,3 +309,71 @@ func executePipelinedBlock(t *testing.T, executor *Executor, chainID *big.Int, n require.NoError(t, err) return result } + +// heldCommitStore holds every commit until release is closed. +type heldCommitStore struct { + *recordingGigaStore + release chan struct{} +} + +func (s *heldCommitStore) CommitStateChanges(blockNum int64, changes *gigatypes.StateChangeSet) error { + <-s.release + return s.recordingGigaStore.CommitStateChanges(blockNum, changes) +} + +// ReadLatest serves the state a block produced while that block's commit is still running. +func TestReadLatestServesTheBlockStillCommitting(t *testing.T) { + chainID := big.NewInt(testChainID) + key, err := crypto.GenerateKey() + require.NoError(t, err) + sender := crypto.PubkeyToAddress(key.PublicKey) + recipient := testAddress(0xa9) + + snapshot := newMemoryGigaSnapshot(40) + snapshot.setBalance(sender, big.NewInt(testFundedBalanceWei)) + store := &heldCommitStore{recordingGigaStore: &recordingGigaStore{snapshot: snapshot}, release: make(chan struct{})} + executor := NewExecutor(Config{}, withTestStores(store, NewMemoryReceiptStore())) + defer executor.Close() + var released sync.Once + release := func() { released.Do(func() { close(store.release) }) } + defer release() + + executePipelinedBlock(t, executor, chainID, 41, + signLegacyTx(t, key, chainID, 0, &recipient, big.NewInt(7), nil)) + + var balance *big.Int + require.NoError(t, executor.ReadLatest(func(state precompiles.State) error { + balance = state.GetBalance(recipient) + return nil + })) + require.Equal(t, big.NewInt(7), balance, "block 41's payment is served while its commit is held") + + release() + require.NoError(t, executor.AwaitCommits()) + require.Equal(t, []int64{41}, store.commitBlock) +} + +// ReadLatest refuses once a commit has failed, whether or not anything has waited on it, since the +// store then predates that block. +func TestReadLatestFailsOnceACommitHasFailed(t *testing.T) { + chainID := big.NewInt(testChainID) + key, err := crypto.GenerateKey() + require.NoError(t, err) + sender := crypto.PubkeyToAddress(key.PublicKey) + recipient := testAddress(0xa9) + + snapshot := newMemoryGigaSnapshot(40) + snapshot.setBalance(sender, big.NewInt(testFundedBalanceWei)) + store := &recordingGigaStore{snapshot: snapshot, commitErr: errTestCommitFailed} + executor := NewExecutor(Config{}, withTestStores(store, NewMemoryReceiptStore())) + defer executor.Close() + + executePipelinedBlock(t, executor, chainID, 41, + signLegacyTx(t, key, chainID, 0, &recipient, big.NewInt(7), nil)) + + read := func(precompiles.State) error { return nil } + require.Eventually(t, func() bool { return errors.Is(executor.ReadLatest(read), errTestCommitFailed) }, + 5*time.Second, time.Millisecond, "a failed commit is reported before anything waits on it") + require.ErrorIs(t, executor.AwaitCommits(), errTestCommitFailed) + require.ErrorIs(t, executor.ReadLatest(read), errTestCommitFailed, "and still once it has been waited on") +} diff --git a/giga/evmonly/precompiles/context.go b/giga/evmonly/precompiles/context.go index 7dc62bef47..b99cd76c76 100644 --- a/giga/evmonly/precompiles/context.go +++ b/giga/evmonly/precompiles/context.go @@ -6,6 +6,8 @@ import ( "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" + + "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils" ) var ErrCustomPrecompilesOpen = errors.New("evm-only custom precompiles are not implemented") @@ -82,6 +84,9 @@ type BlockContext struct { // Replay is set when the block runs only to rebuild its state, as for a // trace, rather than to execute it. Replay bool + // ClosingEpoch is the consensus epoch this block is the last block of, if + // it is one. + ClosingEpoch utils.Option[uint64] } // State is the precompile-facing state API. Implementations must make these diff --git a/giga/evmonly/precompiles/staking/bonded_set.go b/giga/evmonly/precompiles/staking/bonded_set.go new file mode 100644 index 0000000000..ec9801a899 --- /dev/null +++ b/giga/evmonly/precompiles/staking/bonded_set.go @@ -0,0 +1,53 @@ +package staking + +import ( + "fmt" + + "github.com/ethereum/go-ethereum/common" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" +) + +// BondedValidator is a member of the bonded set. +type BondedValidator struct { + Operator common.Address + ConsensusPubkey common.Hash // ed25519 + Power uint64 +} + +// BondedValidators returns the bonded set the last EndBlock stored, in the +// order it ranked them, or none before staking has bonded a set. It fails when +// the stored set does not add up. +func BondedValidators(state precompiles.State) ([]BondedValidator, error) { + return bondedValidators(newStore(state)) +} + +// EpochValidators returns the bonded set snapshotted at the end of the latest +// epoch, in the order it ranked them, or none before the first snapshot. It +// fails when the stored set does not add up. +func EpochValidators(state precompiles.State) ([]BondedValidator, error) { + s := newStore(state) + epoch, ok := s.latestSnapshotEpoch() + if !ok { + return nil, nil + } + return s.epochValidators(epoch) +} + +// bondedValidators returns the bonded set the last EndBlock stored, with each +// member's consensus key. +func bondedValidators(s store) ([]BondedValidator, error) { + last, err := s.lastValidators() + if err != nil { + return nil, err + } + bonded := make([]BondedValidator, len(last)) + for i, v := range last { + pubkey := s.consensusPubkey(v.operator) + if pubkey == (common.Hash{}) { + return nil, fmt.Errorf("%w: %s", errUnknownValidator, v.operator) + } + bonded[i] = BondedValidator{Operator: v.operator, ConsensusPubkey: pubkey, Power: v.power} + } + return bonded, nil +} diff --git a/giga/evmonly/precompiles/staking/bonded_set_test.go b/giga/evmonly/precompiles/staking/bonded_set_test.go new file mode 100644 index 0000000000..25b52365c2 --- /dev/null +++ b/giga/evmonly/precompiles/staking/bonded_set_test.go @@ -0,0 +1,121 @@ +package staking + +import ( + "errors" + "testing" + + "github.com/ethereum/go-ethereum/common" + "github.com/stretchr/testify/require" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" +) + +func TestBondedValidatorsAreTheSetTheLastEndBlockStored(t *testing.T) { + h := newHarness(t, testParams) + want := []BondedValidator{ + {Operator: val1, ConsensusPubkey: common.BytesToHash(val1[:]), Power: 30}, + {Operator: val2, ConsensusPubkey: common.BytesToHash(val2[:]), Power: 20}, + } + require.Equal(t, want, must(BondedValidators(h.state))) + + require.NoError(t, h.delegate(alice, val3, sei(15))) + require.Equal(t, want, must(BondedValidators(h.state)), "a delegation moves the set only at EndBlock") + h.endBlock() + require.Equal(t, []BondedValidator{ + {Operator: val1, ConsensusPubkey: common.BytesToHash(val1[:]), Power: 30}, + {Operator: val3, ConsensusPubkey: common.BytesToHash(val3[:]), Power: 25}, + }, must(BondedValidators(h.state)), "the set moves at any EndBlock, not only an epoch's last") +} + +func TestNoValidatorsAreBondedBeforeStakingBondsASet(t *testing.T) { + state := newMemState() + require.Empty(t, must(BondedValidators(state))) + require.NoError(t, SetParams(state, testParams)) + require.Empty(t, must(BondedValidators(state))) +} + +func TestBondedValidatorsFailOnAStoredSetThatDoesNotAddUp(t *testing.T) { + h := newHarness(t, testParams) + h.store().setLastValidators([]validatorPower{{val1, 30}, {alice, 20}}) + _, err := BondedValidators(h.state) + require.ErrorIs(t, err, errUnknownValidator, "a member with no validator") + + h.store().SetUint64(solstorage.Slot(slotLastValidators), 0, 101) + _, err = BondedValidators(h.state) + require.ErrorIs(t, err, errInvalidStoredSet, "a set longer than any MaxValidators allows") +} + +func TestEpochValidatorsAreTheSetAtTheLatestEpochEnd(t *testing.T) { + h := newHarness(t, testParams) + require.Empty(t, must(EpochValidators(h.state)), "no epoch has ended") + + h.endEpoch(0) + want := []BondedValidator{ + {Operator: val1, ConsensusPubkey: common.BytesToHash(val1[:]), Power: 30}, + {Operator: val2, ConsensusPubkey: common.BytesToHash(val2[:]), Power: 20}, + } + require.Equal(t, want, must(EpochValidators(h.state))) + + require.NoError(t, h.delegate(alice, val3, sei(15))) + h.endBlock() + require.Equal(t, want, must(EpochValidators(h.state)), "the bonded set moves within an epoch, its snapshot only at the epoch's end") + h.endEpoch(1) + require.Equal(t, []BondedValidator{ + {Operator: val1, ConsensusPubkey: common.BytesToHash(val1[:]), Power: 30}, + {Operator: val3, ConsensusPubkey: common.BytesToHash(val3[:]), Power: 25}, + }, must(EpochValidators(h.state))) +} + +func TestEpochSnapshotsKeepTheLatestThree(t *testing.T) { + h := newHarness(t, testParams) + for epoch := range uint64(5) { + h.endEpoch(epoch) + } + s := h.store() + for epoch, kept := range []bool{false, false, true, true, true} { + require.Equal(t, kept, len(must(s.epochValidators(uint64(epoch)))) > 0, "epoch %d", epoch) + } + latest, ok := s.latestSnapshotEpoch() + require.True(t, ok) + require.Equal(t, uint64(4), latest) +} + +func TestNoEpochValidatorsBeforeStakingStarts(t *testing.T) { + state := newMemState() + require.Empty(t, must(EpochValidators(state))) + require.NoError(t, SetParams(state, testParams)) + require.Empty(t, must(EpochValidators(state))) +} + +func TestEpochValidatorsOutliveTheirValidators(t *testing.T) { + h := newHarness(t, testParams) + h.endEpoch(0) + want := must(EpochValidators(h.state)) + + require.NoError(t, h.delegate(alice, val3, sei(15))) + h.endBlock() + require.NoError(t, h.undelegate(val2, val2, sei(20))) + h.advance(testParams.UnbondingTime) + require.Empty(t, h.failures) + _, ok := h.store().validator(val2) + require.False(t, ok, "val2 left the bonded set and was removed once it unbonded with no shares") + require.Equal(t, want, must(EpochValidators(h.state))) +} + +func TestAnEpochWhoseSetDoesNotAddUpIsNotSnapshotted(t *testing.T) { + h := newHarness(t, testParams) + h.endEpoch(0) + want := must(EpochValidators(h.state)) + h.store().setLastValidators([]validatorPower{{val1, 30}, {alice, 20}}) + h.endEpoch(1) + require.ErrorIs(t, errors.Join(h.failures...), errUnknownValidator, "a member with no validator") + require.Equal(t, want, must(EpochValidators(h.state)), "epoch 0's snapshot stays the latest") +} + +func TestEpochValidatorsFailOnAStoredSetThatDoesNotAddUp(t *testing.T) { + h := newHarness(t, testParams) + h.endEpoch(0) + h.store().SetUint64(solstorage.MapUint64(solstorage.Slot(slotEpochValidators), 0), 0, 101) + _, err := EpochValidators(h.state) + require.ErrorIs(t, err, errInvalidStoredSet, "a set longer than any MaxValidators allows") +} diff --git a/giga/evmonly/precompiles/staking/endblock.go b/giga/evmonly/precompiles/staking/endblock.go index 7ccd29417c..de8ba9985f 100644 --- a/giga/evmonly/precompiles/staking/endblock.go +++ b/giga/evmonly/precompiles/staking/endblock.go @@ -33,12 +33,13 @@ var ( // undelegations. const endBlockBudget = 3_000 -// EndBlock updates the bonded set, then completes the validators, unbonding -// entries and redelegation entries whose unbonding period is over, in that -// order, as x/staking's BlockValidatorUpdates does. Before staking's params are -// written it does nothing. Its failures are a bonded set that could not be -// updated, which is kept as it was, and queue entries whose stored data does -// not add up, which are dropped. It returns no error. +// EndBlock updates the bonded set, snapshots it when the block closes an epoch, +// then completes the validators, unbonding entries and redelegation entries +// whose unbonding period is over, in that order, as x/staking's +// BlockValidatorUpdates does. Before staking's params are written it does +// nothing. Its failures are a bonded set that could not be updated, which is +// kept as it was, a snapshot that could not be taken, and queue entries whose +// stored data does not add up, which are dropped. It returns no error. func (p Precompile) EndBlock(block precompiles.BlockContext, state precompiles.State) ([]error, error) { if !chainparams.HasStaking(state) { return nil, nil @@ -49,6 +50,11 @@ func (p Precompile) EndBlock(block precompiles.BlockContext, state precompiles.S if err := p.updateBondedSet(block, s, params); err != nil { failures = append(failures, fmt.Errorf("%w: bonded set kept as it was: %w", precompiles.ErrDegraded, err)) } + if epoch, ok := block.ClosingEpoch.Get(); ok { + if err := snapshotEpoch(s, epoch); err != nil { + failures = append(failures, fmt.Errorf("%w: epoch %d's bonded set not snapshotted: %w", precompiles.ErrDegraded, epoch, err)) + } + } drain(block, s.validatorQueue(), "validator", &failures, func(common.Hash) uint64 { return 1 }, func(e common.Hash) error { return p.completeValidatorUnbonding(block, s, e) }) @@ -156,6 +162,28 @@ func (p Precompile) applyBondedSet(block precompiles.BlockContext, s store, para return nil } +// epochSnapshotsKept is how many epoch snapshots are kept, as the committee +// serving an epoch is the bonded set at the end of the epoch two before it. +const epochSnapshotsKept = 3 + +// snapshotEpoch copies the bonded set, with each member's consensus key, into +// epoch's snapshot and deletes the one that no longer falls among the latest +// epochSnapshotsKept. +func snapshotEpoch(s store, epoch uint64) error { + set, err := bondedValidators(s) + if err != nil { + return err + } + // The keys are copied rather than looked up when the snapshot is read, + // because a member can be removed before its snapshot is retired. + s.setEpochValidators(epoch, set) + if epoch >= epochSnapshotsKept { + s.setEpochValidators(epoch-epochSnapshotsKept, nil) + } + s.setLatestSnapshotEpoch(epoch) + return nil +} + // drain completes each entry due in q, in queue order, under a budget of its // own, until none is due or the next does not fit what is left. Each entry is // removed from q once completed. A completion that fails is reverted and its diff --git a/giga/evmonly/precompiles/staking/helpers_test.go b/giga/evmonly/precompiles/staking/helpers_test.go index bbfdc1411c..c612658b77 100644 --- a/giga/evmonly/precompiles/staking/helpers_test.go +++ b/giga/evmonly/precompiles/staking/helpers_test.go @@ -18,6 +18,7 @@ import ( "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/dec" chainparams "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/params" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" + "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils" ) // memState is a map-backed precompiles.State and LogSink. @@ -171,7 +172,18 @@ func (h *harness) block() precompiles.BlockContext { // endBlock runs EndBlock at the current block, then starts the next block one // second later. func (h *harness) endBlock() { - failures, err := h.staking.EndBlock(h.block(), h.state) + h.endBlockWith(h.block()) +} + +// endEpoch ends the current block as the last block of epoch. +func (h *harness) endEpoch(epoch uint64) { + block := h.block() + block.ClosingEpoch = utils.Some(epoch) + h.endBlockWith(block) +} + +func (h *harness) endBlockWith(block precompiles.BlockContext) { + failures, err := h.staking.EndBlock(block, h.state) require.NoError(h.t, err) h.failures = failures h.number++ diff --git a/giga/evmonly/precompiles/staking/layout.go b/giga/evmonly/precompiles/staking/layout.go index a8a99d168b..b55844b4d3 100644 --- a/giga/evmonly/precompiles/staking/layout.go +++ b/giga/evmonly/precompiles/staking/layout.go @@ -12,22 +12,24 @@ var Address = common.HexToAddress("0x0000000000000000000000000000000000001005") const ( slotLastValidators = 0 slotLastTotalPower = 1 - slotValidators = 2 - slotValidatorSet = 3 - slotValidatorsByConsensusPubkey = 5 - slotValidatorsByPower = 6 - slotDelegations = 7 - slotDelegationsByDelegator = 8 - slotDelegationsByValidator = 9 - slotUnbondingDelegations = 10 - slotRedelegationEntryCounts = 11 - slotRedelegationsByValDst = 12 - slotUnbondingQueueBounds = 13 - slotUnbondingQueue = 14 - slotRedelegationQueueBounds = 15 - slotRedelegationQueue = 16 - slotValidatorQueueBounds = 17 - slotValidatorQueue = 18 + slotEpochValidators = 2 + slotNextSnapshotEpoch = 3 + slotValidators = 4 + slotValidatorSet = 5 + slotValidatorsByConsensusPubkey = 7 + slotValidatorsByPower = 8 + slotDelegations = 9 + slotDelegationsByDelegator = 10 + slotDelegationsByValidator = 11 + slotUnbondingDelegations = 12 + slotRedelegationEntryCounts = 13 + slotRedelegationsByValDst = 14 + slotUnbondingQueueBounds = 15 + slotUnbondingQueue = 16 + slotRedelegationQueueBounds = 17 + slotRedelegationQueue = 18 + slotValidatorQueueBounds = 19 + slotValidatorQueue = 20 ) // member is a struct member's position relative to the struct's base slot. @@ -66,6 +68,16 @@ var ( validatorPowerPower = member{0, 20} ) +// StakingStorage.EpochValidator members. +var ( + epochValidatorOperator = member{0, 0} + epochValidatorPower = member{0, 20} + epochValidatorConsensusPubkey = member{1, 0} +) + +// epochValidatorSlots is how many slots a StakingStorage.EpochValidator takes. +const epochValidatorSlots = 2 + // StakingStorage.UnbondingDelegationEntry members. var ( unbondingEntryCreationHeight = member{0, 0} diff --git a/giga/evmonly/precompiles/staking/layout_test.go b/giga/evmonly/precompiles/staking/layout_test.go index adf4ffeb3a..e257115db0 100644 --- a/giga/evmonly/precompiles/staking/layout_test.go +++ b/giga/evmonly/precompiles/staking/layout_test.go @@ -52,6 +52,8 @@ func TestLayoutMatchesSolc(t *testing.T) { require.Equal(t, map[string]uint64{ "lastValidators": slotLastValidators, "lastTotalPower": slotLastTotalPower, + "epochValidators": slotEpochValidators, + "nextSnapshotEpoch": slotNextSnapshotEpoch, "validators": slotValidators, "validatorSet": slotValidatorSet, "validatorsByConsensusPubkey": slotValidatorsByConsensusPubkey, @@ -68,9 +70,9 @@ func TestLayoutMatchesSolc(t *testing.T) { "redelegationQueue": slotRedelegationQueue, "validatorQueueBounds": slotValidatorQueueBounds, "validatorQueue": slotValidatorQueue, - "migrating": 19, - "migrationCursor": 20, - "migrationFailures": 21, + "migrating": 21, + "migrationCursor": 22, + "migrationFailures": 23, }, got) // Each struct's Go members, and how many slots it takes. Description and @@ -111,6 +113,11 @@ func TestLayoutMatchesSolc(t *testing.T) { "operator": validatorPowerOperator, "power": validatorPowerPower, }, 1}, + "struct StakingStorage.EpochValidator": {map[string]member{ + "operator": epochValidatorOperator, + "power": epochValidatorPower, + "consensusPubkey": epochValidatorConsensusPubkey, + }, epochValidatorSlots}, "struct StakingStorage.Delegation": {map[string]member{"shares": {0, 0}}, 1}, "struct StakingStorage.UnbondingDelegationEntry": {map[string]member{ "creationHeight": unbondingEntryCreationHeight, @@ -198,6 +205,10 @@ func TestStoreReadsCompilerWrites(t *testing.T) { require.NoError(t, err) require.Equal(t, []validatorPower{{op, 30}, {other, 20}}, set) require.Equal(t, big.NewInt(50), s.lastTotalPower()) + require.Equal(t, []BondedValidator{{Operator: other, ConsensusPubkey: pubkey, Power: 21}}, must(s.epochValidators(7))) + latest, ok := s.latestSnapshotEpoch() + require.True(t, ok) + require.Equal(t, uint64(7), latest) v, ok := s.validator(op) require.True(t, ok) diff --git a/giga/evmonly/precompiles/staking/storage.go b/giga/evmonly/precompiles/staking/storage.go index 464847e411..92d38c9ce3 100644 --- a/giga/evmonly/precompiles/staking/storage.go +++ b/giga/evmonly/precompiles/staking/storage.go @@ -145,6 +145,12 @@ func (s store) validatorPower(op common.Address) *big.Int { return consensusPower(s.Uint256(at(validatorBase(op), validatorTokens))) } +// consensusPubkey returns op's stored consensus key, zero when op has no +// validator. +func (s store) consensusPubkey(op common.Address) common.Hash { + return s.Word(at(validatorBase(op), validatorConsensusPubkey)) +} + func (s store) validatorSet() solstorage.Set { return solstorage.Set{Store: s.Store, Base: solstorage.Slot(slotValidatorSet)} } @@ -207,6 +213,62 @@ func (s store) setLastValidators(set []validatorPower) { s.SetWord(base, solstorage.Slot(uint64(len(set)))) } +func epochValidatorsBase(epoch uint64) common.Hash { + return solstorage.MapUint64(solstorage.Slot(slotEpochValidators), epoch) +} + +// epochValidators returns the bonded set snapshotted at the end of epoch, or +// none when that epoch has no snapshot. It fails on a set longer than any +// MaxValidators allows. +func (s store) epochValidators(epoch uint64) ([]BondedValidator, error) { + base := epochValidatorsBase(epoch) + n := s.Uint64(base, 0) + if n > uint64(chainparams.MaxBondedValidators) { + return nil, fmt.Errorf("%w: %d validators", errInvalidStoredSet, n) + } + data := solstorage.ArrayData(base) + out := make([]BondedValidator, n) + for i := range out { + e := solstorage.Offset(data, uint64(i)*epochValidatorSlots) //nolint:gosec // i is below n + out[i] = BondedValidator{ + Operator: s.AddressAt(at(e, epochValidatorOperator), epochValidatorOperator.offset), + ConsensusPubkey: s.Word(at(e, epochValidatorConsensusPubkey)), + Power: s.Uint64(at(e, epochValidatorPower), epochValidatorPower.offset), + } + } + return out, nil +} + +// setEpochValidators replaces epoch's snapshot, zeroing elements the new one no +// longer covers. +func (s store) setEpochValidators(epoch uint64, set []BondedValidator) { + base := epochValidatorsBase(epoch) + old := min(s.Uint64(base, 0), uint64(chainparams.MaxBondedValidators)) + data := solstorage.ArrayData(base) + for i, v := range set { + e := solstorage.Offset(data, uint64(i)*epochValidatorSlots) //nolint:gosec // i is non-negative + s.SetWord(at(e, epochValidatorOperator), common.Hash{}) + s.SetAddressAt(at(e, epochValidatorOperator), epochValidatorOperator.offset, v.Operator) + s.SetUint64(at(e, epochValidatorPower), epochValidatorPower.offset, v.Power) + s.SetWord(at(e, epochValidatorConsensusPubkey), v.ConsensusPubkey) + } + for i := uint64(len(set)) * epochValidatorSlots; i < old*epochValidatorSlots; i++ { + s.SetWord(solstorage.Offset(data, i), common.Hash{}) + } + s.SetWord(base, solstorage.Slot(uint64(len(set)))) +} + +// latestSnapshotEpoch returns the latest epoch with a snapshot, and false +// before any. +func (s store) latestSnapshotEpoch() (uint64, bool) { + next := s.Uint64(solstorage.Slot(slotNextSnapshotEpoch), 0) + return next - 1, next > 0 +} + +func (s store) setLatestSnapshotEpoch(epoch uint64) { + s.SetUint64(solstorage.Slot(slotNextSnapshotEpoch), 0, epoch+1) +} + // lastTotalPower returns the consensus power of the bonded set as last stored. func (s store) lastTotalPower() *big.Int { return s.Uint256(solstorage.Slot(slotLastTotalPower)) diff --git a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime index 6747b79150..5f84c63551 100644 --- a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime +++ b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime @@ -1 +1 @@ -608060405234801561000f575f5ffd5b5060043610610029575f3560e01c80633afaaf0e1461002d575b5f5ffd5b610047600480360381019061004291906110fa565b610049565b005b5f60405180604001604052808673ffffffffffffffffffffffffffffffffffffffff168152602001601e67ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555050505f60405180604001604052808573ffffffffffffffffffffffffffffffffffffffff168152602001601467ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550505060326001819055505f60025f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20905081815f01819055506001816001015f6101000a81548160ff02191690831515021790555060028160010160016101000a81548160ff021916908360ff1602179055506801ae361fc1451c000081600201819055506f1812f9cf7920e2b66973e20000000000816003018190555060405180606001604052806034815260200161146b60349139816004015f0190816102c3919061139b565b506040518060400160405280600181526020017f640000000000000000000000000000000000000000000000000000000000000081525081600401600401908161030d919061139b565b506021816009015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060228160090160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602381600a015f015f0181905550602481600a016003015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602581600e0181905550600360025f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2060010160016101000a81548160ff021916908360ff160217905550610410600386610fba565b61041b600385610fba565b8460055f8481526020019081526020015f205f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600684908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600685908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550602960075f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f01819055506105f060085f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2086610fba565b61063660095f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2084610fba565b600a5f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603367ffffffffffffffff168152602001603467ffffffffffffffff168152602001603581526020016036815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060408201518160010155606082015181600201555050600a5f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603767ffffffffffffffff168152602001603867ffffffffffffffff16815260200160398152602001603a815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550604082015181600101556060820151816002015550506002600b5f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506003600c5f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506040518060400160405280600167ffffffffffffffff168152602001600267ffffffffffffffff16815250600d5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280603d67ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff16815250600e5f600167ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555090505060405180604001604052805f67ffffffffffffffff168152602001600167ffffffffffffffff16815250600f5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060e00160405280604767ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff168152602001604867ffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff16815260200160498152602001604a81525060105f5f67ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060608201518160010160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506080820151816002015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060a0820151816003015560c082015181600401559050506040518060400160405280600467ffffffffffffffff168152602001600567ffffffffffffffff1681525060115f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280605167ffffffffffffffff168152602001605267ffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff1681525060125f600467ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055509050505050505050565b815f0181908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550815f0180549050826001015f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055505050565b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6110968261106d565b9050919050565b6110a68161108c565b81146110b0575f5ffd5b50565b5f813590506110c18161109d565b92915050565b5f819050919050565b6110d9816110c7565b81146110e3575f5ffd5b50565b5f813590506110f4816110d0565b92915050565b5f5f5f5f6080858703121561111257611111611069565b5b5f61111f878288016110b3565b9450506020611130878288016110b3565b9350506040611141878288016110b3565b9250506060611152878288016110e6565b91505092959194509250565b5f81519050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f60028204905060018216806111d957607f821691505b6020821081036111ec576111eb611195565b5b50919050565b5f819050815f5260205f209050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f6008830261124e7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82611213565b6112588683611213565b95508019841693508086168417925050509392505050565b5f819050919050565b5f819050919050565b5f61129c61129761129284611270565b611279565b611270565b9050919050565b5f819050919050565b6112b583611282565b6112c96112c1826112a3565b84845461121f565b825550505050565b5f5f905090565b6112e06112d1565b6112eb8184846112ac565b505050565b5b8181101561130e576113035f826112d8565b6001810190506112f1565b5050565b601f82111561135357611324816111f2565b61132d84611204565b8101602085101561133c578190505b61135061134885611204565b8301826112f0565b50505b505050565b5f82821c905092915050565b5f6113735f1984600802611358565b1980831691505092915050565b5f61138b8383611364565b9150826002028217905092915050565b6113a48261115e565b67ffffffffffffffff8111156113bd576113bc611168565b5b6113c782546111c2565b6113d2828285611312565b5f60209050601f831160018114611403575f84156113f1578287015190505b6113fb8582611380565b865550611462565b601f198416611411866111f2565b5f5b8281101561143857848901518255600182019150602085019450602081019050611413565b868310156114555784890151611451601f891682611364565b8355505b6001600288020188555050505b50505050505056fe61206d6f6e696b6572206c6f6e6720656e6f75676820746f207370696c6c2070617374206f6e652073746f7261676520776f7264a2646970667358221220ca5344d3b5f6f14544837d3f326231a5017eb67a3e45fd84e5063d42ade3370764736f6c634300081e0033 +608060405234801561000f575f5ffd5b5060043610610029575f3560e01c80633afaaf0e1461002d575b5f5ffd5b6100476004803603810190610042919061121f565b610049565b005b5f60405180604001604052808673ffffffffffffffffffffffffffffffffffffffff168152602001601e67ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555050505f60405180604001604052808573ffffffffffffffffffffffffffffffffffffffff168152602001601467ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055505050603260018190555060025f600767ffffffffffffffff1681526020019081526020015f2060405180606001604052808573ffffffffffffffffffffffffffffffffffffffff168152602001601567ffffffffffffffff16815260200183815250908060018154018082558091505060019003905f5260205f2090600202015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550604082015181600101555050600860035f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055505f60045f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20905081815f01819055506001816001015f6101000a81548160ff02191690831515021790555060028160010160016101000a81548160ff021916908360ff1602179055506801ae361fc1451c000081600201819055506f1812f9cf7920e2b66973e20000000000816003018190555060405180606001604052806034815260200161159060349139816004015f0190816103e891906114c0565b506040518060400160405280600181526020017f640000000000000000000000000000000000000000000000000000000000000081525081600401600401908161043291906114c0565b506021816009015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060228160090160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602381600a015f015f0181905550602481600a016003015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602581600e0181905550600360045f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2060010160016101000a81548160ff021916908360ff1602179055506105356005866110df565b6105406005856110df565b8460075f8481526020019081526020015f205f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600884908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600885908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550602960095f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f0181905550610715600a5f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20866110df565b61075b600b5f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20846110df565b600c5f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603367ffffffffffffffff168152602001603467ffffffffffffffff168152602001603581526020016036815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060408201518160010155606082015181600201555050600c5f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603767ffffffffffffffff168152602001603867ffffffffffffffff16815260200160398152602001603a815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550604082015181600101556060820151816002015550506002600d5f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506003600e5f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506040518060400160405280600167ffffffffffffffff168152602001600267ffffffffffffffff16815250600f5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280603d67ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff1681525060105f600167ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555090505060405180604001604052805f67ffffffffffffffff168152602001600167ffffffffffffffff1681525060115f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060e00160405280604767ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff168152602001604867ffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff16815260200160498152602001604a81525060125f5f67ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060608201518160010160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506080820151816002015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060a0820151816003015560c082015181600401559050506040518060400160405280600467ffffffffffffffff168152602001600567ffffffffffffffff1681525060135f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280605167ffffffffffffffff168152602001605267ffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff1681525060145f600467ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055509050505050505050565b815f0181908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550815f0180549050826001015f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055505050565b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6111bb82611192565b9050919050565b6111cb816111b1565b81146111d5575f5ffd5b50565b5f813590506111e6816111c2565b92915050565b5f819050919050565b6111fe816111ec565b8114611208575f5ffd5b50565b5f81359050611219816111f5565b92915050565b5f5f5f5f608085870312156112375761123661118e565b5b5f611244878288016111d8565b9450506020611255878288016111d8565b9350506040611266878288016111d8565b92505060606112778782880161120b565b91505092959194509250565b5f81519050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f60028204905060018216806112fe57607f821691505b602082108103611311576113106112ba565b5b50919050565b5f819050815f5260205f209050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f600883026113737fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82611338565b61137d8683611338565b95508019841693508086168417925050509392505050565b5f819050919050565b5f819050919050565b5f6113c16113bc6113b784611395565b61139e565b611395565b9050919050565b5f819050919050565b6113da836113a7565b6113ee6113e6826113c8565b848454611344565b825550505050565b5f5f905090565b6114056113f6565b6114108184846113d1565b505050565b5b81811015611433576114285f826113fd565b600181019050611416565b5050565b601f8211156114785761144981611317565b61145284611329565b81016020851015611461578190505b61147561146d85611329565b830182611415565b50505b505050565b5f82821c905092915050565b5f6114985f198460080261147d565b1980831691505092915050565b5f6114b08383611489565b9150826002028217905092915050565b6114c982611283565b67ffffffffffffffff8111156114e2576114e161128d565b5b6114ec82546112e7565b6114f7828285611437565b5f60209050601f831160018114611528575f8415611516578287015190505b61152085826114a5565b865550611587565b601f19841661153686611317565b5f5b8281101561155d57848901518255600182019150602085019450602081019050611538565b8683101561157a5784890151611576601f891682611489565b8355505b6001600288020188555050505b50505050505056fe61206d6f6e696b6572206c6f6e6720656e6f75676820746f207370696c6c2070617374206f6e652073746f7261676520776f7264a2646970667358221220be5dd9b21d97abe0f8e1b526f2bcc050b141fa92e35ab20b3b11b5b3a3756d4264736f6c634300081e0033 diff --git a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol index 16178f9852..0340f0a02b 100644 --- a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol +++ b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol @@ -10,6 +10,8 @@ contract StakingStorageHarness is StakingStorage { lastValidators.push(ValidatorPower({operator: op, power: 30})); lastValidators.push(ValidatorPower({operator: other, power: 20})); lastTotalPower = 50; + epochValidators[7].push(EpochValidator({operator: other, power: 21, consensusPubkey: pubkey})); + nextSnapshotEpoch = 8; Validator storage v = validators[op]; v.consensusPubkey = pubkey; diff --git a/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json b/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json index 8615ae68fe..e73adb0f33 100644 --- a/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json +++ b/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json @@ -1,15 +1,15 @@ { "storage": [ { - "astId": 426, + "astId": 449, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "lastValidators", "offset": 0, "slot": "0", - "type": "t_array(t_struct(ValidatorPower)372_storage)dyn_storage" + "type": "t_array(t_struct(ValidatorPower)387_storage)dyn_storage" }, { - "astId": 428, + "astId": 451, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "lastTotalPower", "offset": 0, @@ -17,155 +17,171 @@ "type": "t_uint256" }, { - "astId": 433, + "astId": 458, "contract": "giga-storage/StakingStorage.sol:StakingStorage", - "label": "validators", + "label": "epochValidators", "offset": 0, "slot": "2", - "type": "t_mapping(t_address,t_struct(Validator)366_storage)" + "type": "t_mapping(t_uint64,t_array(t_struct(EpochValidator)395_storage)dyn_storage)" }, { - "astId": 436, + "astId": 460, "contract": "giga-storage/StakingStorage.sol:StakingStorage", - "label": "validatorSet", + "label": "nextSnapshotEpoch", "offset": 0, "slot": "3", - "type": "t_struct(AddressSet)526_storage" + "type": "t_uint64" }, { - "astId": 440, + "astId": 465, "contract": "giga-storage/StakingStorage.sol:StakingStorage", - "label": "validatorsByConsensusPubkey", + "label": "validators", + "offset": 0, + "slot": "4", + "type": "t_mapping(t_address,t_struct(Validator)381_storage)" + }, + { + "astId": 468, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "validatorSet", "offset": 0, "slot": "5", + "type": "t_struct(AddressSet)558_storage" + }, + { + "astId": 472, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "validatorsByConsensusPubkey", + "offset": 0, + "slot": "7", "type": "t_mapping(t_bytes32,t_address)" }, { - "astId": 443, + "astId": 475, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorsByPower", "offset": 0, - "slot": "6", + "slot": "8", "type": "t_array(t_address)dyn_storage" }, { - "astId": 450, + "astId": 482, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegations", "offset": 0, - "slot": "7", - "type": "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)375_storage))" + "slot": "9", + "type": "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)398_storage))" }, { - "astId": 455, + "astId": 487, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegationsByDelegator", "offset": 0, - "slot": "8", - "type": "t_mapping(t_address,t_struct(AddressSet)526_storage)" + "slot": "10", + "type": "t_mapping(t_address,t_struct(AddressSet)558_storage)" }, { - "astId": 460, + "astId": 492, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegationsByValidator", "offset": 0, - "slot": "9", - "type": "t_mapping(t_address,t_struct(AddressSet)526_storage)" + "slot": "11", + "type": "t_mapping(t_address,t_struct(AddressSet)558_storage)" }, { - "astId": 468, + "astId": 500, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingDelegations", "offset": 0, - "slot": "10", - "type": "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage))" + "slot": "12", + "type": "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)407_storage)dyn_storage))" }, { - "astId": 476, + "astId": 508, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationEntryCounts", "offset": 0, - "slot": "11", + "slot": "13", "type": "t_mapping(t_address,t_mapping(t_address,t_mapping(t_address,t_uint256)))" }, { - "astId": 482, + "astId": 514, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationsByValDst", "offset": 0, - "slot": "12", + "slot": "14", "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))" }, { - "astId": 485, + "astId": 517, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingQueueBounds", "offset": 0, - "slot": "13", - "type": "t_struct(QueueBounds)422_storage" + "slot": "15", + "type": "t_struct(QueueBounds)445_storage" }, { - "astId": 490, + "astId": 522, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingQueue", "offset": 0, - "slot": "14", - "type": "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)392_storage)" + "slot": "16", + "type": "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)415_storage)" }, { - "astId": 493, + "astId": 525, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationQueueBounds", "offset": 0, - "slot": "15", - "type": "t_struct(QueueBounds)422_storage" + "slot": "17", + "type": "t_struct(QueueBounds)445_storage" }, { - "astId": 498, + "astId": 530, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationQueue", "offset": 0, - "slot": "16", - "type": "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)408_storage)" + "slot": "18", + "type": "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)431_storage)" }, { - "astId": 501, + "astId": 533, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorQueueBounds", "offset": 0, - "slot": "17", - "type": "t_struct(QueueBounds)422_storage" + "slot": "19", + "type": "t_struct(QueueBounds)445_storage" }, { - "astId": 506, + "astId": 538, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorQueue", "offset": 0, - "slot": "18", - "type": "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)416_storage)" + "slot": "20", + "type": "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)439_storage)" }, { - "astId": 509, + "astId": 541, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "migrating", "offset": 0, - "slot": "19", + "slot": "21", "type": "t_bool" }, { - "astId": 511, + "astId": 543, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "migrationCursor", "offset": 0, - "slot": "20", + "slot": "22", "type": "t_bytes_storage" }, { - "astId": 514, + "astId": 546, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "migrationFailures", "offset": 0, - "slot": "21", + "slot": "23", "type": "t_array(t_bytes_storage)dyn_storage" } ], @@ -187,14 +203,20 @@ "label": "bytes[]", "numberOfBytes": "32" }, - "t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage": { - "base": "t_struct(UnbondingDelegationEntry)384_storage", + "t_array(t_struct(EpochValidator)395_storage)dyn_storage": { + "base": "t_struct(EpochValidator)395_storage", + "encoding": "dynamic_array", + "label": "struct StakingStorage.EpochValidator[]", + "numberOfBytes": "32" + }, + "t_array(t_struct(UnbondingDelegationEntry)407_storage)dyn_storage": { + "base": "t_struct(UnbondingDelegationEntry)407_storage", "encoding": "dynamic_array", "label": "struct StakingStorage.UnbondingDelegationEntry[]", "numberOfBytes": "32" }, - "t_array(t_struct(ValidatorPower)372_storage)dyn_storage": { - "base": "t_struct(ValidatorPower)372_storage", + "t_array(t_struct(ValidatorPower)387_storage)dyn_storage": { + "base": "t_struct(ValidatorPower)387_storage", "encoding": "dynamic_array", "label": "struct StakingStorage.ValidatorPower[]", "numberOfBytes": "32" @@ -214,19 +236,19 @@ "label": "bytes", "numberOfBytes": "32" }, - "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage)": { + "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)407_storage)dyn_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct StakingStorage.UnbondingDelegationEntry[])", "numberOfBytes": "32", - "value": "t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage" + "value": "t_array(t_struct(UnbondingDelegationEntry)407_storage)dyn_storage" }, - "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage))": { + "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)407_storage)dyn_storage))": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => mapping(address => struct StakingStorage.UnbondingDelegationEntry[]))", "numberOfBytes": "32", - "value": "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage)" + "value": "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)407_storage)dyn_storage)" }, "t_mapping(t_address,t_mapping(t_address,t_mapping(t_address,t_uint256)))": { "encoding": "mapping", @@ -235,12 +257,12 @@ "numberOfBytes": "32", "value": "t_mapping(t_address,t_mapping(t_address,t_uint256))" }, - "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)375_storage))": { + "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)398_storage))": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => mapping(address => struct StakingStorage.Delegation))", "numberOfBytes": "32", - "value": "t_mapping(t_address,t_struct(Delegation)375_storage)" + "value": "t_mapping(t_address,t_struct(Delegation)398_storage)" }, "t_mapping(t_address,t_mapping(t_address,t_uint256))": { "encoding": "mapping", @@ -249,26 +271,26 @@ "numberOfBytes": "32", "value": "t_mapping(t_address,t_uint256)" }, - "t_mapping(t_address,t_struct(AddressSet)526_storage)": { + "t_mapping(t_address,t_struct(AddressSet)558_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct AddressSet)", "numberOfBytes": "32", - "value": "t_struct(AddressSet)526_storage" + "value": "t_struct(AddressSet)558_storage" }, - "t_mapping(t_address,t_struct(Delegation)375_storage)": { + "t_mapping(t_address,t_struct(Delegation)398_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct StakingStorage.Delegation)", "numberOfBytes": "32", - "value": "t_struct(Delegation)375_storage" + "value": "t_struct(Delegation)398_storage" }, - "t_mapping(t_address,t_struct(Validator)366_storage)": { + "t_mapping(t_address,t_struct(Validator)381_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct StakingStorage.Validator)", "numberOfBytes": "32", - "value": "t_struct(Validator)366_storage" + "value": "t_struct(Validator)381_storage" }, "t_mapping(t_address,t_uint256)": { "encoding": "mapping", @@ -284,47 +306,54 @@ "numberOfBytes": "32", "value": "t_address" }, - "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)408_storage)": { + "t_mapping(t_uint64,t_array(t_struct(EpochValidator)395_storage)dyn_storage)": { + "encoding": "mapping", + "key": "t_uint64", + "label": "mapping(uint64 => struct StakingStorage.EpochValidator[])", + "numberOfBytes": "32", + "value": "t_array(t_struct(EpochValidator)395_storage)dyn_storage" + }, + "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)431_storage)": { "encoding": "mapping", "key": "t_uint64", "label": "mapping(uint64 => struct StakingStorage.RedelegationQueueEntry)", "numberOfBytes": "32", - "value": "t_struct(RedelegationQueueEntry)408_storage" + "value": "t_struct(RedelegationQueueEntry)431_storage" }, - "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)392_storage)": { + "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)415_storage)": { "encoding": "mapping", "key": "t_uint64", "label": "mapping(uint64 => struct StakingStorage.UnbondingQueueEntry)", "numberOfBytes": "32", - "value": "t_struct(UnbondingQueueEntry)392_storage" + "value": "t_struct(UnbondingQueueEntry)415_storage" }, - "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)416_storage)": { + "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)439_storage)": { "encoding": "mapping", "key": "t_uint64", "label": "mapping(uint64 => struct StakingStorage.ValidatorQueueEntry)", "numberOfBytes": "32", - "value": "t_struct(ValidatorQueueEntry)416_storage" + "value": "t_struct(ValidatorQueueEntry)439_storage" }, "t_string_storage": { "encoding": "bytes", "label": "string", "numberOfBytes": "32" }, - "t_struct(AddressSet)526_storage": { + "t_struct(AddressSet)558_storage": { "encoding": "inplace", "label": "struct AddressSet", "members": [ { - "astId": 521, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 553, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "values", "offset": 0, "slot": "0", "type": "t_array(t_address)dyn_storage" }, { - "astId": 525, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 557, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "positions", "offset": 0, "slot": "1", @@ -333,21 +362,21 @@ ], "numberOfBytes": "64" }, - "t_struct(Commission)343_storage": { + "t_struct(Commission)358_storage": { "encoding": "inplace", "label": "struct StakingStorage.Commission", "members": [ { - "astId": 340, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 355, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "commissionRates", "offset": 0, "slot": "0", - "type": "t_struct(CommissionRates)337_storage" + "type": "t_struct(CommissionRates)352_storage" }, { - "astId": 342, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 357, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "updateTime", "offset": 0, "slot": "3", @@ -356,29 +385,29 @@ ], "numberOfBytes": "128" }, - "t_struct(CommissionRates)337_storage": { + "t_struct(CommissionRates)352_storage": { "encoding": "inplace", "label": "struct StakingStorage.CommissionRates", "members": [ { - "astId": 332, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 347, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "rate", "offset": 0, "slot": "0", "type": "t_uint256" }, { - "astId": 334, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 349, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "maxRate", "offset": 0, "slot": "1", "type": "t_uint256" }, { - "astId": 336, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 351, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "maxChangeRate", "offset": 0, "slot": "2", @@ -387,13 +416,13 @@ ], "numberOfBytes": "96" }, - "t_struct(Delegation)375_storage": { + "t_struct(Delegation)398_storage": { "encoding": "inplace", "label": "struct StakingStorage.Delegation", "members": [ { - "astId": 374, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 397, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "shares", "offset": 0, "slot": "0", @@ -402,45 +431,45 @@ ], "numberOfBytes": "32" }, - "t_struct(Description)330_storage": { + "t_struct(Description)345_storage": { "encoding": "inplace", "label": "struct StakingStorage.Description", "members": [ { - "astId": 321, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 336, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "moniker", "offset": 0, "slot": "0", "type": "t_string_storage" }, { - "astId": 323, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 338, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "identity", "offset": 0, "slot": "1", "type": "t_string_storage" }, { - "astId": 325, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 340, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "website", "offset": 0, "slot": "2", "type": "t_string_storage" }, { - "astId": 327, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 342, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "securityContact", "offset": 0, "slot": "3", "type": "t_string_storage" }, { - "astId": 329, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 344, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "details", "offset": 0, "slot": "4", @@ -449,21 +478,52 @@ ], "numberOfBytes": "160" }, - "t_struct(QueueBounds)422_storage": { + "t_struct(EpochValidator)395_storage": { + "encoding": "inplace", + "label": "struct StakingStorage.EpochValidator", + "members": [ + { + "astId": 390, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", + "label": "operator", + "offset": 0, + "slot": "0", + "type": "t_address" + }, + { + "astId": 392, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", + "label": "power", + "offset": 20, + "slot": "0", + "type": "t_uint64" + }, + { + "astId": 394, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", + "label": "consensusPubkey", + "offset": 0, + "slot": "1", + "type": "t_bytes32" + } + ], + "numberOfBytes": "64" + }, + "t_struct(QueueBounds)445_storage": { "encoding": "inplace", "label": "struct StakingStorage.QueueBounds", "members": [ { - "astId": 419, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 442, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "head", "offset": 0, "slot": "0", "type": "t_uint64" }, { - "astId": 421, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 444, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "tail", "offset": 8, "slot": "0", @@ -472,61 +532,61 @@ ], "numberOfBytes": "32" }, - "t_struct(RedelegationQueueEntry)408_storage": { + "t_struct(RedelegationQueueEntry)431_storage": { "encoding": "inplace", "label": "struct StakingStorage.RedelegationQueueEntry", "members": [ { - "astId": 395, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 418, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 0, "slot": "0", "type": "t_uint64" }, { - "astId": 397, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 420, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "delegator", "offset": 8, "slot": "0", "type": "t_address" }, { - "astId": 399, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 422, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "creationHeight", "offset": 0, "slot": "1", "type": "t_uint64" }, { - "astId": 401, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 424, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "srcValidator", "offset": 8, "slot": "1", "type": "t_address" }, { - "astId": 403, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 426, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "dstValidator", "offset": 0, "slot": "2", "type": "t_address" }, { - "astId": 405, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 428, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "initialBalance", "offset": 0, "slot": "3", "type": "t_uint256" }, { - "astId": 407, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 430, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "sharesDst", "offset": 0, "slot": "4", @@ -535,37 +595,37 @@ ], "numberOfBytes": "160" }, - "t_struct(UnbondingDelegationEntry)384_storage": { + "t_struct(UnbondingDelegationEntry)407_storage": { "encoding": "inplace", "label": "struct StakingStorage.UnbondingDelegationEntry", "members": [ { - "astId": 377, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 400, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "creationHeight", "offset": 0, "slot": "0", "type": "t_uint64" }, { - "astId": 379, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 402, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 8, "slot": "0", "type": "t_uint64" }, { - "astId": 381, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 404, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "initialBalance", "offset": 0, "slot": "1", "type": "t_uint256" }, { - "astId": 383, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 406, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "balance", "offset": 0, "slot": "2", @@ -574,29 +634,29 @@ ], "numberOfBytes": "96" }, - "t_struct(UnbondingQueueEntry)392_storage": { + "t_struct(UnbondingQueueEntry)415_storage": { "encoding": "inplace", "label": "struct StakingStorage.UnbondingQueueEntry", "members": [ { - "astId": 387, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 410, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 0, "slot": "0", "type": "t_uint64" }, { - "astId": 389, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 412, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "delegator", "offset": 8, "slot": "0", "type": "t_address" }, { - "astId": 391, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 414, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "validator", "offset": 0, "slot": "1", @@ -605,85 +665,85 @@ ], "numberOfBytes": "64" }, - "t_struct(Validator)366_storage": { + "t_struct(Validator)381_storage": { "encoding": "inplace", "label": "struct StakingStorage.Validator", "members": [ { - "astId": 345, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 360, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "consensusPubkey", "offset": 0, "slot": "0", "type": "t_bytes32" }, { - "astId": 347, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 362, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "jailed", "offset": 0, "slot": "1", "type": "t_bool" }, { - "astId": 349, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 364, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "status", "offset": 1, "slot": "1", "type": "t_uint8" }, { - "astId": 351, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 366, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "tokens", "offset": 0, "slot": "2", "type": "t_uint256" }, { - "astId": 353, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 368, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "delegatorShares", "offset": 0, "slot": "3", "type": "t_uint256" }, { - "astId": 356, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 371, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "description", "offset": 0, "slot": "4", - "type": "t_struct(Description)330_storage" + "type": "t_struct(Description)345_storage" }, { - "astId": 358, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 373, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingHeight", "offset": 0, "slot": "9", "type": "t_uint64" }, { - "astId": 360, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 375, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingTime", "offset": 8, "slot": "9", "type": "t_uint64" }, { - "astId": 363, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 378, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "commission", "offset": 0, "slot": "10", - "type": "t_struct(Commission)343_storage" + "type": "t_struct(Commission)358_storage" }, { - "astId": 365, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 380, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "minSelfDelegation", "offset": 0, "slot": "14", @@ -692,21 +752,21 @@ ], "numberOfBytes": "480" }, - "t_struct(ValidatorPower)372_storage": { + "t_struct(ValidatorPower)387_storage": { "encoding": "inplace", "label": "struct StakingStorage.ValidatorPower", "members": [ { - "astId": 369, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 384, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "operator", "offset": 0, "slot": "0", "type": "t_address" }, { - "astId": 371, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 386, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "power", "offset": 20, "slot": "0", @@ -715,29 +775,29 @@ ], "numberOfBytes": "32" }, - "t_struct(ValidatorQueueEntry)416_storage": { + "t_struct(ValidatorQueueEntry)439_storage": { "encoding": "inplace", "label": "struct StakingStorage.ValidatorQueueEntry", "members": [ { - "astId": 411, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 434, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 0, "slot": "0", "type": "t_uint64" }, { - "astId": 413, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 436, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingHeight", "offset": 8, "slot": "0", "type": "t_uint64" }, { - "astId": 415, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 438, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "operator", "offset": 0, "slot": "1", diff --git a/giga/evmonly/types.go b/giga/evmonly/types.go index bc9b14080f..481ce1ea5c 100644 --- a/giga/evmonly/types.go +++ b/giga/evmonly/types.go @@ -87,6 +87,9 @@ type BlockContext struct { ParentHash common.Hash BlockHash common.Hash PrevRandao common.Hash + // ClosingEpoch is the consensus epoch this block is the last block of, if + // it is one. + ClosingEpoch utils.Option[uint64] } // BlockResult is the executor output consumed by the new runtime boundary. diff --git a/sei-tendermint/internal/autobahn/epoch/registry.go b/sei-tendermint/internal/autobahn/epoch/registry.go index e349f43738..a4bdfa449f 100644 --- a/sei-tendermint/internal/autobahn/epoch/registry.go +++ b/sei-tendermint/internal/autobahn/epoch/registry.go @@ -88,14 +88,16 @@ func (r *Registry) IndexForRoad(road types.RoadIndex) types.EpochIndex { // ClosingEpoch returns the epoch that road ends, if road is that epoch's last // road. Otherwise None. func (r *Registry) ClosingEpoch(road types.RoadIndex) utils.Option[types.EpochIndex] { - if road < r.firstRoad { - return utils.None[types.EpochIndex]() - } - idx := r.IndexForRoad(road) - if road != r.LastRoad(idx) { + return ClosingEpoch(r.firstRoad, road) +} + +// ClosingEpoch returns the epoch that road ends, for epochs counted from +// firstRoad, if road is that epoch's last road. Otherwise None. +func ClosingEpoch(firstRoad, road types.RoadIndex) utils.Option[types.EpochIndex] { + if road < firstRoad || (road-firstRoad+1)%epochLength != 0 { return utils.None[types.EpochIndex]() } - return utils.Some(idx) + return utils.Some(types.EpochIndex((road - firstRoad) / epochLength)) } // GenesisTimestamp returns the genesis epoch timestamp. diff --git a/sei-tendermint/internal/autobahn/epoch/registry_test.go b/sei-tendermint/internal/autobahn/epoch/registry_test.go index 3b7b169850..fa88e0e944 100644 --- a/sei-tendermint/internal/autobahn/epoch/registry_test.go +++ b/sei-tendermint/internal/autobahn/epoch/registry_test.go @@ -15,6 +15,16 @@ import ( "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils/scope" ) +func TestClosingEpochIsTheLastRoadOfEachEpoch(t *testing.T) { + for _, first := range []types.RoadIndex{0, 1, 2*epochLength + 7} { + require.Equal(t, utils.None[types.EpochIndex](), ClosingEpoch(first, first)) + require.Equal(t, utils.Some(types.EpochIndex(0)), ClosingEpoch(first, first+epochLength-1)) + require.Equal(t, utils.None[types.EpochIndex](), ClosingEpoch(first, first+epochLength)) + require.Equal(t, utils.Some(types.EpochIndex(2)), ClosingEpoch(first, first+3*epochLength-1)) + } + require.Equal(t, utils.None[types.EpochIndex](), ClosingEpoch(epochLength, epochLength-1), "a road before the first") +} + func TestRegistryGenesisAndLookups(t *testing.T) { for _, first := range []types.RoadIndex{0, 2*epochLength + 7} { t.Run(fmt.Sprint(first), func(t *testing.T) { diff --git a/sei-tendermint/internal/autobahn/execution/execution.go b/sei-tendermint/internal/autobahn/execution/execution.go index 1175a2e7de..8489a028d8 100644 --- a/sei-tendermint/internal/autobahn/execution/execution.go +++ b/sei-tendermint/internal/autobahn/execution/execution.go @@ -11,6 +11,7 @@ import ( gigametrics "github.com/sei-protocol/sei-chain/giga/metrics" "github.com/sei-protocol/sei-chain/sei-tendermint/autobahn/blockstore" atypes "github.com/sei-protocol/sei-chain/sei-tendermint/autobahn/types" + "github.com/sei-protocol/sei-chain/sei-tendermint/internal/autobahn/epoch" "github.com/sei-protocol/sei-chain/sei-tendermint/internal/autobahn/execution/metrics" "github.com/sei-protocol/sei-chain/sei-tendermint/internal/proxy" "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils" @@ -154,6 +155,8 @@ func (e *Executor) executeBlock(ctx context.Context, b *atypes.SuperBlock) error // WARNING: the reward distribution has corner cases where it forgets the proposer, // because reward is distributed with a delay. This is not our problem here though. ProposerAddress: proposerAddress, + // Epochs count from the genesis initial height, as the epoch registry's do. + ClosingEpoch: epoch.ClosingEpoch(atypes.RoadIndex(e.cfg.GenDoc.InitialHeight), b.Height), // nolint:gosec // verified to be positive. }, }) if err != nil { diff --git a/sei-tendermint/internal/evmonlyapp/app.go b/sei-tendermint/internal/evmonlyapp/app.go index 0b4a038f3a..c4f19ec7c8 100644 --- a/sei-tendermint/internal/evmonlyapp/app.go +++ b/sei-tendermint/internal/evmonlyapp/app.go @@ -113,7 +113,8 @@ type evmOnlyApplication struct { execution gigaconfig.ExecutionConfig minGasPrice *big.Int storage *bootstrap.GigaStorageManager - validators []proxy.ValidatorUpdate + // validators are the configured validators, served until staking bonds a set. + validators []proxy.ValidatorUpdate // customPrecompiles are the native contracts every executor runs. customPrecompiles utils.Option[precompiles.Registry] // alloc, when set, funds the chain at its initial height, and every @@ -412,10 +413,6 @@ func (a *evmOnlyApplication) EvmGasLimit() uint64 { panic("unreachable") } -func (a *evmOnlyApplication) GetValidators() []proxy.ValidatorUpdate { - return slices.Clone(a.validators) -} - func (a *evmOnlyApplication) CheckTx(_ context.Context, req *proxy.RequestCheckTxV2) *proxy.ResponseCheckTxV2 { // TODO(evmonly-production): close the gap between admission and block validity // before accepting arbitrary traffic; this test app assumes executable load-test transactions. @@ -975,8 +972,12 @@ func (a *evmOnlyApplication) finalizeBlock(ctx context.Context, req *proxy.Reque defer a.finalizePhases.Reset() a.finalizePhases.SetPhase(finalizePhaseTakeSenders) senders := a.takeSenders(req.Txs) + block := a.blockContext(number, timestamp, parent.gasLimit, parent.blockHash, blockHash) + if epoch, ok := req.Header.ClosingEpoch.Get(); ok { + block.ClosingEpoch = utils.Some(uint64(epoch)) + } result, err := a.executeBlockPipelined(ctx, executor, evmonly.BlockRequest{ - Context: a.blockContext(number, timestamp, parent.gasLimit, parent.blockHash, blockHash), + Context: block, Txs: req.Txs, Senders: senders, }) diff --git a/sei-tendermint/internal/evmonlyapp/app_test.go b/sei-tendermint/internal/evmonlyapp/app_test.go index fc79fca4ec..63adb4ba3c 100644 --- a/sei-tendermint/internal/evmonlyapp/app_test.go +++ b/sei-tendermint/internal/evmonlyapp/app_test.go @@ -23,6 +23,7 @@ import ( gigaconfig "github.com/sei-protocol/sei-chain/giga/config" "github.com/sei-protocol/sei-chain/giga/evmonly" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/staking" sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" "github.com/sei-protocol/sei-chain/sei-db/bootstrap" "github.com/sei-protocol/sei-chain/sei-db/common/keys" @@ -30,6 +31,7 @@ import ( seidbconfig "github.com/sei-protocol/sei-chain/sei-db/config" "github.com/sei-protocol/sei-chain/sei-db/ledger_db/receipt" gigatypes "github.com/sei-protocol/sei-chain/sei-db/state_db/giga/types" + "github.com/sei-protocol/sei-chain/sei-tendermint/autobahn/types" "github.com/sei-protocol/sei-chain/sei-tendermint/internal/proxy" "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils" "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils/require" @@ -91,6 +93,33 @@ func evmOnlyTestEpochBlock(height int64, state proxy.EpochState) *proxy.RequestF return req } +// evmOnlyTestClosingBlock returns an empty block at height that closes epoch. +func evmOnlyTestClosingBlock(height int64, epoch types.EpochIndex) *proxy.RequestFinalizeBlock { + req := evmOnlyTestBlock(height) + req.Header.ClosingEpoch = utils.Some(epoch) + return req +} + +// closingEpochRecorder is staking, with each EndBlock only recording the epoch +// its block closes. +type closingEpochRecorder struct { + staking.Precompile + closed *[]utils.Option[uint64] +} + +func (r closingEpochRecorder) EndBlock(block precompiles.BlockContext, _ precompiles.State) ([]error, error) { + *r.closed = append(*r.closed, block.ClosingEpoch) + return nil, nil +} + +func TestEVMOnlyApplicationTellsEndBlockersWhichEpochABlockCloses(t *testing.T) { + var closed []utils.Option[uint64] + app := newStakingEVMOnlyTestApp(t, []proxy.ValidatorUpdate{{Power: 1}}, closingEpochRecorder{closed: &closed}) + finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestBlock(1)) + finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestClosingBlock(2, 7)) + require.Equal(t, []utils.Option[uint64]{utils.None[uint64](), utils.Some[uint64](7)}, closed) +} + func finalizeAndCommitEVMOnlyTestBlock(t *testing.T, app proxy.EVMApplication, req *proxy.RequestFinalizeBlock) []byte { t.Helper() response, err := app.FinalizeBlock(t.Context(), req) diff --git a/sei-tendermint/internal/evmonlyapp/validators.go b/sei-tendermint/internal/evmonlyapp/validators.go new file mode 100644 index 0000000000..52eda7b097 --- /dev/null +++ b/sei-tendermint/internal/evmonlyapp/validators.go @@ -0,0 +1,71 @@ +package evmonlyapp + +import ( + "fmt" + "slices" + + "github.com/sei-protocol/sei-chain/giga/evmonly" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/staking" + "github.com/sei-protocol/sei-chain/sei-tendermint/autobahn/types" + "github.com/sei-protocol/sei-chain/sei-tendermint/internal/proxy" + "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils" +) + +// GetValidators returns staking's bonded set after the latest finalized block, +// and the configured validators until staking has bonded one. It returns none +// once a block is known to have failed to commit or the stored set does not add +// up, and autobahn cannot stage an empty committee. +func (a *evmOnlyApplication) GetValidators() []proxy.ValidatorUpdate { + bonded, err := a.bondedValidators() + if err != nil { + logger.Error("EVM-only bonded validator set is unavailable", "err", err) + return nil + } + if len(bonded) == 0 { + return slices.Clone(a.validators) + } + return bonded +} + +// bondedValidators returns staking's bonded set after the latest finalized +// block, without waiting for that block's commit. +func (a *evmOnlyApplication) bondedValidators() ([]proxy.ValidatorUpdate, error) { + var bonded []staking.BondedValidator + read := func(state precompiles.State) (err error) { + bonded, err = staking.BondedValidators(state) + return err + } + // Autobahn calls this before every block, so it must not hold execution + // behind the previous block's commit. + if executor, ok := a.settler.Load().Get(); ok { + if err := executor.ReadLatest(read); err != nil { + return nil, err + } + } else { + view := a.storage.StateDB().OpenView() + defer view.Close() + if err := read(evmonly.ReadOnlyState(view)); err != nil { + return nil, err + } + } + updates := make([]proxy.ValidatorUpdate, len(bonded)) + for i, v := range bonded { + var err error + if updates[i], err = validatorUpdate(v); err != nil { + return nil, err + } + } + return updates, nil +} + +// validatorUpdate returns bonded validator v as consensus reads it. +func validatorUpdate(v staking.BondedValidator) (proxy.ValidatorUpdate, error) { + power, ok := utils.SafeCast[int64](v.Power) + if !ok { + return proxy.ValidatorUpdate{}, fmt.Errorf("validator %s power %d does not fit int64", v.Operator, v.Power) + } + // PublicKeyFromBytes checks only the length, and a common.Hash is always 32 bytes. + key := utils.OrPanic1(types.PublicKeyFromBytes(v.ConsensusPubkey[:])) + return proxy.ValidatorUpdate{PubKey: key, Power: power}, nil +} diff --git a/sei-tendermint/internal/evmonlyapp/validators_test.go b/sei-tendermint/internal/evmonlyapp/validators_test.go new file mode 100644 index 0000000000..76ae5f81ee --- /dev/null +++ b/sei-tendermint/internal/evmonlyapp/validators_test.go @@ -0,0 +1,138 @@ +package evmonlyapp + +import ( + "math/big" + "testing" + + "github.com/ethereum/go-ethereum/common" + + gigaconfig "github.com/sei-protocol/sei-chain/giga/config" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/staking" + seidbconfig "github.com/sei-protocol/sei-chain/sei-db/config" + "github.com/sei-protocol/sei-chain/sei-tendermint/autobahn/types" + "github.com/sei-protocol/sei-chain/sei-tendermint/crypto/ed25519" + "github.com/sei-protocol/sei-chain/sei-tendermint/internal/proxy" + "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils" + "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils/require" +) + +// stakingGenesis is staking with the params and validators it writes at its +// first EndBlock. +type stakingGenesis struct { + staking.Precompile + validators []staking.GenesisValidator +} + +func (g stakingGenesis) EndBlock(block precompiles.BlockContext, state precompiles.State) ([]error, error) { + if !staking.HasParams(state) { + if err := staking.SetParams(state, staking.DefaultParams()); err != nil { + return nil, err + } + for _, v := range g.validators { + if err := g.AddGenesisValidator(block, state, v); err != nil { + return nil, err + } + } + } + return g.Precompile.EndBlock(block, state) +} + +// corruptBondedSet stores a bonded set longer than staking allows at every +// EndBlock. +type corruptBondedSet struct { + staking.Precompile +} + +func (corruptBondedSet) EndBlock(_ precompiles.BlockContext, state precompiles.State) ([]error, error) { + // Slot 0 of StakingStorage holds the bonded set's length. + state.SetState(staking.Address, common.Hash{}, common.BigToHash(big.NewInt(101))) + return nil, nil +} + +// newStakingEVMOnlyTestApp returns an initialized application serving the +// configured validators and running staking as contract. +func newStakingEVMOnlyTestApp(t *testing.T, configured []proxy.ValidatorUpdate, contract precompiles.Contract) proxy.EVMApplication { + t.Helper() + storageConfig, err := seidbconfig.AutobahnStorageConfig(t.TempDir()) + require.NoError(t, err) + storage := openEVMOnlyTestStorage(t, storageConfig) + registry := precompiles.NewStaticRegistry(map[common.Address]precompiles.Contract{staking.Address: contract}, staking.Address) + app, err := NewEVMOnlyApplication( + evmOnlyTestChainID, + configured, + storage, + gigaconfig.DefaultConfig.Execution, + utils.Some[precompiles.Registry](registry), + utils.None[GenesisAlloc](), + utils.None[string](), + ) + require.NoError(t, err) + t.Cleanup(func() { closeEVMOnlyTestApp(t, app, storage) }) + _, err = app.InitChain(evmOnlyTestInitChain()) + require.NoError(t, err) + return app +} + +// testSei returns n SEI in wei. +func testSei(n int64) *big.Int { + return new(big.Int).Mul(big.NewInt(n), big.NewInt(1_000_000_000_000_000_000)) +} + +func testGenesisValidator(operator common.Address, key ed25519.PublicKey, self int64) staking.GenesisValidator { + return staking.GenesisValidator{ + Operator: operator, + ConsensusPubkey: common.BytesToHash(key.Bytes()), + SelfDelegation: testSei(self), + MinSelfDelegation: testSei(1), + } +} + +func TestEVMOnlyApplicationServesStakingsBondedSet(t *testing.T) { + configured := []proxy.ValidatorUpdate{{PubKey: autobahnKey(ed25519.TestSecretKey([]byte("configured")).Public()), Power: 1}} + key1 := ed25519.TestSecretKey([]byte("validator-1")).Public() + key2 := ed25519.TestSecretKey([]byte("validator-2")).Public() + app := newStakingEVMOnlyTestApp(t, configured, stakingGenesis{validators: []staking.GenesisValidator{ + testGenesisValidator(common.HexToAddress("0xa2"), key2, 20), + testGenesisValidator(common.HexToAddress("0xa1"), key1, 30), + }}) + require.Equal(t, configured, app.GetValidators(), "the configured validators serve until staking bonds a set") + + finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestBlock(1)) + require.Equal(t, []proxy.ValidatorUpdate{ + {PubKey: autobahnKey(key1), Power: 30}, + {PubKey: autobahnKey(key2), Power: 20}, + }, app.GetValidators()) +} + +func TestEVMOnlyApplicationServesNoValidatorsAfterAFailedCommit(t *testing.T) { + storageConfig, err := seidbconfig.AutobahnStorageConfig(t.TempDir()) + require.NoError(t, err) + storage := openEVMOnlyTestStorage(t, storageConfig) + t.Cleanup(func() { require.NoError(t, storage.Close()) }) + configured := []proxy.ValidatorUpdate{{PubKey: autobahnKey(ed25519.TestSecretKey([]byte("configured")).Public()), Power: 1}} + app, err := NewEVMOnlyApplication(evmOnlyTestChainID, configured, storage, gigaconfig.DefaultConfig.Execution, utils.None[precompiles.Registry](), utils.None[GenesisAlloc](), utils.None[string]()) + require.NoError(t, err) + _, err = app.InitChain(evmOnlyTestInitChain()) + require.NoError(t, err) + settler, ok := app.(*evmOnlyApplication) + require.True(t, ok) + installUnwritableEVMExecutor(settler) + require.Equal(t, configured, app.GetValidators()) + + raw, _ := signedEVMOnlyTestTx(t, evmOnlyTestChainID, 0) + finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestBlock(1, raw)) + require.Error(t, settler.AwaitCommits()) + require.Empty(t, app.GetValidators(), "block 1 failed to commit, so the committed state predates it") +} + +func TestEVMOnlyApplicationServesNoValidatorsFromACorruptBondedSet(t *testing.T) { + app := newStakingEVMOnlyTestApp(t, []proxy.ValidatorUpdate{{Power: 1}}, corruptBondedSet{}) + finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestBlock(1)) + require.Empty(t, app.GetValidators()) +} + +// autobahnKey returns key as consensus reads it. +func autobahnKey(key ed25519.PublicKey) types.PublicKey { + return utils.OrPanic1(types.PublicKeyFromBytes(key.Bytes())) +} diff --git a/sei-tendermint/internal/p2p/giga_router_common.go b/sei-tendermint/internal/p2p/giga_router_common.go index f2350566a1..dadbee133f 100644 --- a/sei-tendermint/internal/p2p/giga_router_common.go +++ b/sei-tendermint/internal/p2p/giga_router_common.go @@ -192,11 +192,12 @@ func (r *gigaRouterCommon) runPushAppHashes(ctx context.Context) error { if err != nil { return fmt.Errorf("AppHashBuilder.GetAppHash(%v): %w", n, err) } - // TODO: PushAppHash needs the validator set from right after block n. - // GetValidators() is the app tip, which can be past n. This is exact only - // while the app's validator set never changes, as for the EVM-only and mock - // apps Autobahn runs. Read the next epoch's validator set from app state - // once it keeps one. + // PushAppHash needs the validator set from right after block n, and uses it + // only when n closes an epoch. GetValidators() reads the app tip, which can + // be past n, so the set is block n's only while no later block has changed + // it. The mock app's set never changes; the EVM-only app's can change at + // any block. + // TODO: ask the app for the set as of block n, to drop that bound. weights, err := committeeWeights(r.app.GetValidators()) if err != nil { return err diff --git a/sei-tendermint/internal/proxy/evm_types.go b/sei-tendermint/internal/proxy/evm_types.go index a88054a7ab..fff04f6374 100644 --- a/sei-tendermint/internal/proxy/evm_types.go +++ b/sei-tendermint/internal/proxy/evm_types.go @@ -47,6 +47,8 @@ type Header struct { Height int64 Time time.Time ProposerAddress []byte + // ClosingEpoch is the epoch this block is the last block of, if it is one. + ClosingEpoch utils.Option[types.EpochIndex] } // RequestCheckTxV2 is a transaction submitted for admission.