Initial code for peer in go

This commit is contained in:
Mike Goelzer 2018-09-04 14:30:16 -07:00
parent bffe948488
commit 99d19685dd
No known key found for this signature in database
GPG Key ID: EDAC46A37751AD6D
2 changed files with 197 additions and 0 deletions

12
Makefile Normal file
View File

@ -0,0 +1,12 @@
#SRC = main.go
SRC = main-dht-bootstrap.go
BIN = $(SRC:.go=)
DHT_SERVER = libp2p-bootstrap.goelzer.io
all: $(SRC)
# go build -o $(SRC:.go=) $(SRC)
go build -o $(BIN) $(SRC)
install:
scp $(SRC:.go=) $(DHT_SERVER):~/
ssh $(DHT_SERVER) ./$(BIN)

185
main-dht-bootstrap.go Normal file
View File

@ -0,0 +1,185 @@
package main
import (
"bufio"
"context"
"fmt"
"os"
"time"
"github.com/multiformats/go-multihash"
"github.com/libp2p/go-floodsub"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p-kad-dht"
"github.com/libp2p/go-libp2p-kad-dht/opts"
_ "github.com/libp2p/go-libp2p-peerstore"
"github.com/ipfs/go-cid"
// "github.com/ipfs/go-datastore"
_ "github.com/ipfs/go-ipfs-addr"
)
var f_bootstrap bool
const bootstrapHostname string = "libp2p-bootstrap.goelzer.io"
func usage() {
fmt.Printf("Usage: %s [OPTIONS]\n\n", os.Args[1]);
fmt.Printf(" --bootstrapper Start a DHT; initial peer only.\n");
fmt.Printf(" --peer=IP Connect to IP to join the libp2p swarm\n");
fmt.Printf(" --port=N Listen and connect on N\n");
fmt.Printf(" --help Display this message\n");
fmt.Printf("Note that --bootstrapper and --peer are mutually exclusive.\n");
fmt.Printf("\nThis program demonstrates a libp2p swarm. The first node");
fmt.Printf("is started with `--bootstrapper`. Add a second node with");
fmt.Printf("`--peer=IP_OF_FIRST_NODE`.");
}
func main() {
usage(); os.Exit(1);
//
// Bootstrap mode '--bootstrap' => we create a DHT
// Else: we connect to an existing DHT at known location
//
arg := os.Args[1]
if (arg=="--bootstrap") {
f_bootstrap = true;
} else {
f_bootstrap = false;
}
fmt.Println("f_bootstrap = %d", f_bootstrap)
ctx := context.Background()
//
// Set up a libp2p host.
//
host, err := libp2p.New(ctx, libp2p.Defaults)
if err != nil {
fmt.Println("libp2p.New: failed: %v",err)
panic(err)
}
// TODO: get my own public IP instead of assuming 159.89.221.55 (IP of libp2p-bootstrap.goelzer.io)
fmt.Println("My adress: /ip4/159.89.221.55/tcp/5555/ipfs/%s", host.ID().Pretty() )
// TODO: rename to PubSubTopicName
TopicName := "libp2p-go-js-rust-chat"
_ = TopicName
//
// Construct ourselves a pubsub instance using that libp2p host.
//
fsub, err := floodsub.NewFloodSub(ctx, host)
if err != nil {
panic(err)
}
_ = fsub
//
// Construct a DHT for discovery.
//
dht, err := dht.New(ctx, host, dhtopts.Client(false) )
if err != nil {
panic(err)
}
_ = dht
// These are the IPFS bootstrap nodes:
//
// bootstrapPeers := []string{
// "/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ",
// "/ip4/104.236.179.241/tcp/4001/ipfs/QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM",
// "/ip4/104.236.76.40/tcp/4001/ipfs/QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64",
// "/ip4/128.199.219.111/tcp/4001/ipfs/QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu",
// "/ip4/178.62.158.247/tcp/4001/ipfs/QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd",
// }
//// bootstrapPeers := []string{
//// fmt.Sprintf("/ip4/159.89.221.55/tcp/5555/ipfs/%s", host.ID().Pretty()),
//// }
//
// fmt.Println("bootstrapping...")
// for _, addr := range bootstrapPeers {
// iaddr, _ := ipfsaddr.ParseString(addr)
//
// pinfo, _ := peerstore.InfoFromP2pAddr(iaddr.Multiaddr())
//
// if err := host.Connect(ctx, *pinfo); err != nil {
// fmt.Println("bootstrapping to peer failed: ", err)
// }
// }
// Using the sha256 of our "topic" as our rendezvous value
c, _ := cid.NewPrefixV1(cid.Raw, multihash.SHA2_256).Sum([]byte(TopicName))
// First, announce ourselves as participating in this topic
fmt.Println("announcing ourselves...")
tctx, _ := context.WithTimeout(ctx, time.Second*10)
if err := dht.Provide(tctx, c, true); err != nil {
panic(err)
}
// // Now, look for others who have announced
// fmt.Println("searching for other peers...")
// tctx, _ = context.WithTimeout(ctx, time.Second*10)
// peers, err := dht.FindProviders(tctx, c)
// if err != nil {
// panic(err)
// }
// fmt.Printf("Found %d peers!\n", len(peers))
//
// // Now connect to them!
// for _, p := range peers {
// if p.ID == host.ID() {
// // No sense connecting to ourselves
// continue
// }
//
// tctx, _ := context.WithTimeout(ctx, time.Second*5)
// if err := host.Connect(tctx, p); err != nil {
// fmt.Println("failed to connect to peer: ", err)
// }
// }
//
// fmt.Println("bootstrapping and discovery complete!")
//
sub, err := fsub.Subscribe(TopicName)
if err != nil {
panic(err)
}
// Go and listen for messages from them, and print them to the screen
go func() {
for {
msg, err := sub.Next(ctx)
if err != nil {
panic(err)
}
fmt.Printf("%s: %s\n", msg.GetFrom(), string(msg.GetData()))
}
}()
// Now, wait for input from the user, and send that out!
fmt.Println("Type something and hit enter to send:")
scan := bufio.NewScanner(os.Stdin)
for scan.Scan() {
if err := fsub.Publish(TopicName, scan.Bytes()); err != nil {
panic(err)
}
}
}