github.com/prysmaticlabs/prysm@v1.4.4/beacon-chain/rpc/prysm/v1alpha1/debug/state.go (about)

     1  package debug
     2  
     3  import (
     4  	"context"
     5  
     6  	pbrpc "github.com/prysmaticlabs/prysm/proto/beacon/rpc/v1"
     7  	"github.com/prysmaticlabs/prysm/shared/bytesutil"
     8  	"google.golang.org/grpc/codes"
     9  	"google.golang.org/grpc/status"
    10  )
    11  
    12  // GetBeaconState retrieves an ssz-encoded beacon state
    13  // from the beacon node by either a slot or block root.
    14  func (ds *Server) GetBeaconState(
    15  	ctx context.Context,
    16  	req *pbrpc.BeaconStateRequest,
    17  ) (*pbrpc.SSZResponse, error) {
    18  	switch q := req.QueryFilter.(type) {
    19  	case *pbrpc.BeaconStateRequest_Slot:
    20  		currentSlot := ds.GenesisTimeFetcher.CurrentSlot()
    21  		requestedSlot := q.Slot
    22  		if requestedSlot > currentSlot {
    23  			return nil, status.Errorf(
    24  				codes.InvalidArgument,
    25  				"Cannot retrieve information about a slot in the future, current slot %d, requested slot %d",
    26  				currentSlot,
    27  				requestedSlot,
    28  			)
    29  		}
    30  
    31  		st, err := ds.StateGen.StateBySlot(ctx, q.Slot)
    32  		if err != nil {
    33  			return nil, status.Errorf(codes.Internal, "Could not compute state by slot: %v", err)
    34  		}
    35  		encoded, err := st.MarshalSSZ()
    36  		if err != nil {
    37  			return nil, status.Errorf(codes.Internal, "Could not ssz encode beacon state: %v", err)
    38  		}
    39  		return &pbrpc.SSZResponse{
    40  			Encoded: encoded,
    41  		}, nil
    42  	case *pbrpc.BeaconStateRequest_BlockRoot:
    43  		st, err := ds.StateGen.StateByRoot(ctx, bytesutil.ToBytes32(q.BlockRoot))
    44  		if err != nil {
    45  			return nil, status.Errorf(codes.Internal, "Could not compute state by block root: %v", err)
    46  		}
    47  		encoded, err := st.MarshalSSZ()
    48  		if err != nil {
    49  			return nil, status.Errorf(codes.Internal, "Could not ssz encode beacon state: %v", err)
    50  		}
    51  		return &pbrpc.SSZResponse{
    52  			Encoded: encoded,
    53  		}, nil
    54  	default:
    55  		return nil, status.Error(codes.InvalidArgument, "Need to specify either a block root or slot to request state")
    56  	}
    57  }