prysm-pulse/beacon-chain/rpc/attester/server_test.go
Raul Jordan 3332abbb5a
Restructure Beacon Chain RPC Servers Into Subpackages (#3975)
* Update seed domains (#3872)

* Remove Transfers (#3870)

* Remove active index roots and compact committee roots (#3869)

* Update inclusion reward (#3886)

* Alter proposer selection logic (#3884)

* Fix early committee bias (#3888)

* Remove shards and committees (#3896)

* Epoch spec tests v0.9 (#3907)

* Block spec test v0.9 (#3905)

* rm'ed in protobuf

* build proto

* build proto

* build proto

* fix core package

* Gazelle

* Fixed all the tests

* Fixed static test

* Comment out spec test for now

* One more skip

* fix-roundRobinSync (#3862)

* Starting but need new seed function

* Revert initial sync

* Updated Proposer Slashing

* Fixed all tests

* Lint

* Update inclusion reward

* Fill randao mixes with eth1 data hash

* Test

* Fixing test part1

* All tests passing

* One last test

* Updated config

* Build proto

* Proper skip message

* Conflict and fmt

* Removed crosslinks and shards. Built

* Format and gazelle

* Fixed all the block package tests

* Fixed all the helper tests

* All epoch package tests pass

* All core package tests pass

* Fixed operation tests

* Started fixing rpc test

* RPC tests passed!

* Fixed all init sync tests

* All tests pass

* Fixed blockchain tests

* Lint

* Lint

* Preston's feedback

* Starting

* Remove container

* Fixed block spec tests

* All passing except for block_processing test

* Failing block processing test

* Starting

* Add AggregateAndProof

* All mainnet test passes

* Update deposit contract (#3906)

* Proto spec tests v0.9 (#3908)

* Starting

* Add AggregateAndProof

* Unskip block util tests (#3910)

* rm'ed in protobuf

* build proto

* build proto

* build proto

* fix core package

* Gazelle

* Fixed all the tests

* Fixed static test

* Comment out spec test for now

* One more skip

* fix-roundRobinSync (#3862)

* Starting but need new seed function

* Revert initial sync

* Updated Proposer Slashing

* Fixed all tests

* Lint

* Update inclusion reward

* Fill randao mixes with eth1 data hash

* Test

* Fixing test part1

* All tests passing

* One last test

* Updated config

* Build proto

* Proper skip message

* Conflict and fmt

* Removed crosslinks and shards. Built

* Format and gazelle

* Fixed all the block package tests

* Fixed all the helper tests

* All epoch package tests pass

* All core package tests pass

* Fixed operation tests

* Started fixing rpc test

* RPC tests passed!

* Fixed all init sync tests

* All tests pass

* Fixed blockchain tests

* Lint

* Lint

* Preston's feedback

* Starting

* Remove container

* Fixed block spec tests

* All passing except for block_processing test

* Failing block processing test

* Starting

* Add AggregateAndProof

* All mainnet test passes

* Unskip block util tests

* Slot processing spec test V0.9 (#3912)

* Starting

* Add AggregateAndProof

* Unskip slot processing mainnet test

* Unskip minimal spec test for finalization (#3920)

* Remove outdated interop tests (#3922)

* Rm outdated interop tests

* Rm test runner

* Gazelle

* Update validator to use proposer slot (#3919)

* Fix committee assignment (#3931)

* Replace shard with committee index (#3930)

* Conflict

* Clean up (#3933)

* Remove shard filter in db (#3936)

* Remove lightouse compatibility test (#3939)

* Update Committee Cache for v0.9 (#3948)

* Updated committee cache

* Removed shuffled indices cache

* Started testing run time

* Lint

* Fixed test

* Safeguard against nil head state

* address edge case

* add test

* Fixed TestRoundRobinSync by doubling the epochs

* Unskip TestProtoCompatability (#3958)

* Unskip TestProtoCompatability

* Update WORKSPACE

* Fix minimal config (#3959)

* fix minimal configs

* fix hardcoded value in test

* Simplify verify att time (#3961)

* update readme for deposit contract, regen bindings for vyper 0.1.0b12 (#3963)

* update readme for deposit contract, regen bindings

* medium

* Check nil base state (#3964)

* Copy Block When Receiving it From Sync (#3966)

* copy block

* clone for other service methods too

* Change logging of Bitfield  (#3956)

* change logging of bits

* preston's review

* Unskip Beacon Server Test (#3962)

* run test till the end

* fix up proto message types

* fmt

* resolve broken tests

* better error handling

* fixing new logic to use archived proposer info

* fix up logic

* clip using the max effective balance

* broken build fix with num arg mismatch

* amend archive

* archival logic changed

* rename test

* archive both proposer and attester seeds

* page size 100

* further experiments

* further experimentation, archivedProposerIndex seems wrong

* test passes

* rem log

* fix broken test

* fix test

* gaz

* fix imports

* ethapis

* attester server split into subpackage

* attester impl split up successfully

* validator cleaned up

* all packages isolated

* include proposer

* proper naming

* test fix

* proper viz

* naming

* resolved timeout due to config values

* init use minimal

* added all subfiles

* subfile split and gazelle

* shards

* validator folder

* cleanup val

* shay feedback
2019-11-12 11:01:27 -06:00

305 lines
8.8 KiB
Go

package attester
import (
"context"
"strings"
"sync"
"testing"
"github.com/gogo/protobuf/proto"
"github.com/prysmaticlabs/go-ssz"
mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/beacon-chain/cache"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
dbutil "github.com/prysmaticlabs/prysm/beacon-chain/db/testing"
mockOps "github.com/prysmaticlabs/prysm/beacon-chain/operations/testing"
mockp2p "github.com/prysmaticlabs/prysm/beacon-chain/p2p/testing"
mockSync "github.com/prysmaticlabs/prysm/beacon-chain/sync/initial-sync/testing"
pbp2p "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
pb "github.com/prysmaticlabs/prysm/proto/beacon/rpc/v1"
ethpb "github.com/prysmaticlabs/prysm/proto/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"github.com/prysmaticlabs/prysm/shared/params"
)
func init() {
// Use minimal config to reduce test setup time.
params.OverrideBeaconConfig(params.MinimalSpecConfig())
}
func TestSubmitAttestation_OK(t *testing.T) {
db := dbutil.SetupDB(t)
defer dbutil.TeardownDB(t, db)
ctx := context.Background()
attesterServer := &Server{
HeadFetcher: &mock.ChainService{},
AttReceiver: &mock.ChainService{},
OperationsHandler: &mockOps.Operations{},
P2p: &mockp2p.MockBroadcaster{},
BeaconDB: db,
AttestationCache: cache.NewAttestationCache(),
}
head := &ethpb.BeaconBlock{
Slot: 999,
ParentRoot: []byte{'a'},
}
if err := db.SaveBlock(ctx, head); err != nil {
t.Fatal(err)
}
root, err := ssz.SigningRoot(head)
if err != nil {
t.Fatal(err)
}
validators := make([]*ethpb.Validator, params.BeaconConfig().MinGenesisActiveValidatorCount/16)
for i := 0; i < len(validators); i++ {
validators[i] = &ethpb.Validator{
ExitEpoch: params.BeaconConfig().FarFutureEpoch,
EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance,
}
}
state := &pbp2p.BeaconState{
Slot: params.BeaconConfig().SlotsPerEpoch + 1,
Validators: validators,
RandaoMixes: make([][]byte, params.BeaconConfig().EpochsPerHistoricalVector),
}
if err := db.SaveHeadBlockRoot(ctx, root); err != nil {
t.Fatal(err)
}
if err := db.SaveState(ctx, state, root); err != nil {
t.Fatal(err)
}
req := &ethpb.Attestation{
Data: &ethpb.AttestationData{
BeaconBlockRoot: root[:],
Source: &ethpb.Checkpoint{},
Target: &ethpb.Checkpoint{},
},
}
if _, err := attesterServer.SubmitAttestation(context.Background(), req); err != nil {
t.Errorf("Could not attest head correctly: %v", err)
}
}
func TestRequestAttestation_OK(t *testing.T) {
block := &ethpb.BeaconBlock{
Slot: 3*params.BeaconConfig().SlotsPerEpoch + 1,
}
targetBlock := &ethpb.BeaconBlock{
Slot: 1 * params.BeaconConfig().SlotsPerEpoch,
}
justifiedBlock := &ethpb.BeaconBlock{
Slot: 2 * params.BeaconConfig().SlotsPerEpoch,
}
blockRoot, err := ssz.SigningRoot(block)
if err != nil {
t.Fatalf("Could not hash beacon block: %v", err)
}
justifiedRoot, err := ssz.SigningRoot(justifiedBlock)
if err != nil {
t.Fatalf("Could not get signing root for justified block: %v", err)
}
targetRoot, err := ssz.SigningRoot(targetBlock)
if err != nil {
t.Fatalf("Could not get signing root for target block: %v", err)
}
beaconState := &pbp2p.BeaconState{
Slot: 3*params.BeaconConfig().SlotsPerEpoch + 1,
BlockRoots: make([][]byte, params.BeaconConfig().SlotsPerHistoricalRoot),
CurrentJustifiedCheckpoint: &ethpb.Checkpoint{
Epoch: 2,
Root: justifiedRoot[:],
},
}
beaconState.BlockRoots[1] = blockRoot[:]
beaconState.BlockRoots[1*params.BeaconConfig().SlotsPerEpoch] = targetRoot[:]
beaconState.BlockRoots[2*params.BeaconConfig().SlotsPerEpoch] = justifiedRoot[:]
attesterServer := &Server{
P2p: &mockp2p.MockBroadcaster{},
SyncChecker: &mockSync.Sync{IsSyncing: false},
AttestationCache: cache.NewAttestationCache(),
HeadFetcher: &mock.ChainService{State: beaconState, Root: blockRoot[:]},
AttReceiver: &mock.ChainService{State: beaconState, Root: blockRoot[:]},
}
req := &pb.AttestationRequest{
CommitteeIndex: 0,
Slot: 3*params.BeaconConfig().SlotsPerEpoch + 1,
}
res, err := attesterServer.RequestAttestation(context.Background(), req)
if err != nil {
t.Fatalf("Could not get attestation info at slot: %v", err)
}
expectedInfo := &ethpb.AttestationData{
Slot: 3*params.BeaconConfig().SlotsPerEpoch + 1,
BeaconBlockRoot: blockRoot[:],
Source: &ethpb.Checkpoint{
Epoch: 2,
Root: justifiedRoot[:],
},
Target: &ethpb.Checkpoint{
Epoch: 3,
},
}
if !proto.Equal(res, expectedInfo) {
t.Errorf("Expected attestation info to match, received %v, wanted %v", res, expectedInfo)
}
}
func TestRequestAttestation_SyncNotReady(t *testing.T) {
as := &Server{
SyncChecker: &mockSync.Sync{IsSyncing: true},
}
_, err := as.RequestAttestation(context.Background(), &pb.AttestationRequest{})
if strings.Contains(err.Error(), "syncing to latest head") {
t.Error("Did not get wanted error")
}
}
func TestAttestationDataAtSlot_handlesFarAwayJustifiedEpoch(t *testing.T) {
// Scenario:
//
// State slot = 10000
// Last justified slot = epoch start of 1500
// HistoricalRootsLimit = 8192
//
// More background: https://github.com/prysmaticlabs/prysm/issues/2153
// This test breaks if it doesnt use mainnet config
params.OverrideBeaconConfig(params.MainnetConfig())
defer params.OverrideBeaconConfig(params.MinimalSpecConfig())
// Ensure HistoricalRootsLimit matches scenario
cfg := params.BeaconConfig()
cfg.HistoricalRootsLimit = 8192
params.OverrideBeaconConfig(cfg)
block := &ethpb.BeaconBlock{
Slot: 10000,
}
epochBoundaryBlock := &ethpb.BeaconBlock{
Slot: helpers.StartSlot(helpers.SlotToEpoch(10000)),
}
justifiedBlock := &ethpb.BeaconBlock{
Slot: helpers.StartSlot(helpers.SlotToEpoch(1500)) - 2, // Imagine two skip block
}
blockRoot, err := ssz.SigningRoot(block)
if err != nil {
t.Fatalf("Could not hash beacon block: %v", err)
}
justifiedBlockRoot, err := ssz.SigningRoot(justifiedBlock)
if err != nil {
t.Fatalf("Could not hash justified block: %v", err)
}
epochBoundaryRoot, err := ssz.SigningRoot(epochBoundaryBlock)
if err != nil {
t.Fatalf("Could not hash justified block: %v", err)
}
beaconState := &pbp2p.BeaconState{
Slot: 10000,
BlockRoots: make([][]byte, params.BeaconConfig().SlotsPerHistoricalRoot),
CurrentJustifiedCheckpoint: &ethpb.Checkpoint{
Epoch: helpers.SlotToEpoch(1500),
Root: justifiedBlockRoot[:],
},
}
beaconState.BlockRoots[1] = blockRoot[:]
beaconState.BlockRoots[1*params.BeaconConfig().SlotsPerEpoch] = epochBoundaryRoot[:]
beaconState.BlockRoots[2*params.BeaconConfig().SlotsPerEpoch] = justifiedBlockRoot[:]
attesterServer := &Server{
P2p: &mockp2p.MockBroadcaster{},
AttestationCache: cache.NewAttestationCache(),
HeadFetcher: &mock.ChainService{State: beaconState, Root: blockRoot[:]},
AttReceiver: &mock.ChainService{State: beaconState, Root: blockRoot[:]},
SyncChecker: &mockSync.Sync{IsSyncing: false},
}
req := &pb.AttestationRequest{
CommitteeIndex: 0,
Slot: 10000,
}
res, err := attesterServer.RequestAttestation(context.Background(), req)
if err != nil {
t.Fatalf("Could not get attestation info at slot: %v", err)
}
expectedInfo := &ethpb.AttestationData{
Slot: req.Slot,
BeaconBlockRoot: blockRoot[:],
Source: &ethpb.Checkpoint{
Epoch: helpers.SlotToEpoch(1500),
Root: justifiedBlockRoot[:],
},
Target: &ethpb.Checkpoint{
Epoch: 312,
},
}
if !proto.Equal(res, expectedInfo) {
t.Errorf("Expected attestation info to match, received %v, wanted %v", res, expectedInfo)
}
}
func TestAttestationDataAtSlot_handlesInProgressRequest(t *testing.T) {
// Cache toggled by feature flag for now. See https://github.com/prysmaticlabs/prysm/issues/3106.
featureconfig.Init(&featureconfig.Flag{
EnableAttestationCache: true,
})
defer func() {
featureconfig.Init(nil)
}()
ctx := context.Background()
server := &Server{
AttestationCache: cache.NewAttestationCache(),
SyncChecker: &mockSync.Sync{IsSyncing: false},
}
req := &pb.AttestationRequest{
CommitteeIndex: 1,
Slot: 2,
}
res := &ethpb.AttestationData{
Target: &ethpb.Checkpoint{Epoch: 55},
}
if err := server.AttestationCache.MarkInProgress(req); err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
response, err := server.RequestAttestation(ctx, req)
if err != nil {
t.Error(err)
}
if !proto.Equal(res, response) {
t.Error("Expected equal responses from cache")
}
}()
wg.Add(1)
go func() {
defer wg.Done()
if err := server.AttestationCache.Put(ctx, req, res); err != nil {
t.Error(err)
}
if err := server.AttestationCache.MarkNotInProgress(req); err != nil {
t.Error(err)
}
}()
wg.Wait()
}