github.com/koko1123/flow-go-1@v0.29.6/admin/commands/common/get_identity.go (about) 1 package common 2 3 import ( 4 "context" 5 "encoding/hex" 6 "fmt" 7 8 "github.com/libp2p/go-libp2p/core/peer" 9 10 "github.com/koko1123/flow-go-1/admin" 11 "github.com/koko1123/flow-go-1/admin/commands" 12 "github.com/koko1123/flow-go-1/model/flow" 13 "github.com/koko1123/flow-go-1/module" 14 ) 15 16 var _ commands.AdminCommand = (*GetIdentityCommand)(nil) 17 18 type getIdentityRequestType int 19 20 const ( 21 FlowID getIdentityRequestType = iota 22 PeerID 23 ) 24 25 type getIdentityRequestData struct { 26 requestType getIdentityRequestType 27 flowID flow.Identifier 28 peerID peer.ID 29 } 30 31 type GetIdentityCommand struct { 32 idProvider module.IdentityProvider 33 } 34 35 func (r *GetIdentityCommand) Handler(ctx context.Context, req *admin.CommandRequest) (interface{}, error) { 36 data := req.ValidatorData.(*getIdentityRequestData) 37 38 if data.requestType == FlowID { 39 identity, ok := r.idProvider.ByNodeID(data.flowID) 40 if !ok { 41 return nil, fmt.Errorf("no identity found for flow ID: %s", data.flowID) 42 } 43 return commands.ConvertToMap(identity) 44 } else { 45 identity, ok := r.idProvider.ByPeerID(data.peerID) 46 if !ok { 47 return nil, fmt.Errorf("no identity found for peer ID: %s", data.peerID) 48 } 49 return commands.ConvertToMap(identity) 50 } 51 } 52 53 // Validator validates the request. 54 // Returns admin.InvalidAdminReqError for invalid/malformed requests. 55 func (r *GetIdentityCommand) Validator(req *admin.CommandRequest) error { 56 input, ok := req.Data.(map[string]interface{}) 57 if !ok { 58 return admin.NewInvalidAdminReqFormatError("expected map[string]any") 59 } 60 61 data := &getIdentityRequestData{} 62 63 req.ValidatorData = data 64 65 if flowID, ok := input["flow_id"]; ok { 66 data.requestType = FlowID 67 68 if flowID, ok := flowID.(string); ok { 69 if len(flowID) == 2*flow.IdentifierLen { 70 if b, err := hex.DecodeString(flowID); err == nil { 71 data.flowID = flow.HashToID(b) 72 return nil 73 } 74 } 75 } 76 return admin.NewInvalidAdminReqParameterError("flow_id", "must be 64-char hex string", flowID) 77 } else if peerID, ok := input["peer_id"]; ok { 78 data.requestType = PeerID 79 80 if peerID, ok := peerID.(string); ok { 81 if pid, err := peer.Decode(peerID); err == nil { 82 data.peerID = pid 83 return nil 84 } 85 } 86 return admin.NewInvalidAdminReqParameterError("peer_id", "must be valid peer id string", peerID) 87 } 88 return admin.NewInvalidAdminReqErrorf("either \"flow_id\" or \"peer_id\" field is required") 89 } 90 91 func NewGetIdentityCommand(idProvider module.IdentityProvider) commands.AdminCommand { 92 return &GetIdentityCommand{ 93 idProvider: idProvider, 94 } 95 }