testutil: peer gen with addrs
Juan Batiz-Benet committed
Dec 17, 2014 at 17:18 UTC
ad43e1d462ace950380190025e9c57f2d3778ada
1 file changed
+42
util/testutil/gen.go
+42
@@ -2,9 +2,14 @@ package testutil
2
3
import (
4
crand "crypto/rand"
5
+ "fmt"
6
+ "math/rand"
7
+
8
ci "github.com/jbenet/go-ipfs/crypto"
9
peer "github.com/jbenet/go-ipfs/peer"
10
u "github.com/jbenet/go-ipfs/util"
11
+
12
+ ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
13
)
14
15
func RandPeer() peer.Peer {
@@ -22,3 +27,40 @@ func PeerWithNewKeys() (peer.Peer, error) {
27
28
return NewPeerWithKeyPair(sk, pk)
29
}
30
+
31
+func PeerWithKeysAndStringAddress(addr string) (peer.Peer, error) {
32
+ maddr, err := ma.NewMultiaddr(addr)
33
+ if err != nil {
34
+ return nil, err
35
+ }
36
+
37
+ return PeerWithKeysAndAddress(maddr)
38
+}
39
+
40
+func PeerWithKeysAndAddress(maddr ma.Multiaddr) (peer.Peer, error) {
41
+ sk, pk, err := ci.GenerateKeyPair(ci.RSA, 512)
42
+ if err != nil {
43
+ return nil, err
44
+ }
45
+
46
+ p, err := NewPeerWithKeyPair(sk, pk)
47
+ if err != nil {
48
+ return nil, err
49
+ }
50
+
51
+ p.AddAddress(maddr)
52
+ return p, nil
53
+}
54
+
55
+// RandLocalTCPAddress returns a random multiaddr. it suppresses errors
56
+// for nice composability-- do check the address isn't nil.
57
+func RandLocalTCPAddress() ma.Multiaddr {
58
+
59
+ // chances are it will work out, but it **might** fail if the port is in use
60
+ // most ports above 10000 aren't in use by long running processes, so yay.
61
+ // (maybe there should be a range of "loopback" ports that are guaranteed
62
+ // to be open for the process, but naturally can only talk to self.)
63
+ addr := fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", 10000+rand.Intn(50000))
64
+ maddr, _ := ma.NewMultiaddr(addr)
65
+ return maddr
66
+}