mirror of
https://github.com/OffchainLabs/prysm.git
synced 2026-01-10 22:07:59 -05:00
Compare commits
4 Commits
check-time
...
improveDif
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e97651512 | ||
|
|
5cb1cb2e15 | ||
|
|
b3cb2770df | ||
|
|
a12f6ae30a |
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -368,7 +369,7 @@ type WeakSubjectivityData struct {
|
||||
}
|
||||
|
||||
func non200Err(response *http.Response) error {
|
||||
bodyBytes, err := io.ReadAll(response.Body)
|
||||
bodyBytes, err := ioutil.ReadAll(response.Body)
|
||||
var body string
|
||||
if err != nil {
|
||||
body = "(Unable to read response body.)"
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -51,7 +52,7 @@ func SetRequestBodyToRequestContainer(requestContainer interface{}, req *http.Re
|
||||
return InternalServerErrorWithMessage(err, "could not marshal request")
|
||||
}
|
||||
// Set the body to the new JSON.
|
||||
req.Body = io.NopCloser(bytes.NewReader(j))
|
||||
req.Body = ioutil.NopCloser(bytes.NewReader(j))
|
||||
req.Header.Set("Content-Length", strconv.Itoa(len(j)))
|
||||
req.ContentLength = int64(len(j))
|
||||
return nil
|
||||
@@ -92,7 +93,7 @@ func (m *ApiProxyMiddleware) ProxyRequest(req *http.Request) (*http.Response, Er
|
||||
|
||||
// ReadGrpcResponseBody reads the body from the grpc-gateway's response.
|
||||
func ReadGrpcResponseBody(r io.Reader) ([]byte, ErrorJson) {
|
||||
body, err := io.ReadAll(r)
|
||||
body, err := ioutil.ReadAll(r)
|
||||
if err != nil {
|
||||
return nil, InternalServerErrorWithMessage(err, "could not read response body")
|
||||
}
|
||||
@@ -194,7 +195,7 @@ func WriteMiddlewareResponseHeadersAndBody(grpcResp *http.Response, responseJson
|
||||
} else {
|
||||
w.WriteHeader(grpcResp.StatusCode)
|
||||
}
|
||||
if _, err := io.Copy(w, io.NopCloser(bytes.NewReader(responseJson))); err != nil {
|
||||
if _, err := io.Copy(w, ioutil.NopCloser(bytes.NewReader(responseJson))); err != nil {
|
||||
return InternalServerErrorWithMessage(err, "could not write response message")
|
||||
}
|
||||
} else {
|
||||
@@ -248,7 +249,7 @@ func WriteError(w http.ResponseWriter, errJson ErrorJson, responseHeader http.He
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(j)))
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(errJson.StatusCode())
|
||||
if _, err := io.Copy(w, io.NopCloser(bytes.NewReader(j))); err != nil {
|
||||
if _, err := io.Copy(w, ioutil.NopCloser(bytes.NewReader(j))); err != nil {
|
||||
log.WithError(err).Error("Could not write error message")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,13 +5,13 @@ go_library(
|
||||
srcs = [
|
||||
"chain_info.go",
|
||||
"error.go",
|
||||
"execution_engine.go",
|
||||
"head.go",
|
||||
"head_sync_committee_info.go",
|
||||
"init_sync_process_block.go",
|
||||
"log.go",
|
||||
"metrics.go",
|
||||
"new_slot.go",
|
||||
"optimistic_sync.go",
|
||||
"options.go",
|
||||
"pow_block.go",
|
||||
"process_attestation.go",
|
||||
@@ -103,13 +103,13 @@ go_test(
|
||||
"blockchain_test.go",
|
||||
"chain_info_test.go",
|
||||
"checktags_test.go",
|
||||
"execution_engine_test.go",
|
||||
"head_sync_committee_info_test.go",
|
||||
"head_test.go",
|
||||
"init_test.go",
|
||||
"log_test.go",
|
||||
"metrics_test.go",
|
||||
"mock_test.go",
|
||||
"optimistic_sync_test.go",
|
||||
"pow_block_test.go",
|
||||
"process_attestation_test.go",
|
||||
"process_block_test.go",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package blockchain
|
||||
|
||||
import (
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
logrus.SetLevel(logrus.DebugLevel)
|
||||
logrus.SetOutput(io.Discard)
|
||||
logrus.SetOutput(ioutil.Discard)
|
||||
|
||||
m.Run()
|
||||
}
|
||||
|
||||
@@ -6,9 +6,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/core/altair"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/core/epoch/precompute"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/core/feed"
|
||||
statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
|
||||
@@ -111,24 +109,6 @@ func (s *Service) onBlock(ctx context.Context, signed block.SignedBeaconBlock, b
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
testState := postState.Copy()
|
||||
t := time.Now()
|
||||
vp, bp, err := altair.InitializePrecomputeValidators(ctx, testState)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// New in Altair.
|
||||
vp, bp, err = altair.ProcessEpochParticipation(ctx, testState, bp, vp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
testState, err = precompute.ProcessJustificationAndFinalizationPreCompute(testState, bp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.WithField("elapsed", time.Since(t)).Info("Process justifications and finalizations")
|
||||
|
||||
postStateVersion, postStateHeader, err := getStateVersionAndPayload(postState)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -168,7 +148,7 @@ func (s *Service) onBlock(ctx context.Context, signed block.SignedBeaconBlock, b
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.savePostStateInfo(ctx, blockRoot, signed, postState); err != nil {
|
||||
if err := s.savePostStateInfo(ctx, blockRoot, signed, postState, false /* reg sync */); err != nil {
|
||||
return err
|
||||
}
|
||||
// If slasher is configured, forward the attestations in the block via
|
||||
@@ -426,6 +406,7 @@ func (s *Service) onBlockBatch(ctx context.Context, blks []block.SignedBeaconBlo
|
||||
|
||||
// blocks have been verified, add them to forkchoice and call the engine
|
||||
for i, b := range blks {
|
||||
s.saveInitSyncBlock(blockRoots[i], b)
|
||||
isValidPayload, err := s.notifyNewPayload(ctx,
|
||||
preVersionAndHeaders[i].version,
|
||||
postVersionAndHeaders[i].version,
|
||||
@@ -453,7 +434,10 @@ func (s *Service) onBlockBatch(ctx context.Context, blks []block.SignedBeaconBlo
|
||||
return nil, nil, errors.Wrap(err, "could not set optimistic block to valid")
|
||||
}
|
||||
}
|
||||
s.saveInitSyncBlock(blockRoots[i], b)
|
||||
|
||||
if _, err := s.notifyForkchoiceUpdate(ctx, preState, b.Block(), blockRoots[i], bytesutil.ToBytes32(fCheckpoints[i].Root)); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
for r, st := range boundaries {
|
||||
@@ -467,10 +451,6 @@ func (s *Service) onBlockBatch(ctx context.Context, blks []block.SignedBeaconBlo
|
||||
if err := s.cfg.StateGen.SaveState(ctx, lastBR, preState); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
f := fCheckpoints[len(fCheckpoints)-1]
|
||||
if _, err := s.notifyForkchoiceUpdate(ctx, preState, lastB.Block(), lastBR, bytesutil.ToBytes32(f.Root)); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if err := s.saveHeadNoDB(ctx, lastB, lastBR, preState); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -621,10 +601,12 @@ func getBlockPayloadHash(blk block.BeaconBlock) ([32]byte, error) {
|
||||
|
||||
// This saves post state info to DB or cache. This also saves post state info to fork choice store.
|
||||
// Post state info consists of processed block and state. Do not call this method unless the block and state are verified.
|
||||
func (s *Service) savePostStateInfo(ctx context.Context, r [32]byte, b block.SignedBeaconBlock, st state.BeaconState) error {
|
||||
func (s *Service) savePostStateInfo(ctx context.Context, r [32]byte, b block.SignedBeaconBlock, st state.BeaconState, initSync bool) error {
|
||||
ctx, span := trace.StartSpan(ctx, "blockChain.savePostStateInfo")
|
||||
defer span.End()
|
||||
if err := s.cfg.BeaconDB.SaveBlock(ctx, b); err != nil {
|
||||
if initSync {
|
||||
s.saveInitSyncBlock(r, b)
|
||||
} else if err := s.cfg.BeaconDB.SaveBlock(ctx, b); err != nil {
|
||||
return errors.Wrapf(err, "could not save block from slot %d", b.Block().Slot())
|
||||
}
|
||||
if err := s.cfg.StateGen.SaveState(ctx, r, st); err != nil {
|
||||
|
||||
@@ -407,10 +407,6 @@ func (s *Service) insertFinalizedDeposits(ctx context.Context, fRoot [32]byte) e
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not cast eth1 deposit index")
|
||||
}
|
||||
// The deposit index in the state is always the index of the next deposit
|
||||
// to be included(rather than the last one to be processed). This was most likely
|
||||
// done as the state cannot represent signed integers.
|
||||
eth1DepositIndex -= 1
|
||||
s.cfg.DepositCache.InsertFinalizedDeposits(ctx, int64(eth1DepositIndex))
|
||||
// Deposit proofs are only used during state transition and can be safely removed to save space.
|
||||
if err = s.cfg.DepositCache.PruneProofs(ctx, int64(eth1DepositIndex)); err != nil {
|
||||
|
||||
@@ -1516,7 +1516,7 @@ func TestInsertFinalizedDeposits(t *testing.T) {
|
||||
service.store.SetFinalizedCheckpt(ðpb.Checkpoint{Root: gRoot[:]})
|
||||
gs = gs.Copy()
|
||||
assert.NoError(t, gs.SetEth1Data(ðpb.Eth1Data{DepositCount: 10}))
|
||||
assert.NoError(t, gs.SetEth1DepositIndex(8))
|
||||
assert.NoError(t, gs.SetEth1DepositIndex(7))
|
||||
assert.NoError(t, service.cfg.StateGen.SaveState(ctx, [32]byte{'m', 'o', 'c', 'k'}, gs))
|
||||
zeroSig := [96]byte{}
|
||||
for i := uint64(0); i < uint64(4*params.BeaconConfig().SlotsPerEpoch); i++ {
|
||||
@@ -1555,11 +1555,11 @@ func TestInsertFinalizedDeposits_MultipleFinalizedRoutines(t *testing.T) {
|
||||
service.store.SetFinalizedCheckpt(ðpb.Checkpoint{Root: gRoot[:]})
|
||||
gs = gs.Copy()
|
||||
assert.NoError(t, gs.SetEth1Data(ðpb.Eth1Data{DepositCount: 7}))
|
||||
assert.NoError(t, gs.SetEth1DepositIndex(6))
|
||||
assert.NoError(t, gs.SetEth1DepositIndex(5))
|
||||
assert.NoError(t, service.cfg.StateGen.SaveState(ctx, [32]byte{'m', 'o', 'c', 'k'}, gs))
|
||||
gs2 := gs.Copy()
|
||||
assert.NoError(t, gs2.SetEth1Data(ðpb.Eth1Data{DepositCount: 15}))
|
||||
assert.NoError(t, gs2.SetEth1DepositIndex(13))
|
||||
assert.NoError(t, gs2.SetEth1DepositIndex(12))
|
||||
assert.NoError(t, service.cfg.StateGen.SaveState(ctx, [32]byte{'m', 'o', 'c', 'k', '2'}, gs2))
|
||||
zeroSig := [96]byte{}
|
||||
for i := uint64(0); i < uint64(4*params.BeaconConfig().SlotsPerEpoch); i++ {
|
||||
|
||||
@@ -78,7 +78,7 @@ func (s *Service) ReceiveBlockBatch(ctx context.Context, blocks []block.SignedBe
|
||||
ctx, span := trace.StartSpan(ctx, "blockChain.ReceiveBlockBatch")
|
||||
defer span.End()
|
||||
|
||||
// Apply state transition on the incoming newly received block batches, one by one.
|
||||
// Apply state transition on the incoming newly received blockCopy without verifying its BLS contents.
|
||||
fCheckpoints, jCheckpoints, err := s.onBlockBatch(ctx, blocks, blkRoots)
|
||||
if err != nil {
|
||||
err := errors.Wrap(err, "could not process block in batch")
|
||||
|
||||
@@ -2,7 +2,7 @@ package blockchain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
|
||||
testDB "github.com/prysmaticlabs/prysm/beacon-chain/db/testing"
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
|
||||
func init() {
|
||||
logrus.SetLevel(logrus.DebugLevel)
|
||||
logrus.SetOutput(io.Discard)
|
||||
logrus.SetOutput(ioutil.Discard)
|
||||
}
|
||||
|
||||
func TestChainService_SaveHead_DataRace(t *testing.T) {
|
||||
|
||||
2
beacon-chain/cache/BUILD.bazel
vendored
2
beacon-chain/cache/BUILD.bazel
vendored
@@ -33,6 +33,7 @@ go_library(
|
||||
deps = [
|
||||
"//beacon-chain/state:go_default_library",
|
||||
"//cache/lru:go_default_library",
|
||||
"//config/features:go_default_library",
|
||||
"//config/params:go_default_library",
|
||||
"//container/slice:go_default_library",
|
||||
"//crypto/hash:go_default_library",
|
||||
@@ -76,6 +77,7 @@ go_test(
|
||||
"//beacon-chain/state/v1:go_default_library",
|
||||
"//beacon-chain/state/v2:go_default_library",
|
||||
"//beacon-chain/state/v3:go_default_library",
|
||||
"//config/features:go_default_library",
|
||||
"//config/fieldparams:go_default_library",
|
||||
"//config/params:go_default_library",
|
||||
"//encoding/bytesutil:go_default_library",
|
||||
|
||||
7
beacon-chain/cache/active_balance.go
vendored
7
beacon-chain/cache/active_balance.go
vendored
@@ -14,6 +14,7 @@ import (
|
||||
ethTypes "github.com/prysmaticlabs/eth2-types"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state"
|
||||
lruwrpr "github.com/prysmaticlabs/prysm/cache/lru"
|
||||
"github.com/prysmaticlabs/prysm/config/features"
|
||||
"github.com/prysmaticlabs/prysm/config/params"
|
||||
)
|
||||
|
||||
@@ -50,6 +51,9 @@ func NewEffectiveBalanceCache() *BalanceCache {
|
||||
|
||||
// AddTotalEffectiveBalance adds a new total effective balance entry for current balance for state `st` into the cache.
|
||||
func (c *BalanceCache) AddTotalEffectiveBalance(st state.ReadOnlyBeaconState, balance uint64) error {
|
||||
if !features.Get().EnableActiveBalanceCache {
|
||||
return nil
|
||||
}
|
||||
key, err := balanceCacheKey(st)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -64,6 +68,9 @@ func (c *BalanceCache) AddTotalEffectiveBalance(st state.ReadOnlyBeaconState, ba
|
||||
|
||||
// Get returns the current epoch's effective balance for state `st` in cache.
|
||||
func (c *BalanceCache) Get(st state.ReadOnlyBeaconState) (uint64, error) {
|
||||
if !features.Get().EnableActiveBalanceCache {
|
||||
return 0, ErrNotFound
|
||||
}
|
||||
key, err := balanceCacheKey(st)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
|
||||
6
beacon-chain/cache/active_balance_test.go
vendored
6
beacon-chain/cache/active_balance_test.go
vendored
@@ -7,12 +7,18 @@ import (
|
||||
|
||||
types "github.com/prysmaticlabs/eth2-types"
|
||||
state "github.com/prysmaticlabs/prysm/beacon-chain/state/v1"
|
||||
"github.com/prysmaticlabs/prysm/config/features"
|
||||
"github.com/prysmaticlabs/prysm/config/params"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
"github.com/prysmaticlabs/prysm/testing/require"
|
||||
)
|
||||
|
||||
func TestBalanceCache_AddGetBalance(t *testing.T) {
|
||||
resetCfg := features.InitWithReset(&features.Flags{
|
||||
EnableActiveBalanceCache: true,
|
||||
})
|
||||
defer resetCfg()
|
||||
|
||||
blockRoots := make([][]byte, params.BeaconConfig().SlotsPerHistoricalRoot)
|
||||
for i := 0; i < len(blockRoots); i++ {
|
||||
b := make([]byte, 8)
|
||||
|
||||
@@ -749,85 +749,6 @@ func TestNonFinalizedDeposits_ReturnsNonFinalizedDepositsUpToBlockNumber(t *test
|
||||
assert.Equal(t, 1, len(deps))
|
||||
}
|
||||
|
||||
func TestFinalizedDeposits_ReturnsTrieCorrectly(t *testing.T) {
|
||||
dc, err := New()
|
||||
require.NoError(t, err)
|
||||
|
||||
generateCtr := func(height uint64, index int64) *ethpb.DepositContainer {
|
||||
return ðpb.DepositContainer{
|
||||
Eth1BlockHeight: height,
|
||||
Deposit: ðpb.Deposit{
|
||||
Data: ðpb.Deposit_Data{
|
||||
PublicKey: bytesutil.PadTo([]byte{uint8(index)}, 48),
|
||||
WithdrawalCredentials: make([]byte, 32),
|
||||
Signature: make([]byte, 96),
|
||||
},
|
||||
},
|
||||
Index: index,
|
||||
}
|
||||
}
|
||||
|
||||
finalizedDeposits := []*ethpb.DepositContainer{
|
||||
generateCtr(10, 0),
|
||||
generateCtr(11, 1),
|
||||
generateCtr(12, 2),
|
||||
generateCtr(12, 3),
|
||||
generateCtr(13, 4),
|
||||
generateCtr(13, 5),
|
||||
generateCtr(13, 6),
|
||||
generateCtr(14, 7),
|
||||
}
|
||||
dc.deposits = append(finalizedDeposits,
|
||||
generateCtr(15, 8),
|
||||
generateCtr(15, 9),
|
||||
generateCtr(30, 10))
|
||||
trieItems := make([][]byte, 0, len(dc.deposits))
|
||||
for _, dep := range dc.allDeposits(big.NewInt(30)) {
|
||||
depHash, err := dep.Data.HashTreeRoot()
|
||||
assert.NoError(t, err)
|
||||
trieItems = append(trieItems, depHash[:])
|
||||
}
|
||||
depositTrie, err := trie.GenerateTrieFromItems(trieItems, params.BeaconConfig().DepositContractTreeDepth)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Perform this in a non-sensical ordering
|
||||
dc.InsertFinalizedDeposits(context.Background(), 10)
|
||||
dc.InsertFinalizedDeposits(context.Background(), 2)
|
||||
dc.InsertFinalizedDeposits(context.Background(), 3)
|
||||
dc.InsertFinalizedDeposits(context.Background(), 4)
|
||||
|
||||
// Mimick finalized deposit trie fetch.
|
||||
fd := dc.FinalizedDeposits(context.Background())
|
||||
deps := dc.NonFinalizedDeposits(context.Background(), fd.MerkleTrieIndex, big.NewInt(14))
|
||||
insertIndex := fd.MerkleTrieIndex + 1
|
||||
|
||||
for _, dep := range deps {
|
||||
depHash, err := dep.Data.HashTreeRoot()
|
||||
assert.NoError(t, err)
|
||||
if err = fd.Deposits.Insert(depHash[:], int(insertIndex)); err != nil {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
insertIndex++
|
||||
}
|
||||
dc.InsertFinalizedDeposits(context.Background(), 15)
|
||||
dc.InsertFinalizedDeposits(context.Background(), 15)
|
||||
dc.InsertFinalizedDeposits(context.Background(), 14)
|
||||
|
||||
fd = dc.FinalizedDeposits(context.Background())
|
||||
deps = dc.NonFinalizedDeposits(context.Background(), fd.MerkleTrieIndex, big.NewInt(30))
|
||||
insertIndex = fd.MerkleTrieIndex + 1
|
||||
|
||||
for _, dep := range deps {
|
||||
depHash, err := dep.Data.HashTreeRoot()
|
||||
assert.NoError(t, err)
|
||||
if err = fd.Deposits.Insert(depHash[:], int(insertIndex)); err != nil {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
insertIndex++
|
||||
}
|
||||
assert.Equal(t, fd.Deposits.NumOfItems(), depositTrie.NumOfItems())
|
||||
}
|
||||
|
||||
func TestPruneProofs_Ok(t *testing.T) {
|
||||
dc, err := New()
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -2,7 +2,7 @@ package blocks_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
|
||||
"github.com/prysmaticlabs/go-bitfield"
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
// valid att.Data.Committee index would be 0, so this is an off by one error.
|
||||
// See: https://github.com/sigp/beacon-fuzz/issues/78
|
||||
func TestProcessAttestationNoVerifySignature_BeaconFuzzIssue78(t *testing.T) {
|
||||
attData, err := os.ReadFile("testdata/beaconfuzz_78_attestation.ssz")
|
||||
attData, err := ioutil.ReadFile("testdata/beaconfuzz_78_attestation.ssz")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -28,7 +28,7 @@ func TestProcessAttestationNoVerifySignature_BeaconFuzzIssue78(t *testing.T) {
|
||||
if err := att.UnmarshalSSZ(attData); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stateData, err := os.ReadFile("testdata/beaconfuzz_78_beacon.ssz")
|
||||
stateData, err := ioutil.ReadFile("testdata/beaconfuzz_78_beacon.ssz")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ package blocks_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
|
||||
@@ -23,7 +23,7 @@ import (
|
||||
)
|
||||
|
||||
func init() {
|
||||
logrus.SetOutput(io.Discard) // Ignore "validator activated" logs
|
||||
logrus.SetOutput(ioutil.Discard) // Ignore "validator activated" logs
|
||||
}
|
||||
|
||||
func TestProcessBlockHeader_ImproperBlockSlot(t *testing.T) {
|
||||
|
||||
@@ -18,12 +18,6 @@ import (
|
||||
"github.com/prysmaticlabs/prysm/time/slots"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidPayloadBlockHash = errors.New("invalid payload block hash")
|
||||
ErrInvalidPayloadTimeStamp = errors.New("invalid payload timestamp")
|
||||
ErrInvalidPayloadPrevRandao = errors.New("invalid payload previous randao")
|
||||
)
|
||||
|
||||
// IsMergeTransitionComplete returns true if the transition to Bellatrix has completed.
|
||||
// Meaning the payload header in beacon state is not `ExecutionPayloadHeader()` (i.e. not empty).
|
||||
//
|
||||
@@ -152,14 +146,14 @@ func ValidatePayload(st state.BeaconState, payload *enginev1.ExecutionPayload) e
|
||||
}
|
||||
|
||||
if !bytes.Equal(payload.PrevRandao, random) {
|
||||
return ErrInvalidPayloadPrevRandao
|
||||
return errors.New("incorrect prev randao")
|
||||
}
|
||||
t, err := slots.ToTime(st.GenesisTime(), st.Slot())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if payload.Timestamp != uint64(t.Unix()) {
|
||||
return ErrInvalidPayloadTimeStamp
|
||||
return errors.New("incorrect timestamp")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -226,7 +220,7 @@ func PayloadToHeader(payload *enginev1.ExecutionPayload) (*ethpb.ExecutionPayloa
|
||||
ParentHash: bytesutil.SafeCopyBytes(payload.ParentHash),
|
||||
FeeRecipient: bytesutil.SafeCopyBytes(payload.FeeRecipient),
|
||||
StateRoot: bytesutil.SafeCopyBytes(payload.StateRoot),
|
||||
ReceiptsRoot: bytesutil.SafeCopyBytes(payload.ReceiptsRoot),
|
||||
ReceiptRoot: bytesutil.SafeCopyBytes(payload.ReceiptsRoot),
|
||||
LogsBloom: bytesutil.SafeCopyBytes(payload.LogsBloom),
|
||||
PrevRandao: bytesutil.SafeCopyBytes(payload.PrevRandao),
|
||||
BlockNumber: payload.BlockNumber,
|
||||
@@ -299,7 +293,7 @@ func isEmptyHeader(h *ethpb.ExecutionPayloadHeader) bool {
|
||||
if !bytes.Equal(h.StateRoot, make([]byte, fieldparams.RootLength)) {
|
||||
return false
|
||||
}
|
||||
if !bytes.Equal(h.ReceiptsRoot, make([]byte, fieldparams.RootLength)) {
|
||||
if !bytes.Equal(h.ReceiptRoot, make([]byte, fieldparams.RootLength)) {
|
||||
return false
|
||||
}
|
||||
if !bytes.Equal(h.LogsBloom, make([]byte, fieldparams.LogsBloomLength)) {
|
||||
@@ -334,62 +328,3 @@ func isEmptyHeader(h *ethpb.ExecutionPayloadHeader) bool {
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ValidatePayloadHeaderWhenMergeCompletes validates the payload header when the merge completes.
|
||||
func ValidatePayloadHeaderWhenMergeCompletes(st state.BeaconState, header *ethpb.ExecutionPayloadHeader) error {
|
||||
// Skip validation if the state is not merge compatible.
|
||||
complete, err := IsMergeTransitionComplete(st)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !complete {
|
||||
return nil
|
||||
}
|
||||
// Validate current header's parent hash matches state header's block hash.
|
||||
h, err := st.LatestExecutionPayloadHeader()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !bytes.Equal(header.ParentHash, h.BlockHash) {
|
||||
return ErrInvalidPayloadBlockHash
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidatePayloadHeader validates the payload header.
|
||||
func ValidatePayloadHeader(st state.BeaconState, header *ethpb.ExecutionPayloadHeader) error {
|
||||
// Validate header's random mix matches with state in current epoch
|
||||
random, err := helpers.RandaoMix(st, time.CurrentEpoch(st))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !bytes.Equal(header.PrevRandao, random) {
|
||||
return ErrInvalidPayloadPrevRandao
|
||||
}
|
||||
|
||||
// Validate header's timestamp matches with state in current slot.
|
||||
t, err := slots.ToTime(st.GenesisTime(), st.Slot())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if header.Timestamp != uint64(t.Unix()) {
|
||||
return ErrInvalidPayloadTimeStamp
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ProcessPayloadHeader processes the payload header.
|
||||
func ProcessPayloadHeader(st state.BeaconState, header *ethpb.ExecutionPayloadHeader) (state.BeaconState, error) {
|
||||
if err := ValidatePayloadHeaderWhenMergeCompletes(st, header); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := ValidatePayloadHeader(st, header); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := st.SetLatestExecutionPayloadHeader(header); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/core/time"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state"
|
||||
fieldparams "github.com/prysmaticlabs/prysm/config/fieldparams"
|
||||
"github.com/prysmaticlabs/prysm/encoding/bytesutil"
|
||||
"github.com/prysmaticlabs/prysm/encoding/ssz"
|
||||
@@ -61,7 +60,7 @@ func Test_IsMergeComplete(t *testing.T) {
|
||||
name: "has receipt root",
|
||||
payload: func() *ethpb.ExecutionPayloadHeader {
|
||||
h := emptyPayloadHeader()
|
||||
h.ReceiptsRoot = bytesutil.PadTo([]byte{'a'}, fieldparams.RootLength)
|
||||
h.ReceiptRoot = bytesutil.PadTo([]byte{'a'}, fieldparams.RootLength)
|
||||
return h
|
||||
}(),
|
||||
want: true,
|
||||
@@ -601,7 +600,7 @@ func Test_ValidatePayload(t *testing.T) {
|
||||
{
|
||||
name: "incorrect prev randao",
|
||||
payload: emptyPayload(),
|
||||
err: blocks.ErrInvalidPayloadPrevRandao,
|
||||
err: errors.New("incorrect prev randao"),
|
||||
},
|
||||
{
|
||||
name: "incorrect timestamp",
|
||||
@@ -611,7 +610,7 @@ func Test_ValidatePayload(t *testing.T) {
|
||||
h.Timestamp = 1
|
||||
return h
|
||||
}(),
|
||||
err: blocks.ErrInvalidPayloadTimeStamp,
|
||||
err: errors.New("incorrect timestamp"),
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
@@ -649,7 +648,7 @@ func Test_ProcessPayload(t *testing.T) {
|
||||
{
|
||||
name: "incorrect prev randao",
|
||||
payload: emptyPayload(),
|
||||
err: blocks.ErrInvalidPayloadPrevRandao,
|
||||
err: errors.New("incorrect prev randao"),
|
||||
},
|
||||
{
|
||||
name: "incorrect timestamp",
|
||||
@@ -659,7 +658,7 @@ func Test_ProcessPayload(t *testing.T) {
|
||||
h.Timestamp = 1
|
||||
return h
|
||||
}(),
|
||||
err: blocks.ErrInvalidPayloadTimeStamp,
|
||||
err: errors.New("incorrect timestamp"),
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
@@ -679,149 +678,6 @@ func Test_ProcessPayload(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func Test_ProcessPayloadHeader(t *testing.T) {
|
||||
st, _ := util.DeterministicGenesisStateBellatrix(t, 1)
|
||||
random, err := helpers.RandaoMix(st, time.CurrentEpoch(st))
|
||||
require.NoError(t, err)
|
||||
ts, err := slots.ToTime(st.GenesisTime(), st.Slot())
|
||||
require.NoError(t, err)
|
||||
tests := []struct {
|
||||
name string
|
||||
header *ethpb.ExecutionPayloadHeader
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "process passes",
|
||||
header: func() *ethpb.ExecutionPayloadHeader {
|
||||
h := emptyPayloadHeader()
|
||||
h.PrevRandao = random
|
||||
h.Timestamp = uint64(ts.Unix())
|
||||
return h
|
||||
}(), err: nil,
|
||||
},
|
||||
{
|
||||
name: "incorrect prev randao",
|
||||
header: emptyPayloadHeader(),
|
||||
err: blocks.ErrInvalidPayloadPrevRandao,
|
||||
},
|
||||
{
|
||||
name: "incorrect timestamp",
|
||||
header: func() *ethpb.ExecutionPayloadHeader {
|
||||
h := emptyPayloadHeader()
|
||||
h.PrevRandao = random
|
||||
h.Timestamp = 1
|
||||
return h
|
||||
}(),
|
||||
err: blocks.ErrInvalidPayloadTimeStamp,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
st, err := blocks.ProcessPayloadHeader(st, tt.header)
|
||||
if err != nil {
|
||||
require.Equal(t, tt.err.Error(), err.Error())
|
||||
} else {
|
||||
require.Equal(t, tt.err, err)
|
||||
got, err := st.LatestExecutionPayloadHeader()
|
||||
require.NoError(t, err)
|
||||
require.DeepSSZEqual(t, tt.header, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_ValidatePayloadHeader(t *testing.T) {
|
||||
st, _ := util.DeterministicGenesisStateBellatrix(t, 1)
|
||||
random, err := helpers.RandaoMix(st, time.CurrentEpoch(st))
|
||||
require.NoError(t, err)
|
||||
ts, err := slots.ToTime(st.GenesisTime(), st.Slot())
|
||||
require.NoError(t, err)
|
||||
tests := []struct {
|
||||
name string
|
||||
header *ethpb.ExecutionPayloadHeader
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "process passes",
|
||||
header: func() *ethpb.ExecutionPayloadHeader {
|
||||
h := emptyPayloadHeader()
|
||||
h.PrevRandao = random
|
||||
h.Timestamp = uint64(ts.Unix())
|
||||
return h
|
||||
}(), err: nil,
|
||||
},
|
||||
{
|
||||
name: "incorrect prev randao",
|
||||
header: emptyPayloadHeader(),
|
||||
err: blocks.ErrInvalidPayloadPrevRandao,
|
||||
},
|
||||
{
|
||||
name: "incorrect timestamp",
|
||||
header: func() *ethpb.ExecutionPayloadHeader {
|
||||
h := emptyPayloadHeader()
|
||||
h.PrevRandao = random
|
||||
h.Timestamp = 1
|
||||
return h
|
||||
}(),
|
||||
err: blocks.ErrInvalidPayloadTimeStamp,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := blocks.ValidatePayloadHeader(st, tt.header)
|
||||
require.Equal(t, tt.err, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_ValidatePayloadHeaderWhenMergeCompletes(t *testing.T) {
|
||||
st, _ := util.DeterministicGenesisStateBellatrix(t, 1)
|
||||
emptySt := st.Copy()
|
||||
require.NoError(t, st.SetLatestExecutionPayloadHeader(ðpb.ExecutionPayloadHeader{BlockHash: []byte{'a'}}))
|
||||
tests := []struct {
|
||||
name string
|
||||
state state.BeaconState
|
||||
header *ethpb.ExecutionPayloadHeader
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "no merge",
|
||||
header: func() *ethpb.ExecutionPayloadHeader {
|
||||
h := emptyPayloadHeader()
|
||||
return h
|
||||
}(),
|
||||
state: emptySt,
|
||||
err: nil,
|
||||
},
|
||||
{
|
||||
name: "process passes",
|
||||
header: func() *ethpb.ExecutionPayloadHeader {
|
||||
h := emptyPayloadHeader()
|
||||
h.ParentHash = []byte{'a'}
|
||||
return h
|
||||
}(),
|
||||
state: st,
|
||||
err: nil,
|
||||
},
|
||||
{
|
||||
name: "invalid block hash",
|
||||
header: func() *ethpb.ExecutionPayloadHeader {
|
||||
h := emptyPayloadHeader()
|
||||
h.ParentHash = []byte{'b'}
|
||||
return h
|
||||
}(),
|
||||
state: st,
|
||||
err: blocks.ErrInvalidPayloadBlockHash,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := blocks.ValidatePayloadHeaderWhenMergeCompletes(tt.state, tt.header)
|
||||
require.Equal(t, tt.err, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_PayloadToHeader(t *testing.T) {
|
||||
p := emptyPayload()
|
||||
h, err := blocks.PayloadToHeader(p)
|
||||
@@ -849,7 +705,7 @@ func Test_PayloadToHeader(t *testing.T) {
|
||||
require.DeepSSZEqual(t, h.ParentHash, make([]byte, fieldparams.RootLength))
|
||||
require.DeepSSZEqual(t, h.FeeRecipient, make([]byte, fieldparams.FeeRecipientLength))
|
||||
require.DeepSSZEqual(t, h.StateRoot, make([]byte, fieldparams.RootLength))
|
||||
require.DeepSSZEqual(t, h.ReceiptsRoot, make([]byte, fieldparams.RootLength))
|
||||
require.DeepSSZEqual(t, h.ReceiptRoot, make([]byte, fieldparams.RootLength))
|
||||
require.DeepSSZEqual(t, h.LogsBloom, make([]byte, fieldparams.LogsBloomLength))
|
||||
require.DeepSSZEqual(t, h.PrevRandao, make([]byte, fieldparams.RootLength))
|
||||
require.DeepSSZEqual(t, h.ExtraData, make([]byte, 0))
|
||||
@@ -877,7 +733,7 @@ func emptyPayloadHeader() *ethpb.ExecutionPayloadHeader {
|
||||
ParentHash: make([]byte, fieldparams.RootLength),
|
||||
FeeRecipient: make([]byte, fieldparams.FeeRecipientLength),
|
||||
StateRoot: make([]byte, fieldparams.RootLength),
|
||||
ReceiptsRoot: make([]byte, fieldparams.RootLength),
|
||||
ReceiptRoot: make([]byte, fieldparams.RootLength),
|
||||
LogsBloom: make([]byte, fieldparams.LogsBloomLength),
|
||||
PrevRandao: make([]byte, fieldparams.RootLength),
|
||||
BaseFeePerGas: make([]byte, fieldparams.RootLength),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package blocks_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
// when it was not in actuality.
|
||||
// See: https://github.com/sigp/beacon-fuzz/issues/91
|
||||
func TestVerifyProposerSlashing_BeaconFuzzIssue91(t *testing.T) {
|
||||
file, err := os.ReadFile("testdata/beaconfuzz_91_beacon.ssz")
|
||||
file, err := ioutil.ReadFile("testdata/beaconfuzz_91_beacon.ssz")
|
||||
require.NoError(t, err)
|
||||
rawState := ðpb.BeaconState{}
|
||||
err = rawState.UnmarshalSSZ(file)
|
||||
@@ -25,7 +25,7 @@ func TestVerifyProposerSlashing_BeaconFuzzIssue91(t *testing.T) {
|
||||
st, err := v1.InitializeFromProtoUnsafe(rawState)
|
||||
require.NoError(t, err)
|
||||
|
||||
file, err = os.ReadFile("testdata/beaconfuzz_91_proposer_slashing.ssz")
|
||||
file, err = ioutil.ReadFile("testdata/beaconfuzz_91_proposer_slashing.ssz")
|
||||
require.NoError(t, err)
|
||||
slashing := ðpb.ProposerSlashing{}
|
||||
err = slashing.UnmarshalSSZ(file)
|
||||
|
||||
@@ -13,6 +13,7 @@ go_library(
|
||||
"//beacon-chain/core/time:go_default_library",
|
||||
"//beacon-chain/core/validators:go_default_library",
|
||||
"//beacon-chain/state:go_default_library",
|
||||
"//config/features:go_default_library",
|
||||
"//config/params:go_default_library",
|
||||
"//math:go_default_library",
|
||||
"//proto/prysm/v1alpha1:go_default_library",
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/core/time"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/core/validators"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state"
|
||||
"github.com/prysmaticlabs/prysm/config/features"
|
||||
"github.com/prysmaticlabs/prysm/config/params"
|
||||
"github.com/prysmaticlabs/prysm/math"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
@@ -249,7 +250,6 @@ func ProcessEffectiveBalanceUpdates(state state.BeaconState) (state.BeaconState,
|
||||
upwardThreshold := hysteresisInc * params.BeaconConfig().HysteresisUpwardMultiplier
|
||||
|
||||
bals := state.Balances()
|
||||
|
||||
// Update effective balances with hysteresis.
|
||||
validatorFunc := func(idx int, val *ethpb.Validator) (bool, *ethpb.Validator, error) {
|
||||
if val == nil {
|
||||
@@ -261,18 +261,40 @@ func ProcessEffectiveBalanceUpdates(state state.BeaconState) (state.BeaconState,
|
||||
balance := bals[idx]
|
||||
|
||||
if balance+downwardThreshold < val.EffectiveBalance || val.EffectiveBalance+upwardThreshold < balance {
|
||||
effectiveBal := maxEffBalance
|
||||
if effectiveBal > balance-balance%effBalanceInc {
|
||||
effectiveBal = balance - balance%effBalanceInc
|
||||
newVal := ethpb.CopyValidator(val)
|
||||
newVal.EffectiveBalance = maxEffBalance
|
||||
if newVal.EffectiveBalance > balance-balance%effBalanceInc {
|
||||
newVal.EffectiveBalance = balance - balance%effBalanceInc
|
||||
}
|
||||
if effectiveBal != val.EffectiveBalance {
|
||||
newVal := ethpb.CopyValidator(val)
|
||||
newVal.EffectiveBalance = effectiveBal
|
||||
return true, newVal, nil
|
||||
return true, newVal, nil
|
||||
}
|
||||
return false, val, nil
|
||||
}
|
||||
|
||||
if features.Get().EnableOptimizedBalanceUpdate {
|
||||
validatorFunc = func(idx int, val *ethpb.Validator) (bool, *ethpb.Validator, error) {
|
||||
if val == nil {
|
||||
return false, nil, fmt.Errorf("validator %d is nil in state", idx)
|
||||
}
|
||||
if idx >= len(bals) {
|
||||
return false, nil, fmt.Errorf("validator index exceeds validator length in state %d >= %d", idx, len(state.Balances()))
|
||||
}
|
||||
balance := bals[idx]
|
||||
|
||||
if balance+downwardThreshold < val.EffectiveBalance || val.EffectiveBalance+upwardThreshold < balance {
|
||||
effectiveBal := maxEffBalance
|
||||
if effectiveBal > balance-balance%effBalanceInc {
|
||||
effectiveBal = balance - balance%effBalanceInc
|
||||
}
|
||||
if effectiveBal != val.EffectiveBalance {
|
||||
newVal := ethpb.CopyValidator(val)
|
||||
newVal.EffectiveBalance = effectiveBal
|
||||
return true, newVal, nil
|
||||
}
|
||||
return false, val, nil
|
||||
}
|
||||
return false, val, nil
|
||||
}
|
||||
return false, val, nil
|
||||
}
|
||||
|
||||
if err := state.ApplyToEveryValidator(validatorFunc); err != nil {
|
||||
|
||||
@@ -69,7 +69,7 @@ func UpgradeToBellatrix(ctx context.Context, state state.BeaconState) (state.Bea
|
||||
ParentHash: make([]byte, 32),
|
||||
FeeRecipient: make([]byte, 20),
|
||||
StateRoot: make([]byte, 32),
|
||||
ReceiptsRoot: make([]byte, 32),
|
||||
ReceiptRoot: make([]byte, 32),
|
||||
LogsBloom: make([]byte, 256),
|
||||
PrevRandao: make([]byte, 32),
|
||||
BlockNumber: 0,
|
||||
|
||||
@@ -65,7 +65,7 @@ func TestUpgradeToBellatrix(t *testing.T) {
|
||||
ParentHash: make([]byte, 32),
|
||||
FeeRecipient: make([]byte, 20),
|
||||
StateRoot: make([]byte, 32),
|
||||
ReceiptsRoot: make([]byte, 32),
|
||||
ReceiptRoot: make([]byte, 32),
|
||||
LogsBloom: make([]byte, 256),
|
||||
PrevRandao: make([]byte, 32),
|
||||
BlockNumber: 0,
|
||||
|
||||
@@ -63,6 +63,7 @@ go_test(
|
||||
"//beacon-chain/state:go_default_library",
|
||||
"//beacon-chain/state/v1:go_default_library",
|
||||
"//beacon-chain/state/v2:go_default_library",
|
||||
"//config/features:go_default_library",
|
||||
"//config/fieldparams:go_default_library",
|
||||
"//config/params:go_default_library",
|
||||
"//container/slice:go_default_library",
|
||||
|
||||
@@ -374,7 +374,6 @@ func ClearCache() {
|
||||
committeeCache = cache.NewCommitteesCache()
|
||||
proposerIndicesCache = cache.NewProposerIndicesCache()
|
||||
syncCommitteeCache = cache.NewSyncCommittee()
|
||||
balanceCache = cache.NewEffectiveBalanceCache()
|
||||
}
|
||||
|
||||
// computeCommittee returns the requested shuffled committee out of the total committees using
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
types "github.com/prysmaticlabs/eth2-types"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/core/time"
|
||||
v1 "github.com/prysmaticlabs/prysm/beacon-chain/state/v1"
|
||||
"github.com/prysmaticlabs/prysm/config/features"
|
||||
"github.com/prysmaticlabs/prysm/config/params"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
"github.com/prysmaticlabs/prysm/testing/assert"
|
||||
@@ -75,6 +76,11 @@ func TestTotalActiveBalance(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestTotalActiveBalance_WithCache(t *testing.T) {
|
||||
resetCfg := features.InitWithReset(&features.Flags{
|
||||
EnableActiveBalanceCache: true,
|
||||
})
|
||||
defer resetCfg()
|
||||
|
||||
tests := []struct {
|
||||
vCount int
|
||||
wantCount int
|
||||
|
||||
@@ -290,24 +290,13 @@ func ProcessBlockForStateRoot(
|
||||
return nil, errors.Wrap(err, "could not check if execution is enabled")
|
||||
}
|
||||
if enabled {
|
||||
if blk.IsBlinded() {
|
||||
header, err := blk.Body().ExecutionPayloadHeader()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
state, err = b.ProcessPayloadHeader(state, header)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "could not process execution payload header")
|
||||
}
|
||||
} else {
|
||||
payload, err := blk.Body().ExecutionPayload()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
state, err = b.ProcessPayload(state, payload)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "could not process execution payload")
|
||||
}
|
||||
payload, err := blk.Body().ExecutionPayload()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
state, err = b.ProcessPayload(state, payload)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "could not process execution payload")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package kv
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
@@ -33,7 +34,7 @@ func TestStore_Backup(t *testing.T) {
|
||||
require.NoError(t, db.Backup(ctx, "", false))
|
||||
|
||||
backupsPath := filepath.Join(db.databasePath, backupsDirectoryName)
|
||||
files, err := os.ReadDir(backupsPath)
|
||||
files, err := ioutil.ReadDir(backupsPath)
|
||||
require.NoError(t, err)
|
||||
require.NotEqual(t, 0, len(files), "No backups created")
|
||||
require.NoError(t, db.Close(), "Failed to close database")
|
||||
@@ -77,7 +78,7 @@ func TestStore_BackupMultipleBuckets(t *testing.T) {
|
||||
require.NoError(t, db.Backup(ctx, "", false))
|
||||
|
||||
backupsPath := filepath.Join(db.databasePath, backupsDirectoryName)
|
||||
files, err := os.ReadDir(backupsPath)
|
||||
files, err := ioutil.ReadDir(backupsPath)
|
||||
require.NoError(t, err)
|
||||
require.NotEqual(t, 0, len(files), "No backups created")
|
||||
require.NoError(t, db.Close(), "Failed to close database")
|
||||
|
||||
@@ -18,7 +18,7 @@ const batchSize = 10
|
||||
|
||||
var migrationStateValidatorsKey = []byte("migration_state_validator")
|
||||
|
||||
func shouldMigrateValidators(db *bolt.DB) (bool, error) {
|
||||
func migrateStateValidators(ctx context.Context, db *bolt.DB) error {
|
||||
migrateDB := false
|
||||
if updateErr := db.View(func(tx *bolt.Tx) error {
|
||||
mb := tx.Bucket(migrationsBucket)
|
||||
@@ -46,17 +46,11 @@ func shouldMigrateValidators(db *bolt.DB) (bool, error) {
|
||||
return nil
|
||||
}); updateErr != nil {
|
||||
log.WithError(updateErr).Errorf("could not migrate bucket: %s", stateBucket)
|
||||
return false, updateErr
|
||||
return updateErr
|
||||
}
|
||||
|
||||
return migrateDB, nil
|
||||
}
|
||||
|
||||
func migrateStateValidators(ctx context.Context, db *bolt.DB) error {
|
||||
if ok, err := shouldMigrateValidators(db); err != nil {
|
||||
return err
|
||||
} else if !ok {
|
||||
// A migration is not required.
|
||||
// do not migrate the DB
|
||||
if !migrateDB {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -151,10 +151,6 @@ func (s *Store) SaveStates(ctx context.Context, states []state.ReadOnlyBeaconSta
|
||||
})
|
||||
}
|
||||
|
||||
type withValidators interface {
|
||||
GetValidators() []*ethpb.Validator
|
||||
}
|
||||
|
||||
// SaveStatesEfficient stores multiple states to the db (new schema) using the provided corresponding roots.
|
||||
func (s *Store) SaveStatesEfficient(ctx context.Context, states []state.ReadOnlyBeaconState, blockRoots [][32]byte) error {
|
||||
ctx, span := trace.StartSpan(ctx, "BeaconDB.SaveStatesEfficient")
|
||||
@@ -165,12 +161,29 @@ func (s *Store) SaveStatesEfficient(ctx context.Context, states []state.ReadOnly
|
||||
validatorsEntries := make(map[string]*ethpb.Validator) // It's a map to make sure that you store only new validator entries.
|
||||
validatorKeys := make([][]byte, len(states)) // For every state, this stores a compressed list of validator keys.
|
||||
for i, st := range states {
|
||||
pb, ok := st.InnerStateUnsafe().(withValidators)
|
||||
if !ok {
|
||||
return errors.New("could not cast state to interface with GetValidators()")
|
||||
var validators []*ethpb.Validator
|
||||
switch st.InnerStateUnsafe().(type) {
|
||||
case *ethpb.BeaconState:
|
||||
pbState, err := v1.ProtobufBeaconState(st.InnerStateUnsafe())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
validators = pbState.Validators
|
||||
case *ethpb.BeaconStateAltair:
|
||||
pbState, err := v2.ProtobufBeaconState(st.InnerStateUnsafe())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
validators = pbState.Validators
|
||||
case *ethpb.BeaconStateBellatrix:
|
||||
pbState, err := v3.ProtobufBeaconState(st.InnerStateUnsafe())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
validators = pbState.Validators
|
||||
default:
|
||||
return errors.New("invalid state type")
|
||||
}
|
||||
validators := pb.GetValidators()
|
||||
|
||||
// yank out the validators and store them in separate table to save space.
|
||||
var hashes []byte
|
||||
for _, val := range validators {
|
||||
|
||||
@@ -3,6 +3,7 @@ package db
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path"
|
||||
"testing"
|
||||
@@ -54,7 +55,7 @@ func TestRestore(t *testing.T) {
|
||||
|
||||
assert.NoError(t, Restore(cliCtx))
|
||||
|
||||
files, err := os.ReadDir(path.Join(restoreDir, kv.BeaconNodeDbDirName))
|
||||
files, err := ioutil.ReadDir(path.Join(restoreDir, kv.BeaconNodeDbDirName))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, len(files))
|
||||
assert.Equal(t, kv.DatabaseFileName, files[0].Name())
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package slasherkv
|
||||
|
||||
import (
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
@@ -9,6 +9,6 @@ import (
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
logrus.SetLevel(logrus.DebugLevel)
|
||||
logrus.SetOutput(io.Discard)
|
||||
logrus.SetOutput(ioutil.Discard)
|
||||
m.Run()
|
||||
}
|
||||
|
||||
@@ -5,8 +5,8 @@ package interopcoldstart
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io/ioutil"
|
||||
"math/big"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
types "github.com/prysmaticlabs/eth2-types"
|
||||
@@ -47,21 +47,17 @@ type Config struct {
|
||||
// into the beacon chain database and running services at start up. This service should not be used in production
|
||||
// as it does not have any value other than ease of use for testing purposes.
|
||||
func NewService(ctx context.Context, cfg *Config) *Service {
|
||||
log.Warn("Saving generated genesis state in database for interop testing")
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
|
||||
return &Service{
|
||||
s := &Service{
|
||||
cfg: cfg,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
}
|
||||
}
|
||||
|
||||
// Start initializes the genesis state from configured flags.
|
||||
func (s *Service) Start() {
|
||||
log.Warn("Saving generated genesis state in database for interop testing")
|
||||
|
||||
if s.cfg.GenesisPath != "" {
|
||||
data, err := os.ReadFile(s.cfg.GenesisPath)
|
||||
data, err := ioutil.ReadFile(s.cfg.GenesisPath)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not read pre-loaded state: %v", err)
|
||||
}
|
||||
@@ -73,14 +69,14 @@ func (s *Service) Start() {
|
||||
if err != nil {
|
||||
log.Fatalf("Could not get state trie: %v", err)
|
||||
}
|
||||
if err := s.saveGenesisState(s.ctx, genesisTrie); err != nil {
|
||||
if err := s.saveGenesisState(ctx, genesisTrie); err != nil {
|
||||
log.Fatalf("Could not save interop genesis state %v", err)
|
||||
}
|
||||
return
|
||||
return s
|
||||
}
|
||||
|
||||
// Save genesis state in db
|
||||
genesisState, _, err := interop.GenerateGenesisState(s.ctx, s.cfg.GenesisTime, s.cfg.NumValidators)
|
||||
genesisState, _, err := interop.GenerateGenesisState(ctx, s.cfg.GenesisTime, s.cfg.NumValidators)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not generate interop genesis state: %v", err)
|
||||
}
|
||||
@@ -96,11 +92,17 @@ func (s *Service) Start() {
|
||||
if err != nil {
|
||||
log.Fatalf("Could not hash tree root genesis state: %v", err)
|
||||
}
|
||||
go slots.CountdownToGenesis(s.ctx, time.Unix(int64(s.cfg.GenesisTime), 0), s.cfg.NumValidators, gRoot)
|
||||
go slots.CountdownToGenesis(ctx, time.Unix(int64(s.cfg.GenesisTime), 0), s.cfg.NumValidators, gRoot)
|
||||
|
||||
if err := s.saveGenesisState(s.ctx, genesisTrie); err != nil {
|
||||
if err := s.saveGenesisState(ctx, genesisTrie); err != nil {
|
||||
log.Fatalf("Could not save interop genesis state %v", err)
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// Start initializes the genesis state from configured flags.
|
||||
func (_ *Service) Start() {
|
||||
}
|
||||
|
||||
// Stop does nothing.
|
||||
|
||||
@@ -95,7 +95,6 @@ func NewService(ctx context.Context, config *ValidatorMonitorConfig, tracked []t
|
||||
latestPerformance: make(map[types.ValidatorIndex]ValidatorLatestPerformance),
|
||||
aggregatedPerformance: make(map[types.ValidatorIndex]ValidatorAggregatedPerformance),
|
||||
trackedSyncCommitteeIndices: make(map[types.ValidatorIndex][]types.CommitteeIndex),
|
||||
isLogging: false,
|
||||
}
|
||||
for _, idx := range tracked {
|
||||
r.TrackedValidators[idx] = true
|
||||
@@ -118,6 +117,7 @@ func (s *Service) Start() {
|
||||
"ValidatorIndices": tracked,
|
||||
}).Info("Starting service")
|
||||
|
||||
s.isLogging = false
|
||||
stateChannel := make(chan *feed.Event, 1)
|
||||
stateSub := s.config.StateNotifier.StateFeed().Subscribe(stateChannel)
|
||||
|
||||
|
||||
@@ -906,7 +906,6 @@ func (b *BeaconNode) registerDeterminsticGenesisService() error {
|
||||
DepositCache: b.depositCache,
|
||||
GenesisPath: genesisStatePath,
|
||||
})
|
||||
svc.Start()
|
||||
|
||||
// Register genesis state as start-up state when interop mode.
|
||||
// The start-up state gets reused across services.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package registration
|
||||
|
||||
import (
|
||||
"os"
|
||||
"io/ioutil"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/prysmaticlabs/prysm/cmd"
|
||||
@@ -42,7 +42,7 @@ func P2PPreregistration(cliCtx *cli.Context) (bootstrapNodeAddrs []string, dataD
|
||||
}
|
||||
|
||||
func readbootNodes(fileName string) ([]string, error) {
|
||||
fileContent, err := os.ReadFile(fileName) // #nosec G304
|
||||
fileContent, err := ioutil.ReadFile(fileName) // #nosec G304
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ package registration
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"os"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
|
||||
"github.com/prysmaticlabs/prysm/cmd"
|
||||
@@ -27,9 +27,9 @@ func TestP2PPreregistration(t *testing.T) {
|
||||
sampleNode := "- enr:-TESTNODE"
|
||||
testDataDir := "testDataDir"
|
||||
|
||||
file, err := os.CreateTemp(t.TempDir(), "bootstrapFile*.yaml")
|
||||
file, err := ioutil.TempFile(t.TempDir(), "bootstrapFile*.yaml")
|
||||
require.NoError(t, err)
|
||||
err = os.WriteFile(file.Name(), []byte(sampleNode), 0644)
|
||||
err = ioutil.WriteFile(file.Name(), []byte(sampleNode), 0644)
|
||||
require.NoError(t, err, "Error in WriteFile call")
|
||||
params.SetupTestConfigCleanup(t)
|
||||
config := params.BeaconNetworkConfig()
|
||||
@@ -49,7 +49,7 @@ func TestP2PPreregistration(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestBootStrapNodeFile(t *testing.T) {
|
||||
file, err := os.CreateTemp(t.TempDir(), "bootstrapFile")
|
||||
file, err := ioutil.TempFile(t.TempDir(), "bootstrapFile")
|
||||
require.NoError(t, err)
|
||||
|
||||
sampleNode0 := "- enr:-Ku4QMKVC_MowDsmEa20d5uGjrChI0h8_KsKXDmgVQbIbngZV0i" +
|
||||
@@ -58,7 +58,7 @@ func TestBootStrapNodeFile(t *testing.T) {
|
||||
"E1rtwzvGy40mq9eD66XfHPBWgIIN1ZHCCD6A"
|
||||
sampleNode1 := "- enr:-TESTNODE2"
|
||||
sampleNode2 := "- enr:-TESTNODE3"
|
||||
err = os.WriteFile(file.Name(), []byte(sampleNode0+"\n"+sampleNode1+"\n"+sampleNode2), 0644)
|
||||
err = ioutil.WriteFile(file.Name(), []byte(sampleNode0+"\n"+sampleNode1+"\n"+sampleNode2), 0644)
|
||||
require.NoError(t, err, "Error in WriteFile call")
|
||||
nodeList, err := readbootNodes(file.Name())
|
||||
require.NoError(t, err, "Error in readbootNodes call")
|
||||
|
||||
@@ -127,7 +127,6 @@ go_test(
|
||||
],
|
||||
embed = [":go_default_library"],
|
||||
flaky = True,
|
||||
tags = ["requires-network"],
|
||||
deps = [
|
||||
"//async/event:go_default_library",
|
||||
"//beacon-chain/blockchain/testing:go_default_library",
|
||||
|
||||
@@ -3,8 +3,8 @@ package p2p
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
gethCrypto "github.com/ethereum/go-ethereum/crypto"
|
||||
@@ -17,7 +17,7 @@ import (
|
||||
)
|
||||
|
||||
func TestPrivateKeyLoading(t *testing.T) {
|
||||
file, err := os.CreateTemp(t.TempDir(), "key")
|
||||
file, err := ioutil.TempFile(t.TempDir(), "key")
|
||||
require.NoError(t, err)
|
||||
key, _, err := crypto.GenerateSecp256k1Key(rand.Reader)
|
||||
require.NoError(t, err, "Could not generate key")
|
||||
@@ -27,7 +27,7 @@ func TestPrivateKeyLoading(t *testing.T) {
|
||||
}
|
||||
out := hex.EncodeToString(raw)
|
||||
|
||||
err = os.WriteFile(file.Name(), []byte(out), params.BeaconIoConfig().ReadWritePermissions)
|
||||
err = ioutil.WriteFile(file.Name(), []byte(out), params.BeaconIoConfig().ReadWritePermissions)
|
||||
require.NoError(t, err, "Could not write key to file")
|
||||
log.WithField("file", file.Name()).WithField("key", out).Info("Wrote key to file")
|
||||
cfg := &Config{
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package peers_test
|
||||
|
||||
import (
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
|
||||
"github.com/prysmaticlabs/prysm/cmd/beacon-chain/flags"
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
logrus.SetLevel(logrus.DebugLevel)
|
||||
logrus.SetOutput(io.Discard)
|
||||
logrus.SetOutput(ioutil.Discard)
|
||||
|
||||
resetCfg := features.InitWithReset(&features.Flags{
|
||||
EnablePeerScorer: true,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package scorers_test
|
||||
|
||||
import (
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
logrus.SetLevel(logrus.DebugLevel)
|
||||
logrus.SetOutput(io.Discard)
|
||||
logrus.SetOutput(ioutil.Discard)
|
||||
|
||||
resetCfg := features.InitWithReset(&features.Flags{
|
||||
EnablePeerScorer: true,
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"os"
|
||||
"path"
|
||||
@@ -88,7 +89,7 @@ func privKey(cfg *Config) (*ecdsa.PrivateKey, error) {
|
||||
|
||||
// Retrieves a p2p networking private key from a file path.
|
||||
func privKeyFromFile(path string) (*ecdsa.PrivateKey, error) {
|
||||
src, err := os.ReadFile(path) // #nosec G304
|
||||
src, err := ioutil.ReadFile(path) // #nosec G304
|
||||
if err != nil {
|
||||
log.WithError(err).Error("Error reading private key from file")
|
||||
return nil, err
|
||||
@@ -134,7 +135,7 @@ func metaDataFromConfig(cfg *Config) (metadata.Metadata, error) {
|
||||
if defaultMetadataExist && metaDataPath == "" {
|
||||
metaDataPath = defaultKeyPath
|
||||
}
|
||||
src, err := os.ReadFile(metaDataPath) // #nosec G304
|
||||
src, err := ioutil.ReadFile(metaDataPath) // #nosec G304
|
||||
if err != nil {
|
||||
log.WithError(err).Error("Error reading metadata from file")
|
||||
return nil, err
|
||||
|
||||
@@ -118,7 +118,7 @@ func (s *Service) BlockByTimestamp(ctx context.Context, time uint64) (*types.Hea
|
||||
latestBlkTime := s.latestEth1Data.BlockTime
|
||||
|
||||
if time > latestBlkTime {
|
||||
return nil, errors.Errorf("provided time is later than the current eth1 head. %d > %d", time, latestBlkTime)
|
||||
return nil, errors.New("provided time is later than the current eth1 head")
|
||||
}
|
||||
// Initialize a pointer to eth1 chain's history to start our search
|
||||
// from.
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -100,7 +100,7 @@ func TestClient_HTTP(t *testing.T) {
|
||||
defer func() {
|
||||
require.NoError(t, r.Body.Close())
|
||||
}()
|
||||
enc, err := io.ReadAll(r.Body)
|
||||
enc, err := ioutil.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
jsonRequestString := string(enc)
|
||||
|
||||
@@ -350,7 +350,7 @@ func TestClient_HTTP(t *testing.T) {
|
||||
defer func() {
|
||||
require.NoError(t, r.Body.Close())
|
||||
}()
|
||||
enc, err := io.ReadAll(r.Body)
|
||||
enc, err := ioutil.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
jsonRequestString := string(enc)
|
||||
// We expect the JSON string RPC request contains the right arguments.
|
||||
@@ -387,7 +387,7 @@ func TestClient_HTTP(t *testing.T) {
|
||||
defer func() {
|
||||
require.NoError(t, r.Body.Close())
|
||||
}()
|
||||
enc, err := io.ReadAll(r.Body)
|
||||
enc, err := ioutil.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
jsonRequestString := string(enc)
|
||||
// We expect the JSON string RPC request contains the right arguments.
|
||||
@@ -972,7 +972,7 @@ func forkchoiceUpdateSetup(t *testing.T, fcs *pb.ForkchoiceState, att *pb.Payloa
|
||||
defer func() {
|
||||
require.NoError(t, r.Body.Close())
|
||||
}()
|
||||
enc, err := io.ReadAll(r.Body)
|
||||
enc, err := ioutil.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
jsonRequestString := string(enc)
|
||||
|
||||
@@ -1011,7 +1011,7 @@ func newPayloadSetup(t *testing.T, status *pb.PayloadStatus, payload *pb.Executi
|
||||
defer func() {
|
||||
require.NoError(t, r.Body.Close())
|
||||
}()
|
||||
enc, err := io.ReadAll(r.Body)
|
||||
enc, err := ioutil.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
jsonRequestString := string(enc)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package powchain
|
||||
|
||||
import (
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
logrus.SetLevel(logrus.DebugLevel)
|
||||
logrus.SetOutput(io.Discard)
|
||||
logrus.SetOutput(ioutil.Discard)
|
||||
|
||||
m.Run()
|
||||
}
|
||||
|
||||
@@ -413,14 +413,11 @@ func (s *Service) initDepositCaches(ctx context.Context, ctrs []*ethpb.DepositCo
|
||||
// accumulates. we finalize them here before we are ready to receive a block.
|
||||
// Otherwise, the first few blocks will be slower to compute as we will
|
||||
// hold the lock and be busy finalizing the deposits.
|
||||
// The deposit index in the state is always the index of the next deposit
|
||||
// to be included(rather than the last one to be processed). This was most likely
|
||||
// done as the state cannot represent signed integers.
|
||||
actualIndex := int64(currIndex) - 1 // lint:ignore uintcast -- deposit index will not exceed int64 in your lifetime.
|
||||
s.cfg.depositCache.InsertFinalizedDeposits(ctx, actualIndex)
|
||||
s.cfg.depositCache.InsertFinalizedDeposits(ctx, int64(currIndex)) // lint:ignore uintcast -- deposit index will not exceed int64 in your lifetime.
|
||||
// Deposit proofs are only used during state transition and can be safely removed to save space.
|
||||
|
||||
if err = s.cfg.depositCache.PruneProofs(ctx, actualIndex); err != nil {
|
||||
// lint:ignore uintcast -- deposit index will not exceed int64 in your lifetime.
|
||||
if err = s.cfg.depositCache.PruneProofs(ctx, int64(currIndex)); err != nil {
|
||||
return errors.Wrap(err, "could not prune deposit proofs")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -472,7 +472,7 @@ func TestInitDepositCacheWithFinalization_OK(t *testing.T) {
|
||||
require.NoError(t, s.cfg.beaconDB.SaveState(context.Background(), emptyState, headRoot))
|
||||
require.NoError(t, stateGen.SaveState(context.Background(), headRoot, emptyState))
|
||||
s.cfg.stateGen = stateGen
|
||||
require.NoError(t, emptyState.SetEth1DepositIndex(3))
|
||||
require.NoError(t, emptyState.SetEth1DepositIndex(2))
|
||||
|
||||
ctx := context.Background()
|
||||
require.NoError(t, beaconDB.SaveFinalizedCheckpoint(ctx, ðpb.Checkpoint{Epoch: slots.ToEpoch(0), Root: headRoot[:]}))
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -178,7 +179,7 @@ func writeSSZResponseHeaderAndBody(grpcResp *http.Response, w http.ResponseWrite
|
||||
} else {
|
||||
w.WriteHeader(grpcResp.StatusCode)
|
||||
}
|
||||
if _, err := io.Copy(w, io.NopCloser(bytes.NewReader(respSsz))); err != nil {
|
||||
if _, err := io.Copy(w, ioutil.NopCloser(bytes.NewReader(respSsz))); err != nil {
|
||||
return apimiddleware.InternalServerErrorWithMessage(err, "could not write response message")
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -36,7 +36,7 @@ func wrapFeeRecipientsArray(
|
||||
if err != nil {
|
||||
return false, apimiddleware.InternalServerErrorWithMessage(err, "could not marshal wrapped body")
|
||||
}
|
||||
req.Body = io.NopCloser(bytes.NewReader(b))
|
||||
req.Body = ioutil.NopCloser(bytes.NewReader(b))
|
||||
return true, nil
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ func wrapAttestationsArray(
|
||||
if err != nil {
|
||||
return false, apimiddleware.InternalServerErrorWithMessage(err, "could not marshal wrapped body")
|
||||
}
|
||||
req.Body = io.NopCloser(bytes.NewReader(b))
|
||||
req.Body = ioutil.NopCloser(bytes.NewReader(b))
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -79,7 +79,7 @@ func wrapValidatorIndicesArray(
|
||||
if err != nil {
|
||||
return false, apimiddleware.InternalServerErrorWithMessage(err, "could not marshal wrapped body")
|
||||
}
|
||||
req.Body = io.NopCloser(bytes.NewReader(b))
|
||||
req.Body = ioutil.NopCloser(bytes.NewReader(b))
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -101,7 +101,7 @@ func wrapSignedAggregateAndProofArray(
|
||||
if err != nil {
|
||||
return false, apimiddleware.InternalServerErrorWithMessage(err, "could not marshal wrapped body")
|
||||
}
|
||||
req.Body = io.NopCloser(bytes.NewReader(b))
|
||||
req.Body = ioutil.NopCloser(bytes.NewReader(b))
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -123,7 +123,7 @@ func wrapBeaconCommitteeSubscriptionsArray(
|
||||
if err != nil {
|
||||
return false, apimiddleware.InternalServerErrorWithMessage(err, "could not marshal wrapped body")
|
||||
}
|
||||
req.Body = io.NopCloser(bytes.NewReader(b))
|
||||
req.Body = ioutil.NopCloser(bytes.NewReader(b))
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -145,7 +145,7 @@ func wrapSyncCommitteeSubscriptionsArray(
|
||||
if err != nil {
|
||||
return false, apimiddleware.InternalServerErrorWithMessage(err, "could not marshal wrapped body")
|
||||
}
|
||||
req.Body = io.NopCloser(bytes.NewReader(b))
|
||||
req.Body = ioutil.NopCloser(bytes.NewReader(b))
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -167,7 +167,7 @@ func wrapSyncCommitteeSignaturesArray(
|
||||
if err != nil {
|
||||
return false, apimiddleware.InternalServerErrorWithMessage(err, "could not marshal wrapped body")
|
||||
}
|
||||
req.Body = io.NopCloser(bytes.NewReader(b))
|
||||
req.Body = ioutil.NopCloser(bytes.NewReader(b))
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -189,7 +189,7 @@ func wrapSignedContributionAndProofsArray(
|
||||
if err != nil {
|
||||
return false, apimiddleware.InternalServerErrorWithMessage(err, "could not marshal wrapped body")
|
||||
}
|
||||
req.Body = io.NopCloser(bytes.NewReader(b))
|
||||
req.Body = ioutil.NopCloser(bytes.NewReader(b))
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -224,7 +224,7 @@ func setInitialPublishBlockPostRequest(endpoint *apimiddleware.Endpoint,
|
||||
}
|
||||
}{}
|
||||
|
||||
buf, err := io.ReadAll(req.Body)
|
||||
buf, err := ioutil.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
return false, apimiddleware.InternalServerErrorWithMessage(err, "could not read body")
|
||||
}
|
||||
@@ -243,7 +243,7 @@ func setInitialPublishBlockPostRequest(endpoint *apimiddleware.Endpoint,
|
||||
} else {
|
||||
endpoint.PostRequest = &signedBeaconBlockBellatrixContainerJson{}
|
||||
}
|
||||
req.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
req.Body = ioutil.NopCloser(bytes.NewBuffer(buf))
|
||||
return true, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@ go_library(
|
||||
"//beacon-chain/state:go_default_library",
|
||||
"//beacon-chain/state/stategen:go_default_library",
|
||||
"//beacon-chain/sync:go_default_library",
|
||||
"//config/features:go_default_library",
|
||||
"//config/fieldparams:go_default_library",
|
||||
"//config/params:go_default_library",
|
||||
"//container/trie:go_default_library",
|
||||
@@ -139,6 +140,7 @@ go_test(
|
||||
"//beacon-chain/state/stategen/mock:go_default_library",
|
||||
"//beacon-chain/state/v1:go_default_library",
|
||||
"//beacon-chain/sync/initial-sync/testing:go_default_library",
|
||||
"//config/features:go_default_library",
|
||||
"//config/fieldparams:go_default_library",
|
||||
"//config/params:go_default_library",
|
||||
"//container/trie:go_default_library",
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state"
|
||||
"github.com/prysmaticlabs/prysm/config/features"
|
||||
"github.com/prysmaticlabs/prysm/config/params"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
"github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/attestation/aggregation"
|
||||
@@ -116,7 +117,16 @@ func (a proposerAtts) sortByProfitability() (proposerAtts, error) {
|
||||
if len(a) < 2 {
|
||||
return a, nil
|
||||
}
|
||||
return a.sortByProfitabilityUsingMaxCover()
|
||||
if features.Get().ProposerAttsSelectionUsingMaxCover {
|
||||
return a.sortByProfitabilityUsingMaxCover()
|
||||
}
|
||||
sort.Slice(a, func(i, j int) bool {
|
||||
if a[i].Data.Slot == a[j].Data.Slot {
|
||||
return a[i].AggregationBits.Count() > a[j].AggregationBits.Count()
|
||||
}
|
||||
return a[i].Data.Slot > a[j].Data.Slot
|
||||
})
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// sortByProfitabilityUsingMaxCover orders attestations by highest slot and by highest aggregation bit count.
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
types "github.com/prysmaticlabs/eth2-types"
|
||||
"github.com/prysmaticlabs/go-bitfield"
|
||||
"github.com/prysmaticlabs/prysm/config/features"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
"github.com/prysmaticlabs/prysm/testing/assert"
|
||||
"github.com/prysmaticlabs/prysm/testing/require"
|
||||
@@ -38,6 +39,11 @@ func TestProposer_ProposerAtts_sortByProfitability(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestProposer_ProposerAtts_sortByProfitabilityUsingMaxCover(t *testing.T) {
|
||||
resetCfg := features.InitWithReset(&features.Flags{
|
||||
ProposerAttsSelectionUsingMaxCover: true,
|
||||
})
|
||||
defer resetCfg()
|
||||
|
||||
type testData struct {
|
||||
slot types.Slot
|
||||
bits bitfield.Bitlist
|
||||
@@ -110,9 +116,38 @@ func TestProposer_ProposerAtts_sortByProfitabilityUsingMaxCover(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("compare to native sort", func(t *testing.T) {
|
||||
// The naive sort will end up with 0b11001000 being selected second (which is not optimal
|
||||
// as it only contains a single unknown bit).
|
||||
// The max-cover based approach will select 0b00001100 instead, despite lower bit count
|
||||
// (since it has two new/unknown bits).
|
||||
t.Run("naive", func(t *testing.T) {
|
||||
resetCfg := features.InitWithReset(&features.Flags{
|
||||
ProposerAttsSelectionUsingMaxCover: false,
|
||||
})
|
||||
defer resetCfg()
|
||||
|
||||
atts := getAtts([]testData{
|
||||
{1, bitfield.Bitlist{0b11000011, 0b1}},
|
||||
{1, bitfield.Bitlist{0b11001000, 0b1}},
|
||||
{1, bitfield.Bitlist{0b00001100, 0b1}},
|
||||
})
|
||||
want := getAtts([]testData{
|
||||
{1, bitfield.Bitlist{0b11000011, 0b1}},
|
||||
{1, bitfield.Bitlist{0b11001000, 0b1}},
|
||||
{1, bitfield.Bitlist{0b00001100, 0b1}},
|
||||
})
|
||||
atts, err := atts.sortByProfitability()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
require.DeepEqual(t, want, atts)
|
||||
})
|
||||
t.Run("max-cover", func(t *testing.T) {
|
||||
resetCfg := features.InitWithReset(&features.Flags{
|
||||
ProposerAttsSelectionUsingMaxCover: true,
|
||||
})
|
||||
defer resetCfg()
|
||||
|
||||
atts := getAtts([]testData{
|
||||
{1, bitfield.Bitlist{0b11000011, 0b1}},
|
||||
{1, bitfield.Bitlist{0b11001000, 0b1}},
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state"
|
||||
"github.com/prysmaticlabs/prysm/config/features"
|
||||
"github.com/prysmaticlabs/prysm/config/params"
|
||||
"github.com/prysmaticlabs/prysm/container/trie"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
@@ -17,6 +18,30 @@ import (
|
||||
)
|
||||
|
||||
func (vs *Server) packDepositsAndAttestations(ctx context.Context, head state.BeaconState, eth1Data *ethpb.Eth1Data) ([]*ethpb.Deposit, []*ethpb.Attestation, error) {
|
||||
if features.Get().EnableGetBlockOptimizations {
|
||||
deposits, atts, err := vs.optimizedPackDepositsAndAttestations(ctx, head, eth1Data)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return deposits, atts, nil
|
||||
}
|
||||
|
||||
// Pack ETH1 deposits which have not been included in the beacon chain.
|
||||
deposits, err := vs.deposits(ctx, head, eth1Data)
|
||||
if err != nil {
|
||||
return nil, nil, status.Errorf(codes.Internal, "Could not get ETH1 deposits: %v", err)
|
||||
}
|
||||
|
||||
// Pack aggregated attestations which have not been included in the beacon chain.
|
||||
atts, err := vs.packAttestations(ctx, head)
|
||||
if err != nil {
|
||||
return nil, nil, status.Errorf(codes.Internal, "Could not get attestations to pack into block: %v", err)
|
||||
}
|
||||
|
||||
return deposits, atts, nil
|
||||
}
|
||||
|
||||
func (vs *Server) optimizedPackDepositsAndAttestations(ctx context.Context, head state.BeaconState, eth1Data *ethpb.Eth1Data) ([]*ethpb.Deposit, []*ethpb.Attestation, error) {
|
||||
eg, egctx := errgroup.WithContext(ctx)
|
||||
var deposits []*ethpb.Deposit
|
||||
var atts []*ethpb.Attestation
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
types "github.com/prysmaticlabs/eth2-types"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state"
|
||||
"github.com/prysmaticlabs/prysm/config/features"
|
||||
"github.com/prysmaticlabs/prysm/config/params"
|
||||
"github.com/prysmaticlabs/prysm/crypto/hash"
|
||||
"github.com/prysmaticlabs/prysm/crypto/rand"
|
||||
@@ -48,6 +49,14 @@ func (vs *Server) eth1DataMajorityVote(ctx context.Context, beaconState state.Be
|
||||
earliestValidTime := votingPeriodStartTime - 2*params.BeaconConfig().SecondsPerETH1Block*eth1FollowDistance
|
||||
latestValidTime := votingPeriodStartTime - params.BeaconConfig().SecondsPerETH1Block*eth1FollowDistance
|
||||
|
||||
if !features.Get().EnableGetBlockOptimizations {
|
||||
_, err := vs.Eth1BlockFetcher.BlockByTimestamp(ctx, earliestValidTime)
|
||||
if err != nil {
|
||||
log.WithError(err).Error("Could not get last block by earliest valid time")
|
||||
return vs.randomETH1DataVote(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
lastBlockByLatestValidTime, err := vs.Eth1BlockFetcher.BlockByTimestamp(ctx, latestValidTime)
|
||||
if err != nil {
|
||||
log.WithError(err).Error("Could not get last block by latest valid time")
|
||||
|
||||
@@ -27,6 +27,7 @@ import (
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/stategen"
|
||||
v1 "github.com/prysmaticlabs/prysm/beacon-chain/state/v1"
|
||||
mockSync "github.com/prysmaticlabs/prysm/beacon-chain/sync/initial-sync/testing"
|
||||
"github.com/prysmaticlabs/prysm/config/features"
|
||||
fieldparams "github.com/prysmaticlabs/prysm/config/fieldparams"
|
||||
"github.com/prysmaticlabs/prysm/config/params"
|
||||
"github.com/prysmaticlabs/prysm/container/trie"
|
||||
@@ -2521,6 +2522,19 @@ func BenchmarkGetBlock(b *testing.B) {
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkOptimisedGetBlock(b *testing.B) {
|
||||
// enable block optimisations flag
|
||||
resetCfg := features.InitWithReset(&features.Flags{
|
||||
EnableGetBlockOptimizations: true,
|
||||
})
|
||||
defer resetCfg()
|
||||
proposerServer, beaconState, privKeys := setupGetBlock(b)
|
||||
ctx := context.Background()
|
||||
for n := 1; n < b.N; n++ {
|
||||
runGetBlock(ctx, b, proposerServer, beaconState, privKeys, n)
|
||||
}
|
||||
}
|
||||
|
||||
func runGetBlock(ctx context.Context, b *testing.B, proposerServer *Server, beaconState state.BeaconState, privKeys []bls.SecretKey, counter int) {
|
||||
randaoReveal, err := util.RandaoReveal(beaconState, 0, privKeys)
|
||||
require.NoError(b, err)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/prysmaticlabs/go-bitfield"
|
||||
"github.com/prysmaticlabs/prysm/config/features"
|
||||
"github.com/prysmaticlabs/prysm/config/params"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
aggtesting "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/attestation/aggregation/testing"
|
||||
@@ -54,8 +55,24 @@ func BenchmarkProposerAtts_sortByProfitability(b *testing.B) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
b.Run(fmt.Sprintf("naive_%s", tt.name), func(b *testing.B) {
|
||||
b.StopTimer()
|
||||
resetCfg := features.InitWithReset(&features.Flags{
|
||||
ProposerAttsSelectionUsingMaxCover: false,
|
||||
})
|
||||
defer resetCfg()
|
||||
atts := aggtesting.MakeAttestationsFromBitlists(tt.inputs)
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
runner(atts)
|
||||
}
|
||||
})
|
||||
b.Run(fmt.Sprintf("max-cover_%s", tt.name), func(b *testing.B) {
|
||||
b.StopTimer()
|
||||
resetCfg := features.InitWithReset(&features.Flags{
|
||||
ProposerAttsSelectionUsingMaxCover: true,
|
||||
})
|
||||
defer resetCfg()
|
||||
atts := aggtesting.MakeAttestationsFromBitlists(tt.inputs)
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package validator
|
||||
|
||||
import (
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
|
||||
"github.com/prysmaticlabs/prysm/config/params"
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
logrus.SetLevel(logrus.DebugLevel)
|
||||
logrus.SetOutput(io.Discard)
|
||||
logrus.SetOutput(ioutil.Discard)
|
||||
// Use minimal config to reduce test setup time.
|
||||
prevConfig := params.BeaconConfig().Copy()
|
||||
defer params.OverrideBeaconConfig(prevConfig)
|
||||
|
||||
@@ -116,14 +116,21 @@ type Config struct {
|
||||
// be registered into a running beacon node.
|
||||
func NewService(ctx context.Context, cfg *Config) *Service {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
s := &Service{
|
||||
return &Service{
|
||||
cfg: cfg,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
incomingAttestation: make(chan *ethpbv1alpha1.Attestation, params.BeaconConfig().DefaultBufferSize),
|
||||
connectedRPCClients: make(map[net.Addr]bool),
|
||||
}
|
||||
}
|
||||
|
||||
// paranoid build time check to ensure ChainInfoFetcher implements required interfaces
|
||||
var _ stategen.CanonicalChecker = blockchain.ChainInfoFetcher(nil)
|
||||
var _ stategen.CurrentSlotter = blockchain.ChainInfoFetcher(nil)
|
||||
|
||||
// Start the gRPC server.
|
||||
func (s *Service) Start() {
|
||||
address := fmt.Sprintf("%s:%s", s.cfg.Host, s.cfg.Port)
|
||||
lis, err := net.Listen("tcp", address)
|
||||
if err != nil {
|
||||
@@ -152,6 +159,7 @@ func NewService(ctx context.Context, cfg *Config) *Service {
|
||||
)),
|
||||
grpc.MaxRecvMsgSize(s.cfg.MaxMsgSize),
|
||||
}
|
||||
grpc_prometheus.EnableHandlingTimeHistogram()
|
||||
if s.cfg.CertFlag != "" && s.cfg.KeyFlag != "" {
|
||||
creds, err := credentials.NewServerTLSFromFile(s.cfg.CertFlag, s.cfg.KeyFlag)
|
||||
if err != nil {
|
||||
@@ -165,17 +173,6 @@ func NewService(ctx context.Context, cfg *Config) *Service {
|
||||
}
|
||||
s.grpcServer = grpc.NewServer(opts...)
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// paranoid build time check to ensure ChainInfoFetcher implements required interfaces
|
||||
var _ stategen.CanonicalChecker = blockchain.ChainInfoFetcher(nil)
|
||||
var _ stategen.CurrentSlotter = blockchain.ChainInfoFetcher(nil)
|
||||
|
||||
// Start the gRPC server.
|
||||
func (s *Service) Start() {
|
||||
grpc_prometheus.EnableHandlingTimeHistogram()
|
||||
|
||||
var stateCache stategen.CachedGetter
|
||||
if s.cfg.StateGen != nil {
|
||||
stateCache = s.cfg.StateGen.CombinedCache()
|
||||
|
||||
@@ -3,7 +3,7 @@ package rpc
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
|
||||
func init() {
|
||||
logrus.SetLevel(logrus.DebugLevel)
|
||||
logrus.SetOutput(io.Discard)
|
||||
logrus.SetOutput(ioutil.Discard)
|
||||
}
|
||||
|
||||
func TestLifecycle_OK(t *testing.T) {
|
||||
|
||||
@@ -2,7 +2,7 @@ package slasher
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -26,7 +26,7 @@ var _ = SlashingChecker(&mockslasher.MockSlashingChecker{})
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
logrus.SetLevel(logrus.DebugLevel)
|
||||
logrus.SetOutput(io.Discard)
|
||||
logrus.SetOutput(ioutil.Discard)
|
||||
|
||||
m.Run()
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ go_library(
|
||||
visibility = ["//beacon-chain:__subpackages__"],
|
||||
deps = [
|
||||
"//beacon-chain/state/state-native/custom-types:go_default_library",
|
||||
"//beacon-chain/state/state-native/types:go_default_library",
|
||||
"//beacon-chain/state/stateutil:go_default_library",
|
||||
"//beacon-chain/state/types:go_default_library",
|
||||
"//crypto/hash:go_default_library",
|
||||
|
||||
@@ -16,7 +16,7 @@ type FieldTrie struct {
|
||||
*sync.RWMutex
|
||||
reference *stateutil.Reference
|
||||
fieldLayers [][]*[32]byte
|
||||
field types.FieldIndex
|
||||
field types.FieldIdx
|
||||
dataType types.DataType
|
||||
length uint64
|
||||
numOfElems int
|
||||
@@ -25,7 +25,7 @@ type FieldTrie struct {
|
||||
// NewFieldTrie is the constructor for the field trie data structure. It creates the corresponding
|
||||
// trie according to the given parameters. Depending on whether the field is a basic/composite array
|
||||
// which is either fixed/variable length, it will appropriately determine the trie.
|
||||
func NewFieldTrie(field types.FieldIndex, dataType types.DataType, elements interface{}, length uint64) (*FieldTrie, error) {
|
||||
func NewFieldTrie(field types.FieldIdx, dataType types.DataType, elements interface{}, length uint64) (*FieldTrie, error) {
|
||||
if elements == nil {
|
||||
return &FieldTrie{
|
||||
field: field,
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"github.com/pkg/errors"
|
||||
customtypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/custom-types"
|
||||
nativetypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/types"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/types"
|
||||
"github.com/prysmaticlabs/prysm/crypto/hash"
|
||||
@@ -18,7 +19,7 @@ import (
|
||||
)
|
||||
|
||||
// ProofFromMerkleLayers creates a proof starting at the leaf index of the state Merkle layers.
|
||||
func ProofFromMerkleLayers(layers [][][]byte, startingLeafIndex types.FieldIndex) [][]byte {
|
||||
func ProofFromMerkleLayers(layers [][][]byte, startingLeafIndex int) [][]byte {
|
||||
// The merkle tree structure looks as follows:
|
||||
// [[r1, r2, r3, r4], [parent1, parent2], [root]]
|
||||
proof := make([][]byte, 0)
|
||||
@@ -49,7 +50,7 @@ func (f *FieldTrie) validateIndices(idxs []uint64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateElements(field types.FieldIndex, dataType types.DataType, elements interface{}, length uint64) error {
|
||||
func validateElements(field types.FieldIdx, dataType types.DataType, elements interface{}, length uint64) error {
|
||||
if dataType == types.CompressedArray {
|
||||
comLength, err := field.ElemsInChunk()
|
||||
if err != nil {
|
||||
@@ -65,68 +66,117 @@ func validateElements(field types.FieldIndex, dataType types.DataType, elements
|
||||
}
|
||||
|
||||
// fieldConverters converts the corresponding field and the provided elements to the appropriate roots.
|
||||
func fieldConverters(field types.FieldIndex, indices []uint64, elements interface{}, convertAll bool) ([][32]byte, error) {
|
||||
func fieldConverters(field types.FieldIdx, indices []uint64, elements interface{}, convertAll bool) ([][32]byte, error) {
|
||||
if field.Native() {
|
||||
switch field {
|
||||
case nativetypes.BlockRoots:
|
||||
return convertBlockRoots(indices, elements, convertAll)
|
||||
case nativetypes.StateRoots:
|
||||
return convertStateRoots(indices, elements, convertAll)
|
||||
case nativetypes.RandaoMixes:
|
||||
return convertRandaoMixes(indices, elements, convertAll)
|
||||
case nativetypes.Eth1DataVotes:
|
||||
return convertEth1DataVotes(indices, elements, convertAll)
|
||||
case nativetypes.Validators:
|
||||
return convertValidators(indices, elements, convertAll)
|
||||
case nativetypes.PreviousEpochAttestations, nativetypes.CurrentEpochAttestations:
|
||||
return convertAttestations(indices, elements, convertAll)
|
||||
case nativetypes.Balances:
|
||||
return convertBalances(indices, elements, convertAll)
|
||||
default:
|
||||
return [][32]byte{}, errors.Errorf("got unsupported type of %v", reflect.TypeOf(elements).Name())
|
||||
}
|
||||
}
|
||||
|
||||
switch field {
|
||||
case types.BlockRoots:
|
||||
switch val := elements.(type) {
|
||||
case [][]byte:
|
||||
return handleByteArrays(val, indices, convertAll)
|
||||
case *customtypes.BlockRoots:
|
||||
return handle32ByteArrays(val[:], indices, convertAll)
|
||||
default:
|
||||
return nil, errors.Errorf("Incorrect type used for block roots")
|
||||
}
|
||||
return convertBlockRoots(indices, elements, convertAll)
|
||||
case types.StateRoots:
|
||||
switch val := elements.(type) {
|
||||
case [][]byte:
|
||||
return handleByteArrays(val, indices, convertAll)
|
||||
case *customtypes.StateRoots:
|
||||
return handle32ByteArrays(val[:], indices, convertAll)
|
||||
default:
|
||||
return nil, errors.Errorf("Incorrect type used for state roots")
|
||||
}
|
||||
return convertStateRoots(indices, elements, convertAll)
|
||||
case types.RandaoMixes:
|
||||
switch val := elements.(type) {
|
||||
case [][]byte:
|
||||
return handleByteArrays(val, indices, convertAll)
|
||||
case *customtypes.RandaoMixes:
|
||||
return handle32ByteArrays(val[:], indices, convertAll)
|
||||
default:
|
||||
return nil, errors.Errorf("Incorrect type used for randao mixes")
|
||||
}
|
||||
return convertRandaoMixes(indices, elements, convertAll)
|
||||
case types.Eth1DataVotes:
|
||||
val, ok := elements.([]*ethpb.Eth1Data)
|
||||
if !ok {
|
||||
return nil, errors.Errorf("Wanted type of %v but got %v",
|
||||
reflect.TypeOf([]*ethpb.Eth1Data{}).Name(), reflect.TypeOf(elements).Name())
|
||||
}
|
||||
return handleEth1DataSlice(val, indices, convertAll)
|
||||
return convertEth1DataVotes(indices, elements, convertAll)
|
||||
case types.Validators:
|
||||
val, ok := elements.([]*ethpb.Validator)
|
||||
if !ok {
|
||||
return nil, errors.Errorf("Wanted type of %v but got %v",
|
||||
reflect.TypeOf([]*ethpb.Validator{}).Name(), reflect.TypeOf(elements).Name())
|
||||
}
|
||||
return handleValidatorSlice(val, indices, convertAll)
|
||||
return convertValidators(indices, elements, convertAll)
|
||||
case types.PreviousEpochAttestations, types.CurrentEpochAttestations:
|
||||
val, ok := elements.([]*ethpb.PendingAttestation)
|
||||
if !ok {
|
||||
return nil, errors.Errorf("Wanted type of %v but got %v",
|
||||
reflect.TypeOf([]*ethpb.PendingAttestation{}).Name(), reflect.TypeOf(elements).Name())
|
||||
}
|
||||
return handlePendingAttestationSlice(val, indices, convertAll)
|
||||
return convertAttestations(indices, elements, convertAll)
|
||||
case types.Balances:
|
||||
val, ok := elements.([]uint64)
|
||||
if !ok {
|
||||
return nil, errors.Errorf("Wanted type of %v but got %v",
|
||||
reflect.TypeOf([]uint64{}).Name(), reflect.TypeOf(elements).Name())
|
||||
}
|
||||
return handleBalanceSlice(val, indices, convertAll)
|
||||
return convertBalances(indices, elements, convertAll)
|
||||
default:
|
||||
return [][32]byte{}, errors.Errorf("got unsupported type of %v", reflect.TypeOf(elements).Name())
|
||||
}
|
||||
}
|
||||
|
||||
func convertBlockRoots(indices []uint64, elements interface{}, convertAll bool) ([][32]byte, error) {
|
||||
switch val := elements.(type) {
|
||||
case [][]byte:
|
||||
return handleByteArrays(val, indices, convertAll)
|
||||
case *customtypes.BlockRoots:
|
||||
return handle32ByteArrays(val[:], indices, convertAll)
|
||||
default:
|
||||
return nil, errors.Errorf("Incorrect type used for block roots")
|
||||
}
|
||||
}
|
||||
|
||||
func convertStateRoots(indices []uint64, elements interface{}, convertAll bool) ([][32]byte, error) {
|
||||
switch val := elements.(type) {
|
||||
case [][]byte:
|
||||
return handleByteArrays(val, indices, convertAll)
|
||||
case *customtypes.StateRoots:
|
||||
return handle32ByteArrays(val[:], indices, convertAll)
|
||||
default:
|
||||
return nil, errors.Errorf("Incorrect type used for state roots")
|
||||
}
|
||||
}
|
||||
|
||||
func convertRandaoMixes(indices []uint64, elements interface{}, convertAll bool) ([][32]byte, error) {
|
||||
switch val := elements.(type) {
|
||||
case [][]byte:
|
||||
return handleByteArrays(val, indices, convertAll)
|
||||
case *customtypes.RandaoMixes:
|
||||
return handle32ByteArrays(val[:], indices, convertAll)
|
||||
default:
|
||||
return nil, errors.Errorf("Incorrect type used for randao mixes")
|
||||
}
|
||||
}
|
||||
|
||||
func convertEth1DataVotes(indices []uint64, elements interface{}, convertAll bool) ([][32]byte, error) {
|
||||
val, ok := elements.([]*ethpb.Eth1Data)
|
||||
if !ok {
|
||||
return nil, errors.Errorf("Wanted type of %v but got %v",
|
||||
reflect.TypeOf([]*ethpb.Eth1Data{}).Name(), reflect.TypeOf(elements).Name())
|
||||
}
|
||||
return handleEth1DataSlice(val, indices, convertAll)
|
||||
}
|
||||
|
||||
func convertValidators(indices []uint64, elements interface{}, convertAll bool) ([][32]byte, error) {
|
||||
val, ok := elements.([]*ethpb.Validator)
|
||||
if !ok {
|
||||
return nil, errors.Errorf("Wanted type of %v but got %v",
|
||||
reflect.TypeOf([]*ethpb.Validator{}).Name(), reflect.TypeOf(elements).Name())
|
||||
}
|
||||
return handleValidatorSlice(val, indices, convertAll)
|
||||
}
|
||||
|
||||
func convertAttestations(indices []uint64, elements interface{}, convertAll bool) ([][32]byte, error) {
|
||||
val, ok := elements.([]*ethpb.PendingAttestation)
|
||||
if !ok {
|
||||
return nil, errors.Errorf("Wanted type of %v but got %v",
|
||||
reflect.TypeOf([]*ethpb.PendingAttestation{}).Name(), reflect.TypeOf(elements).Name())
|
||||
}
|
||||
return handlePendingAttestationSlice(val, indices, convertAll)
|
||||
}
|
||||
|
||||
func convertBalances(indices []uint64, elements interface{}, convertAll bool) ([][32]byte, error) {
|
||||
val, ok := elements.([]uint64)
|
||||
if !ok {
|
||||
return nil, errors.Errorf("Wanted type of %v but got %v",
|
||||
reflect.TypeOf([]uint64{}).Name(), reflect.TypeOf(elements).Name())
|
||||
}
|
||||
return handleBalanceSlice(val, indices, convertAll)
|
||||
}
|
||||
|
||||
// handleByteArrays computes and returns byte arrays in a slice of root format.
|
||||
func handleByteArrays(val [][]byte, indices []uint64, convertAll bool) ([][32]byte, error) {
|
||||
length := len(indices)
|
||||
|
||||
@@ -18,7 +18,7 @@ func TestFieldTrie_NewTrie(t *testing.T) {
|
||||
newState, _ := util.DeterministicGenesisState(t, 40)
|
||||
|
||||
// 5 represents the enum value of state roots
|
||||
trie, err := fieldtrie.NewFieldTrie(5, stateTypes.BasicArray, newState.StateRoots(), uint64(params.BeaconConfig().SlotsPerHistoricalRoot))
|
||||
trie, err := fieldtrie.NewFieldTrie(stateTypes.FieldIndex(5), stateTypes.BasicArray, newState.StateRoots(), uint64(params.BeaconConfig().SlotsPerHistoricalRoot))
|
||||
require.NoError(t, err)
|
||||
root, err := stateutil.RootsArrayHashTreeRoot(newState.StateRoots(), uint64(params.BeaconConfig().SlotsPerHistoricalRoot))
|
||||
require.NoError(t, err)
|
||||
@@ -30,7 +30,7 @@ func TestFieldTrie_NewTrie(t *testing.T) {
|
||||
func TestFieldTrie_RecomputeTrie(t *testing.T) {
|
||||
newState, _ := util.DeterministicGenesisState(t, 32)
|
||||
// 10 represents the enum value of validators
|
||||
trie, err := fieldtrie.NewFieldTrie(11, stateTypes.CompositeArray, newState.Validators(), params.BeaconConfig().ValidatorRegistryLimit)
|
||||
trie, err := fieldtrie.NewFieldTrie(stateTypes.FieldIndex(11), stateTypes.CompositeArray, newState.Validators(), params.BeaconConfig().ValidatorRegistryLimit)
|
||||
require.NoError(t, err)
|
||||
|
||||
changedIdx := []uint64{2, 29}
|
||||
@@ -58,7 +58,7 @@ func TestFieldTrie_RecomputeTrie(t *testing.T) {
|
||||
func TestFieldTrie_CopyTrieImmutable(t *testing.T) {
|
||||
newState, _ := util.DeterministicGenesisState(t, 32)
|
||||
// 12 represents the enum value of randao mixes.
|
||||
trie, err := fieldtrie.NewFieldTrie(13, stateTypes.BasicArray, newState.RandaoMixes(), uint64(params.BeaconConfig().EpochsPerHistoricalVector))
|
||||
trie, err := fieldtrie.NewFieldTrie(stateTypes.FieldIndex(13), stateTypes.BasicArray, newState.RandaoMixes(), uint64(params.BeaconConfig().EpochsPerHistoricalVector))
|
||||
require.NoError(t, err)
|
||||
|
||||
newTrie := trie.CopyTrie()
|
||||
|
||||
76
beacon-chain/state/state-native/BUILD.bazel
Normal file
76
beacon-chain/state/state-native/BUILD.bazel
Normal file
@@ -0,0 +1,76 @@
|
||||
load("@prysm//tools/go:def.bzl", "go_library")
|
||||
|
||||
go_library(
|
||||
name = "go_default_library",
|
||||
srcs = [
|
||||
"doc.go",
|
||||
"getters_attestation.go",
|
||||
"getters_block.go",
|
||||
"getters_checkpoint.go",
|
||||
"getters_eth1.go",
|
||||
"getters_misc.go",
|
||||
"getters_participation.go",
|
||||
"getters_payload_header.go",
|
||||
"getters_randao.go",
|
||||
"getters_state.go",
|
||||
"getters_sync_committee.go",
|
||||
"getters_validator.go",
|
||||
"proofs.go",
|
||||
"readonly_validator.go",
|
||||
"setters_attestation.go",
|
||||
"setters_block.go",
|
||||
"setters_checkpoint.go",
|
||||
"setters_eth1.go",
|
||||
"setters_misc.go",
|
||||
"setters_participation.go",
|
||||
"setters_payload_header.go",
|
||||
"setters_randao.go",
|
||||
"setters_state.go",
|
||||
"setters_sync_committee.go",
|
||||
"setters_validator.go",
|
||||
"ssz.go",
|
||||
"state_trie.go",
|
||||
"types.go",
|
||||
] + select({
|
||||
"//config:mainnet": ["beacon_state_mainnet.go"],
|
||||
"//config:minimal": ["beacon_state_minimal.go"],
|
||||
}),
|
||||
importpath = "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native",
|
||||
visibility = [
|
||||
"//beacon-chain:__subpackages__",
|
||||
"//contracts/deposit:__subpackages__",
|
||||
"//proto/migration:__subpackages__",
|
||||
"//proto/prysm/v1alpha1:__subpackages__",
|
||||
"//proto/testing:__subpackages__",
|
||||
"//runtime/interop:__subpackages__",
|
||||
"//slasher/rpc:__subpackages__",
|
||||
"//testing/benchmark:__pkg__",
|
||||
"//testing/fuzz:__pkg__",
|
||||
"//testing/spectest:__subpackages__",
|
||||
"//testing/util:__pkg__",
|
||||
"//tools/benchmark-files-gen:__pkg__",
|
||||
"//tools/pcli:__pkg__",
|
||||
],
|
||||
deps = [
|
||||
"//beacon-chain/state:go_default_library",
|
||||
"//beacon-chain/state/fieldtrie:go_default_library",
|
||||
"//beacon-chain/state/state-native/custom-types:go_default_library",
|
||||
"//beacon-chain/state/state-native/types:go_default_library",
|
||||
"//beacon-chain/state/stateutil:go_default_library",
|
||||
"//beacon-chain/state/types:go_default_library",
|
||||
"//config/features:go_default_library",
|
||||
"//config/fieldparams:go_default_library",
|
||||
"//config/params:go_default_library",
|
||||
"//container/slice:go_default_library",
|
||||
"//crypto/hash:go_default_library",
|
||||
"//encoding/bytesutil:go_default_library",
|
||||
"//encoding/ssz:go_default_library",
|
||||
"//proto/prysm/v1alpha1:go_default_library",
|
||||
"//runtime/version:go_default_library",
|
||||
"@com_github_pkg_errors//:go_default_library",
|
||||
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
|
||||
"@com_github_prysmaticlabs_go_bitfield//:go_default_library",
|
||||
"@io_opencensus_go//trace:go_default_library",
|
||||
"@org_golang_google_protobuf//proto:go_default_library",
|
||||
],
|
||||
)
|
||||
@@ -1,7 +1,7 @@
|
||||
//go:build !minimal
|
||||
// +build !minimal
|
||||
|
||||
package v3
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"sync"
|
||||
@@ -10,14 +10,15 @@ import (
|
||||
"github.com/prysmaticlabs/go-bitfield"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/fieldtrie"
|
||||
customtypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/custom-types"
|
||||
nativetypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/types"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/types"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
)
|
||||
|
||||
// BeaconState defines a struct containing utilities for the eth2 chain state, defining
|
||||
// BeaconState defines a struct containing utilities for the Ethereum Beacon Chain state, defining
|
||||
// getters and setters for its respective values and helpful functions such as HashTreeRoot().
|
||||
type BeaconState struct {
|
||||
version int
|
||||
genesisTime uint64 `ssz-gen:"true"`
|
||||
genesisValidatorsRoot customtypes.Byte32 `ssz-gen:"true" ssz-size:"32"`
|
||||
slot eth2types.Slot `ssz-gen:"true"`
|
||||
@@ -33,6 +34,8 @@ type BeaconState struct {
|
||||
balances []uint64 `ssz-gen:"true" ssz-max:"1099511627776"`
|
||||
randaoMixes *customtypes.RandaoMixes `ssz-gen:"true" ssz-size:"65536,32"`
|
||||
slashings []uint64 `ssz-gen:"true" ssz-size:"8192"`
|
||||
previousEpochAttestations []*ethpb.PendingAttestation `ssz-gen:"true" ssz-max:"4096"`
|
||||
currentEpochAttestations []*ethpb.PendingAttestation `ssz-gen:"true" ssz-max:"4096"`
|
||||
previousEpochParticipation []byte `ssz-gen:"true" ssz-max:"1099511627776"`
|
||||
currentEpochParticipation []byte `ssz-gen:"true" ssz-max:"1099511627776"`
|
||||
justificationBits bitfield.Bitvector4 `ssz-gen:"true" ssz-size:"1"`
|
||||
@@ -45,11 +48,12 @@ type BeaconState struct {
|
||||
latestExecutionPayloadHeader *ethpb.ExecutionPayloadHeader `ssz-gen:"true"`
|
||||
|
||||
lock sync.RWMutex
|
||||
dirtyFields map[types.FieldIndex]bool
|
||||
dirtyIndices map[types.FieldIndex][]uint64
|
||||
stateFieldLeaves map[types.FieldIndex]*fieldtrie.FieldTrie
|
||||
rebuildTrie map[types.FieldIndex]bool
|
||||
fieldIndexesRev map[nativetypes.FieldIndex]int
|
||||
dirtyFields map[nativetypes.FieldIndex]bool
|
||||
dirtyIndices map[nativetypes.FieldIndex][]uint64
|
||||
stateFieldLeaves map[nativetypes.FieldIndex]*fieldtrie.FieldTrie
|
||||
rebuildTrie map[nativetypes.FieldIndex]bool
|
||||
valMapHandler *stateutil.ValidatorMapHandler
|
||||
merkleLayers [][][]byte
|
||||
sharedFieldReferences map[types.FieldIndex]*stateutil.Reference
|
||||
sharedFieldReferences map[nativetypes.FieldIndex]*stateutil.Reference
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//go:build minimal
|
||||
// +build minimal
|
||||
|
||||
package v3
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"sync"
|
||||
@@ -10,14 +10,15 @@ import (
|
||||
"github.com/prysmaticlabs/go-bitfield"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/fieldtrie"
|
||||
customtypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/custom-types"
|
||||
nativetypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/types"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/types"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
)
|
||||
|
||||
// BeaconState defines a struct containing utilities for the eth2 chain state, defining
|
||||
// BeaconState defines a struct containing utilities for the Ethereum Beacon Chain state, defining
|
||||
// getters and setters for its respective values and helpful functions such as HashTreeRoot().
|
||||
type BeaconState struct {
|
||||
version int
|
||||
genesisTime uint64 `ssz-gen:"true"`
|
||||
genesisValidatorsRoot customtypes.Byte32 `ssz-gen:"true" ssz-size:"32"`
|
||||
slot eth2types.Slot `ssz-gen:"true"`
|
||||
@@ -33,6 +34,8 @@ type BeaconState struct {
|
||||
balances []uint64 `ssz-gen:"true" ssz-max:"1099511627776"`
|
||||
randaoMixes *customtypes.RandaoMixes `ssz-gen:"true" ssz-size:"64,32"`
|
||||
slashings []uint64 `ssz-gen:"true" ssz-size:"64"`
|
||||
previousEpochAttestations []*ethpb.PendingAttestation `ssz-gen:"true" ssz-max:"1024"`
|
||||
currentEpochAttestations []*ethpb.PendingAttestation `ssz-gen:"true" ssz-max:"1024"`
|
||||
previousEpochParticipation []byte `ssz-gen:"true" ssz-max:"1099511627776"`
|
||||
currentEpochParticipation []byte `ssz-gen:"true" ssz-max:"1099511627776"`
|
||||
justificationBits bitfield.Bitvector4 `ssz-gen:"true" ssz-size:"1"`
|
||||
@@ -45,11 +48,12 @@ type BeaconState struct {
|
||||
latestExecutionPayloadHeader *ethpb.ExecutionPayloadHeader `ssz-gen:"true"`
|
||||
|
||||
lock sync.RWMutex
|
||||
dirtyFields map[types.FieldIndex]bool
|
||||
dirtyIndices map[types.FieldIndex][]uint64
|
||||
stateFieldLeaves map[types.FieldIndex]*fieldtrie.FieldTrie
|
||||
rebuildTrie map[types.FieldIndex]bool
|
||||
fieldIndexesRev map[nativetypes.FieldIndex]int
|
||||
dirtyFields map[nativetypes.FieldIndex]bool
|
||||
dirtyIndices map[nativetypes.FieldIndex][]uint64
|
||||
stateFieldLeaves map[nativetypes.FieldIndex]*fieldtrie.FieldTrie
|
||||
rebuildTrie map[nativetypes.FieldIndex]bool
|
||||
valMapHandler *stateutil.ValidatorMapHandler
|
||||
merkleLayers [][][]byte
|
||||
sharedFieldReferences map[types.FieldIndex]*stateutil.Reference
|
||||
sharedFieldReferences map[nativetypes.FieldIndex]*stateutil.Reference
|
||||
}
|
||||
@@ -37,4 +37,4 @@
|
||||
// Although it is technically possible to remove the short-circuit conditions
|
||||
// from the external function, that would require every read to obtain a lock
|
||||
// even if the data was not present, leading to potential slowdowns.
|
||||
package v1
|
||||
package state_native
|
||||
@@ -1,4 +1,4 @@
|
||||
package v1
|
||||
package state_native
|
||||
|
||||
import (
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
@@ -1,4 +1,4 @@
|
||||
package v1
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -1,4 +1,4 @@
|
||||
package v3
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -1,4 +1,4 @@
|
||||
package v2
|
||||
package state_native
|
||||
|
||||
import (
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
@@ -1,9 +1,8 @@
|
||||
package v1
|
||||
package state_native
|
||||
|
||||
import (
|
||||
types "github.com/prysmaticlabs/eth2-types"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
"github.com/prysmaticlabs/prysm/runtime/version"
|
||||
)
|
||||
|
||||
// GenesisTime of the beacon state as a uint64.
|
||||
@@ -25,8 +24,8 @@ func (b *BeaconState) GenesisValidatorsRoot() []byte {
|
||||
// Version of the beacon state. This method
|
||||
// is strictly meant to be used without a lock
|
||||
// internally.
|
||||
func (_ *BeaconState) Version() int {
|
||||
return version.Phase0
|
||||
func (b *BeaconState) Version() int {
|
||||
return b.version
|
||||
}
|
||||
|
||||
// Slot of the current beacon chain state.
|
||||
@@ -1,4 +1,4 @@
|
||||
package v2
|
||||
package state_native
|
||||
|
||||
// CurrentEpochParticipation corresponding to participation bits on the beacon chain.
|
||||
func (b *BeaconState) CurrentEpochParticipation() ([]byte, error) {
|
||||
@@ -1,4 +1,4 @@
|
||||
package v3
|
||||
package state_native
|
||||
|
||||
import (
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
@@ -1,4 +1,4 @@
|
||||
package v3
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -1,4 +1,4 @@
|
||||
package v1
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -116,9 +116,9 @@ func (b *BeaconState) stateRootAtIndex(idx uint64) ([32]byte, error) {
|
||||
return b.stateRoots[idx], nil
|
||||
}
|
||||
|
||||
// ProtobufBeaconState transforms an input into beacon state in the form of protobuf.
|
||||
// ProtobufBeaconStatePhase0 transforms an input into beacon state in the form of protobuf.
|
||||
// Error is returned if the input is not type protobuf beacon state.
|
||||
func ProtobufBeaconState(s interface{}) (*ethpb.BeaconState, error) {
|
||||
func ProtobufBeaconStatePhase0(s interface{}) (*ethpb.BeaconState, error) {
|
||||
pbState, ok := s.(*ethpb.BeaconState)
|
||||
if !ok {
|
||||
return nil, errors.New("input is not type ethpb.BeaconState")
|
||||
@@ -1,4 +1,4 @@
|
||||
package v3
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"github.com/prysmaticlabs/prysm/encoding/bytesutil"
|
||||
@@ -1,4 +1,4 @@
|
||||
package v3
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"github.com/pkg/errors"
|
||||
types "github.com/prysmaticlabs/eth2-types"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state"
|
||||
v1 "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/v1"
|
||||
fieldparams "github.com/prysmaticlabs/prysm/config/fieldparams"
|
||||
"github.com/prysmaticlabs/prysm/encoding/bytesutil"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
@@ -111,7 +110,7 @@ func (b *BeaconState) ValidatorAtIndexReadOnly(idx types.ValidatorIndex) (state.
|
||||
b.lock.RLock()
|
||||
defer b.lock.RUnlock()
|
||||
|
||||
return v1.NewValidator(b.validators[idx])
|
||||
return NewValidator(b.validators[idx])
|
||||
}
|
||||
|
||||
// ValidatorIndexByPubkey returns a given validator by its 48-byte public key.
|
||||
@@ -164,7 +163,7 @@ func (b *BeaconState) ReadFromEveryValidator(f func(idx int, val state.ReadOnlyV
|
||||
b.lock.RUnlock()
|
||||
|
||||
for i, v := range validators {
|
||||
v, err := v1.NewValidator(v)
|
||||
v, err := NewValidator(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package v1
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/fieldtrie"
|
||||
nativetypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/types"
|
||||
"github.com/prysmaticlabs/prysm/encoding/bytesutil"
|
||||
)
|
||||
|
||||
@@ -48,7 +49,7 @@ func (b *BeaconState) FinalizedRootProof(ctx context.Context) ([][]byte, error)
|
||||
epochRoot := bytesutil.ToBytes32(epochBuf)
|
||||
proof := make([][]byte, 0)
|
||||
proof = append(proof, epochRoot[:])
|
||||
branch := fieldtrie.ProofFromMerkleLayers(b.merkleLayers, finalizedCheckpoint)
|
||||
branch := fieldtrie.ProofFromMerkleLayers(b.merkleLayers, b.fieldIndexesRev[nativetypes.FinalizedCheckpoint])
|
||||
proof = append(proof, branch...)
|
||||
return proof, nil
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package v1
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
@@ -1,8 +1,9 @@
|
||||
package v1
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
nativetypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/types"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
|
||||
fieldparams "github.com/prysmaticlabs/prysm/config/fieldparams"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
@@ -20,21 +21,21 @@ func (b *BeaconState) RotateAttestations() error {
|
||||
}
|
||||
|
||||
func (b *BeaconState) setPreviousEpochAttestations(val []*ethpb.PendingAttestation) {
|
||||
b.sharedFieldReferences[previousEpochAttestations].MinusRef()
|
||||
b.sharedFieldReferences[previousEpochAttestations] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.PreviousEpochAttestations].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.PreviousEpochAttestations] = stateutil.NewRef(1)
|
||||
|
||||
b.previousEpochAttestations = val
|
||||
b.markFieldAsDirty(previousEpochAttestations)
|
||||
b.rebuildTrie[previousEpochAttestations] = true
|
||||
b.markFieldAsDirty(nativetypes.PreviousEpochAttestations)
|
||||
b.rebuildTrie[nativetypes.PreviousEpochAttestations] = true
|
||||
}
|
||||
|
||||
func (b *BeaconState) setCurrentEpochAttestations(val []*ethpb.PendingAttestation) {
|
||||
b.sharedFieldReferences[currentEpochAttestations].MinusRef()
|
||||
b.sharedFieldReferences[currentEpochAttestations] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.CurrentEpochAttestations].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.CurrentEpochAttestations] = stateutil.NewRef(1)
|
||||
|
||||
b.currentEpochAttestations = val
|
||||
b.markFieldAsDirty(currentEpochAttestations)
|
||||
b.rebuildTrie[currentEpochAttestations] = true
|
||||
b.markFieldAsDirty(nativetypes.CurrentEpochAttestations)
|
||||
b.rebuildTrie[nativetypes.CurrentEpochAttestations] = true
|
||||
}
|
||||
|
||||
// AppendCurrentEpochAttestations for the beacon state. Appends the new value
|
||||
@@ -49,17 +50,17 @@ func (b *BeaconState) AppendCurrentEpochAttestations(val *ethpb.PendingAttestati
|
||||
return fmt.Errorf("current pending attestation exceeds max length %d", max)
|
||||
}
|
||||
|
||||
if b.sharedFieldReferences[currentEpochAttestations].Refs() > 1 {
|
||||
if b.sharedFieldReferences[nativetypes.CurrentEpochAttestations].Refs() > 1 {
|
||||
// Copy elements in underlying array by reference.
|
||||
atts = make([]*ethpb.PendingAttestation, len(b.currentEpochAttestations))
|
||||
copy(atts, b.currentEpochAttestations)
|
||||
b.sharedFieldReferences[currentEpochAttestations].MinusRef()
|
||||
b.sharedFieldReferences[currentEpochAttestations] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.CurrentEpochAttestations].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.CurrentEpochAttestations] = stateutil.NewRef(1)
|
||||
}
|
||||
|
||||
b.currentEpochAttestations = append(atts, val)
|
||||
b.markFieldAsDirty(currentEpochAttestations)
|
||||
b.addDirtyIndices(currentEpochAttestations, []uint64{uint64(len(b.currentEpochAttestations) - 1)})
|
||||
b.markFieldAsDirty(nativetypes.CurrentEpochAttestations)
|
||||
b.addDirtyIndices(nativetypes.CurrentEpochAttestations, []uint64{uint64(len(b.currentEpochAttestations) - 1)})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -75,15 +76,15 @@ func (b *BeaconState) AppendPreviousEpochAttestations(val *ethpb.PendingAttestat
|
||||
return fmt.Errorf("previous pending attestation exceeds max length %d", max)
|
||||
}
|
||||
|
||||
if b.sharedFieldReferences[previousEpochAttestations].Refs() > 1 {
|
||||
if b.sharedFieldReferences[nativetypes.PreviousEpochAttestations].Refs() > 1 {
|
||||
atts = make([]*ethpb.PendingAttestation, len(b.previousEpochAttestations))
|
||||
copy(atts, b.previousEpochAttestations)
|
||||
b.sharedFieldReferences[previousEpochAttestations].MinusRef()
|
||||
b.sharedFieldReferences[previousEpochAttestations] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.PreviousEpochAttestations].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.PreviousEpochAttestations] = stateutil.NewRef(1)
|
||||
}
|
||||
|
||||
b.previousEpochAttestations = append(atts, val)
|
||||
b.markFieldAsDirty(previousEpochAttestations)
|
||||
b.addDirtyIndices(previousEpochAttestations, []uint64{uint64(len(b.previousEpochAttestations) - 1)})
|
||||
b.markFieldAsDirty(nativetypes.PreviousEpochAttestations)
|
||||
b.addDirtyIndices(nativetypes.PreviousEpochAttestations, []uint64{uint64(len(b.previousEpochAttestations) - 1)})
|
||||
return nil
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
package v1
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
customtypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/custom-types"
|
||||
nativetypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/types"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
|
||||
fieldparams "github.com/prysmaticlabs/prysm/config/fieldparams"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
@@ -15,7 +16,7 @@ func (b *BeaconState) SetLatestBlockHeader(val *ethpb.BeaconBlockHeader) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.latestBlockHeader = ethpb.CopyBeaconBlockHeader(val)
|
||||
b.markFieldAsDirty(latestBlockHeader)
|
||||
b.markFieldAsDirty(nativetypes.LatestBlockHeader)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -25,8 +26,8 @@ func (b *BeaconState) SetBlockRoots(val [][]byte) error {
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.sharedFieldReferences[blockRoots].MinusRef()
|
||||
b.sharedFieldReferences[blockRoots] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.BlockRoots].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.BlockRoots] = stateutil.NewRef(1)
|
||||
|
||||
var rootsArr [fieldparams.BlockRootsLength][32]byte
|
||||
for i := 0; i < len(rootsArr); i++ {
|
||||
@@ -34,8 +35,8 @@ func (b *BeaconState) SetBlockRoots(val [][]byte) error {
|
||||
}
|
||||
roots := customtypes.BlockRoots(rootsArr)
|
||||
b.blockRoots = &roots
|
||||
b.markFieldAsDirty(blockRoots)
|
||||
b.rebuildTrie[blockRoots] = true
|
||||
b.markFieldAsDirty(nativetypes.BlockRoots)
|
||||
b.rebuildTrie[nativetypes.BlockRoots] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -49,19 +50,19 @@ func (b *BeaconState) UpdateBlockRootAtIndex(idx uint64, blockRoot [32]byte) err
|
||||
defer b.lock.Unlock()
|
||||
|
||||
r := b.blockRoots
|
||||
if ref := b.sharedFieldReferences[blockRoots]; ref.Refs() > 1 {
|
||||
if ref := b.sharedFieldReferences[nativetypes.BlockRoots]; ref.Refs() > 1 {
|
||||
// Copy elements in underlying array by reference.
|
||||
roots := *b.blockRoots
|
||||
rootsCopy := roots
|
||||
r = &rootsCopy
|
||||
ref.MinusRef()
|
||||
b.sharedFieldReferences[blockRoots] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.BlockRoots] = stateutil.NewRef(1)
|
||||
}
|
||||
|
||||
r[idx] = blockRoot
|
||||
b.blockRoots = r
|
||||
|
||||
b.markFieldAsDirty(blockRoots)
|
||||
b.addDirtyIndices(blockRoots, []uint64{idx})
|
||||
b.markFieldAsDirty(nativetypes.BlockRoots)
|
||||
b.addDirtyIndices(nativetypes.BlockRoots, []uint64{idx})
|
||||
return nil
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
package v2
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"github.com/prysmaticlabs/go-bitfield"
|
||||
nativetypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/types"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
)
|
||||
|
||||
@@ -11,7 +12,7 @@ func (b *BeaconState) SetJustificationBits(val bitfield.Bitvector4) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.justificationBits = val
|
||||
b.markFieldAsDirty(justificationBits)
|
||||
b.markFieldAsDirty(nativetypes.JustificationBits)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -21,7 +22,7 @@ func (b *BeaconState) SetPreviousJustifiedCheckpoint(val *ethpb.Checkpoint) erro
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.previousJustifiedCheckpoint = val
|
||||
b.markFieldAsDirty(previousJustifiedCheckpoint)
|
||||
b.markFieldAsDirty(nativetypes.PreviousJustifiedCheckpoint)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -31,7 +32,7 @@ func (b *BeaconState) SetCurrentJustifiedCheckpoint(val *ethpb.Checkpoint) error
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.currentJustifiedCheckpoint = val
|
||||
b.markFieldAsDirty(currentJustifiedCheckpoint)
|
||||
b.markFieldAsDirty(nativetypes.CurrentJustifiedCheckpoint)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -41,6 +42,6 @@ func (b *BeaconState) SetFinalizedCheckpoint(val *ethpb.Checkpoint) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.finalizedCheckpoint = val
|
||||
b.markFieldAsDirty(finalizedCheckpoint)
|
||||
b.markFieldAsDirty(nativetypes.FinalizedCheckpoint)
|
||||
return nil
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package v3
|
||||
package state_native
|
||||
|
||||
import (
|
||||
nativetypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/types"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
)
|
||||
@@ -11,7 +12,7 @@ func (b *BeaconState) SetEth1Data(val *ethpb.Eth1Data) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.eth1Data = val
|
||||
b.markFieldAsDirty(eth1Data)
|
||||
b.markFieldAsDirty(nativetypes.Eth1Data)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -21,12 +22,12 @@ func (b *BeaconState) SetEth1DataVotes(val []*ethpb.Eth1Data) error {
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.sharedFieldReferences[eth1DataVotes].MinusRef()
|
||||
b.sharedFieldReferences[eth1DataVotes] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.Eth1DataVotes].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.Eth1DataVotes] = stateutil.NewRef(1)
|
||||
|
||||
b.eth1DataVotes = val
|
||||
b.markFieldAsDirty(eth1DataVotes)
|
||||
b.rebuildTrie[eth1DataVotes] = true
|
||||
b.markFieldAsDirty(nativetypes.Eth1DataVotes)
|
||||
b.rebuildTrie[nativetypes.Eth1DataVotes] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -36,7 +37,7 @@ func (b *BeaconState) SetEth1DepositIndex(val uint64) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.eth1DepositIndex = val
|
||||
b.markFieldAsDirty(eth1DepositIndex)
|
||||
b.markFieldAsDirty(nativetypes.Eth1DepositIndex)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -47,16 +48,16 @@ func (b *BeaconState) AppendEth1DataVotes(val *ethpb.Eth1Data) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
votes := b.eth1DataVotes
|
||||
if b.sharedFieldReferences[eth1DataVotes].Refs() > 1 {
|
||||
if b.sharedFieldReferences[nativetypes.Eth1DataVotes].Refs() > 1 {
|
||||
// Copy elements in underlying array by reference.
|
||||
votes = make([]*ethpb.Eth1Data, len(b.eth1DataVotes))
|
||||
copy(votes, b.eth1DataVotes)
|
||||
b.sharedFieldReferences[eth1DataVotes].MinusRef()
|
||||
b.sharedFieldReferences[eth1DataVotes] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.Eth1DataVotes].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.Eth1DataVotes] = stateutil.NewRef(1)
|
||||
}
|
||||
|
||||
b.eth1DataVotes = append(votes, val)
|
||||
b.markFieldAsDirty(eth1DataVotes)
|
||||
b.addDirtyIndices(eth1DataVotes, []uint64{uint64(len(b.eth1DataVotes) - 1)})
|
||||
b.markFieldAsDirty(nativetypes.Eth1DataVotes)
|
||||
b.addDirtyIndices(nativetypes.Eth1DataVotes, []uint64{uint64(len(b.eth1DataVotes) - 1)})
|
||||
return nil
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
package v1
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
types "github.com/prysmaticlabs/eth2-types"
|
||||
nativetypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/types"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
|
||||
stateTypes "github.com/prysmaticlabs/prysm/beacon-chain/state/types"
|
||||
"github.com/prysmaticlabs/prysm/config/features"
|
||||
fieldparams "github.com/prysmaticlabs/prysm/config/fieldparams"
|
||||
"github.com/prysmaticlabs/prysm/crypto/hash"
|
||||
@@ -47,7 +47,7 @@ func (b *BeaconState) SetGenesisTime(val uint64) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.genesisTime = val
|
||||
b.markFieldAsDirty(genesisTime)
|
||||
b.markFieldAsDirty(nativetypes.GenesisTime)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ func (b *BeaconState) SetGenesisValidatorsRoot(val []byte) error {
|
||||
return errors.New("incorrect validators root length")
|
||||
}
|
||||
b.genesisValidatorsRoot = bytesutil.ToBytes32(val)
|
||||
b.markFieldAsDirty(genesisValidatorsRoot)
|
||||
b.markFieldAsDirty(nativetypes.GenesisValidatorsRoot)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ func (b *BeaconState) SetSlot(val types.Slot) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.slot = val
|
||||
b.markFieldAsDirty(slot)
|
||||
b.markFieldAsDirty(nativetypes.Slot)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ func (b *BeaconState) SetFork(val *ethpb.Fork) error {
|
||||
return errors.New("proto.Clone did not return a fork proto")
|
||||
}
|
||||
b.fork = fk
|
||||
b.markFieldAsDirty(fork)
|
||||
b.markFieldAsDirty(nativetypes.Fork)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -94,15 +94,15 @@ func (b *BeaconState) SetHistoricalRoots(val [][]byte) error {
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.sharedFieldReferences[historicalRoots].MinusRef()
|
||||
b.sharedFieldReferences[historicalRoots] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.HistoricalRoots].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.HistoricalRoots] = stateutil.NewRef(1)
|
||||
|
||||
roots := make([][32]byte, len(val))
|
||||
for i, r := range val {
|
||||
copy(roots[i][:], r)
|
||||
}
|
||||
b.historicalRoots = roots
|
||||
b.markFieldAsDirty(historicalRoots)
|
||||
b.markFieldAsDirty(nativetypes.HistoricalRoots)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -113,15 +113,15 @@ func (b *BeaconState) AppendHistoricalRoots(root [32]byte) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
roots := b.historicalRoots
|
||||
if b.sharedFieldReferences[historicalRoots].Refs() > 1 {
|
||||
if b.sharedFieldReferences[nativetypes.HistoricalRoots].Refs() > 1 {
|
||||
roots = make([][32]byte, len(b.historicalRoots))
|
||||
copy(roots, b.historicalRoots)
|
||||
b.sharedFieldReferences[historicalRoots].MinusRef()
|
||||
b.sharedFieldReferences[historicalRoots] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.HistoricalRoots].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.HistoricalRoots] = stateutil.NewRef(1)
|
||||
}
|
||||
|
||||
b.historicalRoots = append(roots, root)
|
||||
b.markFieldAsDirty(historicalRoots)
|
||||
b.markFieldAsDirty(nativetypes.HistoricalRoots)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -160,18 +160,18 @@ func (b *BeaconState) recomputeRoot(idx int) {
|
||||
b.merkleLayers = layers
|
||||
}
|
||||
|
||||
func (b *BeaconState) markFieldAsDirty(field stateTypes.FieldIndex) {
|
||||
func (b *BeaconState) markFieldAsDirty(field nativetypes.FieldIndex) {
|
||||
b.dirtyFields[field] = true
|
||||
}
|
||||
|
||||
// addDirtyIndices adds the relevant dirty field indices, so that they
|
||||
// can be recomputed.
|
||||
func (b *BeaconState) addDirtyIndices(index stateTypes.FieldIndex, indices []uint64) {
|
||||
func (b *BeaconState) addDirtyIndices(index nativetypes.FieldIndex, indices []uint64) {
|
||||
if b.rebuildTrie[index] {
|
||||
return
|
||||
}
|
||||
// Exit early if balance trie computation isn't enabled.
|
||||
if !features.Get().EnableBalanceTrieComputation && index == balances {
|
||||
if !features.Get().EnableBalanceTrieComputation && index == nativetypes.Balances {
|
||||
return
|
||||
}
|
||||
totalIndicesLen := len(b.dirtyIndices[index]) + len(indices)
|
||||
@@ -1,6 +1,7 @@
|
||||
package v2
|
||||
package state_native
|
||||
|
||||
import (
|
||||
nativetypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/types"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
|
||||
)
|
||||
|
||||
@@ -10,12 +11,12 @@ func (b *BeaconState) SetPreviousParticipationBits(val []byte) error {
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.sharedFieldReferences[previousEpochParticipationBits].MinusRef()
|
||||
b.sharedFieldReferences[previousEpochParticipationBits] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits] = stateutil.NewRef(1)
|
||||
|
||||
b.previousEpochParticipation = val
|
||||
b.markFieldAsDirty(previousEpochParticipationBits)
|
||||
b.rebuildTrie[previousEpochParticipationBits] = true
|
||||
b.markFieldAsDirty(nativetypes.PreviousEpochParticipationBits)
|
||||
b.rebuildTrie[nativetypes.PreviousEpochParticipationBits] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -25,12 +26,12 @@ func (b *BeaconState) SetCurrentParticipationBits(val []byte) error {
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.sharedFieldReferences[currentEpochParticipationBits].MinusRef()
|
||||
b.sharedFieldReferences[currentEpochParticipationBits] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits] = stateutil.NewRef(1)
|
||||
|
||||
b.currentEpochParticipation = val
|
||||
b.markFieldAsDirty(currentEpochParticipationBits)
|
||||
b.rebuildTrie[currentEpochParticipationBits] = true
|
||||
b.markFieldAsDirty(nativetypes.CurrentEpochParticipationBits)
|
||||
b.rebuildTrie[nativetypes.CurrentEpochParticipationBits] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -41,17 +42,17 @@ func (b *BeaconState) AppendCurrentParticipationBits(val byte) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
participation := b.currentEpochParticipation
|
||||
if b.sharedFieldReferences[currentEpochParticipationBits].Refs() > 1 {
|
||||
if b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits].Refs() > 1 {
|
||||
// Copy elements in underlying array by reference.
|
||||
participation = make([]byte, len(b.currentEpochParticipation))
|
||||
copy(participation, b.currentEpochParticipation)
|
||||
b.sharedFieldReferences[currentEpochParticipationBits].MinusRef()
|
||||
b.sharedFieldReferences[currentEpochParticipationBits] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits] = stateutil.NewRef(1)
|
||||
}
|
||||
|
||||
b.currentEpochParticipation = append(participation, val)
|
||||
b.markFieldAsDirty(currentEpochParticipationBits)
|
||||
b.addDirtyIndices(currentEpochParticipationBits, []uint64{uint64(len(b.currentEpochParticipation) - 1)})
|
||||
b.markFieldAsDirty(nativetypes.CurrentEpochParticipationBits)
|
||||
b.addDirtyIndices(nativetypes.CurrentEpochParticipationBits, []uint64{uint64(len(b.currentEpochParticipation) - 1)})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -62,16 +63,16 @@ func (b *BeaconState) AppendPreviousParticipationBits(val byte) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
bits := b.previousEpochParticipation
|
||||
if b.sharedFieldReferences[previousEpochParticipationBits].Refs() > 1 {
|
||||
if b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits].Refs() > 1 {
|
||||
bits = make([]byte, len(b.previousEpochParticipation))
|
||||
copy(bits, b.previousEpochParticipation)
|
||||
b.sharedFieldReferences[previousEpochParticipationBits].MinusRef()
|
||||
b.sharedFieldReferences[previousEpochParticipationBits] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits] = stateutil.NewRef(1)
|
||||
}
|
||||
|
||||
b.previousEpochParticipation = append(bits, val)
|
||||
b.markFieldAsDirty(previousEpochParticipationBits)
|
||||
b.addDirtyIndices(previousEpochParticipationBits, []uint64{uint64(len(b.previousEpochParticipation) - 1)})
|
||||
b.markFieldAsDirty(nativetypes.PreviousEpochParticipationBits)
|
||||
b.addDirtyIndices(nativetypes.PreviousEpochParticipationBits, []uint64{uint64(len(b.previousEpochParticipation) - 1)})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -82,12 +83,12 @@ func (b *BeaconState) ModifyPreviousParticipationBits(mutator func(val []byte) (
|
||||
b.lock.Lock()
|
||||
|
||||
participation := b.previousEpochParticipation
|
||||
if b.sharedFieldReferences[previousEpochParticipationBits].Refs() > 1 {
|
||||
if b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits].Refs() > 1 {
|
||||
// Copy elements in underlying array by reference.
|
||||
participation = make([]byte, len(b.previousEpochParticipation))
|
||||
copy(participation, b.previousEpochParticipation)
|
||||
b.sharedFieldReferences[previousEpochParticipationBits].MinusRef()
|
||||
b.sharedFieldReferences[previousEpochParticipationBits] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.PreviousEpochParticipationBits] = stateutil.NewRef(1)
|
||||
}
|
||||
// Lock is released so that mutator can
|
||||
// acquire it.
|
||||
@@ -101,8 +102,8 @@ func (b *BeaconState) ModifyPreviousParticipationBits(mutator func(val []byte) (
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
b.previousEpochParticipation = participation
|
||||
b.markFieldAsDirty(previousEpochParticipationBits)
|
||||
b.rebuildTrie[previousEpochParticipationBits] = true
|
||||
b.markFieldAsDirty(nativetypes.PreviousEpochParticipationBits)
|
||||
b.rebuildTrie[nativetypes.PreviousEpochParticipationBits] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -112,12 +113,12 @@ func (b *BeaconState) ModifyCurrentParticipationBits(mutator func(val []byte) ([
|
||||
b.lock.Lock()
|
||||
|
||||
participation := b.currentEpochParticipation
|
||||
if b.sharedFieldReferences[currentEpochParticipationBits].Refs() > 1 {
|
||||
if b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits].Refs() > 1 {
|
||||
// Copy elements in underlying array by reference.
|
||||
participation = make([]byte, len(b.currentEpochParticipation))
|
||||
copy(participation, b.currentEpochParticipation)
|
||||
b.sharedFieldReferences[currentEpochParticipationBits].MinusRef()
|
||||
b.sharedFieldReferences[currentEpochParticipationBits] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.CurrentEpochParticipationBits] = stateutil.NewRef(1)
|
||||
}
|
||||
// Lock is released so that mutator can
|
||||
// acquire it.
|
||||
@@ -131,7 +132,7 @@ func (b *BeaconState) ModifyCurrentParticipationBits(mutator func(val []byte) ([
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
b.currentEpochParticipation = participation
|
||||
b.markFieldAsDirty(currentEpochParticipationBits)
|
||||
b.rebuildTrie[currentEpochParticipationBits] = true
|
||||
b.markFieldAsDirty(nativetypes.CurrentEpochParticipationBits)
|
||||
b.rebuildTrie[nativetypes.CurrentEpochParticipationBits] = true
|
||||
return nil
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
package v3
|
||||
package state_native
|
||||
|
||||
import ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
import (
|
||||
nativetypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/types"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
)
|
||||
|
||||
// SetLatestExecutionPayloadHeader for the beacon state.
|
||||
func (b *BeaconState) SetLatestExecutionPayloadHeader(val *ethpb.ExecutionPayloadHeader) error {
|
||||
@@ -8,6 +11,6 @@ func (b *BeaconState) SetLatestExecutionPayloadHeader(val *ethpb.ExecutionPayloa
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.latestExecutionPayloadHeader = val
|
||||
b.markFieldAsDirty(latestExecutionPayloadHeader)
|
||||
b.markFieldAsDirty(nativetypes.LatestExecutionPayloadHeader)
|
||||
return nil
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
package v1
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
customtypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/custom-types"
|
||||
nativetypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/types"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
|
||||
fieldparams "github.com/prysmaticlabs/prysm/config/fieldparams"
|
||||
"github.com/prysmaticlabs/prysm/encoding/bytesutil"
|
||||
@@ -14,8 +15,8 @@ func (b *BeaconState) SetRandaoMixes(val [][]byte) error {
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.sharedFieldReferences[randaoMixes].MinusRef()
|
||||
b.sharedFieldReferences[randaoMixes] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.RandaoMixes].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.RandaoMixes] = stateutil.NewRef(1)
|
||||
|
||||
var mixesArr [fieldparams.RandaoMixesLength][32]byte
|
||||
for i := 0; i < len(mixesArr); i++ {
|
||||
@@ -23,8 +24,8 @@ func (b *BeaconState) SetRandaoMixes(val [][]byte) error {
|
||||
}
|
||||
mixes := customtypes.RandaoMixes(mixesArr)
|
||||
b.randaoMixes = &mixes
|
||||
b.markFieldAsDirty(randaoMixes)
|
||||
b.rebuildTrie[randaoMixes] = true
|
||||
b.markFieldAsDirty(nativetypes.RandaoMixes)
|
||||
b.rebuildTrie[nativetypes.RandaoMixes] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -38,19 +39,19 @@ func (b *BeaconState) UpdateRandaoMixesAtIndex(idx uint64, val []byte) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
mixes := b.randaoMixes
|
||||
if refs := b.sharedFieldReferences[randaoMixes].Refs(); refs > 1 {
|
||||
if refs := b.sharedFieldReferences[nativetypes.RandaoMixes].Refs(); refs > 1 {
|
||||
// Copy elements in underlying array by reference.
|
||||
m := *b.randaoMixes
|
||||
mCopy := m
|
||||
mixes = &mCopy
|
||||
b.sharedFieldReferences[randaoMixes].MinusRef()
|
||||
b.sharedFieldReferences[randaoMixes] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.RandaoMixes].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.RandaoMixes] = stateutil.NewRef(1)
|
||||
}
|
||||
|
||||
mixes[idx] = bytesutil.ToBytes32(val)
|
||||
b.randaoMixes = mixes
|
||||
b.markFieldAsDirty(randaoMixes)
|
||||
b.addDirtyIndices(randaoMixes, []uint64{idx})
|
||||
b.markFieldAsDirty(nativetypes.RandaoMixes)
|
||||
b.addDirtyIndices(nativetypes.RandaoMixes, []uint64{idx})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
package v1
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
customtypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/custom-types"
|
||||
nativetypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/types"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
|
||||
fieldparams "github.com/prysmaticlabs/prysm/config/fieldparams"
|
||||
)
|
||||
@@ -13,8 +14,8 @@ func (b *BeaconState) SetStateRoots(val [][]byte) error {
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.sharedFieldReferences[stateRoots].MinusRef()
|
||||
b.sharedFieldReferences[stateRoots] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.StateRoots].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.StateRoots] = stateutil.NewRef(1)
|
||||
|
||||
var rootsArr [fieldparams.StateRootsLength][32]byte
|
||||
for i := 0; i < len(rootsArr); i++ {
|
||||
@@ -22,8 +23,8 @@ func (b *BeaconState) SetStateRoots(val [][]byte) error {
|
||||
}
|
||||
roots := customtypes.StateRoots(rootsArr)
|
||||
b.stateRoots = &roots
|
||||
b.markFieldAsDirty(stateRoots)
|
||||
b.rebuildTrie[stateRoots] = true
|
||||
b.markFieldAsDirty(nativetypes.StateRoots)
|
||||
b.rebuildTrie[nativetypes.StateRoots] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -42,19 +43,19 @@ func (b *BeaconState) UpdateStateRootAtIndex(idx uint64, stateRoot [32]byte) err
|
||||
|
||||
// Check if we hold the only reference to the shared state roots slice.
|
||||
r := b.stateRoots
|
||||
if ref := b.sharedFieldReferences[stateRoots]; ref.Refs() > 1 {
|
||||
if ref := b.sharedFieldReferences[nativetypes.StateRoots]; ref.Refs() > 1 {
|
||||
// Copy elements in underlying array by reference.
|
||||
roots := *b.stateRoots
|
||||
rootsCopy := roots
|
||||
r = &rootsCopy
|
||||
ref.MinusRef()
|
||||
b.sharedFieldReferences[stateRoots] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.StateRoots] = stateutil.NewRef(1)
|
||||
}
|
||||
|
||||
r[idx] = stateRoot
|
||||
b.stateRoots = r
|
||||
|
||||
b.markFieldAsDirty(stateRoots)
|
||||
b.addDirtyIndices(stateRoots, []uint64{idx})
|
||||
b.markFieldAsDirty(nativetypes.StateRoots)
|
||||
b.addDirtyIndices(nativetypes.StateRoots, []uint64{idx})
|
||||
return nil
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package v3
|
||||
package state_native
|
||||
|
||||
import (
|
||||
nativetypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/types"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
)
|
||||
|
||||
@@ -10,7 +11,7 @@ func (b *BeaconState) SetCurrentSyncCommittee(val *ethpb.SyncCommittee) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.currentSyncCommittee = val
|
||||
b.markFieldAsDirty(currentSyncCommittee)
|
||||
b.markFieldAsDirty(nativetypes.CurrentSyncCommittee)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -20,6 +21,6 @@ func (b *BeaconState) SetNextSyncCommittee(val *ethpb.SyncCommittee) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.nextSyncCommittee = val
|
||||
b.markFieldAsDirty(nextSyncCommittee)
|
||||
b.markFieldAsDirty(nativetypes.NextSyncCommittee)
|
||||
return nil
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
package v3
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
types "github.com/prysmaticlabs/eth2-types"
|
||||
nativetypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/types"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
|
||||
"github.com/prysmaticlabs/prysm/encoding/bytesutil"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
@@ -15,10 +16,10 @@ func (b *BeaconState) SetValidators(val []*ethpb.Validator) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.validators = val
|
||||
b.sharedFieldReferences[validators].MinusRef()
|
||||
b.sharedFieldReferences[validators] = stateutil.NewRef(1)
|
||||
b.markFieldAsDirty(validators)
|
||||
b.rebuildTrie[validators] = true
|
||||
b.sharedFieldReferences[nativetypes.Validators].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.Validators] = stateutil.NewRef(1)
|
||||
b.markFieldAsDirty(nativetypes.Validators)
|
||||
b.rebuildTrie[nativetypes.Validators] = true
|
||||
b.valMapHandler = stateutil.NewValMapHandler(b.validators)
|
||||
return nil
|
||||
}
|
||||
@@ -28,10 +29,10 @@ func (b *BeaconState) SetValidators(val []*ethpb.Validator) error {
|
||||
func (b *BeaconState) ApplyToEveryValidator(f func(idx int, val *ethpb.Validator) (bool, *ethpb.Validator, error)) error {
|
||||
b.lock.Lock()
|
||||
v := b.validators
|
||||
if ref := b.sharedFieldReferences[validators]; ref.Refs() > 1 {
|
||||
if ref := b.sharedFieldReferences[nativetypes.Validators]; ref.Refs() > 1 {
|
||||
v = b.validatorsReferences()
|
||||
ref.MinusRef()
|
||||
b.sharedFieldReferences[validators] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.Validators] = stateutil.NewRef(1)
|
||||
}
|
||||
b.lock.Unlock()
|
||||
var changedVals []uint64
|
||||
@@ -50,8 +51,8 @@ func (b *BeaconState) ApplyToEveryValidator(f func(idx int, val *ethpb.Validator
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.validators = v
|
||||
b.markFieldAsDirty(validators)
|
||||
b.addDirtyIndices(validators, changedVals)
|
||||
b.markFieldAsDirty(nativetypes.Validators)
|
||||
b.addDirtyIndices(nativetypes.Validators, changedVals)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -66,16 +67,16 @@ func (b *BeaconState) UpdateValidatorAtIndex(idx types.ValidatorIndex, val *ethp
|
||||
defer b.lock.Unlock()
|
||||
|
||||
v := b.validators
|
||||
if ref := b.sharedFieldReferences[validators]; ref.Refs() > 1 {
|
||||
if ref := b.sharedFieldReferences[nativetypes.Validators]; ref.Refs() > 1 {
|
||||
v = b.validatorsReferences()
|
||||
ref.MinusRef()
|
||||
b.sharedFieldReferences[validators] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.Validators] = stateutil.NewRef(1)
|
||||
}
|
||||
|
||||
v[idx] = val
|
||||
b.validators = v
|
||||
b.markFieldAsDirty(validators)
|
||||
b.addDirtyIndices(validators, []uint64{uint64(idx)})
|
||||
b.markFieldAsDirty(nativetypes.Validators)
|
||||
b.addDirtyIndices(nativetypes.Validators, []uint64{uint64(idx)})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -86,12 +87,12 @@ func (b *BeaconState) SetBalances(val []uint64) error {
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.sharedFieldReferences[balances].MinusRef()
|
||||
b.sharedFieldReferences[balances] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.Balances].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.Balances] = stateutil.NewRef(1)
|
||||
|
||||
b.balances = val
|
||||
b.markFieldAsDirty(balances)
|
||||
b.rebuildTrie[balances] = true
|
||||
b.markFieldAsDirty(nativetypes.Balances)
|
||||
b.rebuildTrie[nativetypes.Balances] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -105,16 +106,16 @@ func (b *BeaconState) UpdateBalancesAtIndex(idx types.ValidatorIndex, val uint64
|
||||
defer b.lock.Unlock()
|
||||
|
||||
bals := b.balances
|
||||
if b.sharedFieldReferences[balances].Refs() > 1 {
|
||||
if b.sharedFieldReferences[nativetypes.Balances].Refs() > 1 {
|
||||
bals = b.balancesVal()
|
||||
b.sharedFieldReferences[balances].MinusRef()
|
||||
b.sharedFieldReferences[balances] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.Balances].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.Balances] = stateutil.NewRef(1)
|
||||
}
|
||||
|
||||
bals[idx] = val
|
||||
b.balances = bals
|
||||
b.markFieldAsDirty(balances)
|
||||
b.addDirtyIndices(balances, []uint64{uint64(idx)})
|
||||
b.markFieldAsDirty(nativetypes.Balances)
|
||||
b.addDirtyIndices(nativetypes.Balances, []uint64{uint64(idx)})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -124,11 +125,11 @@ func (b *BeaconState) SetSlashings(val []uint64) error {
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.sharedFieldReferences[slashings].MinusRef()
|
||||
b.sharedFieldReferences[slashings] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.Slashings].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.Slashings] = stateutil.NewRef(1)
|
||||
|
||||
b.slashings = val
|
||||
b.markFieldAsDirty(slashings)
|
||||
b.markFieldAsDirty(nativetypes.Slashings)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -142,17 +143,17 @@ func (b *BeaconState) UpdateSlashingsAtIndex(idx, val uint64) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
s := b.slashings
|
||||
if b.sharedFieldReferences[slashings].Refs() > 1 {
|
||||
if b.sharedFieldReferences[nativetypes.Slashings].Refs() > 1 {
|
||||
s = b.slashingsVal()
|
||||
b.sharedFieldReferences[slashings].MinusRef()
|
||||
b.sharedFieldReferences[slashings] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.Slashings].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.Slashings] = stateutil.NewRef(1)
|
||||
}
|
||||
|
||||
s[idx] = val
|
||||
|
||||
b.slashings = s
|
||||
|
||||
b.markFieldAsDirty(slashings)
|
||||
b.markFieldAsDirty(nativetypes.Slashings)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -163,10 +164,10 @@ func (b *BeaconState) AppendValidator(val *ethpb.Validator) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
vals := b.validators
|
||||
if b.sharedFieldReferences[validators].Refs() > 1 {
|
||||
if b.sharedFieldReferences[nativetypes.Validators].Refs() > 1 {
|
||||
vals = b.validatorsReferences()
|
||||
b.sharedFieldReferences[validators].MinusRef()
|
||||
b.sharedFieldReferences[validators] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.Validators].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.Validators] = stateutil.NewRef(1)
|
||||
}
|
||||
|
||||
// append validator to slice
|
||||
@@ -175,8 +176,8 @@ func (b *BeaconState) AppendValidator(val *ethpb.Validator) error {
|
||||
|
||||
b.valMapHandler.Set(bytesutil.ToBytes48(val.PublicKey), valIdx)
|
||||
|
||||
b.markFieldAsDirty(validators)
|
||||
b.addDirtyIndices(validators, []uint64{uint64(valIdx)})
|
||||
b.markFieldAsDirty(nativetypes.Validators)
|
||||
b.addDirtyIndices(nativetypes.Validators, []uint64{uint64(valIdx)})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -187,16 +188,16 @@ func (b *BeaconState) AppendBalance(bal uint64) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
bals := b.balances
|
||||
if b.sharedFieldReferences[balances].Refs() > 1 {
|
||||
if b.sharedFieldReferences[nativetypes.Balances].Refs() > 1 {
|
||||
bals = b.balancesVal()
|
||||
b.sharedFieldReferences[balances].MinusRef()
|
||||
b.sharedFieldReferences[balances] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.Balances].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.Balances] = stateutil.NewRef(1)
|
||||
}
|
||||
|
||||
b.balances = append(bals, bal)
|
||||
balIdx := len(b.balances) - 1
|
||||
b.markFieldAsDirty(balances)
|
||||
b.addDirtyIndices(balances, []uint64{uint64(balIdx)})
|
||||
b.markFieldAsDirty(nativetypes.Balances)
|
||||
b.addDirtyIndices(nativetypes.Balances, []uint64{uint64(balIdx)})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -206,14 +207,14 @@ func (b *BeaconState) AppendInactivityScore(s uint64) error {
|
||||
defer b.lock.Unlock()
|
||||
|
||||
scores := b.inactivityScores
|
||||
if b.sharedFieldReferences[inactivityScores].Refs() > 1 {
|
||||
if b.sharedFieldReferences[nativetypes.InactivityScores].Refs() > 1 {
|
||||
scores = b.inactivityScoresVal()
|
||||
b.sharedFieldReferences[inactivityScores].MinusRef()
|
||||
b.sharedFieldReferences[inactivityScores] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.InactivityScores].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.InactivityScores] = stateutil.NewRef(1)
|
||||
}
|
||||
|
||||
b.inactivityScores = append(scores, s)
|
||||
b.markFieldAsDirty(inactivityScores)
|
||||
b.markFieldAsDirty(nativetypes.InactivityScores)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -223,10 +224,10 @@ func (b *BeaconState) SetInactivityScores(val []uint64) error {
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
|
||||
b.sharedFieldReferences[inactivityScores].MinusRef()
|
||||
b.sharedFieldReferences[inactivityScores] = stateutil.NewRef(1)
|
||||
b.sharedFieldReferences[nativetypes.InactivityScores].MinusRef()
|
||||
b.sharedFieldReferences[nativetypes.InactivityScores] = stateutil.NewRef(1)
|
||||
|
||||
b.inactivityScores = val
|
||||
b.markFieldAsDirty(inactivityScores)
|
||||
b.markFieldAsDirty(nativetypes.InactivityScores)
|
||||
return nil
|
||||
}
|
||||
36
beacon-chain/state/state-native/ssz.go
Normal file
36
beacon-chain/state/state-native/ssz.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
"github.com/prysmaticlabs/prysm/runtime/version"
|
||||
)
|
||||
|
||||
var errAssertionFailed = errors.New("failed to convert interface to proto state")
|
||||
var errUnsupportedVersion = errors.New("unsupported beacon state version")
|
||||
|
||||
func (b *BeaconState) MarshalSSZ() ([]byte, error) {
|
||||
proto := b.ToProto()
|
||||
switch b.Version() {
|
||||
case version.Phase0:
|
||||
s, ok := proto.(*ethpb.BeaconState)
|
||||
if !ok {
|
||||
return nil, errAssertionFailed
|
||||
}
|
||||
return s.MarshalSSZ()
|
||||
case version.Altair:
|
||||
s, ok := proto.(*ethpb.BeaconStateAltair)
|
||||
if !ok {
|
||||
return nil, errAssertionFailed
|
||||
}
|
||||
return s.MarshalSSZ()
|
||||
case version.Bellatrix:
|
||||
s, ok := proto.(*ethpb.BeaconStateBellatrix)
|
||||
if !ok {
|
||||
return nil, errAssertionFailed
|
||||
}
|
||||
return s.MarshalSSZ()
|
||||
default:
|
||||
return nil, errUnsupportedVersion
|
||||
}
|
||||
}
|
||||
1064
beacon-chain/state/state-native/state_trie.go
Normal file
1064
beacon-chain/state/state-native/state_trie.go
Normal file
File diff suppressed because it is too large
Load Diff
29
beacon-chain/state/state-native/types.go
Normal file
29
beacon-chain/state/state-native/types.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package state_native
|
||||
|
||||
import (
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state"
|
||||
nativetypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/types"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/types"
|
||||
)
|
||||
|
||||
// Ensure type BeaconState below implements BeaconState interface.
|
||||
var _ state.BeaconState = (*BeaconState)(nil)
|
||||
|
||||
func init() {
|
||||
fieldMap = make(map[nativetypes.FieldIndex]types.DataType)
|
||||
// Initialize the fixed sized arrays.
|
||||
fieldMap[nativetypes.BlockRoots] = types.BasicArray
|
||||
fieldMap[nativetypes.StateRoots] = types.BasicArray
|
||||
fieldMap[nativetypes.RandaoMixes] = types.BasicArray
|
||||
|
||||
// Initialize the composite arrays.
|
||||
fieldMap[nativetypes.Eth1DataVotes] = types.CompositeArray
|
||||
fieldMap[nativetypes.Validators] = types.CompositeArray
|
||||
fieldMap[nativetypes.PreviousEpochAttestations] = types.CompositeArray
|
||||
fieldMap[nativetypes.CurrentEpochAttestations] = types.CompositeArray
|
||||
fieldMap[nativetypes.Balances] = types.CompressedArray
|
||||
}
|
||||
|
||||
// fieldMap keeps track of each field
|
||||
// to its corresponding data type.
|
||||
var fieldMap map[nativetypes.FieldIndex]types.DataType
|
||||
9
beacon-chain/state/state-native/types/BUILD.bazel
Normal file
9
beacon-chain/state/state-native/types/BUILD.bazel
Normal file
@@ -0,0 +1,9 @@
|
||||
load("@prysm//tools/go:def.bzl", "go_library")
|
||||
|
||||
go_library(
|
||||
name = "go_default_library",
|
||||
srcs = ["types.go"],
|
||||
importpath = "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/types",
|
||||
visibility = ["//visibility:public"],
|
||||
deps = ["@com_github_pkg_errors//:go_default_library"],
|
||||
)
|
||||
124
beacon-chain/state/state-native/types/types.go
Normal file
124
beacon-chain/state/state-native/types/types.go
Normal file
@@ -0,0 +1,124 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// FieldIndex represents the relevant field position in the
|
||||
// state struct for a field.
|
||||
type FieldIndex int
|
||||
|
||||
// String returns the name of the field index.
|
||||
func (f FieldIndex) String(stateVersion int) string {
|
||||
switch f {
|
||||
case GenesisTime:
|
||||
return "genesisTime"
|
||||
case GenesisValidatorsRoot:
|
||||
return "genesisValidatorsRoot"
|
||||
case Slot:
|
||||
return "slot"
|
||||
case Fork:
|
||||
return "fork"
|
||||
case LatestBlockHeader:
|
||||
return "latestBlockHeader"
|
||||
case BlockRoots:
|
||||
return "blockRoots"
|
||||
case StateRoots:
|
||||
return "stateRoots"
|
||||
case HistoricalRoots:
|
||||
return "historicalRoots"
|
||||
case Eth1Data:
|
||||
return "eth1Data"
|
||||
case Eth1DataVotes:
|
||||
return "eth1DataVotes"
|
||||
case Eth1DepositIndex:
|
||||
return "eth1DepositIndex"
|
||||
case Validators:
|
||||
return "validators"
|
||||
case Balances:
|
||||
return "balances"
|
||||
case RandaoMixes:
|
||||
return "randaoMixes"
|
||||
case Slashings:
|
||||
return "slashings"
|
||||
case PreviousEpochAttestations:
|
||||
return "previousEpochAttestations"
|
||||
case CurrentEpochAttestations:
|
||||
return "currentEpochAttestations"
|
||||
case PreviousEpochParticipationBits:
|
||||
return "previousEpochParticipationBits"
|
||||
case CurrentEpochParticipationBits:
|
||||
return "currentEpochParticipationBits"
|
||||
case JustificationBits:
|
||||
return "justificationBits"
|
||||
case PreviousJustifiedCheckpoint:
|
||||
return "previousJustifiedCheckpoint"
|
||||
case CurrentJustifiedCheckpoint:
|
||||
return "currentJustifiedCheckpoint"
|
||||
case FinalizedCheckpoint:
|
||||
return "finalizedCheckpoint"
|
||||
case InactivityScores:
|
||||
return "inactivityScores"
|
||||
case CurrentSyncCommittee:
|
||||
return "currentSyncCommittee"
|
||||
case NextSyncCommittee:
|
||||
return "nextSyncCommittee"
|
||||
case LatestExecutionPayloadHeader:
|
||||
return "latestExecutionPayloadHeader"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// ElemsInChunk returns the number of elements in the chunk (number of
|
||||
// elements that are able to be packed).
|
||||
func (f FieldIndex) ElemsInChunk() (uint64, error) {
|
||||
switch f {
|
||||
case Balances:
|
||||
return 4, nil
|
||||
default:
|
||||
return 0, errors.Errorf("field %d doesn't support element compression", f)
|
||||
}
|
||||
}
|
||||
|
||||
func (f FieldIndex) Native() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Below we define a set of useful enum values for the field
|
||||
// indices of the beacon state. For example, genesisTime is the
|
||||
// 0th field of the beacon state. This is helpful when we are
|
||||
// updating the Merkle branches up the trie representation
|
||||
// of the beacon state. The below field indexes correspond
|
||||
// to the v1 state.
|
||||
const (
|
||||
GenesisTime FieldIndex = iota
|
||||
GenesisValidatorsRoot
|
||||
Slot
|
||||
Fork
|
||||
LatestBlockHeader
|
||||
BlockRoots
|
||||
StateRoots
|
||||
HistoricalRoots
|
||||
Eth1Data
|
||||
Eth1DataVotes
|
||||
Eth1DepositIndex
|
||||
Validators
|
||||
Balances
|
||||
RandaoMixes
|
||||
Slashings
|
||||
PreviousEpochAttestations
|
||||
CurrentEpochAttestations
|
||||
PreviousEpochParticipationBits
|
||||
CurrentEpochParticipationBits
|
||||
JustificationBits
|
||||
PreviousJustifiedCheckpoint
|
||||
CurrentJustifiedCheckpoint
|
||||
FinalizedCheckpoint
|
||||
// State Fields Added in Altair.
|
||||
InactivityScores
|
||||
CurrentSyncCommittee
|
||||
NextSyncCommittee
|
||||
// State fields added in Bellatrix.
|
||||
LatestExecutionPayloadHeader
|
||||
)
|
||||
@@ -1,134 +0,0 @@
|
||||
load("@prysm//tools/go:def.bzl", "go_library", "go_test")
|
||||
load("//proto:ssz_proto_library.bzl", "ssz_proto_files")
|
||||
load("//tools:ssz.bzl", "SSZ_DEPS", "ssz_gen_marshal")
|
||||
|
||||
go_library(
|
||||
name = "go_default_library",
|
||||
srcs = [
|
||||
"doc.go",
|
||||
"field_roots.go",
|
||||
"getters_attestation.go",
|
||||
"getters_block.go",
|
||||
"getters_checkpoint.go",
|
||||
"getters_eth1.go",
|
||||
"getters_misc.go",
|
||||
"getters_randao.go",
|
||||
"getters_state.go",
|
||||
"getters_validator.go",
|
||||
"proofs.go",
|
||||
"readonly_validator.go",
|
||||
"setters_attestation.go",
|
||||
"setters_block.go",
|
||||
"setters_checkpoint.go",
|
||||
"setters_eth1.go",
|
||||
"setters_misc.go",
|
||||
"setters_randao.go",
|
||||
"setters_state.go",
|
||||
"setters_validator.go",
|
||||
"state_trie.go",
|
||||
"types.go",
|
||||
"unsupported_getters.go",
|
||||
"unsupported_setters.go",
|
||||
":ssz_generated_files", # keep
|
||||
] + select({
|
||||
"//config:mainnet": ["beacon_state_mainnet.go"],
|
||||
"//config:minimal": ["beacon_state_minimal.go"],
|
||||
}),
|
||||
importpath = "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/v1",
|
||||
visibility = [
|
||||
"//beacon-chain:__subpackages__",
|
||||
"//contracts/deposit:__subpackages__",
|
||||
"//proto/migration:__subpackages__",
|
||||
"//proto/prysm/v1alpha1:__subpackages__",
|
||||
"//proto/testing:__subpackages__",
|
||||
"//runtime/interop:__subpackages__",
|
||||
"//slasher/rpc:__subpackages__",
|
||||
"//testing/benchmark:__pkg__",
|
||||
"//testing/fuzz:__pkg__",
|
||||
"//testing/spectest:__subpackages__",
|
||||
"//testing/util:__pkg__",
|
||||
"//tools/benchmark-files-gen:__pkg__",
|
||||
"//tools/pcli:__pkg__",
|
||||
],
|
||||
deps = [
|
||||
"//beacon-chain/state:go_default_library",
|
||||
"//beacon-chain/state/fieldtrie:go_default_library",
|
||||
"//beacon-chain/state/state-native/custom-types:go_default_library",
|
||||
"//beacon-chain/state/stateutil:go_default_library",
|
||||
"//beacon-chain/state/types:go_default_library",
|
||||
"//config/features:go_default_library",
|
||||
"//config/fieldparams:go_default_library",
|
||||
"//config/params:go_default_library",
|
||||
"//container/slice:go_default_library",
|
||||
"//crypto/hash:go_default_library",
|
||||
"//encoding/bytesutil:go_default_library",
|
||||
"//encoding/ssz:go_default_library",
|
||||
"//proto/prysm/v1alpha1:go_default_library",
|
||||
"//runtime/version:go_default_library",
|
||||
"@com_github_ferranbt_fastssz//:go_default_library",
|
||||
"@com_github_pkg_errors//:go_default_library",
|
||||
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
|
||||
"@com_github_prysmaticlabs_go_bitfield//:go_default_library",
|
||||
"@io_opencensus_go//trace:go_default_library",
|
||||
"@org_golang_google_protobuf//proto:go_default_library",
|
||||
],
|
||||
)
|
||||
|
||||
# gazelle:exclude types_bench_test.go
|
||||
go_test(
|
||||
name = "go_default_test",
|
||||
srcs = [
|
||||
"getters_attestation_test.go",
|
||||
"getters_block_test.go",
|
||||
"getters_test.go",
|
||||
"getters_validator_test.go",
|
||||
"proofs_test.go",
|
||||
"readonly_validator_test.go",
|
||||
"references_test.go",
|
||||
"setters_attestation_test.go",
|
||||
"state_test.go",
|
||||
"state_trie_test.go",
|
||||
"types_test.go",
|
||||
] + select({
|
||||
"//config:mainnet": ["beacon_state_mainnet_test.go"],
|
||||
"//config:minimal": ["beacon_state_minimal_test.go"],
|
||||
}),
|
||||
embed = [":go_default_library"],
|
||||
deps = [
|
||||
"//beacon-chain/state:go_default_library",
|
||||
"//beacon-chain/state/stateutil:go_default_library",
|
||||
"//beacon-chain/state/testing:go_default_library",
|
||||
"//beacon-chain/state/types:go_default_library",
|
||||
"//config/features:go_default_library",
|
||||
"//config/fieldparams:go_default_library",
|
||||
"//config/params:go_default_library",
|
||||
"//container/trie:go_default_library",
|
||||
"//encoding/bytesutil:go_default_library",
|
||||
"//proto/prysm/v1alpha1:go_default_library",
|
||||
"//runtime/interop:go_default_library",
|
||||
"//testing/assert:go_default_library",
|
||||
"//testing/require:go_default_library",
|
||||
"//testing/util:go_default_library",
|
||||
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
|
||||
"@com_github_prysmaticlabs_go_bitfield//:go_default_library",
|
||||
"@com_github_sirupsen_logrus//:go_default_library",
|
||||
"@org_golang_google_protobuf//proto:go_default_library",
|
||||
],
|
||||
)
|
||||
|
||||
ssz_gen_marshal(
|
||||
name = "ssz_generated_files",
|
||||
srcs = select({
|
||||
"//config:mainnet": ["beacon_state_mainnet.go"],
|
||||
"//config:minimal": ["beacon_state_minimal.go"],
|
||||
}),
|
||||
includes = [
|
||||
"//beacon-chain/state/state-native/custom-types:go_default_library",
|
||||
"//config/fieldparams:go_default_library",
|
||||
"//proto/prysm/v1alpha1:go_default_library",
|
||||
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
|
||||
],
|
||||
objs = [
|
||||
"BeaconState[no-htr]",
|
||||
],
|
||||
)
|
||||
@@ -1,51 +0,0 @@
|
||||
//go:build !minimal
|
||||
// +build !minimal
|
||||
|
||||
package v1
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
eth2types "github.com/prysmaticlabs/eth2-types"
|
||||
"github.com/prysmaticlabs/go-bitfield"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/fieldtrie"
|
||||
customtypes "github.com/prysmaticlabs/prysm/beacon-chain/state/state-native/custom-types"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
|
||||
"github.com/prysmaticlabs/prysm/beacon-chain/state/types"
|
||||
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
|
||||
)
|
||||
|
||||
// BeaconState defines a struct containing utilities for the Ethereum Beacon Chain state, defining
|
||||
// getters and setters for its respective values and helpful functions such as HashTreeRoot().
|
||||
type BeaconState struct {
|
||||
genesisTime uint64 `ssz-gen:"true"`
|
||||
genesisValidatorsRoot customtypes.Byte32 `ssz-gen:"true" ssz-size:"32"`
|
||||
slot eth2types.Slot `ssz-gen:"true"`
|
||||
fork *ethpb.Fork `ssz-gen:"true"`
|
||||
latestBlockHeader *ethpb.BeaconBlockHeader `ssz-gen:"true"`
|
||||
blockRoots *customtypes.BlockRoots `ssz-gen:"true" ssz-size:"8192,32"`
|
||||
stateRoots *customtypes.StateRoots `ssz-gen:"true" ssz-size:"8192,32"`
|
||||
historicalRoots customtypes.HistoricalRoots `ssz-gen:"true" ssz-size:"?,32" ssz-max:"16777216"`
|
||||
eth1Data *ethpb.Eth1Data `ssz-gen:"true"`
|
||||
eth1DataVotes []*ethpb.Eth1Data `ssz-gen:"true" ssz-max:"2048"`
|
||||
eth1DepositIndex uint64 `ssz-gen:"true"`
|
||||
validators []*ethpb.Validator `ssz-gen:"true" ssz-max:"1099511627776"`
|
||||
balances []uint64 `ssz-gen:"true" ssz-max:"1099511627776"`
|
||||
randaoMixes *customtypes.RandaoMixes `ssz-gen:"true" ssz-size:"65536,32"`
|
||||
slashings []uint64 `ssz-gen:"true" ssz-size:"8192"`
|
||||
previousEpochAttestations []*ethpb.PendingAttestation `ssz-gen:"true" ssz-max:"4096"`
|
||||
currentEpochAttestations []*ethpb.PendingAttestation `ssz-gen:"true" ssz-max:"4096"`
|
||||
justificationBits bitfield.Bitvector4 `ssz-gen:"true" ssz-size:"1"`
|
||||
previousJustifiedCheckpoint *ethpb.Checkpoint `ssz-gen:"true"`
|
||||
currentJustifiedCheckpoint *ethpb.Checkpoint `ssz-gen:"true"`
|
||||
finalizedCheckpoint *ethpb.Checkpoint `ssz-gen:"true"`
|
||||
|
||||
lock sync.RWMutex
|
||||
dirtyFields map[types.FieldIndex]bool
|
||||
dirtyIndices map[types.FieldIndex][]uint64
|
||||
stateFieldLeaves map[types.FieldIndex]*fieldtrie.FieldTrie
|
||||
rebuildTrie map[types.FieldIndex]bool
|
||||
valMapHandler *stateutil.ValidatorMapHandler
|
||||
merkleLayers [][][]byte
|
||||
sharedFieldReferences map[types.FieldIndex]*stateutil.Reference
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user