github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/network/p2p/node/libp2pUtils_test.go (about) 1 package p2pnode_test 2 3 import ( 4 "fmt" 5 "testing" 6 7 "github.com/libp2p/go-libp2p/core/peer" 8 "github.com/multiformats/go-multiaddr" 9 "github.com/onflow/crypto" 10 "github.com/stretchr/testify/assert" 11 "github.com/stretchr/testify/require" 12 "github.com/stretchr/testify/suite" 13 14 "github.com/onflow/flow-go/model/flow" 15 "github.com/onflow/flow-go/network/p2p/keyutils" 16 "github.com/onflow/flow-go/network/p2p/utils" 17 "github.com/onflow/flow-go/utils/unittest" 18 ) 19 20 type LibP2PUtilsTestSuite struct { 21 suite.Suite 22 } 23 24 func TestLibP2PUtilsTestSuite(t *testing.T) { 25 suite.Run(t, new(LibP2PUtilsTestSuite)) 26 } 27 28 // TestPeerInfoFromID tests that PeerInfoFromID converts a flow.Identity to peer.AddrInfo correctly 29 func (ts *LibP2PUtilsTestSuite) TestPeerInfoFromID() { 30 ids, exceptedPeerInfos := idsAndPeerInfos(ts.T()) 31 for i, id := range ids { 32 actualAddrInfo, err := utils.PeerAddressInfo(id.IdentitySkeleton) 33 assert.NoError(ts.T(), err) 34 assert.Equal(ts.T(), exceptedPeerInfos[i].String(), actualAddrInfo.String()) 35 } 36 } 37 38 func idsAndPeerInfos(t *testing.T) (flow.IdentityList, []peer.AddrInfo) { 39 ips := []string{"1.1.1.1", "2.2.2.2"} 40 port := "3569" 41 42 ids := make(flow.IdentityList, len(ips)) 43 peerInfos := make([]peer.AddrInfo, len(ips)) 44 45 keyOpt := func(id *flow.Identity) { 46 key, err := generateFlowNetworkingKey(id.NodeID) 47 require.NoError(t, err) 48 id.NetworkPubKey = key.PublicKey() 49 } 50 51 for i, ip := range ips { 52 // create a flow Identity 53 id := unittest.IdentityFixture(keyOpt) 54 id.Address = fmt.Sprintf("%s:%s", ip, port) 55 ids[i] = id 56 57 // create a libp2p p2p.PeerAddressInfo 58 libp2pKey, err := keyutils.LibP2PPublicKeyFromFlow(id.NetworkPubKey) 59 assert.NoError(t, err) 60 peerID, err := peer.IDFromPublicKey(libp2pKey) 61 assert.NoError(t, err) 62 addrInfo := peer.AddrInfo{ 63 ID: peerID, 64 Addrs: []multiaddr.Multiaddr{multiaddr.StringCast(fmt.Sprintf("/ip4/%s/tcp/%s", ip, port))}, 65 } 66 peerInfos[i] = addrInfo 67 } 68 69 return ids, peerInfos 70 } 71 72 func generateFlowNetworkingKey(s flow.Identifier) (crypto.PrivateKey, error) { 73 seed := make([]byte, crypto.KeyGenSeedMinLen) 74 copy(seed, s[:]) 75 return crypto.GeneratePrivateKey(crypto.ECDSASecp256k1, seed) 76 } 77 78 func BenchmarkPeerInfoFromID(b *testing.B) { 79 b.StopTimer() 80 id := unittest.IdentityFixture() 81 key, _ := generateFlowNetworkingKey(id.NodeID) 82 id.NetworkPubKey = key.PublicKey() 83 id.Address = "1.1.1.1:3569" 84 b.StartTimer() 85 for n := 0; n < b.N; n++ { 86 _, _ = utils.PeerAddressInfo(id.IdentitySkeleton) 87 } 88 }