github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/network/p2p/translator/hierarchical_translator.go (about) 1 package translator 2 3 import ( 4 "fmt" 5 6 "github.com/hashicorp/go-multierror" 7 "github.com/libp2p/go-libp2p/core/peer" 8 9 "github.com/onflow/flow-go/network/p2p" 10 11 "github.com/onflow/flow-go/model/flow" 12 ) 13 14 // HierarchicalIDTranslator implements an IDTranslator which combines the ID translation 15 // capabilities of multiple IDTranslators. 16 // When asked to translate an ID, it will iterate through all of the IDTranslators it was 17 // given and return the first successful translation. 18 type HierarchicalIDTranslator struct { 19 translators []p2p.IDTranslator 20 } 21 22 func NewHierarchicalIDTranslator(translators ...p2p.IDTranslator) *HierarchicalIDTranslator { 23 return &HierarchicalIDTranslator{translators} 24 } 25 26 func (t *HierarchicalIDTranslator) GetPeerID(flowID flow.Identifier) (peer.ID, error) { 27 var errs *multierror.Error 28 for _, translator := range t.translators { 29 pid, err := translator.GetPeerID(flowID) 30 if err == nil { 31 return pid, nil 32 } 33 errs = multierror.Append(errs, err) 34 } 35 return "", fmt.Errorf("could not translate the given flow ID: %w", errs) 36 } 37 38 func (t *HierarchicalIDTranslator) GetFlowID(peerID peer.ID) (flow.Identifier, error) { 39 var errs *multierror.Error 40 for _, translator := range t.translators { 41 fid, err := translator.GetFlowID(peerID) 42 if err == nil { 43 return fid, nil 44 } 45 errs = multierror.Append(errs, err) 46 } 47 return flow.ZeroID, fmt.Errorf("could not translate the given peer ID: %w", errs) 48 }