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