Created
August 5, 2014 02:46
-
-
Save whyrusleeping/2d62f5f3453c3b963455 to your computer and use it in GitHub Desktop.
beginning a testbed for ipfs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
dht "github.com/jbenet/go-ipfs/routing/dht" | |
peer "github.com/jbenet/go-ipfs/peer" | |
ma "github.com/jbenet/go-multiaddr" | |
u "github.com/jbenet/go-ipfs/util" | |
"crypto/rand" | |
"time" | |
"fmt" | |
) | |
type dhtInfo struct { | |
dht *dht.IpfsDHT | |
addr *ma.Multiaddr | |
p *peer.Peer | |
} | |
func _randPeerID() peer.ID { | |
buf := make([]byte, 16) | |
rand.Read(buf) | |
return peer.ID(buf) | |
} | |
func setupDHT(addr string) *dhtInfo { | |
addr_ma,err := ma.NewMultiaddr(addr) | |
if err != nil { | |
panic(err) | |
} | |
peer_dht := new(peer.Peer) | |
peer_dht.AddAddress(addr_ma) | |
peer_dht.ID = _randPeerID() | |
ndht,err := dht.NewDHT(peer_dht) | |
if err != nil { | |
panic(err) | |
} | |
ndht.Start() | |
return &dhtInfo{ndht,addr_ma,peer_dht} | |
} | |
func ConnectPeers(dhts []*dhtInfo, a, b int) { | |
di_a := dhts[a] | |
di_b := dhts[b] | |
err := di_a.dht.Connect(di_b.addr) | |
if err != nil { | |
panic(err) | |
} | |
} | |
func PingBetween(dhts []*dhtInfo, a, b int) { | |
dhts[a].dht.Ping(dhts[b].p, time.Second * 2) | |
} | |
func main() { | |
u.Debug = true | |
var dhts []*dhtInfo | |
for i := 0; i < 3; i++ { | |
dhts = append(dhts, setupDHT(fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", 5000 + i))) | |
} | |
ConnectPeers(dhts, 0, 1) | |
ConnectPeers(dhts, 2, 0) | |
//Test that we can ping the node | |
PingBetween(dhts, 0, 1) | |
PingBetween(dhts, 1, 0) | |
dha := dhts[0] | |
err := dha.dht.PutValue(u.Key("hello"), []byte("world")) | |
if err != nil { | |
panic(err) | |
} | |
out,err := dha.dht.GetValue(u.Key("hello"), time.Second * 2) | |
fmt.Println(string(out)) | |
fmt.Println("Done!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment