Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Feat/memory transport #3022

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ require (
github.com/mikioh/tcpinfo v0.0.0-20190314235526-30a79bb1804b
github.com/mr-tron/base58 v1.2.0
github.com/multiformats/go-base32 v0.1.0
github.com/multiformats/go-multiaddr v0.13.0
github.com/multiformats/go-multiaddr v0.14.0
github.com/multiformats/go-multiaddr-dns v0.4.0
github.com/multiformats/go-multiaddr-fmt v0.1.0
github.com/multiformats/go-multibase v0.2.0
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -233,8 +233,8 @@ github.com/multiformats/go-base32 v0.1.0/go.mod h1:Kj3tFY6zNr+ABYMqeUNeGvkIC/UYg
github.com/multiformats/go-base36 v0.2.0 h1:lFsAbNOGeKtuKozrtBsAkSVhv1p9D0/qedU9rQyccr0=
github.com/multiformats/go-base36 v0.2.0/go.mod h1:qvnKE++v+2MWCfePClUEjE78Z7P2a1UV0xHgWc0hkp4=
github.com/multiformats/go-multiaddr v0.1.1/go.mod h1:aMKBKNEYmzmDmxfX88/vz+J5IU55txyt0p4aiWVohjo=
github.com/multiformats/go-multiaddr v0.13.0 h1:BCBzs61E3AGHcYYTv8dqRH43ZfyrqM8RXVPT8t13tLQ=
github.com/multiformats/go-multiaddr v0.13.0/go.mod h1:sBXrNzucqkFJhvKOiwwLyqamGa/P5EIXNPLovyhQCII=
github.com/multiformats/go-multiaddr v0.14.0 h1:bfrHrJhrRuh/NXH5mCnemjpbGjzRw/b+tJFOD41g2tU=
github.com/multiformats/go-multiaddr v0.14.0/go.mod h1:6EkVAxtznq2yC3QT5CM1UTAwG0GTP3EWAIcjHuzQ+r4=
github.com/multiformats/go-multiaddr-dns v0.4.0 h1:P76EJ3qzBXpUXZ3twdCDx/kvagMsNo0LMFXpyms/zgU=
github.com/multiformats/go-multiaddr-dns v0.4.0/go.mod h1:7hfthtB4E4pQwirrz+J0CcDUfbWzTqEzVyYKKIKpgkc=
github.com/multiformats/go-multiaddr-fmt v0.1.0 h1:WLEFClPycPkp4fnIzoFoV9FVd49/eQsuaL3/CWe167E=
Expand Down
16 changes: 16 additions & 0 deletions p2p/test/transport/transport_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
"github.com/libp2p/go-libp2p/p2p/protocol/ping"
"github.com/libp2p/go-libp2p/p2p/security/noise"
tls "github.com/libp2p/go-libp2p/p2p/security/tls"
libp2pmemory "github.com/libp2p/go-libp2p/p2p/transport/memory"
libp2pwebrtc "github.com/libp2p/go-libp2p/p2p/transport/webrtc"
"go.uber.org/mock/gomock"

Expand Down Expand Up @@ -156,6 +157,21 @@ var transportsToTest = []TransportTestCase{
return h
},
},
{
Name: "Memory",
HostGenerator: func(t *testing.T, opts TransportTestCaseOpts) host.Host {
libp2pOpts := transformOpts(opts)
libp2pOpts = append(libp2pOpts, libp2p.Transport(libp2pmemory.NewTransport))
if opts.NoListen {
libp2pOpts = append(libp2pOpts, libp2p.NoListenAddrs)
} else {
libp2pOpts = append(libp2pOpts, libp2p.ListenAddrStrings("/memory/1234"))
}
h, err := libp2p.New(libp2pOpts...)
require.NoError(t, err)
return h
},
},
}

