insecure.go 2.29 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Package insecure provides an insecure, unencrypted implementation of the the SecureConn and SecureTransport interfaces.
//
// Recommended only for testing and other non-production usage.
package insecure

import (
	"context"
	"net"

	"github.com/libp2p/go-libp2p-core/peer"
	"github.com/libp2p/go-libp2p-core/sec"

	ci "github.com/libp2p/go-libp2p-core/crypto"
)

// ID is the multistream-select protocol ID that should be used when identifying
// this security transport.
18
const ID = "/plaintext/1.0.0"
19 20

// Transport is a no-op stream security transport. It provides no
21 22
// security and simply mocks the security and identity methods to
// return peer IDs known ahead of time.
23
type Transport struct {
24
	id peer.ID
25 26 27
}

// New constructs a new insecure transport.
28
func New(id peer.ID) *Transport {
29
	return &Transport{
30
		id: id,
31 32 33
	}
}

34
// LocalPeer returns the transports local peer ID.
35 36 37 38
func (t *Transport) LocalPeer() peer.ID {
	return t.id
}

39
// LocalPrivateKey returns nil. This transport is not secure.
40
func (t *Transport) LocalPrivateKey() ci.PrivKey {
41
	return nil
42 43 44 45
}

// SecureInbound *pretends to secure* an outbound connection to the given peer.
func (t *Transport) SecureInbound(ctx context.Context, insecure net.Conn) (sec.SecureConn, error) {
46 47 48 49
	return &Conn{
		Conn:  insecure,
		local: t.id,
	}, nil
50 51 52 53
}

// SecureOutbound *pretends to secure* an outbound connection to the given peer.
func (t *Transport) SecureOutbound(ctx context.Context, insecure net.Conn, p peer.ID) (sec.SecureConn, error) {
54 55 56 57 58
	return &Conn{
		Conn:   insecure,
		local:  t.id,
		remote: p,
	}, nil
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
}

// Conn is the connection type returned by the insecure transport.
type Conn struct {
	net.Conn
	local  peer.ID
	remote peer.ID
}

// LocalPeer returns the local peer ID.
func (ic *Conn) LocalPeer() peer.ID {
	return ic.local
}

// RemotePeer returns the remote peer ID if we initiated the dial. Otherwise, it
// returns "" (because this connection isn't actually secure).
func (ic *Conn) RemotePeer() peer.ID {
	return ic.remote
}

79
// RemotePublicKey returns nil. This connection is not secure
80
func (ic *Conn) RemotePublicKey() ci.PubKey {
81
	return nil
82 83
}

84
// LocalPrivateKey returns nil. This connection is not secure.
85
func (ic *Conn) LocalPrivateKey() ci.PrivKey {
86
	return nil
87 88 89 90
}

var _ sec.SecureTransport = (*Transport)(nil)
var _ sec.SecureConn = (*Conn)(nil)