Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix(state-transitions): verify deposits against contract #2115

Open
wants to merge 37 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 36 commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
f4a7d79
wip: adding UTs to state transition package
abi87 Oct 29, 2024
0f46172
wip: completed simple UT for state transition package
abi87 Oct 29, 2024
22c7717
wip: minimal execution engine stub
abi87 Oct 29, 2024
05cba80
extended asserts
abi87 Oct 29, 2024
443ac1b
added test case
abi87 Oct 29, 2024
10efd5e
nits
abi87 Oct 29, 2024
099716d
tests for helpers in state transition using mock
nidhi-singh02 Oct 30, 2024
151a533
Revert "tests for helpers in state transition using mock"
nidhi-singh02 Oct 30, 2024
9818c7e
tests with only mock for execution engine
nidhi-singh02 Oct 30, 2024
160cc88
removed test for VerifyAndNotifyNewPayload
nidhi-singh02 Oct 30, 2024
6a191d1
validate deposits against deposit store ones
abi87 Oct 30, 2024
64d19e5
cleaned up UTs
abi87 Oct 30, 2024
d94bf97
nits
abi87 Oct 30, 2024
4a9fe1c
nit
abi87 Oct 31, 2024
67f2597
Merge branch 'state-transition-add-UTs' into verify-deposits-against-…
abi87 Oct 31, 2024
e048be4
improved unit tests asserts
abi87 Oct 31, 2024
8bf34db
appease linter
abi87 Oct 31, 2024
d90a95a
fix(state-transition): fix deposit index upon genesis processing (#2116)
abi87 Oct 31, 2024
e17d29c
fixed bad merge
abi87 Oct 31, 2024
7b2bf91
Merge branch 'state-transition-add-UTs' into verify-deposits-against-…
abi87 Oct 31, 2024
6286b20
Merge branch 'main' into state-transition-add-UTs
abi87 Nov 1, 2024
df81bae
Merge branch 'state-transition-add-UTs' into verify-deposits-against-…
abi87 Nov 1, 2024
af8c5e0
fix(build): erigon repo
gummybera Nov 1, 2024
023ebfd
fix(build): bump erigon to recent version
gummybera Nov 1, 2024
d66b298
nits from code review
abi87 Nov 1, 2024
18ba094
Merge branch 'state-transition-add-UTs' into verify-deposits-against-…
abi87 Nov 4, 2024
e47219a
fixed deposit index use + UTs
abi87 Nov 4, 2024
a3cd2d9
replace DeelEqual with Equal method
abi87 Nov 5, 2024
3a0923e
nits
abi87 Nov 5, 2024
712d3fe
Merge branch 'fix-erigon' into verify-deposits-against-contract
abi87 Nov 5, 2024
6b90b87
added logger to state processor
abi87 Nov 5, 2024
83ad2fd
duly incremented build block deposit index
abi87 Nov 5, 2024
69d568b
tmp debugging
abi87 Nov 5, 2024
a7143e8
improved error expressivity
abi87 Nov 5, 2024
6ce250d
Merge branch 'main' into verify-deposits-against-contract
abi87 Nov 8, 2024
0fc3868
Merge branch 'main' into verify-deposits-against-contract
abi87 Nov 19, 2024
187bf67
tmp debugging: silenced deposit pruner
abi87 Nov 19, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions beacond/cmd/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,8 @@ func DefaultComponents() []any {
],
components.ProvideStateProcessor[
*Logger, *BeaconBlock, *BeaconBlockBody, *BeaconBlockHeader,
*BeaconState, *BeaconStateMarshallable, *Deposit, *ExecutionPayload,
*ExecutionPayloadHeader, *KVStore,
*BeaconState, *BeaconStateMarshallable, *Deposit, *DepositStore,
*ExecutionPayload, *ExecutionPayloadHeader, *KVStore,
],
components.ProvideKVStore[*BeaconBlockHeader, *ExecutionPayloadHeader],
components.ProvideStorageBackend[
Expand Down
8 changes: 8 additions & 0 deletions mod/consensus-types/pkg/types/deposit.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,14 @@ func (d *Deposit) GetTree() (*fastssz.Node, error) {
/* -------------------------------------------------------------------------- */
/* Getters and Setters */
/* -------------------------------------------------------------------------- */
// Equals returns true if the Deposit is equal to the other.
func (d *Deposit) Equals(rhs *Deposit) bool {
return d.Pubkey == rhs.Pubkey &&
d.Credentials == rhs.Credentials &&
d.Amount == rhs.Amount &&
d.Signature == rhs.Signature &&
d.Index == rhs.Index
Comment on lines +191 to +195
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Consider using constant-time comparison for sensitive fields.

To prevent potential timing attacks when comparing cryptographic fields, consider using constant-time comparison for Pubkey, Credentials, and Signature.

+import "crypto/subtle"

 func (d *Deposit) Equals(rhs *Deposit) bool {
-	return d.Pubkey == rhs.Pubkey &&
-		d.Credentials == rhs.Credentials &&
-		d.Amount == rhs.Amount &&
-		d.Signature == rhs.Signature &&
+	return subtle.ConstantTimeCompare(d.Pubkey[:], rhs.Pubkey[:]) == 1 &&
+		subtle.ConstantTimeCompare(d.Credentials[:], rhs.Credentials[:]) == 1 &&
+		d.Amount == rhs.Amount &&
+		subtle.ConstantTimeCompare(d.Signature[:], rhs.Signature[:]) == 1 &&
 		d.Index == rhs.Index

Committable suggestion skipped: line range outside the PR's diff.

}
Comment on lines +189 to +196
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Add documentation explaining the equality comparison's role in deposit validation.

The implementation looks good and covers all necessary fields. Consider adding a doc comment explaining how this method helps prevent fraudulent validators by enabling comparison against contract events.

+// Equals returns true if the Deposit is equal to another deposit.
+// This method is crucial for validating deposits against contract events
+// to prevent fraudulent validator creation.
 func (d *Deposit) Equals(rhs *Deposit) bool {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Equals returns true if the Deposit is equal to the other.
func (d *Deposit) Equals(rhs *Deposit) bool {
return d.Pubkey == rhs.Pubkey &&
d.Credentials == rhs.Credentials &&
d.Amount == rhs.Amount &&
d.Signature == rhs.Signature &&
d.Index == rhs.Index
}
// Equals returns true if the Deposit is equal to another deposit.
// This method is crucial for validating deposits against contract events
// to prevent fraudulent validator creation.
func (d *Deposit) Equals(rhs *Deposit) bool {
return d.Pubkey == rhs.Pubkey &&
d.Credentials == rhs.Credentials &&
d.Amount == rhs.Amount &&
d.Signature == rhs.Signature &&
d.Index == rhs.Index
}


// GetAmount returns the deposit amount in gwei.
func (d *Deposit) GetAmount() math.Gwei {
Expand Down
2 changes: 2 additions & 0 deletions mod/node-core/pkg/components/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,8 @@ type (
crypto.BLSSignature,
uint64,
) T
// Equals returns true if the Deposit is equal to the other.
Equals(T) bool
// GetIndex returns the index of the deposit.
GetIndex() math.U64
// GetAmount returns the amount of the deposit.
Expand Down
8 changes: 6 additions & 2 deletions mod/node-core/pkg/components/state_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ type StateProcessorInput[
ExecutionPayloadT, ExecutionPayloadHeaderT, WithdrawalsT,
],
ExecutionPayloadHeaderT ExecutionPayloadHeader[ExecutionPayloadHeaderT],
DepositT Deposit[DepositT, *ForkData, WithdrawalCredentials],
WithdrawalT Withdrawal[WithdrawalT],
WithdrawalsT Withdrawals[WithdrawalT],
] struct {
Expand All @@ -50,7 +51,8 @@ type StateProcessorInput[
PayloadID,
WithdrawalsT,
]
Signer crypto.BLSSigner
DepositStore DepositStore[DepositT]
Signer crypto.BLSSigner
}

// ProvideStateProcessor provides the state processor to the depinject
Expand All @@ -70,6 +72,7 @@ func ProvideStateProcessor[
],
BeaconStateMarshallableT any,
DepositT Deposit[DepositT, *ForkData, WithdrawalCredentials],
DepositStoreT DepositStore[DepositT],
ExecutionPayloadT ExecutionPayload[
ExecutionPayloadT, ExecutionPayloadHeaderT, WithdrawalsT,
],
Expand All @@ -84,7 +87,7 @@ func ProvideStateProcessor[
in StateProcessorInput[
LoggerT,
ExecutionPayloadT, ExecutionPayloadHeaderT,
WithdrawalT, WithdrawalsT,
DepositT, WithdrawalT, WithdrawalsT,
],
) *core.StateProcessor[
BeaconBlockT, BeaconBlockBodyT, BeaconBlockHeaderT,
Expand Down Expand Up @@ -114,6 +117,7 @@ func ProvideStateProcessor[
in.Logger.With("service", "state-processor"),
in.ChainSpec,
in.ExecutionEngine,
in.DepositStore,
in.Signer,
crypto.GetAddressFromPubKey,
Comment on lines +120 to 122
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Consider enhancing logging for deposit verification.

The implementation correctly integrates the deposit store. Given the PR objectives mention improving logging capabilities, consider adding structured logging fields for deposit verification outcomes.

Add logging fields to track deposit verification:

-    in.Logger.With("service", "state-processor"),
+    in.Logger.With(
+        "service", "state-processor",
+        "features", []string{"deposit-verification"},
+    ),

Committable suggestion skipped: line range outside the PR's diff.

)
Expand Down
35 changes: 21 additions & 14 deletions mod/state-transition/pkg/core/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import (
statedb "github.com/berachain/beacon-kit/mod/state-transition/pkg/core/state"
"github.com/berachain/beacon-kit/mod/storage/pkg/beacondb"
"github.com/berachain/beacon-kit/mod/storage/pkg/db"
depositstore "github.com/berachain/beacon-kit/mod/storage/pkg/deposit"
"github.com/berachain/beacon-kit/mod/storage/pkg/encoding"
dbm "github.com/cosmos/cosmos-db"
sdk "github.com/cosmos/cosmos-sdk/types"
Expand Down Expand Up @@ -91,6 +92,7 @@ func createStateProcessor(
*types.ExecutionPayloadHeader,
engineprimitives.Withdrawals,
],
ds *depositstore.KVStore[*types.Deposit],
signer crypto.BLSSigner,
fGetAddressFromPubKey func(crypto.BLSPubkey) ([]byte, error),
) *core.StateProcessor[
Expand Down Expand Up @@ -134,6 +136,7 @@ func createStateProcessor(
noop.NewLogger[any](),
cs,
execEngine,
ds,
signer,
fGetAddressFromPubKey,
)
Expand All @@ -155,18 +158,20 @@ var (
testCodec = &encoding.SSZInterfaceCodec[*types.ExecutionPayloadHeader]{}
)

func initStore() (
func initTestStores() (
*beacondb.KVStore[
*types.BeaconBlockHeader,
*types.Eth1Data,
*types.ExecutionPayloadHeader,
*types.Fork,
*types.Validator,
types.Validators,
], error) {
],
*depositstore.KVStore[*types.Deposit],
error) {
db, err := db.OpenDB("", dbm.MemDBBackend)
if err != nil {
return nil, fmt.Errorf("failed opening mem db: %w", err)
return nil, nil, fmt.Errorf("failed opening mem db: %w", err)
}
var (
nopLog = log.NewNopLogger()
Expand All @@ -182,21 +187,23 @@ func initStore() (
ctx := sdk.NewContext(cms, true, nopLog)
cms.MountStoreWithDB(testStoreKey, storetypes.StoreTypeIAVL, nil)
if err = cms.LoadLatestVersion(); err != nil {
return nil, fmt.Errorf("failed to load latest version: %w", err)
return nil, nil, fmt.Errorf("failed to load latest version: %w", err)
}
testStoreService := &testKVStoreService{ctx: ctx}

return beacondb.New[
*types.BeaconBlockHeader,
*types.Eth1Data,
*types.ExecutionPayloadHeader,
*types.Fork,
*types.Validator,
types.Validators,
](
testStoreService,
testCodec,
), nil
*types.BeaconBlockHeader,
*types.Eth1Data,
*types.ExecutionPayloadHeader,
*types.Fork,
*types.Validator,
types.Validators,
](
testStoreService,
testCodec,
),
depositstore.NewStore[*types.Deposit](testStoreService),
nil
}

func buildNextBlock(
Expand Down
8 changes: 6 additions & 2 deletions mod/state-transition/pkg/core/state_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ type StateProcessor[
ValidatorT, ValidatorsT, WithdrawalT,
],
ContextT Context,
DepositT Deposit[ForkDataT, WithdrawalCredentialsT],
DepositT Deposit[DepositT, ForkDataT, WithdrawalCredentialsT],
Eth1DataT interface {
New(common.Root, math.U64, common.ExecutionHash) Eth1DataT
GetDepositCount() math.U64
Expand Down Expand Up @@ -92,6 +92,8 @@ type StateProcessor[
executionEngine ExecutionEngine[
ExecutionPayloadT, ExecutionPayloadHeaderT, WithdrawalsT,
]
// ds allows checking payload deposits against the deposit contract
ds DepositStore[DepositT]
Comment on lines +95 to +96
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Enhance deposit store field documentation.

While the comment explains what the field does, it could be more descriptive about its purpose in preventing fraudulent validators and censoring legitimate ones.

Consider updating the comment to:

-	// ds allows checking payload deposits against the deposit contract
+	// ds allows verifying payload deposits against the deposit contract events
+	// to prevent fraudulent validators and ensure legitimate validators aren't censored
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// ds allows checking payload deposits against the deposit contract
ds DepositStore[DepositT]
// ds allows verifying payload deposits against the deposit contract events
// to prevent fraudulent validators and ensure legitimate validators aren't censored
ds DepositStore[DepositT]


// processingGenesis allows initializing correctly
// eth1 deposit index upon genesis
Expand All @@ -116,7 +118,7 @@ func NewStateProcessor[
KVStoreT, ValidatorT, ValidatorsT, WithdrawalT,
],
ContextT Context,
DepositT Deposit[ForkDataT, WithdrawalCredentialsT],
DepositT Deposit[DepositT, ForkDataT, WithdrawalCredentialsT],
Eth1DataT interface {
New(common.Root, math.U64, common.ExecutionHash) Eth1DataT
GetDepositCount() math.U64
Expand Down Expand Up @@ -148,6 +150,7 @@ func NewStateProcessor[
executionEngine ExecutionEngine[
ExecutionPayloadT, ExecutionPayloadHeaderT, WithdrawalsT,
],
ds DepositStore[DepositT],
signer crypto.BLSSigner,
fGetAddressFromPubKey func(crypto.BLSPubkey) ([]byte, error),
) *StateProcessor[
Expand All @@ -167,6 +170,7 @@ func NewStateProcessor[
executionEngine: executionEngine,
signer: signer,
fGetAddressFromPubKey: fGetAddressFromPubKey,
ds: ds,
}
}

Expand Down
20 changes: 11 additions & 9 deletions mod/state-transition/pkg/core/state_processor_genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,19 @@ func TestInitialize(t *testing.T) {
](t)
mocksSigner := &cryptomocks.BLSSigner{}

kvStore, depositStore, err := initTestStores()
require.NoError(t, err)
beaconState := new(TestBeaconStateT).NewFromDB(kvStore, cs)

Comment on lines +51 to +54
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Consider implementing a store provider interface.

Since both the block builder and state-transition processor now require deposit store access, consider introducing a common interface or provider pattern to standardize this access. This would:

  • Reduce duplication of store initialization logic
  • Make it easier to modify store behavior in the future
  • Simplify testing by allowing mock implementations

Also applies to: 58-58, 173-176, 180-180

sp := createStateProcessor(
cs,
execEngine,
depositStore,
mocksSigner,
dummyProposerAddressVerifier,
)

// create test inputs
kvStore, err := initStore()
require.NoError(t, err)
beaconState := new(TestBeaconStateT).NewFromDB(kvStore, cs)

// create test input
var (
deposits = []*types.Deposit{
{
Expand Down Expand Up @@ -169,18 +170,19 @@ func TestInitializeBartio(t *testing.T) {
](t)
mocksSigner := &cryptomocks.BLSSigner{}

kvStore, depositStore, err := initTestStores()
require.NoError(t, err)
beaconState := new(TestBeaconStateT).NewFromDB(kvStore, cs)

sp := createStateProcessor(
cs,
execEngine,
depositStore,
mocksSigner,
dummyProposerAddressVerifier,
)

// create test inputs
kvStore, err := initStore()
require.NoError(t, err)
beaconState := new(TestBeaconStateT).NewFromDB(kvStore, cs)

var (
deposits = []*types.Deposit{
{
Expand Down
41 changes: 28 additions & 13 deletions mod/state-transition/pkg/core/state_processor_staking.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,26 +40,41 @@ func (sp *StateProcessor[
st BeaconStateT,
blk BeaconBlockT,
) error {
// Verify that outstanding deposits are processed up to the maximum number
// of deposits.
deposits := blk.GetBody().GetDeposits()
index, err := st.GetEth1DepositIndex()
// Verify that outstanding deposits matches those listed by contract
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Fix grammatical error in comment

Correct the comment for grammatical accuracy.

Apply this diff:

-// Verify that outstanding deposits matches those listed by contract
+// Verify that outstanding deposits match those listed by contract
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Verify that outstanding deposits matches those listed by contract
// Verify that outstanding deposits match those listed by contract

depositIndex, err := st.GetEth1DepositIndex()
if err != nil {
return err
}
eth1Data, err := st.GetEth1Data()

stateDeposits, err := sp.ds.GetDepositsByIndex(
depositIndex+1,
sp.cs.MaxDepositsPerBlock(),
)
if err != nil {
return err
}
depositCount := min(
sp.cs.MaxDepositsPerBlock(),
eth1Data.GetDepositCount().Unwrap()-index,

deposits := blk.GetBody().GetDeposits()
sp.logger.Info(
"Expected deposit index from payload", depositIndex,
"deposits withdrawals length", len(deposits),
)
Comment on lines +58 to 61
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Clarify logging message for better readability

Improve the clarity of the logging message for better understanding.

Apply this diff to enhance the logging message:

-	sp.logger.Info(
-		"Expected deposit index from payload", depositIndex,
-		"deposits withdrawals length", len(deposits),
-	)
+	sp.logger.Info(
+		"Processing deposits starting from index", depositIndex,
+		"number of deposits in payload", len(deposits),
+	)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
sp.logger.Info(
"Expected deposit index from payload", depositIndex,
"deposits withdrawals length", len(deposits),
)
sp.logger.Info(
"Processing deposits starting from index", depositIndex,
"number of deposits in payload", len(deposits),
)

_ = depositCount
// TODO: Update eth1data count and check this.
// if uint64(len(deposits)) != depositCount {
// return errors.New("deposit count mismatch")
// }

if len(stateDeposits) != len(deposits) {
return fmt.Errorf("deposits mismatched lengths, state: %d, payload: %d",
len(stateDeposits),
len(deposits),
)
}

for i, sd := range stateDeposits {
if !sd.Equals(deposits[i]) {
return fmt.Errorf("deposits mismatched, state: %#v, payload: %#v",
sd, deposits[i],
)
}
Comment on lines +72 to +75
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid logging sensitive data in error messages

Using %#v may expose sensitive internal data. Consider logging minimal identifying information to avoid potential information leakage.

Adjust the error message to include only essential details:

-	return fmt.Errorf("deposits mismatched, state: %#v, payload: %#v",
-		sd, deposits[i],
-	)
+	return fmt.Errorf("deposit mismatch at index %d", i)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return fmt.Errorf("deposits mismatched, state: %#v, payload: %#v",
sd, deposits[i],
)
}
return fmt.Errorf("deposit mismatch at index %d", i)
}

}

Comment on lines +43 to +77
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Consider adding unit tests for deposit verification logic

To ensure the correctness and reliability of the new deposit verification implemented in processOperations, it's advisable to add unit tests covering various scenarios. This will help catch potential issues early and maintain code quality over time.

return sp.processDeposits(st, deposits)
}

Expand Down
16 changes: 11 additions & 5 deletions mod/state-transition/pkg/core/state_processor_staking_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ import (
"github.com/stretchr/testify/require"
)

// TestTransitionUpdateValidators shows that when validator is
// updated (increasing amount), corrensponding balance is updated.
Comment on lines +40 to +41
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Fix typo in test comment.

"corrensponding" should be "corresponding"

func TestTransitionUpdateValidators(t *testing.T) {
// Create state processor to test
cs := spec.BetnetChainSpec()
Expand All @@ -48,19 +50,20 @@ func TestTransitionUpdateValidators(t *testing.T) {
mocksSigner := &cryptomocks.BLSSigner{}
dummyProposerAddr := []byte{0xff}

kvStore, depositStore, err := initTestStores()
require.NoError(t, err)
beaconState := new(TestBeaconStateT).NewFromDB(kvStore, cs)

sp := createStateProcessor(
cs,
execEngine,
depositStore,
mocksSigner,
func(bytes.B48) ([]byte, error) {
return dummyProposerAddr, nil
},
)

kvStore, err := initStore()
require.NoError(t, err)
beaconState := new(TestBeaconStateT).NewFromDB(kvStore, cs)

var (
maxBalance = math.Gwei(cs.MaxEffectiveBalance())
minBalance = math.Gwei(cs.EffectiveBalanceIncrement())
Expand Down Expand Up @@ -116,7 +119,7 @@ func TestTransitionUpdateValidators(t *testing.T) {
Pubkey: genDeposits[0].Pubkey,
Credentials: emptyCredentials,
Amount: minBalance, // avoid breaching maxBalance
Index: genDeposits[0].Index,
Index: uint64(len(genDeposits)),
},
}
)
Expand All @@ -137,6 +140,9 @@ func TestTransitionUpdateValidators(t *testing.T) {
},
)

// make sure included deposit is already available in deposit store
require.NoError(t, depositStore.EnqueueDeposits(blkDeposits))

Comment on lines +143 to +145
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Consider enhancing deposit verification error handling.

While the deposit verification step is good and aligns with PR objectives, consider adding more descriptive error messaging to help debug test failures.

-	require.NoError(t, depositStore.EnqueueDeposits(blkDeposits))
+	err = depositStore.EnqueueDeposits(blkDeposits)
+	require.NoError(t, err, "failed to enqueue deposits in store before transition")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// make sure included deposit is already available in deposit store
require.NoError(t, depositStore.EnqueueDeposits(blkDeposits))
// make sure included deposit is already available in deposit store
err = depositStore.EnqueueDeposits(blkDeposits)
require.NoError(t, err, "failed to enqueue deposits in store before transition")

// run the test
vals, err := sp.Transition(ctx, beaconState, blk)

Expand Down
12 changes: 12 additions & 0 deletions mod/state-transition/pkg/core/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,12 @@ type Context interface {

// Deposit is the interface for a deposit.
type Deposit[
DepositT any,
ForkDataT any,
WithdrawlCredentialsT ~[32]byte,
] interface {
// Equals returns true if the Deposit is equal to the other.
Equals(DepositT) bool
// GetAmount returns the amount of the deposit.
GetAmount() math.Gwei
// GetPubkey returns the public key of the validator.
Expand All @@ -149,6 +152,15 @@ type Deposit[
) error
}

// DepositStore defines the interface for deposit storage.
type DepositStore[DepositT any] interface {
// GetDepositsByIndex returns `numView` expected deposits.
GetDepositsByIndex(
startIndex uint64,
numView uint64,
) ([]DepositT, error)
}
Comment on lines +155 to +162
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Consider adding deposit pruning strategy.

While the interface looks good for deposit retrieval, consider adding methods for deposit pruning to prevent unbounded growth of the store. This is particularly important as the past review comments mention deposit store pruning process issues.

Consider adding these methods to the interface:

  1. A method to prune old deposits
  2. A method to get the current size/capacity
  3. A method to configure retention policy

This would help prevent potential memory issues and align with the mentioned deposit store pruning requirements.


type ExecutionPayload[
ExecutionPayloadT, ExecutionPayloadHeaderT, WithdrawalsT any,
] interface {
Expand Down
Loading
Loading