@@ -5,47 +5,48 @@ import (
5
5
"crypto/rand"
6
6
"fmt"
7
7
8
+ libp2p "github.com/libp2p/go-libp2p"
8
9
crypto "github.com/libp2p/go-libp2p-crypto"
9
- peer "github.com/libp2p/go-libp2p-peer"
10
- pstore "github.com/libp2p/go-libp2p-peerstore"
11
- swarm "github.com/libp2p/go-libp2p-swarm"
12
- bhost "github.com/libp2p/go-libp2p/p2p/host/basic"
13
10
ma "github.com/multiformats/go-multiaddr"
14
11
)
15
12
16
13
func main () {
17
- // Generate an identity keypair using go's cryptographic randomness source
18
- priv , pub , err := crypto .GenerateEd25519Key (rand .Reader )
14
+ // The context governs the lifetime of the libp2p node
15
+ ctx , cancel := context .WithCancel (context .Background ())
16
+ defer cancel ()
17
+
18
+ // To construct a simple host with all the default settings, just use `New`
19
+ h , err := libp2p .New (ctx )
19
20
if err != nil {
20
21
panic (err )
21
22
}
22
23
23
- // A peers ID is the hash of its public key
24
- pid , err := peer .IDFromPublicKey (pub )
24
+ fmt .Printf ("Hello World, my hosts ID is %s\n " , h .ID ())
25
+
26
+ // If you want more control over the configuration, you can fill out fields
27
+ // in the libp2p config, and use `NewWithCfg`
28
+ cfg := new (libp2p.Config )
29
+
30
+ // Set your own keypair
31
+ priv , _ , err := crypto .GenerateEd25519Key (rand .Reader )
25
32
if err != nil {
26
33
panic (err )
27
34
}
35
+ cfg .PeerKey = priv
28
36
29
- // We've created the identity, now we need to store it.
30
- // A peerstore holds information about peers, including your own
31
- ps := pstore .NewPeerstore ()
32
- ps .AddPrivKey (pid , priv )
33
- ps .AddPubKey (pid , pub )
34
-
37
+ // Set your own listen address
35
38
maddr , err := ma .NewMultiaddr ("/ip4/0.0.0.0/tcp/9000" )
36
39
if err != nil {
37
40
panic (err )
38
41
}
39
42
40
- // Make a context to govern the lifespan of the swarm
41
- ctx := context . Background ()
43
+ // The config takes an array of addresses, specify as many as you want.
44
+ cfg . ListenAddrs = []ma. Multiaddr { maddr }
42
45
43
- // Put all this together
44
- netw , err := swarm .NewNetwork (ctx , []ma.Multiaddr {maddr }, pid , ps , nil )
46
+ h2 , err := libp2p .NewWithCfg (ctx , cfg )
45
47
if err != nil {
46
48
panic (err )
47
49
}
48
50
49
- myhost := bhost .New (netw )
50
- fmt .Printf ("Hello World, my hosts ID is %s\n " , myhost .ID ())
51
+ fmt .Printf ("Hello World, my second hosts ID is %s\n " , h2 .ID ())
51
52
}
0 commit comments