p2p: Change p2p.Server back to a concrete type

This commit is contained in:
Lewis Marshall 2017-05-14 16:45:41 -07:00
parent 91c198778c
commit 3ba68dc7af
33 changed files with 120 additions and 131 deletions

View file

@ -459,7 +459,7 @@ func getPassPhrase(prompt string, i int, passwords []string) string {
return password return password
} }
func injectBootnodes(srv p2p.Server, nodes []string) { func injectBootnodes(srv *p2p.Server, nodes []string) {
for _, url := range nodes { for _, url := range nodes {
n, err := discover.ParseNode(url) n, err := discover.ParseNode(url)
if err != nil { if err != nil {

View file

@ -51,7 +51,7 @@ const quitCommand = "~Q"
// singletons // singletons
var ( var (
server p2p.Server server *p2p.Server
shh *whisper.Whisper shh *whisper.Whisper
done chan struct{} done chan struct{}
mailServer mailserver.WMailServer mailServer mailserver.WMailServer
@ -253,17 +253,19 @@ func initialize() {
maxPeers = 800 maxPeers = 800
} }
server = p2p.NewServer(p2p.Config{ server = &p2p.Server{
PrivateKey: nodeid, Config: p2p.Config{
MaxPeers: maxPeers, PrivateKey: nodeid,
Name: common.MakeName("wnode", "5.0"), MaxPeers: maxPeers,
Protocols: shh.Protocols(), Name: common.MakeName("wnode", "5.0"),
ListenAddr: *argIP, Protocols: shh.Protocols(),
NAT: nat.Any(), ListenAddr: *argIP,
BootstrapNodes: peers, NAT: nat.Any(),
StaticNodes: peers, BootstrapNodes: peers,
TrustedNodes: peers, StaticNodes: peers,
}) TrustedNodes: peers,
},
}
} }
func startServer() { func startServer() {

View file

@ -94,7 +94,7 @@ func (r *ReleaseService) Protocols() []p2p.Protocol { return nil }
func (r *ReleaseService) APIs() []rpc.API { return nil } func (r *ReleaseService) APIs() []rpc.API { return nil }
// Start spawns the periodic version checker goroutine // Start spawns the periodic version checker goroutine
func (r *ReleaseService) Start(server p2p.Server) error { func (r *ReleaseService) Start(server *p2p.Server) error {
go r.checker() go r.checker()
return nil return nil
} }

View file

@ -49,7 +49,7 @@ import (
) )
type LesServer interface { type LesServer interface {
Start(srvr p2p.Server) Start(srvr *p2p.Server)
Stop() Stop()
Protocols() []p2p.Protocol Protocols() []p2p.Protocol
} }
@ -362,7 +362,7 @@ func (s *Ethereum) Protocols() []p2p.Protocol {
// Start implements node.Service, starting all internal goroutines needed by the // Start implements node.Service, starting all internal goroutines needed by the
// Ethereum protocol implementation. // Ethereum protocol implementation.
func (s *Ethereum) Start(srvr p2p.Server) error { func (s *Ethereum) Start(srvr *p2p.Server) error {
s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion()) s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion())
s.protocolManager.Start() s.protocolManager.Start()

View file

@ -52,7 +52,7 @@ const historyUpdateRange = 50
type Service struct { type Service struct {
stack *node.Node // Temporary workaround, remove when API finalized stack *node.Node // Temporary workaround, remove when API finalized
server p2p.Server // Peer-to-peer server to retrieve networking infos server *p2p.Server // Peer-to-peer server to retrieve networking infos
eth *eth.Ethereum // Full Ethereum service if monitoring a full node eth *eth.Ethereum // Full Ethereum service if monitoring a full node
les *les.LightEthereum // Light Ethereum service if monitoring a light node les *les.LightEthereum // Light Ethereum service if monitoring a light node
engine consensus.Engine // Consensus engine to retrieve variadic block fields engine consensus.Engine // Consensus engine to retrieve variadic block fields
@ -101,7 +101,7 @@ func (s *Service) Protocols() []p2p.Protocol { return nil }
func (s *Service) APIs() []rpc.API { return nil } func (s *Service) APIs() []rpc.API { return nil }
// Start implements node.Service, starting up the monitoring and reporting daemon. // Start implements node.Service, starting up the monitoring and reporting daemon.
func (s *Service) Start(server p2p.Server) error { func (s *Service) Start(server *p2p.Server) error {
s.server = server s.server = server
go s.loop() go s.loop()

View file

@ -1434,12 +1434,12 @@ func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) {
// PublicNetAPI offers network related RPC methods // PublicNetAPI offers network related RPC methods
type PublicNetAPI struct { type PublicNetAPI struct {
net p2p.Server net *p2p.Server
networkVersion uint64 networkVersion uint64
} }
// NewPublicNetAPI creates a new net API instance. // NewPublicNetAPI creates a new net API instance.
func NewPublicNetAPI(net p2p.Server, networkVersion uint64) *PublicNetAPI { func NewPublicNetAPI(net *p2p.Server, networkVersion uint64) *PublicNetAPI {
return &PublicNetAPI{net, networkVersion} return &PublicNetAPI{net, networkVersion}
} }

View file

@ -185,7 +185,7 @@ func (s *LightEthereum) Protocols() []p2p.Protocol {
// Start implements node.Service, starting all internal goroutines needed by the // Start implements node.Service, starting all internal goroutines needed by the
// Ethereum protocol implementation. // Ethereum protocol implementation.
func (s *LightEthereum) Start(srvr p2p.Server) error { func (s *LightEthereum) Start(srvr *p2p.Server) error {
log.Warn("Light client mode is an experimental feature") log.Warn("Light client mode is an experimental feature")
s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.networkId) s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.networkId)
s.protocolManager.Start(srvr) s.protocolManager.Start(srvr)

View file

@ -61,10 +61,6 @@ const (
disableClientRemovePeer = false disableClientRemovePeer = false
) )
type discV5Server interface {
DiscV5() *discv5.Network
}
// errIncompatibleConfig is returned if the requested protocols and configs are // errIncompatibleConfig is returned if the requested protocols and configs are
// not compatible (low protocol version restrictions and high requirements). // not compatible (low protocol version restrictions and high requirements).
var errIncompatibleConfig = errors.New("incompatible configuration") var errIncompatibleConfig = errors.New("incompatible configuration")
@ -260,10 +256,10 @@ func (pm *ProtocolManager) removePeer(id string) {
} }
} }
func (pm *ProtocolManager) Start(srvr p2p.Server) { func (pm *ProtocolManager) Start(srvr *p2p.Server) {
var topicDisc *discv5.Network var topicDisc *discv5.Network
if v, ok := srvr.(discV5Server); ok { if srvr != nil {
topicDisc = v.DiscV5() topicDisc = srvr.DiscV5
} }
lesTopic := discv5.Topic("LES@" + common.Bytes2Hex(pm.blockchain.Genesis().Hash().Bytes()[0:8])) lesTopic := discv5.Topic("LES@" + common.Bytes2Hex(pm.blockchain.Genesis().Hash().Bytes()[0:8]))
if pm.lightSync { if pm.lightSync {

View file

@ -68,7 +68,7 @@ func (s *LesServer) Protocols() []p2p.Protocol {
} }
// Start starts the LES server // Start starts the LES server
func (s *LesServer) Start(srvr p2p.Server) { func (s *LesServer) Start(srvr *p2p.Server) {
s.protocolManager.Start(srvr) s.protocolManager.Start(srvr)
} }

View file

@ -97,7 +97,7 @@ const (
type serverPool struct { type serverPool struct {
db ethdb.Database db ethdb.Database
dbKey []byte dbKey []byte
server p2p.Server server *p2p.Server
quit chan struct{} quit chan struct{}
wg *sync.WaitGroup wg *sync.WaitGroup
connWg sync.WaitGroup connWg sync.WaitGroup
@ -118,7 +118,7 @@ type serverPool struct {
} }
// newServerPool creates a new serverPool instance // newServerPool creates a new serverPool instance
func newServerPool(db ethdb.Database, dbPrefix []byte, server p2p.Server, topic discv5.Topic, quit chan struct{}, wg *sync.WaitGroup) *serverPool { func newServerPool(db ethdb.Database, dbPrefix []byte, server *p2p.Server, topic discv5.Topic, quit chan struct{}, wg *sync.WaitGroup) *serverPool {
pool := &serverPool{ pool := &serverPool{
db: db, db: db,
dbKey: append(dbPrefix, []byte(topic)...), dbKey: append(dbPrefix, []byte(topic)...),
@ -139,11 +139,11 @@ func newServerPool(db ethdb.Database, dbPrefix []byte, server p2p.Server, topic
pool.loadNodes() pool.loadNodes()
pool.checkDial() pool.checkDial()
if srv, ok := pool.server.(discV5Server); ok && srv.DiscV5() != nil { if pool.server.DiscV5 != nil {
pool.discSetPeriod = make(chan time.Duration, 1) pool.discSetPeriod = make(chan time.Duration, 1)
pool.discNodes = make(chan *discv5.Node, 100) pool.discNodes = make(chan *discv5.Node, 100)
pool.discLookups = make(chan bool, 100) pool.discLookups = make(chan bool, 100)
go srv.DiscV5().SearchTopic(topic, pool.discSetPeriod, pool.discNodes, pool.discLookups) go pool.server.DiscV5.SearchTopic(topic, pool.discSetPeriod, pool.discNodes, pool.discLookups)
} }
go pool.eventLoop() go pool.eventLoop()

View file

@ -375,7 +375,7 @@ func NewPublicWeb3API(stack *Node) *PublicWeb3API {
// ClientVersion returns the node name // ClientVersion returns the node name
func (s *PublicWeb3API) ClientVersion() string { func (s *PublicWeb3API) ClientVersion() string {
return s.stack.serverConfig.Name return s.stack.Server().Name
} }
// Sha3 applies the ethereum sha3 implementation on the input. // Sha3 applies the ethereum sha3 implementation on the input.

View file

@ -56,7 +56,7 @@ type Node struct {
instanceDirLock storage.Storage // prevents concurrent use of instance directory instanceDirLock storage.Storage // prevents concurrent use of instance directory
serverConfig p2p.Config serverConfig p2p.Config
server p2p.Server // Currently running P2P networking layer server *p2p.Server // Currently running P2P networking layer
serviceFuncs []ServiceConstructor // Service constructors (in dependency order) serviceFuncs []ServiceConstructor // Service constructors (in dependency order)
services map[reflect.Type]Service // Currently running services services map[reflect.Type]Service // Currently running services
@ -165,6 +165,8 @@ func (n *Node) Start() error {
if n.serverConfig.NodeDatabase == "" { if n.serverConfig.NodeDatabase == "" {
n.serverConfig.NodeDatabase = n.config.NodeDB() n.serverConfig.NodeDatabase = n.config.NodeDB()
} }
running := &p2p.Server{Config: n.serverConfig}
log.Info("Starting peer-to-peer node", "instance", n.serverConfig.Name)
// Otherwise copy and specialize the P2P configuration // Otherwise copy and specialize the P2P configuration
services := make(map[reflect.Type]Service) services := make(map[reflect.Type]Service)
@ -192,10 +194,8 @@ func (n *Node) Start() error {
} }
// Gather the protocols and start the freshly assembled P2P server // Gather the protocols and start the freshly assembled P2P server
for _, service := range services { for _, service := range services {
n.serverConfig.Protocols = append(n.serverConfig.Protocols, service.Protocols()...) running.Protocols = append(running.Protocols, service.Protocols()...)
} }
running := p2p.NewServer(n.serverConfig)
log.Info("Starting peer-to-peer node", "instance", n.serverConfig.Name)
if err := running.Start(); err != nil { if err := running.Start(); err != nil {
if errno, ok := err.(syscall.Errno); ok && datadirInUseErrnos[uint(errno)] { if errno, ok := err.(syscall.Errno); ok && datadirInUseErrnos[uint(errno)] {
return ErrDatadirUsed return ErrDatadirUsed
@ -582,7 +582,7 @@ func (n *Node) RPCHandler() (*rpc.Server, error) {
// Server retrieves the currently running P2P network layer. This method is meant // Server retrieves the currently running P2P network layer. This method is meant
// only to inspect fields of the currently running server, life cycle management // only to inspect fields of the currently running server, life cycle management
// should be left to this Node entity. // should be left to this Node entity.
func (n *Node) Server() p2p.Server { func (n *Node) Server() *p2p.Server {
n.lock.RLock() n.lock.RLock()
defer n.lock.RUnlock() defer n.lock.RUnlock()

View file

@ -37,7 +37,7 @@ type SampleService struct{}
func (s *SampleService) Protocols() []p2p.Protocol { return nil } func (s *SampleService) Protocols() []p2p.Protocol { return nil }
func (s *SampleService) APIs() []rpc.API { return nil } func (s *SampleService) APIs() []rpc.API { return nil }
func (s *SampleService) Start(p2p.Server) error { fmt.Println("Service starting..."); return nil } func (s *SampleService) Start(*p2p.Server) error { fmt.Println("Service starting..."); return nil }
func (s *SampleService) Stop() error { fmt.Println("Service stopping..."); return nil } func (s *SampleService) Stop() error { fmt.Println("Service stopping..."); return nil }
func ExampleService() { func ExampleService() {

View file

@ -154,7 +154,7 @@ func TestServiceLifeCycle(t *testing.T) {
id := id // Closure for the constructor id := id // Closure for the constructor
constructor := func(*ServiceContext) (Service, error) { constructor := func(*ServiceContext) (Service, error) {
return &InstrumentedService{ return &InstrumentedService{
startHook: func(p2p.Server) { started[id] = true }, startHook: func(*p2p.Server) { started[id] = true },
stopHook: func() { stopped[id] = true }, stopHook: func() { stopped[id] = true },
}, nil }, nil
} }
@ -200,7 +200,7 @@ func TestServiceRestarts(t *testing.T) {
running = false running = false
return &InstrumentedService{ return &InstrumentedService{
startHook: func(p2p.Server) { startHook: func(*p2p.Server) {
if running { if running {
panic("already running") panic("already running")
} }
@ -250,7 +250,7 @@ func TestServiceConstructionAbortion(t *testing.T) {
id := id // Closure for the constructor id := id // Closure for the constructor
constructor := func(*ServiceContext) (Service, error) { constructor := func(*ServiceContext) (Service, error) {
return &InstrumentedService{ return &InstrumentedService{
startHook: func(p2p.Server) { started[id] = true }, startHook: func(*p2p.Server) { started[id] = true },
}, nil }, nil
} }
if err := stack.Register(maker(constructor)); err != nil { if err := stack.Register(maker(constructor)); err != nil {
@ -299,7 +299,7 @@ func TestServiceStartupAbortion(t *testing.T) {
id := id // Closure for the constructor id := id // Closure for the constructor
constructor := func(*ServiceContext) (Service, error) { constructor := func(*ServiceContext) (Service, error) {
return &InstrumentedService{ return &InstrumentedService{
startHook: func(p2p.Server) { started[id] = true }, startHook: func(*p2p.Server) { started[id] = true },
stopHook: func() { stopped[id] = true }, stopHook: func() { stopped[id] = true },
}, nil }, nil
} }
@ -352,7 +352,7 @@ func TestServiceTerminationGuarantee(t *testing.T) {
id := id // Closure for the constructor id := id // Closure for the constructor
constructor := func(*ServiceContext) (Service, error) { constructor := func(*ServiceContext) (Service, error) {
return &InstrumentedService{ return &InstrumentedService{
startHook: func(p2p.Server) { started[id] = true }, startHook: func(*p2p.Server) { started[id] = true },
stopHook: func() { stopped[id] = true }, stopHook: func() { stopped[id] = true },
}, nil }, nil
} }

View file

@ -86,7 +86,7 @@ type Service interface {
// Start is called after all services have been constructed and the networking // Start is called after all services have been constructed and the networking
// layer was also initialized to spawn any goroutines required by the service. // layer was also initialized to spawn any goroutines required by the service.
Start(server p2p.Server) error Start(server *p2p.Server) error
// Stop terminates all goroutines belonging to the service, blocking until they // Stop terminates all goroutines belonging to the service, blocking until they
// are all terminated. // are all terminated.

View file

@ -31,7 +31,7 @@ type NoopService struct{}
func (s *NoopService) Protocols() []p2p.Protocol { return nil } func (s *NoopService) Protocols() []p2p.Protocol { return nil }
func (s *NoopService) APIs() []rpc.API { return nil } func (s *NoopService) APIs() []rpc.API { return nil }
func (s *NoopService) Start(p2p.Server) error { return nil } func (s *NoopService) Start(*p2p.Server) error { return nil }
func (s *NoopService) Stop() error { return nil } func (s *NoopService) Stop() error { return nil }
func NewNoopService(*ServiceContext) (Service, error) { return new(NoopService), nil } func NewNoopService(*ServiceContext) (Service, error) { return new(NoopService), nil }
@ -57,7 +57,7 @@ type InstrumentedService struct {
stop error stop error
protocolsHook func() protocolsHook func()
startHook func(p2p.Server) startHook func(*p2p.Server)
stopHook func() stopHook func()
} }
@ -74,7 +74,7 @@ func (s *InstrumentedService) APIs() []rpc.API {
return s.apis return s.apis
} }
func (s *InstrumentedService) Start(server p2p.Server) error { func (s *InstrumentedService) Start(server *p2p.Server) error {
if s.startHook != nil { if s.startHook != nil {
s.startHook(server) s.startHook(server)
} }

View file

@ -97,7 +97,7 @@ type pastDial struct {
} }
type task interface { type task interface {
Do(*server) Do(*Server)
} }
// A dialTask is generated for each node that is dialed. Its // A dialTask is generated for each node that is dialed. Its
@ -280,7 +280,7 @@ func (s *dialstate) taskDone(t task, now time.Time) {
} }
} }
func (t *dialTask) Do(srv *server) { func (t *dialTask) Do(srv *Server) {
if t.dest.Incomplete() { if t.dest.Incomplete() {
if !t.resolve(srv) { if !t.resolve(srv) {
return return
@ -301,7 +301,7 @@ func (t *dialTask) Do(srv *server) {
// Resolve operations are throttled with backoff to avoid flooding the // Resolve operations are throttled with backoff to avoid flooding the
// discovery network with useless queries for nodes that don't exist. // discovery network with useless queries for nodes that don't exist.
// The backoff delay resets when the node is found. // The backoff delay resets when the node is found.
func (t *dialTask) resolve(srv *server) bool { func (t *dialTask) resolve(srv *Server) bool {
if srv.ntab == nil { if srv.ntab == nil {
log.Debug("Can't resolve node", "id", t.dest.ID, "err", "discovery is disabled") log.Debug("Can't resolve node", "id", t.dest.ID, "err", "discovery is disabled")
return false return false
@ -330,7 +330,7 @@ func (t *dialTask) resolve(srv *server) bool {
} }
// dial performs the actual connection attempt. // dial performs the actual connection attempt.
func (t *dialTask) dial(srv *server, dest *discover.Node) bool { func (t *dialTask) dial(srv *Server, dest *discover.Node) bool {
fd, err := srv.Dialer.Dial(dest) fd, err := srv.Dialer.Dial(dest)
if err != nil { if err != nil {
log.Trace("Dial error", "task", t, "err", err) log.Trace("Dial error", "task", t, "err", err)
@ -345,7 +345,7 @@ func (t *dialTask) String() string {
return fmt.Sprintf("%v %x %v:%d", t.flags, t.dest.ID[:8], t.dest.IP, t.dest.TCP) return fmt.Sprintf("%v %x %v:%d", t.flags, t.dest.ID[:8], t.dest.IP, t.dest.TCP)
} }
func (t *discoverTask) Do(srv *server) { func (t *discoverTask) Do(srv *Server) {
// newTasks generates a lookup task whenever dynamic dials are // newTasks generates a lookup task whenever dynamic dials are
// necessary. Lookups need to take some time, otherwise the // necessary. Lookups need to take some time, otherwise the
// event loop spins too fast. // event loop spins too fast.
@ -367,7 +367,7 @@ func (t *discoverTask) String() string {
return s return s
} }
func (t waitExpireTask) Do(*server) { func (t waitExpireTask) Do(*Server) {
time.Sleep(t.Duration) time.Sleep(t.Duration)
} }
func (t waitExpireTask) String() string { func (t waitExpireTask) String() string {

View file

@ -141,24 +141,8 @@ type Config struct {
EnableMsgEvents bool EnableMsgEvents bool
} }
type Server interface {
Start() error
Stop() error
SetupConn(net.Conn, connFlag, *discover.Node)
AddPeer(node *discover.Node)
RemovePeer(node *discover.Node)
SubscribeEvents(ch chan *PeerEvent) event.Subscription
PeerCount() int
NodeInfo() *NodeInfo
PeersInfo() []*PeerInfo
}
func NewServer(conf Config) Server {
return &server{Config: conf}
}
// Server manages all peer connections. // Server manages all peer connections.
type server struct { type Server struct {
// Config fields may not be modified while the server is running. // Config fields may not be modified while the server is running.
Config Config
@ -267,7 +251,7 @@ func (c *conn) is(f connFlag) bool {
} }
// Peers returns all connected peers. // Peers returns all connected peers.
func (srv *server) Peers() []*Peer { func (srv *Server) Peers() []*Peer {
var ps []*Peer var ps []*Peer
select { select {
// Note: We'd love to put this function into a variable but // Note: We'd love to put this function into a variable but
@ -285,7 +269,7 @@ func (srv *server) Peers() []*Peer {
} }
// PeerCount returns the number of connected peers. // PeerCount returns the number of connected peers.
func (srv *server) PeerCount() int { func (srv *Server) PeerCount() int {
var count int var count int
select { select {
case srv.peerOp <- func(ps map[discover.NodeID]*Peer) { count = len(ps) }: case srv.peerOp <- func(ps map[discover.NodeID]*Peer) { count = len(ps) }:
@ -298,7 +282,7 @@ func (srv *server) PeerCount() int {
// AddPeer connects to the given node and maintains the connection until the // AddPeer connects to the given node and maintains the connection until the
// server is shut down. If the connection fails for any reason, the server will // server is shut down. If the connection fails for any reason, the server will
// attempt to reconnect the peer. // attempt to reconnect the peer.
func (srv *server) AddPeer(node *discover.Node) { func (srv *Server) AddPeer(node *discover.Node) {
select { select {
case srv.addstatic <- node: case srv.addstatic <- node:
case <-srv.quit: case <-srv.quit:
@ -306,7 +290,7 @@ func (srv *server) AddPeer(node *discover.Node) {
} }
// RemovePeer disconnects from the given node // RemovePeer disconnects from the given node
func (srv *server) RemovePeer(node *discover.Node) { func (srv *Server) RemovePeer(node *discover.Node) {
select { select {
case srv.removestatic <- node: case srv.removestatic <- node:
case <-srv.quit: case <-srv.quit:
@ -314,12 +298,12 @@ func (srv *server) RemovePeer(node *discover.Node) {
} }
// SubscribePeers subscribes the given channel to peer events // SubscribePeers subscribes the given channel to peer events
func (srv *server) SubscribeEvents(ch chan *PeerEvent) event.Subscription { func (srv *Server) SubscribeEvents(ch chan *PeerEvent) event.Subscription {
return srv.peerFeed.Subscribe(ch) return srv.peerFeed.Subscribe(ch)
} }
// Self returns the local node's endpoint information. // Self returns the local node's endpoint information.
func (srv *server) Self() *discover.Node { func (srv *Server) Self() *discover.Node {
srv.lock.Lock() srv.lock.Lock()
defer srv.lock.Unlock() defer srv.lock.Unlock()
@ -329,7 +313,7 @@ func (srv *server) Self() *discover.Node {
return srv.makeSelf(srv.listener, srv.ntab) return srv.makeSelf(srv.listener, srv.ntab)
} }
func (srv *server) makeSelf(listener net.Listener, ntab discoverTable) *discover.Node { func (srv *Server) makeSelf(listener net.Listener, ntab discoverTable) *discover.Node {
// If the server's not running, return an empty node. // If the server's not running, return an empty node.
// If the node is running but discovery is off, manually assemble the node infos. // If the node is running but discovery is off, manually assemble the node infos.
if ntab == nil { if ntab == nil {
@ -351,7 +335,7 @@ func (srv *server) makeSelf(listener net.Listener, ntab discoverTable) *discover
// Stop terminates the server and all active peer connections. // Stop terminates the server and all active peer connections.
// It blocks until all active connections have been closed. // It blocks until all active connections have been closed.
func (srv *server) Stop() error { func (srv *Server) Stop() error {
srv.lock.Lock() srv.lock.Lock()
defer srv.lock.Unlock() defer srv.lock.Unlock()
if !srv.running { if !srv.running {
@ -369,7 +353,7 @@ func (srv *server) Stop() error {
// Start starts running the server. // Start starts running the server.
// Servers can not be re-used after stopping. // Servers can not be re-used after stopping.
func (srv *server) Start() (err error) { func (srv *Server) Start() (err error) {
srv.lock.Lock() srv.lock.Lock()
defer srv.lock.Unlock() defer srv.lock.Unlock()
if srv.running { if srv.running {
@ -447,7 +431,7 @@ func (srv *server) Start() (err error) {
return nil return nil
} }
func (srv *server) startListening() error { func (srv *Server) startListening() error {
// Launch the TCP listener. // Launch the TCP listener.
listener, err := net.Listen("tcp", srv.ListenAddr) listener, err := net.Listen("tcp", srv.ListenAddr)
if err != nil { if err != nil {
@ -476,7 +460,7 @@ type dialer interface {
removeStatic(*discover.Node) removeStatic(*discover.Node)
} }
func (srv *server) run(dialstate dialer) { func (srv *Server) run(dialstate dialer) {
defer srv.loopWG.Done() defer srv.loopWG.Done()
var ( var (
peers = make(map[discover.NodeID]*Peer) peers = make(map[discover.NodeID]*Peer)
@ -617,7 +601,7 @@ running:
} }
} }
func (srv *server) protoHandshakeChecks(peers map[discover.NodeID]*Peer, c *conn) error { func (srv *Server) protoHandshakeChecks(peers map[discover.NodeID]*Peer, c *conn) error {
// Drop connections with no matching protocols. // Drop connections with no matching protocols.
if len(srv.Protocols) > 0 && countMatchingProtocols(srv.Protocols, c.caps) == 0 { if len(srv.Protocols) > 0 && countMatchingProtocols(srv.Protocols, c.caps) == 0 {
return DiscUselessPeer return DiscUselessPeer
@ -627,7 +611,7 @@ func (srv *server) protoHandshakeChecks(peers map[discover.NodeID]*Peer, c *conn
return srv.encHandshakeChecks(peers, c) return srv.encHandshakeChecks(peers, c)
} }
func (srv *server) encHandshakeChecks(peers map[discover.NodeID]*Peer, c *conn) error { func (srv *Server) encHandshakeChecks(peers map[discover.NodeID]*Peer, c *conn) error {
switch { switch {
case !c.is(trustedConn|staticDialedConn) && len(peers) >= srv.MaxPeers: case !c.is(trustedConn|staticDialedConn) && len(peers) >= srv.MaxPeers:
return DiscTooManyPeers return DiscTooManyPeers
@ -646,7 +630,7 @@ type tempError interface {
// listenLoop runs in its own goroutine and accepts // listenLoop runs in its own goroutine and accepts
// inbound connections. // inbound connections.
func (srv *server) listenLoop() { func (srv *Server) listenLoop() {
defer srv.loopWG.Done() defer srv.loopWG.Done()
log.Info("RLPx listener up", "self", srv.makeSelf(srv.listener, srv.ntab)) log.Info("RLPx listener up", "self", srv.makeSelf(srv.listener, srv.ntab))
@ -707,7 +691,7 @@ func (srv *server) listenLoop() {
// setupConn runs the handshakes and attempts to add the connection // setupConn runs the handshakes and attempts to add the connection
// as a peer. It returns when the connection has been added as a peer // as a peer. It returns when the connection has been added as a peer
// or the handshakes have failed. // or the handshakes have failed.
func (srv *server) SetupConn(fd net.Conn, flags connFlag, dialDest *discover.Node) { func (srv *Server) SetupConn(fd net.Conn, flags connFlag, dialDest *discover.Node) {
// Prevent leftover pending conns from entering the handshake. // Prevent leftover pending conns from entering the handshake.
srv.lock.Lock() srv.lock.Lock()
running := srv.running running := srv.running
@ -767,7 +751,7 @@ func truncateName(s string) string {
// checkpoint sends the conn to run, which performs the // checkpoint sends the conn to run, which performs the
// post-handshake checks for the stage (posthandshake, addpeer). // post-handshake checks for the stage (posthandshake, addpeer).
func (srv *server) checkpoint(c *conn, stage chan<- *conn) error { func (srv *Server) checkpoint(c *conn, stage chan<- *conn) error {
select { select {
case stage <- c: case stage <- c:
case <-srv.quit: case <-srv.quit:
@ -784,7 +768,7 @@ func (srv *server) checkpoint(c *conn, stage chan<- *conn) error {
// runPeer runs in its own goroutine for each peer. // runPeer runs in its own goroutine for each peer.
// it waits until the Peer logic returns and removes // it waits until the Peer logic returns and removes
// the peer. // the peer.
func (srv *server) runPeer(p *Peer) { func (srv *Server) runPeer(p *Peer) {
if srv.newPeerHook != nil { if srv.newPeerHook != nil {
srv.newPeerHook(p) srv.newPeerHook(p)
} }
@ -825,7 +809,7 @@ type NodeInfo struct {
} }
// NodeInfo gathers and returns a collection of metadata known about the host. // NodeInfo gathers and returns a collection of metadata known about the host.
func (srv *server) NodeInfo() *NodeInfo { func (srv *Server) NodeInfo() *NodeInfo {
node := srv.Self() node := srv.Self()
// Gather and assemble the generic node infos // Gather and assemble the generic node infos
@ -854,7 +838,7 @@ func (srv *server) NodeInfo() *NodeInfo {
} }
// PeersInfo returns an array of metadata objects describing connected peers. // PeersInfo returns an array of metadata objects describing connected peers.
func (srv *server) PeersInfo() []*PeerInfo { func (srv *Server) PeersInfo() []*PeerInfo {
// Gather all the generic and sub-protocol specific infos // Gather all the generic and sub-protocol specific infos
infos := make([]*PeerInfo, 0, srv.PeerCount()) infos := make([]*PeerInfo, 0, srv.PeerCount())
for _, peer := range srv.Peers() { for _, peer := range srv.Peers() {
@ -873,6 +857,6 @@ func (srv *server) PeersInfo() []*PeerInfo {
return infos return infos
} }
func (srv *server) DiscV5() *discv5.Network { func (srv *Server) DiscV5() *discv5.Network {
return srv.discV5 return srv.discV5
} }

View file

@ -72,7 +72,7 @@ func startTestServer(t *testing.T, id discover.NodeID, pf func(*Peer)) *Server {
ListenAddr: "127.0.0.1:0", ListenAddr: "127.0.0.1:0",
PrivateKey: newkey(), PrivateKey: newkey(),
} }
server := &server{ server := &Server{
Config: config, Config: config,
newPeerHook: pf, newPeerHook: pf,
newTransport: func(fd net.Conn) transport { return newTestTransport(id, fd) }, newTransport: func(fd net.Conn) transport { return newTestTransport(id, fd) },
@ -201,7 +201,7 @@ func TestServerTaskScheduling(t *testing.T) {
// The Server in this test isn't actually running // The Server in this test isn't actually running
// because we're only interested in what run does. // because we're only interested in what run does.
srv := &server{ srv := &Server{
Config: Config{MaxPeers: 10}, Config: Config{MaxPeers: 10},
quit: make(chan struct{}), quit: make(chan struct{}),
ntab: fakeTable{}, ntab: fakeTable{},
@ -246,7 +246,7 @@ func TestServerManyTasks(t *testing.T) {
} }
var ( var (
srv = &server{quit: make(chan struct{}), ntab: fakeTable{}, running: true} srv = &Server{quit: make(chan struct{}), ntab: fakeTable{}, running: true}
done = make(chan *testTask) done = make(chan *testTask)
start, end = 0, 0 start, end = 0, 0
) )
@ -317,7 +317,7 @@ func (t *testTask) Do(srv *Server) {
// at capacity. Trusted connections should still be accepted. // at capacity. Trusted connections should still be accepted.
func TestServerAtCap(t *testing.T) { func TestServerAtCap(t *testing.T) {
trustedID := randomID() trustedID := randomID()
srv := &server{ srv := &Server{
Config: Config{ Config: Config{
PrivateKey: newkey(), PrivateKey: newkey(),
MaxPeers: 10, MaxPeers: 10,
@ -420,7 +420,7 @@ func TestServerSetupConn(t *testing.T) {
} }
for i, test := range tests { for i, test := range tests {
srv := &server{ srv := &Server{
Config: Config{ Config: Config{
PrivateKey: srvkey, PrivateKey: srvkey,
MaxPeers: 10, MaxPeers: 10,
@ -435,7 +435,7 @@ func TestServerSetupConn(t *testing.T) {
} }
} }
p1, _ := net.Pipe() p1, _ := net.Pipe()
srv.setupConn(p1, test.flags, test.dialDest) srv.SetupConn(p1, test.flags, test.dialDest)
if !reflect.DeepEqual(test.tt.closeErr, test.wantCloseErr) { if !reflect.DeepEqual(test.tt.closeErr, test.wantCloseErr) {
t.Errorf("test %d: close error mismatch: got %q, want %q", i, test.tt.closeErr, test.wantCloseErr) t.Errorf("test %d: close error mismatch: got %q, want %q", i, test.tt.closeErr, test.wantCloseErr)
} }

View file

@ -99,7 +99,7 @@ func (p *pingPongService) APIs() []rpc.API {
return nil return nil
} }
func (p *pingPongService) Start(server p2p.Server) error { func (p *pingPongService) Start(server *p2p.Server) error {
p.log.Info("ping-pong service starting") p.log.Info("ping-pong service starting")
return nil return nil
} }

View file

@ -46,7 +46,7 @@ func (t *testService) APIs() []rpc.API {
}} }}
} }
func (t *testService) Start(server p2p.Server) error { func (t *testService) Start(server *p2p.Server) error {
return nil return nil
} }

View file

@ -13,8 +13,7 @@ import (
) )
type ProtocolSession struct { type ProtocolSession struct {
p2p.Server Server *p2p.Server
Ids []*adapters.NodeId Ids []*adapters.NodeId
adapter *adapters.SimAdapter adapter *adapters.SimAdapter
events chan *p2p.PeerEvent events chan *p2p.PeerEvent

View file

@ -62,6 +62,10 @@ func NewProtocolTester(t *testing.T, id *adapters.NodeId, n int, run func(*p2p.P
return self return self
} }
func (self *ProtocolTester) Stop() error {
return self.Server.Stop()
}
func (self *ProtocolTester) Connect(selfId *adapters.NodeId, peers ...*adapters.NodeConfig) { func (self *ProtocolTester) Connect(selfId *adapters.NodeId, peers ...*adapters.NodeConfig) {
for _, peer := range peers { for _, peer := range peers {
log.Trace(fmt.Sprintf("start node %v", peer.Id)) log.Trace(fmt.Sprintf("start node %v", peer.Id))
@ -96,7 +100,7 @@ func (t *testNode) APIs() []rpc.API {
return nil return nil
} }
func (t *testNode) Start(server p2p.Server) error { func (t *testNode) Start(server *p2p.Server) error {
return nil return nil
} }

View file

@ -106,7 +106,7 @@ func NewHive(params *HiveParams, overlay Overlay, store Store) *Hive {
// these are called on the p2p.Server which runs on the node // these are called on the p2p.Server which runs on the node
// af() returns an arbitrary ticker channel // af() returns an arbitrary ticker channel
// rw is a read writer for json configs // rw is a read writer for json configs
func (self *Hive) Start(server p2p.Server) error { func (self *Hive) Start(server *p2p.Server) error {
if self.store != nil { if self.store != nil {
if err := self.loadPeers(); err != nil { if err := self.loadPeers(); err != nil {
return err return err

View file

@ -64,7 +64,7 @@ func TestRegisterAndConnect(t *testing.T) {
ticker: make(chan time.Time), ticker: make(chan time.Time),
} }
pp.newTicker = func() hiveTicker { return tc } pp.newTicker = func() hiveTicker { return tc }
pp.Start(s) pp.Start(s.Server)
defer pp.Stop() defer pp.Stop()
tc.ticker <- time.Now() tc.ticker <- time.Now()

View file

@ -164,7 +164,7 @@ func (b *Bzz) APIs() []rpc.API {
}} }}
} }
func (b *Bzz) Start(server p2p.Server) error { func (b *Bzz) Start(server *p2p.Server) error {
return b.Hive.Start(server) return b.Hive.Start(server)
} }

View file

@ -89,7 +89,7 @@ func newPssTestService(t *testing.T, handlefunc func(interface{}) error, testnod
} }
} }
func (self *pssTestService) Start(server p2p.Server) error { func (self *pssTestService) Start(server *p2p.Server) error {
return self.node.Hive.Start(server) return self.node.Hive.Start(server)
} }

View file

@ -64,7 +64,7 @@ func af() <-chan time.Time {
// Start() starts up the hive // Start() starts up the hive
// makes SimNode implement node.Service // makes SimNode implement node.Service
func (self *SimNode) Start(server p2p.Server) error { func (self *SimNode) Start(server *p2p.Server) error {
self.init() self.init()
return self.hive.Start(server, af, self.rw) return self.hive.Start(server, af, self.rw)
} }

View file

@ -161,7 +161,7 @@ Start is called when the stack is started
* TODO: start subservices like sword, swear, swarmdns * TODO: start subservices like sword, swear, swarmdns
*/ */
// implements the node.Service interface // implements the node.Service interface
func (self *Swarm) Start(net p2p.Server) error { func (self *Swarm) Start(net *p2p.Server) error {
// set chequebook // set chequebook
if self.swapEnabled { if self.swapEnabled {
ctx := context.Background() // The initial setup has no deadline. ctx := context.Background() // The initial setup has no deadline.

View file

@ -48,14 +48,16 @@ func main() {
shh := whisper.New() shh := whisper.New()
// Create an Ethereum peer to communicate through // Create an Ethereum peer to communicate through
server := p2p.NewServer(p2p.Config{ server := &p2p.Server{
PrivateKey: key, Config: p2p.Config{
MaxPeers: 10, PrivateKey: key,
Name: name, MaxPeers: 10,
Protocols: []p2p.Protocol{shh.Protocol()}, Name: name,
ListenAddr: ":30300", Protocols: []p2p.Protocol{shh.Protocol()},
NAT: nat.Any(), ListenAddr: ":30300",
}) NAT: nat.Any(),
},
}
fmt.Println("Starting Ethereum peer...") fmt.Println("Starting Ethereum peer...")
if err := server.Start(); err != nil { if err := server.Start(); err != nil {
fmt.Printf("Failed to start Ethereum peer: %v.\n", err) fmt.Printf("Failed to start Ethereum peer: %v.\n", err)

View file

@ -172,7 +172,7 @@ func (self *Whisper) Send(envelope *Envelope) error {
// Start implements node.Service, starting the background data propagation thread // Start implements node.Service, starting the background data propagation thread
// of the Whisper protocol. // of the Whisper protocol.
func (self *Whisper) Start(p2p.Server) error { func (self *Whisper) Start(*p2p.Server) error {
log.Info(fmt.Sprint("Whisper started")) log.Info(fmt.Sprint("Whisper started"))
go self.update() go self.update()
return nil return nil

View file

@ -78,7 +78,7 @@ type TestData struct {
type TestNode struct { type TestNode struct {
shh *Whisper shh *Whisper
id *ecdsa.PrivateKey id *ecdsa.PrivateKey
server p2p.Server server *p2p.Server
filerId string filerId string
} }
@ -140,17 +140,19 @@ func initialize(t *testing.T) {
peers = append(peers, peer) peers = append(peers, peer)
} }
node.server = p2p.NewServer(p2p.Config{ node.server = &p2p.Server{
PrivateKey: node.id, Config: p2p.Config{
MaxPeers: NumNodes/2 + 1, PrivateKey: node.id,
Name: name, MaxPeers: NumNodes/2 + 1,
Protocols: node.shh.Protocols(), Name: name,
ListenAddr: addr, Protocols: node.shh.Protocols(),
NAT: nat.Any(), ListenAddr: addr,
BootstrapNodes: peers, NAT: nat.Any(),
StaticNodes: peers, BootstrapNodes: peers,
TrustedNodes: peers, StaticNodes: peers,
}) TrustedNodes: peers,
},
}
err = node.server.Start() err = node.server.Start()
if err != nil { if err != nil {

View file

@ -396,7 +396,7 @@ func (w *Whisper) Send(envelope *Envelope) error {
// Start implements node.Service, starting the background data propagation thread // Start implements node.Service, starting the background data propagation thread
// of the Whisper protocol. // of the Whisper protocol.
func (w *Whisper) Start(p2p.Server) error { func (w *Whisper) Start(*p2p.Server) error {
log.Info("started whisper v." + ProtocolVersionStr) log.Info("started whisper v." + ProtocolVersionStr)
go w.update() go w.update()