Skip to content

Commit

Permalink
Merge pull request ethereum#134 from nonsense/p2p-sim-tcp-adapter
Browse files Browse the repository at this point in the history
p2p/simulations: tcp pipe
  • Loading branch information
nonsense authored Nov 22, 2017
2 parents 64ecbcd + ce6b624 commit 6631246
Show file tree
Hide file tree
Showing 3 changed files with 409 additions and 0 deletions.
63 changes: 63 additions & 0 deletions p2p/simulations/adapters/inproc.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ func NewSocketAdapter(services map[string]ServiceFunc) *SimAdapter {
}
}

func NewTCPAdapter(services map[string]ServiceFunc) *SimAdapter {
return &SimAdapter{
pipe: tcpPipe,
nodes: make(map[discover.NodeID]*SimNode),
services: services,
}
}

// Name returns the name of the adapter for logging purposes
func (s *SimAdapter) Name() string {
return "sim-adapter"
Expand Down Expand Up @@ -403,3 +411,58 @@ func netPipe() (net.Conn, net.Conn, error) {
p1, p2 := net.Pipe()
return p1, p2, nil
}

// tcpPipe creates an in process full duplex pipe based on a localhost TCP socket
func tcpPipe() (net.Conn, net.Conn, error) {
type result struct {
conn net.Conn
err error
}

cl := make(chan result)
cd := make(chan result)

start := make(chan net.Addr)

go func(res chan result, start chan net.Addr) {
// resolve
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
res <- result{err: err}
return
}
// listen
l, err := net.ListenTCP("tcp", addr)
if err != nil {
res <- result{err: err}
return
}
start <- l.Addr()
c, err := l.AcceptTCP()
if err != nil {
res <- result{err: err}
return
}
res <- result{conn: c}
}(cl, start)

go func(res chan result, start chan net.Addr) {
addr := <-start
c, err := net.DialTCP("tcp", nil, addr.(*net.TCPAddr))
if err != nil {
res <- result{err: err}
return
}
res <- result{conn: c}
}(cd, start)

a := <-cl
if a.err != nil {
return nil, nil, a.err
}
b := <-cd
if b.err != nil {
return nil, nil, b.err
}
return a.conn, b.conn, nil
}
Loading

0 comments on commit 6631246

Please sign in to comment.