prysm-pulse/beacon-chain/sync/rpc_recent_beacon_blocks.go
Nishant Das 74df2aa0c3 Add Recent Blocks RPC Request Handler (#3281)
* add new rpc handler

* gaz

* add it back

* remove ok

* preston's comments
2019-08-23 13:10:25 -04:00

60 lines
1.9 KiB
Go

package sync
import (
"context"
"time"
"github.com/gogo/protobuf/proto"
libp2pcore "github.com/libp2p/go-libp2p-core"
"github.com/pkg/errors"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
)
// recentBeaconBlocksRPCHandler looks up the request blocks from the database from the given block roots.
func (r *RegularSync) recentBeaconBlocksRPCHandler(ctx context.Context, msg proto.Message, stream libp2pcore.Stream) error {
defer stream.Close()
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
setRPCStreamDeadlines(stream)
log := log.WithField("handler", "recent_beacon_blocks")
m := msg.(*pb.RecentBeaconBlocksRequest)
blockRoots := m.BlockRoots
if len(blockRoots) == 0 {
resp, err := r.generateErrorResponse(responseCodeInvalidRequest, "no block roots provided in request")
if err != nil {
log.WithError(err).Error("Failed to generate a response error")
} else {
if _, err := stream.Write(resp); err != nil {
log.WithError(err).Errorf("Failed to write to stream")
}
}
return errors.New("no block roots provided")
}
ret := &pb.BeaconBlocksResponse{}
for _, root := range blockRoots {
blk, err := r.db.Block(ctx, bytesutil.ToBytes32(root))
if err != nil {
log.WithError(err).Error("Failed to fetch block")
resp, err := r.generateErrorResponse(responseCodeServerError, genericError)
if err != nil {
log.WithError(err).Error("Failed to generate a response error")
} else {
if _, err := stream.Write(resp); err != nil {
log.WithError(err).Errorf("Failed to write to stream")
}
}
return err
}
// if block returned is nil, it appends nil to the slice
ret.Blocks = append(ret.Blocks, blk)
}
if _, err := stream.Write([]byte{responseCodeSuccess}); err != nil {
log.WithError(err).Error("Failed to write to stream")
}
_, err := r.p2p.Encoding().Encode(stream, ret)
return err
}