|
|
@ -5,47 +5,48 @@ import ( |
|
|
|
"crypto/rand" |
|
|
|
"fmt" |
|
|
|
|
|
|
|
libp2p "github.com/libp2p/go-libp2p" |
|
|
|
crypto "github.com/libp2p/go-libp2p-crypto" |
|
|
|
peer "github.com/libp2p/go-libp2p-peer" |
|
|
|
pstore "github.com/libp2p/go-libp2p-peerstore" |
|
|
|
swarm "github.com/libp2p/go-libp2p-swarm" |
|
|
|
bhost "github.com/libp2p/go-libp2p/p2p/host/basic" |
|
|
|
ma "github.com/multiformats/go-multiaddr" |
|
|
|
) |
|
|
|
|
|
|
|
func main() { |
|
|
|
// Generate an identity keypair using go's cryptographic randomness source
|
|
|
|
priv, pub, err := crypto.GenerateEd25519Key(rand.Reader) |
|
|
|
// The context governs the lifetime of the libp2p node
|
|
|
|
ctx, cancel := context.WithCancel(context.Background()) |
|
|
|
defer cancel() |
|
|
|
|
|
|
|
// To construct a simple host with all the default settings, just use `New`
|
|
|
|
h, err := libp2p.New(ctx) |
|
|
|
if err != nil { |
|
|
|
panic(err) |
|
|
|
} |
|
|
|
|
|
|
|
// A peers ID is the hash of its public key
|
|
|
|
pid, err := peer.IDFromPublicKey(pub) |
|
|
|
fmt.Printf("Hello World, my hosts ID is %s\n", h.ID()) |
|
|
|
|
|
|
|
// If you want more control over the configuration, you can fill out fields
|
|
|
|
// in the libp2p config, and use `NewWithCfg`
|
|
|
|
cfg := new(libp2p.Config) |
|
|
|
|
|
|
|
// Set your own keypair
|
|
|
|
priv, _, err := crypto.GenerateEd25519Key(rand.Reader) |
|
|
|
if err != nil { |
|
|
|
panic(err) |
|
|
|
} |
|
|
|
cfg.PeerKey = priv |
|
|
|
|
|
|
|
// We've created the identity, now we need to store it.
|
|
|
|
// A peerstore holds information about peers, including your own
|
|
|
|
ps := pstore.NewPeerstore() |
|
|
|
ps.AddPrivKey(pid, priv) |
|
|
|
ps.AddPubKey(pid, pub) |
|
|
|
|
|
|
|
// Set your own listen address
|
|
|
|
maddr, err := ma.NewMultiaddr("/ip4/0.0.0.0/tcp/9000") |
|
|
|
if err != nil { |
|
|
|
panic(err) |
|
|
|
} |
|
|
|
|
|
|
|
// Make a context to govern the lifespan of the swarm
|
|
|
|
ctx := context.Background() |
|
|
|
// The config takes an array of addresses, specify as many as you want.
|
|
|
|
cfg.ListenAddrs = []ma.Multiaddr{maddr} |
|
|
|
|
|
|
|
// Put all this together
|
|
|
|
netw, err := swarm.NewNetwork(ctx, []ma.Multiaddr{maddr}, pid, ps, nil) |
|
|
|
h2, err := libp2p.NewWithCfg(ctx, cfg) |
|
|
|
if err != nil { |
|
|
|
panic(err) |
|
|
|
} |
|
|
|
|
|
|
|
myhost := bhost.New(netw) |
|
|
|
fmt.Printf("Hello World, my hosts ID is %s\n", myhost.ID()) |
|
|
|
fmt.Printf("Hello World, my second hosts ID is %s\n", h2.ID()) |
|
|
|
} |
|
|
|