forked from prysmaticlabs/prysm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
blocks.go
284 lines (260 loc) · 9.69 KB
/
blocks.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package beacon
import (
"context"
"strconv"
ptypes "github.com/gogo/protobuf/types"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/feed"
blockfeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/block"
statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/db/filters"
"github.com/prysmaticlabs/prysm/beacon-chain/flags"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/pagination"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// ListBlocks retrieves blocks by root, slot, or epoch.
//
// The server may return multiple blocks in the case that a slot or epoch is
// provided as the filter criteria. The server may return an empty list when
// no blocks in their database match the filter criteria. This RPC should
// not return NOT_FOUND. Only one filter criteria should be used.
func (bs *Server) ListBlocks(
ctx context.Context, req *ethpb.ListBlocksRequest,
) (*ethpb.ListBlocksResponse, error) {
if int(req.PageSize) > flags.Get().MaxPageSize {
return nil, status.Errorf(codes.InvalidArgument, "Requested page size %d can not be greater than max size %d",
req.PageSize, flags.Get().MaxPageSize)
}
switch q := req.QueryFilter.(type) {
case *ethpb.ListBlocksRequest_Epoch:
blks, err := bs.BeaconDB.Blocks(ctx, filters.NewFilter().SetStartEpoch(q.Epoch).SetEndEpoch(q.Epoch))
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to get blocks: %v", err)
}
numBlks := len(blks)
if numBlks == 0 {
return ðpb.ListBlocksResponse{
BlockContainers: make([]*ethpb.BeaconBlockContainer, 0),
TotalSize: 0,
NextPageToken: strconv.Itoa(0),
}, nil
}
start, end, nextPageToken, err := pagination.StartAndEndPage(req.PageToken, int(req.PageSize), numBlks)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not paginate blocks: %v", err)
}
returnedBlks := blks[start:end]
containers := make([]*ethpb.BeaconBlockContainer, len(returnedBlks))
for i, b := range returnedBlks {
root, err := stateutil.BlockRoot(b.Block)
if err != nil {
return nil, err
}
containers[i] = ðpb.BeaconBlockContainer{
Block: b,
BlockRoot: root[:],
}
}
return ðpb.ListBlocksResponse{
BlockContainers: containers,
TotalSize: int32(numBlks),
NextPageToken: nextPageToken,
}, nil
case *ethpb.ListBlocksRequest_Root:
blk, err := bs.BeaconDB.Block(ctx, bytesutil.ToBytes32(q.Root))
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not retrieve block: %v", err)
}
if blk == nil {
return ðpb.ListBlocksResponse{
BlockContainers: make([]*ethpb.BeaconBlockContainer, 0),
TotalSize: 0,
NextPageToken: strconv.Itoa(0),
}, nil
}
root, err := stateutil.BlockRoot(blk.Block)
if err != nil {
return nil, err
}
return ðpb.ListBlocksResponse{
BlockContainers: []*ethpb.BeaconBlockContainer{{
Block: blk,
BlockRoot: root[:]},
},
TotalSize: 1,
}, nil
case *ethpb.ListBlocksRequest_Slot:
blks, err := bs.BeaconDB.Blocks(ctx, filters.NewFilter().SetStartSlot(q.Slot).SetEndSlot(q.Slot))
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not retrieve blocks for slot %d: %v", q.Slot, err)
}
numBlks := len(blks)
if numBlks == 0 {
return ðpb.ListBlocksResponse{
BlockContainers: make([]*ethpb.BeaconBlockContainer, 0),
TotalSize: 0,
NextPageToken: strconv.Itoa(0),
}, nil
}
start, end, nextPageToken, err := pagination.StartAndEndPage(req.PageToken, int(req.PageSize), numBlks)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not paginate blocks: %v", err)
}
returnedBlks := blks[start:end]
containers := make([]*ethpb.BeaconBlockContainer, len(returnedBlks))
for i, b := range returnedBlks {
root, err := stateutil.BlockRoot(b.Block)
if err != nil {
return nil, err
}
containers[i] = ðpb.BeaconBlockContainer{
Block: b,
BlockRoot: root[:],
}
}
return ðpb.ListBlocksResponse{
BlockContainers: containers,
TotalSize: int32(numBlks),
NextPageToken: nextPageToken,
}, nil
case *ethpb.ListBlocksRequest_Genesis:
genBlk, err := bs.BeaconDB.GenesisBlock(ctx)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not retrieve blocks for genesis slot: %v", err)
}
if genBlk == nil {
return nil, status.Error(codes.Internal, "Could not find genesis block")
}
root, err := stateutil.BlockRoot(genBlk.Block)
if err != nil {
return nil, err
}
containers := []*ethpb.BeaconBlockContainer{
{
Block: genBlk,
BlockRoot: root[:],
},
}
return ðpb.ListBlocksResponse{
BlockContainers: containers,
TotalSize: int32(1),
NextPageToken: strconv.Itoa(0),
}, nil
}
return nil, status.Error(codes.InvalidArgument, "Must specify a filter criteria for fetching blocks")
}
// GetChainHead retrieves information about the head of the beacon chain from
// the view of the beacon chain node.
//
// This includes the head block slot and root as well as information about
// the most recent finalized and justified slots.
func (bs *Server) GetChainHead(ctx context.Context, _ *ptypes.Empty) (*ethpb.ChainHead, error) {
return bs.chainHeadRetrieval(ctx)
}
// StreamBlocks to clients every single time a block is received by the beacon node.
func (bs *Server) StreamBlocks(_ *ptypes.Empty, stream ethpb.BeaconChain_StreamBlocksServer) error {
blocksChannel := make(chan *feed.Event, 1)
blockSub := bs.BlockNotifier.BlockFeed().Subscribe(blocksChannel)
defer blockSub.Unsubscribe()
for {
select {
case event := <-blocksChannel:
if event.Type == blockfeed.ReceivedBlock {
data, ok := event.Data.(*blockfeed.ReceivedBlockData)
if !ok {
// Got bad data over the stream.
continue
}
if data.SignedBlock == nil {
// One nil block shouldn't stop the stream.
continue
}
if err := stream.Send(data.SignedBlock); err != nil {
return status.Errorf(codes.Unavailable, "Could not send over stream: %v", err)
}
}
case <-blockSub.Err():
return status.Error(codes.Aborted, "Subscriber closed, exiting goroutine")
case <-bs.Ctx.Done():
return status.Error(codes.Canceled, "Context canceled")
case <-stream.Context().Done():
return status.Error(codes.Canceled, "Context canceled")
}
}
}
// StreamChainHead to clients every single time the head block and state of the chain change.
func (bs *Server) StreamChainHead(_ *ptypes.Empty, stream ethpb.BeaconChain_StreamChainHeadServer) error {
stateChannel := make(chan *feed.Event, 1)
stateSub := bs.StateNotifier.StateFeed().Subscribe(stateChannel)
defer stateSub.Unsubscribe()
for {
select {
case event := <-stateChannel:
if event.Type == statefeed.BlockProcessed {
res, err := bs.chainHeadRetrieval(bs.Ctx)
if err != nil {
return status.Errorf(codes.Internal, "Could not retrieve chain head: %v", err)
}
if err := stream.Send(res); err != nil {
return status.Errorf(codes.Unavailable, "Could not send over stream: %v", err)
}
}
case <-stateSub.Err():
return status.Error(codes.Aborted, "Subscriber closed, exiting goroutine")
case <-bs.Ctx.Done():
return status.Error(codes.Canceled, "Context canceled")
case <-stream.Context().Done():
return status.Error(codes.Canceled, "Context canceled")
}
}
}
// Retrieve chain head information from the DB and the current beacon state.
func (bs *Server) chainHeadRetrieval(ctx context.Context) (*ethpb.ChainHead, error) {
headBlock, err := bs.HeadFetcher.HeadBlock(ctx)
if err != nil {
return nil, status.Error(codes.Internal, "Could not get head block")
}
if headBlock == nil {
return nil, status.Error(codes.Internal, "Head block of chain was nil")
}
headBlockRoot, err := stateutil.BlockRoot(headBlock.Block)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not get head block root: %v", err)
}
finalizedCheckpoint := bs.FinalizationFetcher.FinalizedCheckpt()
b, err := bs.BeaconDB.Block(ctx, bytesutil.ToBytes32(finalizedCheckpoint.Root))
if err != nil || b == nil || b.Block == nil {
return nil, status.Error(codes.Internal, "Could not get finalized block")
}
finalizedSlot := b.Block.Slot
justifiedCheckpoint := bs.FinalizationFetcher.CurrentJustifiedCheckpt()
b, err = bs.BeaconDB.Block(ctx, bytesutil.ToBytes32(justifiedCheckpoint.Root))
if err != nil || b == nil || b.Block == nil {
return nil, status.Error(codes.Internal, "Could not get justified block")
}
justifiedSlot := b.Block.Slot
prevJustifiedCheckpoint := bs.FinalizationFetcher.PreviousJustifiedCheckpt()
b, err = bs.BeaconDB.Block(ctx, bytesutil.ToBytes32(prevJustifiedCheckpoint.Root))
if err != nil || b == nil || b.Block == nil {
return nil, status.Error(codes.Internal, "Could not get prev justified block")
}
prevJustifiedSlot := b.Block.Slot
return ðpb.ChainHead{
HeadSlot: headBlock.Block.Slot,
HeadEpoch: helpers.SlotToEpoch(headBlock.Block.Slot),
HeadBlockRoot: headBlockRoot[:],
FinalizedSlot: finalizedSlot,
FinalizedEpoch: finalizedCheckpoint.Epoch,
FinalizedBlockRoot: finalizedCheckpoint.Root,
JustifiedSlot: justifiedSlot,
JustifiedEpoch: justifiedCheckpoint.Epoch,
JustifiedBlockRoot: justifiedCheckpoint.Root,
PreviousJustifiedSlot: prevJustifiedSlot,
PreviousJustifiedEpoch: prevJustifiedCheckpoint.Epoch,
PreviousJustifiedBlockRoot: prevJustifiedCheckpoint.Root,
}, nil
}