status-go/vendor/github.com/libp2p/go-libp2p/config/security.go

79 lines
2.0 KiB
Go
Raw Normal View History

package config
import (
"fmt"
2019-06-09 07:24:20 +00:00
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/sec"
"github.com/libp2p/go-libp2p-core/sec/insecure"
csms "github.com/libp2p/go-conn-security-multistream"
)
// SecC is a security transport constructor
2019-06-09 07:24:20 +00:00
type SecC func(h host.Host) (sec.SecureTransport, error)
// MsSecC is a tuple containing a security transport constructor and a protocol
// ID.
type MsSecC struct {
SecC
ID string
}
var securityArgTypes = newArgTypeSet(
hostType, networkType, peerIDType,
privKeyType, pubKeyType, pstoreType,
)
// SecurityConstructor creates a security constructor from the passed parameter
// using reflection.
2019-06-09 07:24:20 +00:00
func SecurityConstructor(security interface{}) (SecC, error) {
// Already constructed?
2019-06-09 07:24:20 +00:00
if t, ok := security.(sec.SecureTransport); ok {
return func(_ host.Host) (sec.SecureTransport, error) {
return t, nil
}, nil
}
2019-06-09 07:24:20 +00:00
ctor, err := makeConstructor(security, securityType, securityArgTypes)
if err != nil {
return nil, err
}
2019-06-09 07:24:20 +00:00
return func(h host.Host) (sec.SecureTransport, error) {
t, err := ctor(h, nil)
if err != nil {
return nil, err
}
2019-06-09 07:24:20 +00:00
return t.(sec.SecureTransport), nil
}, nil
}
2019-06-09 07:24:20 +00:00
func makeInsecureTransport(id peer.ID) sec.SecureTransport {
secMuxer := new(csms.SSMuxer)
secMuxer.AddTransport(insecure.ID, insecure.New(id))
return secMuxer
}
2019-06-09 07:24:20 +00:00
func makeSecurityTransport(h host.Host, tpts []MsSecC) (sec.SecureTransport, error) {
secMuxer := new(csms.SSMuxer)
transportSet := make(map[string]struct{}, len(tpts))
for _, tptC := range tpts {
if _, ok := transportSet[tptC.ID]; ok {
return nil, fmt.Errorf("duplicate security transport: %s", tptC.ID)
}
2019-06-09 07:24:20 +00:00
transportSet[tptC.ID] = struct{}{}
}
for _, tptC := range tpts {
tpt, err := tptC.SecC(h)
if err != nil {
return nil, err
}
if _, ok := tpt.(*insecure.Transport); ok {
return nil, fmt.Errorf("cannot construct libp2p with an insecure transport, set the Insecure config option instead")
}
secMuxer.AddTransport(tptC.ID, tpt)
}
return secMuxer, nil
}