host.go 1.03 KB
Newer Older
1
2
3
4
package main

import (
	"context"
5
	"crypto/rand"
6
7
	"fmt"

Jeromy's avatar
Jeromy committed
8
	libp2p "github.com/libp2p/go-libp2p"
9
	crypto "github.com/libp2p/go-libp2p-crypto"
10
11
12
)

func main() {
Jeromy's avatar
Jeromy committed
13
14
15
16
17
18
	// 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)
19
20
21
22
	if err != nil {
		panic(err)
	}

Jeromy's avatar
Jeromy committed
23
24
	fmt.Printf("Hello World, my hosts ID is %s\n", h.ID())

Jeromy's avatar
Jeromy committed
25
26
	// If you want more control over the configuration, you can specify some
	// options to the constructor
Jeromy's avatar
Jeromy committed
27
28
29

	// Set your own keypair
	priv, _, err := crypto.GenerateEd25519Key(rand.Reader)
30
31
32
33
	if err != nil {
		panic(err)
	}

Jeromy's avatar
Jeromy committed
34
35
36
	h2, err := libp2p.New(ctx,
		// Use your own created keypair
		libp2p.WithPeerKey(priv),
37

Jeromy's avatar
Jeromy committed
38
39
40
41
		// Set your own listen address
		// The config takes an array of addresses, specify as many as you want.
		libp2p.ListenAddrStrings("/ip4/0.0.0.0/tcp/9000"),
	)
42
43
44
45
	if err != nil {
		panic(err)
	}

Jeromy's avatar
Jeromy committed
46
	fmt.Printf("Hello World, my second hosts ID is %s\n", h2.ID())
47
}