util.go 1.07 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1
2
3
package testutil

import (
Jeromy's avatar
Jeromy committed
4
	"context"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
5
6
	"testing"

7
8
	bhost "github.com/libp2p/go-libp2p/p2p/host/basic"
	swarm "github.com/libp2p/go-libp2p/p2p/net/swarm"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9

Jeromy's avatar
Jeromy committed
10
	pstore "github.com/ipfs/go-libp2p-peerstore"
Jeromy's avatar
Jeromy committed
11
	ma "github.com/jbenet/go-multiaddr"
Jeromy's avatar
Jeromy committed
12
13
	metrics "github.com/libp2p/go-libp2p-metrics"
	inet "github.com/libp2p/go-libp2p-net"
Jeromy's avatar
Jeromy committed
14
	tu "github.com/libp2p/go-testutil"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15
16
17
18
)

func GenSwarmNetwork(t *testing.T, ctx context.Context) *swarm.Network {
	p := tu.RandPeerNetParamsOrFatal(t)
Jeromy's avatar
Jeromy committed
19
	ps := pstore.NewPeerstore()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20
21
	ps.AddPubKey(p.ID, p.PubKey)
	ps.AddPrivKey(p.ID, p.PrivKey)
Jeromy's avatar
Jeromy committed
22
	n, err := swarm.NewNetwork(ctx, []ma.Multiaddr{p.Addr}, p.ID, ps, metrics.NewBandwidthCounter())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
23
24
25
	if err != nil {
		t.Fatal(err)
	}
Jeromy's avatar
Jeromy committed
26
	ps.AddAddrs(p.ID, n.ListenAddresses(), pstore.PermanentAddrTTL)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
27
28
29
30
31
	return n
}

func DivulgeAddresses(a, b inet.Network) {
	id := a.LocalPeer()
32
	addrs := a.Peerstore().Addrs(id)
Jeromy's avatar
Jeromy committed
33
	b.Peerstore().AddAddrs(id, addrs, pstore.PermanentAddrTTL)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
34
35
36
37
38
39
}

func GenHostSwarm(t *testing.T, ctx context.Context) *bhost.BasicHost {
	n := GenSwarmNetwork(t, ctx)
	return bhost.New(n)
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
40
41

var RandPeerID = tu.RandPeerID