Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Sign in / Register
Toggle navigation
Menu
Open sidebar
adam.huang
go-libp2p
Commits
f34163e3
Commit
f34163e3
authored
Nov 04, 2017
by
Jeromy
Browse files
first hack at a nice libp2p constructor
parent
4bba0bb6
Changes
1
Hide whitespace changes
Inline
Side-by-side
libp2p.go
0 → 100644
View file @
f34163e3
package
libp2p
import
(
"context"
"crypto/rand"
crypto
"github.com/libp2p/go-libp2p-crypto"
host
"github.com/libp2p/go-libp2p-host"
pnet
"github.com/libp2p/go-libp2p-interface-pnet"
metrics
"github.com/libp2p/go-libp2p-metrics"
peer
"github.com/libp2p/go-libp2p-peer"
pstore
"github.com/libp2p/go-libp2p-peerstore"
swarm
"github.com/libp2p/go-libp2p-swarm"
transport
"github.com/libp2p/go-libp2p-transport"
bhost
"github.com/libp2p/go-libp2p/p2p/host/basic"
mux
"github.com/libp2p/go-stream-muxer"
ma
"github.com/multiformats/go-multiaddr"
mplex
"github.com/whyrusleeping/go-smux-multiplex"
msmux
"github.com/whyrusleeping/go-smux-multistream"
yamux
"github.com/whyrusleeping/go-smux-yamux"
)
type
Config
struct
{
Transports
[]
transport
.
Transport
Muxer
mux
.
Transport
ListenAddrs
[]
ma
.
Multiaddr
PeerKey
crypto
.
PrivKey
Peerstore
pstore
.
Peerstore
Protector
pnet
.
Protector
Reporter
metrics
.
Reporter
}
func
Construct
(
ctx
context
.
Context
,
cfg
*
Config
)
(
host
.
Host
,
error
)
{
if
cfg
==
nil
{
cfg
=
DefaultConfig
()
}
if
cfg
.
PeerKey
==
nil
{
priv
,
_
,
err
:=
crypto
.
GenerateKeyPairWithReader
(
crypto
.
RSA
,
2048
,
rand
.
Reader
)
if
err
!=
nil
{
return
nil
,
err
}
cfg
.
PeerKey
=
priv
}
// Obtain Peer ID from public key
pid
,
err
:=
peer
.
IDFromPublicKey
(
cfg
.
PeerKey
.
GetPublic
())
if
err
!=
nil
{
return
nil
,
err
}
ps
:=
cfg
.
Peerstore
if
ps
==
nil
{
ps
=
pstore
.
NewPeerstore
()
}
ps
.
AddPrivKey
(
pid
,
cfg
.
PeerKey
)
ps
.
AddPubKey
(
pid
,
cfg
.
PeerKey
.
GetPublic
())
swrm
,
err
:=
swarm
.
NewSwarmWithProtector
(
ctx
,
cfg
.
ListenAddrs
,
pid
,
ps
,
cfg
.
Protector
,
cfg
.
Muxer
,
cfg
.
Reporter
)
if
err
!=
nil
{
return
nil
,
err
}
netw
:=
(
*
swarm
.
Network
)(
swrm
)
return
bhost
.
New
(
netw
),
nil
}
func
DefaultMuxer
()
mux
.
Transport
{
// Set up stream multiplexer
tpt
:=
msmux
.
NewBlankTransport
()
tpt
.
AddTransport
(
"/yamux/1.0.0"
,
yamux
.
DefaultTransport
)
tpt
.
AddTransport
(
"/mplex/6.3.0"
,
mplex
.
DefaultTransport
)
return
tpt
}
func
DefaultConfig
()
*
Config
{
// Create a multiaddress
addr
,
err
:=
ma
.
NewMultiaddr
(
"/ip4/127.0.0.1/tcp/0"
)
if
err
!=
nil
{
panic
(
err
)
}
return
&
Config
{
ListenAddrs
:
[]
ma
.
Multiaddr
{
addr
},
Peerstore
:
pstore
.
NewPeerstore
(),
Muxer
:
DefaultMuxer
(),
}
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment