Skip to content

Commit

Permalink
Implement GetFinalityCheckpoints in the beacon API (#8476)
Browse files Browse the repository at this point in the history
* span

* Implement GetFinalityCheckpoints in the beacon API
  • Loading branch information
rkapka authored Feb 18, 2021
1 parent fc26505 commit 1ae429d
Show file tree
Hide file tree
Showing 2 changed files with 290 additions and 2 deletions.
36 changes: 34 additions & 2 deletions beacon-chain/rpc/beaconv1/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ package beaconv1
import (
"bytes"
"context"
"errors"
"strconv"
"strings"

ptypes "github.com/gogo/protobuf/types"
types "github.com/prysmaticlabs/eth2-types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1"
eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
statetrie "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
Expand Down Expand Up @@ -96,7 +96,26 @@ func (bs *Server) GetStateFork(ctx context.Context, req *ethpb.StateRequest) (*e
// GetFinalityCheckpoints returns finality checkpoints for state with given 'stateId'. In case finality is
// not yet achieved, checkpoint should return epoch 0 and ZERO_HASH as root.
func (bs *Server) GetFinalityCheckpoints(ctx context.Context, req *ethpb.StateRequest) (*ethpb.StateFinalityCheckpointResponse, error) {
return nil, errors.New("unimplemented")
ctx, span := trace.StartSpan(ctx, "beaconv1.GetFinalityCheckpoints")
defer span.End()

var (
state *statetrie.BeaconState
err error
)

state, err = bs.state(ctx, req.StateId)
if err != nil {
return nil, err
}

return &ethpb.StateFinalityCheckpointResponse{
Data: &ethpb.StateFinalityCheckpointResponse_StateFinalityCheckpoint{
PreviousJustified: checkpoint(state.PreviousJustifiedCheckpoint()),
CurrentJustified: checkpoint(state.CurrentJustifiedCheckpoint()),
Finalized: checkpoint(state.FinalizedCheckpoint()),
},
}, nil
}

func (bs *Server) stateRoot(ctx context.Context, stateId []byte) ([]byte, error) {
Expand Down Expand Up @@ -302,3 +321,16 @@ func (bs *Server) stateBySlot(ctx context.Context, slot types.Slot) (*statetrie.
}
return state, nil
}

func checkpoint(sourceCheckpoint *eth.Checkpoint) *ethpb.Checkpoint {
if sourceCheckpoint != nil {
return &ethpb.Checkpoint{
Epoch: sourceCheckpoint.Epoch,
Root: sourceCheckpoint.Root,
}
}
return &ethpb.Checkpoint{
Epoch: 0,
Root: params.BeaconConfig().ZeroHash[:],
}
}
256 changes: 256 additions & 0 deletions beacon-chain/rpc/beaconv1/state_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -472,3 +472,259 @@ func TestGetStateFork(t *testing.T) {
require.ErrorContains(t, "Invalid state ID: foo", err)
})
}

func TestGetFinalityCheckpoints(t *testing.T) {
ctx := context.Background()

// We fill state and block roots with hex representations of natural numbers starting with 0.
// Example: 16 becomes 0x00...0f
fillRoots := func(state *pb.BeaconState) {
rootsLen := params.MainnetConfig().SlotsPerHistoricalRoot
roots := make([][]byte, rootsLen)
for i := types.Slot(0); i < rootsLen; i++ {
roots[i] = make([]byte, 32)
}
for j := 0; j < len(roots); j++ {
// Remove '0x' prefix and left-pad '0' to have 64 chars in total.
s := fmt.Sprintf("%064s", hexutil.EncodeUint64(uint64(j))[2:])
h, err := hexutil.Decode("0x" + s)
require.NoError(t, err, "Failed to decode root "+s)
roots[j] = h
}
state.StateRoots = roots
state.BlockRoots = roots
}
fillCheckpoints := func(state *pb.BeaconState) {
state.PreviousJustifiedCheckpoint = &eth.Checkpoint{
Root: bytesutil.PadTo([]byte("previous"), 32),
Epoch: 113,
}
state.CurrentJustifiedCheckpoint = &eth.Checkpoint{
Root: bytesutil.PadTo([]byte("current"), 32),
Epoch: 123,
}
state.FinalizedCheckpoint = &eth.Checkpoint{
Root: bytesutil.PadTo([]byte("finalized"), 32),
Epoch: 103,
}
}
headSlot := types.Slot(123)
fillSlot := func(state *pb.BeaconState) {
state.Slot = headSlot
}
state, err := testutil.NewBeaconState(fillCheckpoints, fillRoots, fillSlot)
require.NoError(t, err)
stateRoot, err := state.HashTreeRoot(ctx)
require.NoError(t, err)

t.Run("Head", func(t *testing.T) {
s := Server{
ChainInfoFetcher: &chainMock.ChainService{State: state},
}

resp, err := s.GetFinalityCheckpoints(ctx, &ethpb.StateRequest{
StateId: []byte("head"),
})
require.NoError(t, err)
assert.DeepEqual(t, bytesutil.PadTo([]byte("previous"), 32), resp.Data.PreviousJustified.Root)
assert.Equal(t, types.Epoch(113), resp.Data.PreviousJustified.Epoch)
assert.DeepEqual(t, bytesutil.PadTo([]byte("current"), 32), resp.Data.CurrentJustified.Root)
assert.Equal(t, types.Epoch(123), resp.Data.CurrentJustified.Epoch)
assert.DeepEqual(t, bytesutil.PadTo([]byte("finalized"), 32), resp.Data.Finalized.Root)
assert.Equal(t, types.Epoch(103), resp.Data.Finalized.Epoch)
})

t.Run("Genesis", func(t *testing.T) {
db := testDB.SetupDB(t)
b := testutil.NewBeaconBlock()
b.Block.StateRoot = bytesutil.PadTo([]byte("genesis"), 32)
require.NoError(t, db.SaveBlock(ctx, b))
r, err := b.Block.HashTreeRoot()
require.NoError(t, err)
require.NoError(t, db.SaveStateSummary(ctx, &pb.StateSummary{Root: r[:]}))
require.NoError(t, db.SaveGenesisBlockRoot(ctx, r))
st, err := testutil.NewBeaconState(func(state *pb.BeaconState) {
state.PreviousJustifiedCheckpoint = &eth.Checkpoint{
Root: bytesutil.PadTo([]byte("previous"), 32),
Epoch: 113,
}
state.CurrentJustifiedCheckpoint = &eth.Checkpoint{
Root: bytesutil.PadTo([]byte("current"), 32),
Epoch: 123,
}
state.FinalizedCheckpoint = &eth.Checkpoint{
Root: bytesutil.PadTo([]byte("finalized"), 32),
Epoch: 103,
}
})
require.NoError(t, err)
require.NoError(t, db.SaveState(ctx, st, r))

s := Server{
BeaconDB: db,
}

resp, err := s.GetFinalityCheckpoints(ctx, &ethpb.StateRequest{
StateId: []byte("genesis"),
})
require.NoError(t, err)
assert.DeepEqual(t, bytesutil.PadTo([]byte("previous"), 32), resp.Data.PreviousJustified.Root)
assert.Equal(t, types.Epoch(113), resp.Data.PreviousJustified.Epoch)
assert.DeepEqual(t, bytesutil.PadTo([]byte("current"), 32), resp.Data.CurrentJustified.Root)
assert.Equal(t, types.Epoch(123), resp.Data.CurrentJustified.Epoch)
assert.DeepEqual(t, bytesutil.PadTo([]byte("finalized"), 32), resp.Data.Finalized.Root)
assert.Equal(t, types.Epoch(103), resp.Data.Finalized.Epoch)
})

t.Run("Finalized", func(t *testing.T) {
stateGen := stategen.NewMockService()
stateGen.StatesByRoot[stateRoot] = state

s := Server{
ChainInfoFetcher: &chainMock.ChainService{
FinalizedCheckPoint: &eth.Checkpoint{
Root: stateRoot[:],
},
},
StateGenService: stateGen,
}

resp, err := s.GetFinalityCheckpoints(ctx, &ethpb.StateRequest{
StateId: []byte("finalized"),
})
require.NoError(t, err)
assert.DeepEqual(t, bytesutil.PadTo([]byte("previous"), 32), resp.Data.PreviousJustified.Root)
assert.Equal(t, types.Epoch(113), resp.Data.PreviousJustified.Epoch)
assert.DeepEqual(t, bytesutil.PadTo([]byte("current"), 32), resp.Data.CurrentJustified.Root)
assert.Equal(t, types.Epoch(123), resp.Data.CurrentJustified.Epoch)
assert.DeepEqual(t, bytesutil.PadTo([]byte("finalized"), 32), resp.Data.Finalized.Root)
assert.Equal(t, types.Epoch(103), resp.Data.Finalized.Epoch)
})

t.Run("Justified", func(t *testing.T) {
stateGen := stategen.NewMockService()
stateGen.StatesByRoot[stateRoot] = state

s := Server{
ChainInfoFetcher: &chainMock.ChainService{
CurrentJustifiedCheckPoint: &eth.Checkpoint{
Root: stateRoot[:],
},
},
StateGenService: stateGen,
}

resp, err := s.GetFinalityCheckpoints(ctx, &ethpb.StateRequest{
StateId: []byte("justified"),
})
require.NoError(t, err)
assert.DeepEqual(t, bytesutil.PadTo([]byte("previous"), 32), resp.Data.PreviousJustified.Root)
assert.Equal(t, types.Epoch(113), resp.Data.PreviousJustified.Epoch)
assert.DeepEqual(t, bytesutil.PadTo([]byte("current"), 32), resp.Data.CurrentJustified.Root)
assert.Equal(t, types.Epoch(123), resp.Data.CurrentJustified.Epoch)
assert.DeepEqual(t, bytesutil.PadTo([]byte("finalized"), 32), resp.Data.Finalized.Root)
assert.Equal(t, types.Epoch(103), resp.Data.Finalized.Epoch)
})

t.Run("Hex root", func(t *testing.T) {
stateId, err := hexutil.Decode("0x" + strings.Repeat("0", 63) + "1")
require.NoError(t, err)
stateGen := stategen.NewMockService()
stateGen.StatesByRoot[bytesutil.ToBytes32(stateId)] = state

s := Server{
ChainInfoFetcher: &chainMock.ChainService{State: state},
StateGenService: stateGen,
}

resp, err := s.GetFinalityCheckpoints(ctx, &ethpb.StateRequest{
StateId: stateId,
})
require.NoError(t, err)
assert.DeepEqual(t, bytesutil.PadTo([]byte("previous"), 32), resp.Data.PreviousJustified.Root)
assert.Equal(t, types.Epoch(113), resp.Data.PreviousJustified.Epoch)
assert.DeepEqual(t, bytesutil.PadTo([]byte("current"), 32), resp.Data.CurrentJustified.Root)
assert.Equal(t, types.Epoch(123), resp.Data.CurrentJustified.Epoch)
assert.DeepEqual(t, bytesutil.PadTo([]byte("finalized"), 32), resp.Data.Finalized.Root)
assert.Equal(t, types.Epoch(103), resp.Data.Finalized.Epoch)
})

t.Run("Hex root not found", func(t *testing.T) {
s := Server{
ChainInfoFetcher: &chainMock.ChainService{State: state},
}
stateId, err := hexutil.Decode("0x" + strings.Repeat("f", 64))
require.NoError(t, err)
_, err = s.GetFinalityCheckpoints(ctx, &ethpb.StateRequest{
StateId: stateId,
})
require.ErrorContains(t, "State not found in the last 8192 state roots in head state", err)
})

t.Run("Slot", func(t *testing.T) {
stateGen := stategen.NewMockService()
stateGen.StatesBySlot[headSlot] = state

s := Server{
GenesisTimeFetcher: &chainMock.ChainService{Slot: &headSlot},
StateGenService: stateGen,
}

resp, err := s.GetFinalityCheckpoints(ctx, &ethpb.StateRequest{
StateId: []byte(strconv.FormatUint(uint64(headSlot), 10)),
})
require.NoError(t, err)
assert.DeepEqual(t, bytesutil.PadTo([]byte("previous"), 32), resp.Data.PreviousJustified.Root)
assert.Equal(t, types.Epoch(113), resp.Data.PreviousJustified.Epoch)
assert.DeepEqual(t, bytesutil.PadTo([]byte("current"), 32), resp.Data.CurrentJustified.Root)
assert.Equal(t, types.Epoch(123), resp.Data.CurrentJustified.Epoch)
assert.DeepEqual(t, bytesutil.PadTo([]byte("finalized"), 32), resp.Data.Finalized.Root)
assert.Equal(t, types.Epoch(103), resp.Data.Finalized.Epoch)
})

t.Run("Slot too big", func(t *testing.T) {
s := Server{
GenesisTimeFetcher: &chainMock.ChainService{
Genesis: time.Now(),
},
}
_, err := s.GetFinalityCheckpoints(ctx, &ethpb.StateRequest{
StateId: []byte(strconv.FormatUint(1, 10)),
})
assert.ErrorContains(t, "Slot cannot be in the future", err)
})

t.Run("Checkpoints not available", func(t *testing.T) {
st, err := testutil.NewBeaconState()
require.NoError(t, err)
err = st.SetPreviousJustifiedCheckpoint(nil)
require.NoError(t, err)
err = st.SetCurrentJustifiedCheckpoint(nil)
require.NoError(t, err)
err = st.SetFinalizedCheckpoint(nil)
require.NoError(t, err)

s := Server{
ChainInfoFetcher: &chainMock.ChainService{State: st},
}

resp, err := s.GetFinalityCheckpoints(ctx, &ethpb.StateRequest{
StateId: []byte("head"),
})
require.NoError(t, err)
assert.DeepEqual(t, params.BeaconConfig().ZeroHash[:], resp.Data.PreviousJustified.Root)
assert.Equal(t, types.Epoch(0), resp.Data.PreviousJustified.Epoch)
assert.DeepEqual(t, params.BeaconConfig().ZeroHash[:], resp.Data.CurrentJustified.Root)
assert.Equal(t, types.Epoch(0), resp.Data.CurrentJustified.Epoch)
assert.DeepEqual(t, params.BeaconConfig().ZeroHash[:], resp.Data.Finalized.Root)
assert.Equal(t, types.Epoch(0), resp.Data.Finalized.Epoch)
})

t.Run("Invalid state", func(t *testing.T) {
s := Server{}
_, err := s.GetFinalityCheckpoints(ctx, &ethpb.StateRequest{
StateId: []byte("foo"),
})
require.ErrorContains(t, "Invalid state ID: foo", err)
})
}

0 comments on commit 1ae429d

Please sign in to comment.