func TestPing(t *testing.T) {
Expand Down
137 changes: 137 additions & 0 deletions p2p/transport/memory/conn.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package memory

import (
"context"
"io"
"sync"
"sync/atomic"

ic "github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
tpt "github.com/libp2p/go-libp2p/core/transport"
ma "github.com/multiformats/go-multiaddr"
)

type conn struct {
id int32

transport *transport
scope network.ConnManagementScope

localPeer peer.ID
localMultiaddr ma.Multiaddr

remotePeerID peer.ID
remotePubKey ic.PubKey
remoteMultiaddr ma.Multiaddr

isClosed atomic.Bool
closeOnce sync.Once

mu sync.Mutex

streamC chan *stream

nextStreamID atomic.Int32
streams map[int32]network.MuxedStream
}

var _ tpt.CapableConn = &conn{}

func newConnection(
id int32,
s *stream,
localPeer peer.ID,
localMultiaddr ma.Multiaddr,
remotePubKey ic.PubKey,
remotePeer peer.ID,
remoteMultiaddr ma.Multiaddr,
) *conn {
c := &conn{
id: id,
localPeer: localPeer,
localMultiaddr: localMultiaddr,
remotePubKey: remotePubKey,
remotePeerID: remotePeer,
remoteMultiaddr: remoteMultiaddr,
streamC: make(chan *stream, 1),
streams: make(map[int32]network.MuxedStream),
}

streamID := c.nextStreamID.Add(1)
c.addStream(streamID, s)

return c
}

func (c *conn) Close() error {
c.closeOnce.Do(func() {
c.isClosed.Store(true)
c.transport.removeConn(c)
})

return nil
}

func (c *conn) IsClosed() bool {
return c.isClosed.Load()
}

func (c *conn) OpenStream(ctx context.Context) (network.MuxedStream, error) {
ra, wb := io.Pipe()
rb, wa := io.Pipe()
inConnId, outConnId := c.nextStreamID.Add(1), c.nextStreamID.Add(1)
inStream, outStream := newStream(inConnId, ra, wb), newStream(outConnId, rb, wa)

c.streamC <- inStream
return outStream, nil
}

func (c *conn) AcceptStream() (network.MuxedStream, error) {
in := <-c.streamC
id := c.nextStreamID.Add(1)
c.addStream(id, in)
return in, nil
}

func (c *conn) LocalPeer() peer.ID { return c.localPeer }

// RemotePeer returns the peer ID of the remote peer.
func (c *conn) RemotePeer() peer.ID { return c.remotePeerID }

// RemotePublicKey returns the public pkey of the remote peer.
func (c *conn) RemotePublicKey() ic.PubKey { return c.remotePubKey }

// LocalMultiaddr returns the local Multiaddr associated
func (c *conn) LocalMultiaddr() ma.Multiaddr { return c.localMultiaddr }

// RemoteMultiaddr returns the remote Multiaddr associated
func (c *conn) RemoteMultiaddr() ma.Multiaddr { return c.remoteMultiaddr }

func (c *conn) Transport() tpt.Transport {
return c.transport
}

func (c *conn) Scope() network.ConnScope {
return c.scope
}

// ConnState is the state of security connection.
func (c *conn) ConnState() network.ConnectionState {
return network.ConnectionState{Transport: "memory"}
}

func (c *conn) addStream(id int32, stream network.MuxedStream) {
c.mu.Lock()
defer c.mu.Unlock()

c.streams[id] = stream
}

func (c *conn) removeStream(id int32) {
c.mu.Lock()
defer c.mu.Unlock()

delete(c.streams, id)
}
70 changes: 70 additions & 0 deletions p2p/transport/memory/listener.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package memory

import (
"context"
"net"
"sync"

tpt "github.com/libp2p/go-libp2p/core/transport"
ma "github.com/multiformats/go-multiaddr"
)

const (
listenerQueueSize = 16
)

type listener struct {
t *transport
ctx context.Context
cancel context.CancelFunc
laddr ma.Multiaddr

mu sync.Mutex
connCh chan *conn
connections map[int32]*conn
}

func (l *listener) Multiaddr() ma.Multiaddr {
return l.laddr
}

func newListener(t *transport, laddr ma.Multiaddr) *listener {
ctx, cancel := context.WithCancel(context.Background())
return &listener{
t: t,
ctx: ctx,
cancel: cancel,
laddr: laddr,
connCh: make(chan *conn, listenerQueueSize),
connections: make(map[int32]*conn),
}
}

// Accept accepts new connections.
func (l *listener) Accept() (tpt.CapableConn, error) {
select {
case <-l.ctx.Done():
return nil, tpt.ErrListenerClosed
case c, ok := <-l.connCh:
if !ok {
return nil, tpt.ErrListenerClosed
}

l.mu.Lock()
defer l.mu.Unlock()

l.connections[c.id] = c
return c, nil
}
}

// Close closes the listener.
func (l *listener) Close() error {
l.cancel()
return nil
}

// Addr returns the address of this listener.
func (l *listener) Addr() net.Addr {
return nil
}
106 changes: 106 additions & 0 deletions p2p/transport/memory/stream.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package memory

import (
"io"
"sync/atomic"
"time"

"github.com/libp2p/go-libp2p/core/network"
)

type stream struct {
id int32

r *io.PipeReader
w *io.PipeWriter
writeC chan []byte

readCloseC chan struct{}
writeCloseC chan struct{}

closed atomic.Bool
}

func newStream(id int32, r *io.PipeReader, w *io.PipeWriter) *stream {
s := &stream{
id: id,
r: r,
w: w,
writeC: make(chan []byte, 1),
readCloseC: make(chan struct{}, 1),
writeCloseC: make(chan struct{}, 1),
}

go func() {
for {
select {
case b := <-s.writeC:
if _, err := w.Write(b); err != nil {
return
}
case <-s.writeCloseC:
return
}
}
}()

return s
}

func (s *stream) Read(b []byte) (int, error) {
return s.r.Read(b)
}

func (s *stream) Write(b []byte) (int, error) {
if s.closed.Load() {
return 0, network.ErrReset
}

select {
case <-s.writeCloseC:
return 0, network.ErrReset
case s.writeC <- b:
return len(b), nil
}
}

func (s *stream) Reset() error {
if err := s.CloseWrite(); err != nil {
return err
}
if err := s.CloseRead(); err != nil {
return err
}
return nil
}

func (s *stream) Close() error {
s.CloseRead()
s.CloseWrite()
return nil
}

func (s *stream) CloseRead() error {
return s.r.CloseWithError(network.ErrReset)
}

func (s *stream) CloseWrite() error {
select {
case s.writeCloseC <- struct{}{}:
default:
}

s.closed.Store(true)
return nil
}

func (s *stream) SetDeadline(_ time.Time) error {
return nil
}

func (s *stream) SetReadDeadline(_ time.Time) error {
return nil
}
func (s *stream) SetWriteDeadline(_ time.Time) error {
return nil
}
Loading