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

import (
	"testing"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6
	bhost "github.com/ipfs/go-libp2p/p2p/host/basic"
Jeromy's avatar
Jeromy committed
7
	metrics "github.com/ipfs/go-libp2p/p2p/metrics"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8
9
10
	inet "github.com/ipfs/go-libp2p/p2p/net"
	swarm "github.com/ipfs/go-libp2p/p2p/net/swarm"
	peer "github.com/ipfs/go-libp2p/p2p/peer"
Jeromy's avatar
Jeromy committed
11
	tu "util/testutil"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12

Jeromy's avatar
Jeromy committed
13
	ma "QmbWxL1aXQhBjc1XGjGF1f2KGBMCBYSuT2ThA8YXnXJK83/go-multiaddr"
Jeromy's avatar
Jeromy committed
14
	context "golang.org/x/net/context"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15
16
17
18
19
20
21
)

func GenSwarmNetwork(t *testing.T, ctx context.Context) *swarm.Network {
	p := tu.RandPeerNetParamsOrFatal(t)
	ps := peer.NewPeerstore()
	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)
	}
26
	ps.AddAddrs(p.ID, n.ListenAddresses(), peer.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
33
	addrs := a.Peerstore().Addrs(id)
	b.Peerstore().AddAddrs(id, addrs, peer.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