2019-07-02 12:40:25 +00:00
|
|
|
package lp2p
|
2019-07-01 09:09:48 +00:00
|
|
|
|
|
|
|
import (
|
2019-10-03 00:02:06 +00:00
|
|
|
"crypto/rand"
|
|
|
|
"github.com/filecoin-project/go-lotus/chain/types"
|
|
|
|
"github.com/filecoin-project/go-lotus/node/repo"
|
|
|
|
"golang.org/x/xerrors"
|
2019-07-01 09:09:48 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
logging "github.com/ipfs/go-log"
|
|
|
|
"github.com/libp2p/go-libp2p"
|
2019-07-05 11:21:54 +00:00
|
|
|
connmgr "github.com/libp2p/go-libp2p-connmgr"
|
2019-07-01 09:09:48 +00:00
|
|
|
"github.com/libp2p/go-libp2p-core/crypto"
|
|
|
|
"github.com/libp2p/go-libp2p-core/peer"
|
|
|
|
"github.com/libp2p/go-libp2p-core/peerstore"
|
|
|
|
"go.uber.org/fx"
|
|
|
|
)
|
|
|
|
|
|
|
|
var log = logging.Logger("p2pnode")
|
|
|
|
|
2019-10-03 00:02:06 +00:00
|
|
|
const kstorePrivkey = "libp2p-host"
|
|
|
|
|
2019-07-01 09:09:48 +00:00
|
|
|
type Libp2pOpts struct {
|
|
|
|
fx.Out
|
|
|
|
|
|
|
|
Opts []libp2p.Option `group:"libp2p"`
|
|
|
|
}
|
|
|
|
|
2019-10-03 00:02:06 +00:00
|
|
|
func PrivKey(ks types.KeyStore) (crypto.PrivKey, error) {
|
|
|
|
k, err := ks.Get(kstorePrivkey)
|
|
|
|
if err == nil {
|
|
|
|
return crypto.UnmarshalPrivateKey(k.PrivateKey)
|
|
|
|
}
|
|
|
|
if !xerrors.Is(err, repo.ErrKeyNotFound) {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
pk, err := genLibp2pKey()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
kbytes, err := pk.Bytes()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := ks.Put(kstorePrivkey, types.KeyInfo{
|
|
|
|
Type: kstorePrivkey,
|
|
|
|
PrivateKey: kbytes,
|
|
|
|
}); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return pk, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func genLibp2pKey() (crypto.PrivKey, error) {
|
|
|
|
pk, _, err := crypto.GenerateEd25519Key(rand.Reader)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return pk, nil
|
|
|
|
}
|
|
|
|
|
2019-07-01 09:09:48 +00:00
|
|
|
// Misc options
|
|
|
|
|
|
|
|
func ConnectionManager(low, high int, grace time.Duration) func() (opts Libp2pOpts, err error) {
|
|
|
|
return func() (opts Libp2pOpts, err error) {
|
|
|
|
cm := connmgr.NewConnManager(low, high, grace)
|
|
|
|
opts.Opts = append(opts.Opts, libp2p.ConnectionManager(cm))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func PstoreAddSelfKeys(id peer.ID, sk crypto.PrivKey, ps peerstore.Peerstore) error {
|
|
|
|
if err := ps.AddPubKey(id, sk.GetPublic()); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return ps.AddPrivKey(id, sk)
|
|
|
|
}
|
|
|
|
|
|
|
|
func simpleOpt(opt libp2p.Option) func() (opts Libp2pOpts, err error) {
|
|
|
|
return func() (opts Libp2pOpts, err error) {
|
|
|
|
opts.Opts = append(opts.Opts, opt)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|