github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/network/p2p/translator/identity_provider_translator.go (about) 1 package translator 2 3 import ( 4 "fmt" 5 6 "github.com/libp2p/go-libp2p/core/peer" 7 8 "github.com/onflow/flow-go/model/flow" 9 "github.com/onflow/flow-go/model/flow/filter" 10 "github.com/onflow/flow-go/module" 11 "github.com/onflow/flow-go/network/p2p" 12 "github.com/onflow/flow-go/network/p2p/keyutils" 13 p2plogging "github.com/onflow/flow-go/network/p2p/logging" 14 ) 15 16 // IdentityProviderIDTranslator implements an `p2p.IDTranslator` which provides ID 17 // translation capabilities for an IdentityProvider. 18 type IdentityProviderIDTranslator struct { 19 idProvider module.IdentityProvider 20 } 21 22 var _ p2p.IDTranslator = (*IdentityProviderIDTranslator)(nil) 23 24 func (t *IdentityProviderIDTranslator) GetFlowID(p peer.ID) (flow.Identifier, error) { 25 key, err := p.ExtractPublicKey() 26 if err != nil { 27 return flow.ZeroID, err 28 } 29 flowKey, err := keyutils.FlowPublicKeyFromLibP2P(key) 30 if err != nil { 31 return flow.ZeroID, err 32 } 33 ids := t.idProvider.Identities(filter.HasNetworkingKey(flowKey)) 34 if len(ids) == 0 { 35 return flow.ZeroID, fmt.Errorf("could not find identity corresponding to peer id %v", p2plogging.PeerId(p)) 36 } 37 return ids[0].NodeID, nil 38 } 39 40 func (t *IdentityProviderIDTranslator) GetPeerID(n flow.Identifier) (peer.ID, error) { 41 ids := t.idProvider.Identities(filter.HasNodeID[flow.Identity](n)) 42 if len(ids) == 0 { 43 return "", fmt.Errorf("could not find identity with id %v", n.String()) 44 } 45 key, err := keyutils.LibP2PPublicKeyFromFlow(ids[0].NetworkPubKey) 46 if err != nil { 47 return "", err 48 } 49 pid, err := peer.IDFromPublicKey(key) 50 if err != nil { 51 return "", err 52 } 53 return pid, nil 54 } 55 56 func NewIdentityProviderIDTranslator(provider module.IdentityProvider) *IdentityProviderIDTranslator { 57 return &IdentityProviderIDTranslator{provider} 58 }