From de0549fabb8be4dbaf382ee68ec1b702cb0c5c97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Szil=C3=A1gyi?= Date: Wed, 29 Apr 2015 18:04:08 +0300 Subject: [PATCH 01/10] cmd/geth, cmd/mist, cmd/utils, eth, p2p: support trusted peers --- cmd/geth/admin.go | 6 ++-- cmd/geth/main.go | 3 +- cmd/mist/main.go | 2 +- cmd/mist/ui_lib.go | 4 +-- cmd/utils/flags.go | 10 ++++-- eth/backend.go | 56 ++++++++++++++++++++++++++--- p2p/server.go | 90 +++++++++++++++++++++++++++++++++++++++------- p2p/server_test.go | 2 +- 8 files changed, 146 insertions(+), 27 deletions(-) diff --git a/cmd/geth/admin.go b/cmd/geth/admin.go index 31f8d4400..a07e694de 100644 --- a/cmd/geth/admin.go +++ b/cmd/geth/admin.go @@ -25,7 +25,7 @@ func (js *jsre) adminBindings() { js.re.Set("admin", struct{}{}) t, _ := js.re.Get("admin") admin := t.Object() - admin.Set("suggestPeer", js.suggestPeer) + admin.Set("trustPeer", js.trustPeer) admin.Set("startRPC", js.startRPC) admin.Set("stopRPC", js.stopRPC) admin.Set("nodeInfo", js.nodeInfo) @@ -243,13 +243,13 @@ func (js *jsre) stopRPC(call otto.FunctionCall) otto.Value { return otto.FalseValue() } -func (js *jsre) suggestPeer(call otto.FunctionCall) otto.Value { +func (js *jsre) trustPeer(call otto.FunctionCall) otto.Value { nodeURL, err := call.Argument(0).ToString() if err != nil { fmt.Println(err) return otto.FalseValue() } - err = js.ethereum.SuggestPeer(nodeURL) + err = js.ethereum.TrustPeer(nodeURL) if err != nil { fmt.Println(err) return otto.FalseValue() diff --git a/cmd/geth/main.go b/cmd/geth/main.go index ef007051c..d9d1c1b15 100644 --- a/cmd/geth/main.go +++ b/cmd/geth/main.go @@ -232,7 +232,8 @@ JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Conso utils.IdentityFlag, utils.UnlockedAccountFlag, utils.PasswordFileFlag, - utils.BootnodesFlag, + utils.BootNodesFlag, + utils.TrustedNodesFlag, utils.DataDirFlag, utils.BlockchainVersionFlag, utils.JSpathFlag, diff --git a/cmd/mist/main.go b/cmd/mist/main.go index 1030d6ada..18fb919b4 100644 --- a/cmd/mist/main.go +++ b/cmd/mist/main.go @@ -69,7 +69,7 @@ func init() { assetPathFlag, rpcCorsFlag, - utils.BootnodesFlag, + utils.BootNodesFlag, utils.DataDirFlag, utils.ListenPortFlag, utils.LogFileFlag, diff --git a/cmd/mist/ui_lib.go b/cmd/mist/ui_lib.go index 34ce56e77..e1a3aa254 100644 --- a/cmd/mist/ui_lib.go +++ b/cmd/mist/ui_lib.go @@ -104,8 +104,8 @@ func (ui *UiLib) Connect(button qml.Object) { } func (ui *UiLib) ConnectToPeer(nodeURL string) { - if err := ui.eth.SuggestPeer(nodeURL); err != nil { - guilogger.Infoln("SuggestPeer error: " + err.Error()) + if err := ui.eth.TrustPeer(nodeURL); err != nil { + guilogger.Infoln("TrustPeer error: " + err.Error()) } } diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index c013510d8..f52bfc21f 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -202,11 +202,16 @@ var ( Usage: "Network listening port", Value: 30303, } - BootnodesFlag = cli.StringFlag{ + BootNodesFlag = cli.StringFlag{ Name: "bootnodes", Usage: "Space-separated enode URLs for p2p discovery bootstrap", Value: "", } + TrustedNodesFlag = cli.StringFlag{ + Name: "trustednodes", + Usage: "List of trusted nodes (either an enode list or path to a json file of enodes)", + Value: "", + } NodeKeyFileFlag = cli.StringFlag{ Name: "nodekey", Usage: "P2P node key file", @@ -292,7 +297,8 @@ func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config { NodeKey: GetNodeKey(ctx), Shh: ctx.GlobalBool(WhisperEnabledFlag.Name), Dial: true, - BootNodes: ctx.GlobalString(BootnodesFlag.Name), + BootNodes: ctx.GlobalString(BootNodesFlag.Name), + TrustedNodes: ctx.GlobalString(TrustedNodesFlag.Name), } } diff --git a/eth/backend.go b/eth/backend.go index c5fa328b0..f8d57c985 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -2,7 +2,10 @@ package eth import ( "crypto/ecdsa" + "encoding/json" "fmt" + "io/ioutil" + "os" "path" "strings" "time" @@ -56,10 +59,13 @@ type Config struct { MaxPeers int Port string - // This should be a space-separated list of - // discovery node URLs. + // Space-separated list of discovery node URLs BootNodes string + // Either a space-separated list of discovery node URLs, or a path to a json + // file containing such a list. + TrustedNodes string + // This key is used to identify the node on the network. // If nil, an ephemeral key is used. NodeKey *ecdsa.PrivateKey @@ -96,6 +102,46 @@ func (cfg *Config) parseBootNodes() []*discover.Node { return ns } +// parseTrustedNodes parses a list of discovery node URLs either given literally, +// or loaded from a .json file. +func (cfg *Config) parseTrustedNodes() []*discover.Node { + // Short circuit if no trusted nodes were given + if cfg.TrustedNodes == "" { + return nil + } + // Try to interpret the trusted node config as a .json file + if _, err := os.Stat(cfg.TrustedNodes); err == nil { + // Load the file from disk + blob, err := ioutil.ReadFile(cfg.TrustedNodes) + if err != nil { + glog.V(logger.Error).Infof("Failed to access trusted nodes: %v", err) + return nil + } + // Interpret the json contents + list := []string{} + if err := json.Unmarshal(blob, &list); err != nil { + glog.V(logger.Error).Infof("Failed to load trusted nodes: %v", err) + return nil + } + // Swap out the configuration for the actual nodes + cfg.TrustedNodes = strings.Join(list, " ") + } + // Interpret the list as a discovery node array + var nodes []*discover.Node + for _, url := range strings.Split(cfg.TrustedNodes, " ") { + if url == "" { + continue + } + node, err := discover.ParseNode(url) + if err != nil { + glog.V(logger.Error).Infof("Trusted node URL %s: %v\n", url, err) + continue + } + nodes = append(nodes, node) + } + return nodes +} + func (cfg *Config) nodeKey() (*ecdsa.PrivateKey, error) { // use explicit key from command line args if set if cfg.NodeKey != nil { @@ -247,6 +293,7 @@ func New(config *Config) (*Ethereum, error) { NAT: config.NAT, NoDial: !config.Dial, BootstrapNodes: config.parseBootNodes(), + TrustedNodes: config.parseTrustedNodes(), NodeDatabase: nodeDb, } if len(config.Port) > 0 { @@ -442,12 +489,13 @@ func (s *Ethereum) StartForTest() { s.txPool.Start() } -func (self *Ethereum) SuggestPeer(nodeURL string) error { +// TrustPeer injects a new node into the list of privileged nodes. +func (self *Ethereum) TrustPeer(nodeURL string) error { n, err := discover.ParseNode(nodeURL) if err != nil { return fmt.Errorf("invalid node URL: %v", err) } - self.net.SuggestPeer(n) + self.net.TrustPeer(n) return nil } diff --git a/p2p/server.go b/p2p/server.go index 5c5883ae8..794c36125 100644 --- a/p2p/server.go +++ b/p2p/server.go @@ -18,8 +18,9 @@ import ( ) const ( - defaultDialTimeout = 10 * time.Second - refreshPeersInterval = 30 * time.Second + defaultDialTimeout = 10 * time.Second + refreshPeersInterval = 30 * time.Second + trustedPeerCheckInterval = 15 * time.Second // This is the maximum number of inbound connection // that are allowed to linger between 'accepted' and @@ -59,6 +60,10 @@ type Server struct { // with the rest of the network. BootstrapNodes []*discover.Node + // Trusted nodes are used as privileged connections which are always accepted + // and also always maintained. + TrustedNodes []*discover.Node + // NodeDatabase is the path to the database containing the previously seen // live nodes in the network. NodeDatabase string @@ -99,13 +104,15 @@ type Server struct { running bool peers map[discover.NodeID]*Peer + trusts map[discover.NodeID]*discover.Node // Map of currently trusted remote nodes + trustDial chan *discover.Node // Dial request channel reserved for the trusted nodes + ntab *discover.Table listener net.Listener - quit chan struct{} - loopWG sync.WaitGroup // {dial,listen,nat}Loop - peerWG sync.WaitGroup // active peer goroutines - peerConnect chan *discover.Node + quit chan struct{} + loopWG sync.WaitGroup // {dial,listen,nat}Loop + peerWG sync.WaitGroup // active peer goroutines } type setupFunc func(net.Conn, *ecdsa.PrivateKey, *protoHandshake, *discover.Node, bool) (*conn, error) @@ -131,10 +138,9 @@ func (srv *Server) PeerCount() int { return n } -// SuggestPeer creates a connection to the given Node if it -// is not already connected. -func (srv *Server) SuggestPeer(n *discover.Node) { - srv.peerConnect <- n +// TrustPeer inserts a node into the list of privileged nodes. +func (srv *Server) TrustPeer(node *discover.Node) { + srv.trustDial <- node } // Broadcast sends an RLP-encoded message to all connected peers. @@ -195,7 +201,14 @@ func (srv *Server) Start() (err error) { } srv.quit = make(chan struct{}) srv.peers = make(map[discover.NodeID]*Peer) - srv.peerConnect = make(chan *discover.Node) + + // Create the current trust map, and the associated dialing channel + srv.trusts = make(map[discover.NodeID]*discover.Node) + for _, node := range srv.TrustedNodes { + srv.trusts[node.ID] = node + } + srv.trustDial = make(chan *discover.Node) + if srv.setupFunc == nil { srv.setupFunc = setupConn } @@ -229,6 +242,8 @@ func (srv *Server) Start() (err error) { if srv.NoDial && srv.ListenAddr == "" { glog.V(logger.Warn).Infoln("I will be kind-of useless, neither dialing nor listening.") } + // maintain the trusted peers + go srv.trustLoop() srv.running = true return nil @@ -323,6 +338,45 @@ func (srv *Server) listenLoop() { } } +// trustLoop is responsible for periodically checking that trusted connections +// are actually live, and requests dialing if not. +func (srv *Server) trustLoop() { + // Create a ticker for verifying trusted connections + tick := time.Tick(trustedPeerCheckInterval) + + for { + select { + case <-srv.quit: + // Termination requested, simple return + return + + case <-tick: + // Collect all the non-connected trusted nodes + needed := []*discover.Node{} + srv.lock.RLock() + for id, node := range srv.trusts { + if _, ok := srv.peers[id]; !ok { + needed = append(needed, node) + } + } + srv.lock.RUnlock() + + // Try to dial each of them (don't hang if server terminates) + for _, node := range needed { + glog.V(logger.Error).Infof("Dialing trusted peer %v", node) + select { + case srv.trustDial <- node: + // Ok, dialing + + case <-srv.quit: + // Terminating, return + return + } + } + } + } +} + func (srv *Server) dialLoop() { var ( dialed = make(chan *discover.Node) @@ -373,7 +427,7 @@ func (srv *Server) dialLoop() { // below MaxPeers. refresh.Reset(refreshPeersInterval) } - case dest := <-srv.peerConnect: + case dest := <-srv.trustDial: dial(dest) case dests := <-findresults: for _, dest := range dests { @@ -472,16 +526,26 @@ func (srv *Server) addPeer(id discover.NodeID, p *Peer) (bool, DiscReason) { return true, 0 } +// checkPeer verifies whether a peer looks promising and should be allowed/kept +// in the pool, or if it's of no use. func (srv *Server) checkPeer(id discover.NodeID) (bool, DiscReason) { + // First up, figure out if the peer is trusted + _, trusted := srv.trusts[id] + + // Make sure the peer passes all required checks switch { case !srv.running: return false, DiscQuitting - case len(srv.peers) >= srv.MaxPeers: + + case !trusted && len(srv.peers) >= srv.MaxPeers: return false, DiscTooManyPeers + case srv.peers[id] != nil: return false, DiscAlreadyConnected + case id == srv.ntab.Self().ID: return false, DiscSelf + default: return true, 0 } diff --git a/p2p/server_test.go b/p2p/server_test.go index 53cc3c258..e99d37ed0 100644 --- a/p2p/server_test.go +++ b/p2p/server_test.go @@ -102,7 +102,7 @@ func TestServerDial(t *testing.T) { // tell the server to connect tcpAddr := listener.Addr().(*net.TCPAddr) - srv.SuggestPeer(&discover.Node{IP: tcpAddr.IP, TCPPort: tcpAddr.Port}) + srv.trustDial <-&discover.Node{IP: tcpAddr.IP, TCPPort: tcpAddr.Port} select { case conn := <-accepted: From 679c90b873f78b10a97a85ddd29b91bded9b0dd1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Szil=C3=A1gyi?= Date: Wed, 29 Apr 2015 18:50:52 +0300 Subject: [PATCH 02/10] cmd/geth, cmd/utils, eth: internalize trusted node config file --- cmd/geth/main.go | 1 - cmd/utils/flags.go | 6 ------ eth/backend.go | 43 ++++++++++++++++++++----------------------- 3 files changed, 20 insertions(+), 30 deletions(-) diff --git a/cmd/geth/main.go b/cmd/geth/main.go index d9d1c1b15..036ee2d0c 100644 --- a/cmd/geth/main.go +++ b/cmd/geth/main.go @@ -233,7 +233,6 @@ JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Conso utils.UnlockedAccountFlag, utils.PasswordFileFlag, utils.BootNodesFlag, - utils.TrustedNodesFlag, utils.DataDirFlag, utils.BlockchainVersionFlag, utils.JSpathFlag, diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index f52bfc21f..62b49cddc 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -207,11 +207,6 @@ var ( Usage: "Space-separated enode URLs for p2p discovery bootstrap", Value: "", } - TrustedNodesFlag = cli.StringFlag{ - Name: "trustednodes", - Usage: "List of trusted nodes (either an enode list or path to a json file of enodes)", - Value: "", - } NodeKeyFileFlag = cli.StringFlag{ Name: "nodekey", Usage: "P2P node key file", @@ -298,7 +293,6 @@ func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config { Shh: ctx.GlobalBool(WhisperEnabledFlag.Name), Dial: true, BootNodes: ctx.GlobalString(BootNodesFlag.Name), - TrustedNodes: ctx.GlobalString(TrustedNodesFlag.Name), } } diff --git a/eth/backend.go b/eth/backend.go index f8d57c985..c69e4a27a 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -7,6 +7,7 @@ import ( "io/ioutil" "os" "path" + "path/filepath" "strings" "time" @@ -39,6 +40,9 @@ var ( // ETH/DEV cpp-ethereum (poc-9.ethdev.com) discover.MustParseNode("enode://487611428e6c99a11a9795a6abe7b529e81315ca6aad66e2a2fc76e3adf263faba0d35466c2f8f68d561dbefa8878d4df5f1f2ddb1fbeab7f42ffb8cd328bd4a@5.1.83.226:30303"), } + + // Path within to search for the trusted node list + trustedNodes = "trusted-nodes.json" ) type Config struct { @@ -62,10 +66,6 @@ type Config struct { // Space-separated list of discovery node URLs BootNodes string - // Either a space-separated list of discovery node URLs, or a path to a json - // file containing such a list. - TrustedNodes string - // This key is used to identify the node on the network. // If nil, an ephemeral key is used. NodeKey *ecdsa.PrivateKey @@ -105,30 +105,27 @@ func (cfg *Config) parseBootNodes() []*discover.Node { // parseTrustedNodes parses a list of discovery node URLs either given literally, // or loaded from a .json file. func (cfg *Config) parseTrustedNodes() []*discover.Node { - // Short circuit if no trusted nodes were given - if cfg.TrustedNodes == "" { + // Short circuit if no trusted node config is present + path := filepath.Join(cfg.DataDir, trustedNodes) + if _, err := os.Stat(path); err != nil { + fmt.Println("nodes", nil) return nil } - // Try to interpret the trusted node config as a .json file - if _, err := os.Stat(cfg.TrustedNodes); err == nil { - // Load the file from disk - blob, err := ioutil.ReadFile(cfg.TrustedNodes) - if err != nil { - glog.V(logger.Error).Infof("Failed to access trusted nodes: %v", err) - return nil - } - // Interpret the json contents - list := []string{} - if err := json.Unmarshal(blob, &list); err != nil { - glog.V(logger.Error).Infof("Failed to load trusted nodes: %v", err) - return nil - } - // Swap out the configuration for the actual nodes - cfg.TrustedNodes = strings.Join(list, " ") + // Load the trusted nodes from the config file + blob, err := ioutil.ReadFile(path) + if err != nil { + glog.V(logger.Error).Infof("Failed to access trusted nodes: %v", err) + return nil } + nodelist := []string{} + if err := json.Unmarshal(blob, &nodelist); err != nil { + glog.V(logger.Error).Infof("Failed to load trusted nodes: %v", err) + return nil + } + fmt.Println("nodes", nodelist) // Interpret the list as a discovery node array var nodes []*discover.Node - for _, url := range strings.Split(cfg.TrustedNodes, " ") { + for _, url := range nodelist { if url == "" { continue } From 14f32a0c3a30c172c62272aa93f97e8a3d72ddcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Szil=C3=A1gyi?= Date: Wed, 29 Apr 2015 18:59:08 +0300 Subject: [PATCH 03/10] p2p: reduce the severity of a debug log --- p2p/server.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/p2p/server.go b/p2p/server.go index 794c36125..d85696e20 100644 --- a/p2p/server.go +++ b/p2p/server.go @@ -363,7 +363,7 @@ func (srv *Server) trustLoop() { // Try to dial each of them (don't hang if server terminates) for _, node := range needed { - glog.V(logger.Error).Infof("Dialing trusted peer %v", node) + glog.V(logger.Debug).Infof("Dialing trusted peer %v", node) select { case srv.trustDial <- node: // Ok, dialing From 1528dbc17101597348eefe3f3fb8d4f0d5c54b3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Szil=C3=A1gyi?= Date: Thu, 30 Apr 2015 12:41:27 +0300 Subject: [PATCH 04/10] p2p: add trust check to handshake, test privileged connectivity Conflicts: p2p/server_test.go --- p2p/handshake.go | 14 ++++----- p2p/handshake_test.go | 4 +-- p2p/server.go | 17 +++++++++-- p2p/server_test.go | 68 +++++++++++++++++++++++++++++++++++++++++-- 4 files changed, 88 insertions(+), 15 deletions(-) diff --git a/p2p/handshake.go b/p2p/handshake.go index 79395f23f..280b5068e 100644 --- a/p2p/handshake.go +++ b/p2p/handshake.go @@ -70,21 +70,21 @@ type protoHandshake struct { // If dial is non-nil, the connection the local node is the initiator. // If atcap is true, the connection will be disconnected with DiscTooManyPeers // after the key exchange. -func setupConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool) (*conn, error) { +func setupConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool, trust map[discover.NodeID]bool) (*conn, error) { if dial == nil { - return setupInboundConn(fd, prv, our, atcap) + return setupInboundConn(fd, prv, our, atcap, trust) } else { - return setupOutboundConn(fd, prv, our, dial, atcap) + return setupOutboundConn(fd, prv, our, dial, atcap, trust) } } -func setupInboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, atcap bool) (*conn, error) { +func setupInboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, atcap bool, trust map[discover.NodeID]bool) (*conn, error) { secrets, err := receiverEncHandshake(fd, prv, nil) if err != nil { return nil, fmt.Errorf("encryption handshake failed: %v", err) } rw := newRlpxFrameRW(fd, secrets) - if atcap { + if atcap && !trust[secrets.RemoteID] { SendItems(rw, discMsg, DiscTooManyPeers) return nil, errors.New("we have too many peers") } @@ -99,13 +99,13 @@ func setupInboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, a return &conn{rw, rhs}, nil } -func setupOutboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool) (*conn, error) { +func setupOutboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool, trust map[discover.NodeID]bool) (*conn, error) { secrets, err := initiatorEncHandshake(fd, prv, dial.ID, nil) if err != nil { return nil, fmt.Errorf("encryption handshake failed: %v", err) } rw := newRlpxFrameRW(fd, secrets) - if atcap { + if atcap && !trust[secrets.RemoteID] { SendItems(rw, discMsg, DiscTooManyPeers) return nil, errors.New("we have too many peers") } diff --git a/p2p/handshake_test.go b/p2p/handshake_test.go index c22af7a9c..5e63e5c39 100644 --- a/p2p/handshake_test.go +++ b/p2p/handshake_test.go @@ -143,7 +143,7 @@ func TestSetupConn(t *testing.T) { done := make(chan struct{}) go func() { defer close(done) - conn0, err := setupConn(fd0, prv0, hs0, node1, false) + conn0, err := setupConn(fd0, prv0, hs0, node1, false, nil) if err != nil { t.Errorf("outbound side error: %v", err) return @@ -156,7 +156,7 @@ func TestSetupConn(t *testing.T) { } }() - conn1, err := setupConn(fd1, prv1, hs1, nil, false) + conn1, err := setupConn(fd1, prv1, hs1, nil, false, nil) if err != nil { t.Fatalf("inbound side error: %v", err) } diff --git a/p2p/server.go b/p2p/server.go index d85696e20..d8c5ecd77 100644 --- a/p2p/server.go +++ b/p2p/server.go @@ -115,7 +115,7 @@ type Server struct { peerWG sync.WaitGroup // active peer goroutines } -type setupFunc func(net.Conn, *ecdsa.PrivateKey, *protoHandshake, *discover.Node, bool) (*conn, error) +type setupFunc func(net.Conn, *ecdsa.PrivateKey, *protoHandshake, *discover.Node, bool, map[discover.NodeID]bool) (*conn, error) type newPeerHook func(*Peer) // Peers returns all connected peers. @@ -140,7 +140,10 @@ func (srv *Server) PeerCount() int { // TrustPeer inserts a node into the list of privileged nodes. func (srv *Server) TrustPeer(node *discover.Node) { - srv.trustDial <- node + srv.lock.Lock() + defer srv.lock.Unlock() + + srv.trusts[node.ID] = node } // Broadcast sends an RLP-encoded message to all connected peers. @@ -470,10 +473,18 @@ func (srv *Server) startPeer(fd net.Conn, dest *discover.Node) { // returns during that exchange need to call peerWG.Done because // the callers of startPeer added the peer to the wait group already. fd.SetDeadline(time.Now().Add(handshakeTimeout)) + + // Check capacity and trust list srv.lock.RLock() atcap := len(srv.peers) == srv.MaxPeers + + trust := make(map[discover.NodeID]bool) + for id, _ := range srv.trusts { + trust[id] = true + } srv.lock.RUnlock() - conn, err := srv.setupFunc(fd, srv.PrivateKey, srv.ourHandshake, dest, atcap) + + conn, err := srv.setupFunc(fd, srv.PrivateKey, srv.ourHandshake, dest, atcap, trust) if err != nil { fd.Close() glog.V(logger.Debug).Infof("Handshake with %v failed: %v", fd.RemoteAddr(), err) diff --git a/p2p/server_test.go b/p2p/server_test.go index e99d37ed0..a79679ac1 100644 --- a/p2p/server_test.go +++ b/p2p/server_test.go @@ -22,7 +22,7 @@ func startTestServer(t *testing.T, pf newPeerHook) *Server { ListenAddr: "127.0.0.1:0", PrivateKey: newkey(), newPeerHook: pf, - setupFunc: func(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool) (*conn, error) { + setupFunc: func(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool, trust map[discover.NodeID]bool) (*conn, error) { id := randomID() rw := newRlpxFrameRW(fd, secrets{ MAC: zero16, @@ -102,7 +102,7 @@ func TestServerDial(t *testing.T) { // tell the server to connect tcpAddr := listener.Addr().(*net.TCPAddr) - srv.trustDial <-&discover.Node{IP: tcpAddr.IP, TCPPort: tcpAddr.Port} + srv.trustDial <- &discover.Node{IP: tcpAddr.IP, TCPPort: tcpAddr.Port} select { case conn := <-accepted: @@ -200,7 +200,7 @@ func TestServerDisconnectAtCap(t *testing.T) { // Run the handshakes just like a real peer would. key := newkey() hs := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)} - _, err = setupConn(conn, key, hs, srv.Self(), false) + _, err = setupConn(conn, key, hs, srv.Self(), false, nil) if i == nconns-1 { // When handling the last connection, the server should // disconnect immediately instead of running the protocol @@ -219,6 +219,68 @@ func TestServerDisconnectAtCap(t *testing.T) { } } +// Tests that trusted peers and can connect above max peer caps. +func TestServerTrustedPeers(t *testing.T) { + defer testlog(t).detach() + + // Create a test server with limited connection slots + started := make(chan *Peer) + server := &Server{ + ListenAddr: "127.0.0.1:0", + PrivateKey: newkey(), + MaxPeers: 3, + NoDial: true, + newPeerHook: func(p *Peer) { started <- p }, + } + if err := server.Start(); err != nil { + t.Fatal(err) + } + defer server.Stop() + + // Fill up all the slots on the server + dialer := &net.Dialer{Deadline: time.Now().Add(3 * time.Second)} + for i := 0; i < server.MaxPeers; i++ { + // Establish a new connection + conn, err := dialer.Dial("tcp", server.ListenAddr) + if err != nil { + t.Fatalf("conn %d: dial error: %v", i, err) + } + defer conn.Close() + + // Run the handshakes just like a real peer would, and wait for completion + key := newkey() + shake := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)} + if _, err = setupConn(conn, key, shake, server.Self(), false, nil); err != nil { + t.Fatalf("conn %d: unexpected error: %v", i, err) + } + <-started + } + // Inject a trusted node and dial that (we'll connect from this end, don't need IP setup) + key := newkey() + trusted := &discover.Node{ + ID: discover.PubkeyID(&key.PublicKey), + } + server.TrustPeer(trusted) + + conn, err := dialer.Dial("tcp", server.ListenAddr) + if err != nil { + t.Fatalf("trusted node: dial error: %v", err) + } + defer conn.Close() + + shake := &protoHandshake{Version: baseProtocolVersion, ID: trusted.ID} + if _, err = setupConn(conn, key, shake, server.Self(), false, nil); err != nil { + t.Fatalf("trusted node: unexpected error: %v", err) + } + select { + case <-started: + // Ok, trusted peer accepted + + case <-time.After(100 * time.Millisecond): + t.Fatalf("trusted node timeout") + } +} + func newkey() *ecdsa.PrivateKey { key, err := crypto.GenerateKey() if err != nil { From 701591b403a8bae8c1dfb648a49d587968ff0c6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Szil=C3=A1gyi?= Date: Thu, 30 Apr 2015 16:15:29 +0300 Subject: [PATCH 05/10] cmd, eth, p2p: fix review issues enumerated by Felix --- cmd/geth/admin.go | 6 +++--- cmd/geth/main.go | 2 +- cmd/mist/main.go | 2 +- cmd/mist/ui_lib.go | 2 +- cmd/utils/flags.go | 4 ++-- eth/backend.go | 10 +++++----- p2p/server.go | 31 +++++++++++-------------------- p2p/server_test.go | 2 +- 8 files changed, 25 insertions(+), 34 deletions(-) diff --git a/cmd/geth/admin.go b/cmd/geth/admin.go index a07e694de..77510b8b8 100644 --- a/cmd/geth/admin.go +++ b/cmd/geth/admin.go @@ -25,7 +25,7 @@ func (js *jsre) adminBindings() { js.re.Set("admin", struct{}{}) t, _ := js.re.Get("admin") admin := t.Object() - admin.Set("trustPeer", js.trustPeer) + admin.Set("addPeer", js.addPeer) admin.Set("startRPC", js.startRPC) admin.Set("stopRPC", js.stopRPC) admin.Set("nodeInfo", js.nodeInfo) @@ -243,13 +243,13 @@ func (js *jsre) stopRPC(call otto.FunctionCall) otto.Value { return otto.FalseValue() } -func (js *jsre) trustPeer(call otto.FunctionCall) otto.Value { +func (js *jsre) addPeer(call otto.FunctionCall) otto.Value { nodeURL, err := call.Argument(0).ToString() if err != nil { fmt.Println(err) return otto.FalseValue() } - err = js.ethereum.TrustPeer(nodeURL) + err = js.ethereum.AddPeer(nodeURL) if err != nil { fmt.Println(err) return otto.FalseValue() diff --git a/cmd/geth/main.go b/cmd/geth/main.go index 036ee2d0c..ef007051c 100644 --- a/cmd/geth/main.go +++ b/cmd/geth/main.go @@ -232,7 +232,7 @@ JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Conso utils.IdentityFlag, utils.UnlockedAccountFlag, utils.PasswordFileFlag, - utils.BootNodesFlag, + utils.BootnodesFlag, utils.DataDirFlag, utils.BlockchainVersionFlag, utils.JSpathFlag, diff --git a/cmd/mist/main.go b/cmd/mist/main.go index 18fb919b4..1030d6ada 100644 --- a/cmd/mist/main.go +++ b/cmd/mist/main.go @@ -69,7 +69,7 @@ func init() { assetPathFlag, rpcCorsFlag, - utils.BootNodesFlag, + utils.BootnodesFlag, utils.DataDirFlag, utils.ListenPortFlag, utils.LogFileFlag, diff --git a/cmd/mist/ui_lib.go b/cmd/mist/ui_lib.go index e1a3aa254..a20205b03 100644 --- a/cmd/mist/ui_lib.go +++ b/cmd/mist/ui_lib.go @@ -104,7 +104,7 @@ func (ui *UiLib) Connect(button qml.Object) { } func (ui *UiLib) ConnectToPeer(nodeURL string) { - if err := ui.eth.TrustPeer(nodeURL); err != nil { + if err := ui.eth.AddPeer(nodeURL); err != nil { guilogger.Infoln("TrustPeer error: " + err.Error()) } } diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index 62b49cddc..c013510d8 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -202,7 +202,7 @@ var ( Usage: "Network listening port", Value: 30303, } - BootNodesFlag = cli.StringFlag{ + BootnodesFlag = cli.StringFlag{ Name: "bootnodes", Usage: "Space-separated enode URLs for p2p discovery bootstrap", Value: "", @@ -292,7 +292,7 @@ func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config { NodeKey: GetNodeKey(ctx), Shh: ctx.GlobalBool(WhisperEnabledFlag.Name), Dial: true, - BootNodes: ctx.GlobalString(BootNodesFlag.Name), + BootNodes: ctx.GlobalString(BootnodesFlag.Name), } } diff --git a/eth/backend.go b/eth/backend.go index c69e4a27a..11e5c25e8 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -108,7 +108,6 @@ func (cfg *Config) parseTrustedNodes() []*discover.Node { // Short circuit if no trusted node config is present path := filepath.Join(cfg.DataDir, trustedNodes) if _, err := os.Stat(path); err != nil { - fmt.Println("nodes", nil) return nil } // Load the trusted nodes from the config file @@ -122,7 +121,6 @@ func (cfg *Config) parseTrustedNodes() []*discover.Node { glog.V(logger.Error).Infof("Failed to load trusted nodes: %v", err) return nil } - fmt.Println("nodes", nodelist) // Interpret the list as a discovery node array var nodes []*discover.Node for _, url := range nodelist { @@ -486,13 +484,15 @@ func (s *Ethereum) StartForTest() { s.txPool.Start() } -// TrustPeer injects a new node into the list of privileged nodes. -func (self *Ethereum) TrustPeer(nodeURL string) error { +// 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 +// attempt to reconnect the peer. +func (self *Ethereum) AddPeer(nodeURL string) error { n, err := discover.ParseNode(nodeURL) if err != nil { return fmt.Errorf("invalid node URL: %v", err) } - self.net.TrustPeer(n) + self.net.AddPeer(n) return nil } diff --git a/p2p/server.go b/p2p/server.go index d8c5ecd77..dbb2e5f9e 100644 --- a/p2p/server.go +++ b/p2p/server.go @@ -100,10 +100,9 @@ type Server struct { ourHandshake *protoHandshake - lock sync.RWMutex // protects running and peers - running bool - peers map[discover.NodeID]*Peer - + lock sync.RWMutex // protects running, peers and the trust fields + running bool + peers map[discover.NodeID]*Peer trusts map[discover.NodeID]*discover.Node // Map of currently trusted remote nodes trustDial chan *discover.Node // Dial request channel reserved for the trusted nodes @@ -138,8 +137,10 @@ func (srv *Server) PeerCount() int { return n } -// TrustPeer inserts a node into the list of privileged nodes. -func (srv *Server) TrustPeer(node *discover.Node) { +// 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 +// attempt to reconnect the peer. +func (srv *Server) AddPeer(node *discover.Node) { srv.lock.Lock() defer srv.lock.Unlock() @@ -246,7 +247,7 @@ func (srv *Server) Start() (err error) { glog.V(logger.Warn).Infoln("I will be kind-of useless, neither dialing nor listening.") } // maintain the trusted peers - go srv.trustLoop() + go srv.trustedNodesLoop() srv.running = true return nil @@ -341,16 +342,13 @@ func (srv *Server) listenLoop() { } } -// trustLoop is responsible for periodically checking that trusted connections -// are actually live, and requests dialing if not. -func (srv *Server) trustLoop() { - // Create a ticker for verifying trusted connections +// trustedNodesLoop is responsible for periodically checking that trusted +// connections are actually live, and requests dialing if not. +func (srv *Server) trustedNodesLoop() { tick := time.Tick(trustedPeerCheckInterval) - for { select { case <-srv.quit: - // Termination requested, simple return return case <-tick: @@ -369,10 +367,7 @@ func (srv *Server) trustLoop() { glog.V(logger.Debug).Infof("Dialing trusted peer %v", node) select { case srv.trustDial <- node: - // Ok, dialing - case <-srv.quit: - // Terminating, return return } } @@ -547,16 +542,12 @@ func (srv *Server) checkPeer(id discover.NodeID) (bool, DiscReason) { switch { case !srv.running: return false, DiscQuitting - case !trusted && len(srv.peers) >= srv.MaxPeers: return false, DiscTooManyPeers - case srv.peers[id] != nil: return false, DiscAlreadyConnected - case id == srv.ntab.Self().ID: return false, DiscSelf - default: return true, 0 } diff --git a/p2p/server_test.go b/p2p/server_test.go index a79679ac1..3e3fd6cc0 100644 --- a/p2p/server_test.go +++ b/p2p/server_test.go @@ -260,7 +260,7 @@ func TestServerTrustedPeers(t *testing.T) { trusted := &discover.Node{ ID: discover.PubkeyID(&key.PublicKey), } - server.TrustPeer(trusted) + server.AddPeer(trusted) conn, err := dialer.Dial("tcp", server.ListenAddr) if err != nil { From 413ace37d3ba13a551f60e4089f2e0070c607970 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Szil=C3=A1gyi?= Date: Thu, 30 Apr 2015 19:32:48 +0300 Subject: [PATCH 06/10] eth, p2p: rename trusted nodes to static, drop inbound extra slots --- eth/backend.go | 22 +++++++-------- p2p/handshake.go | 14 +++++----- p2p/handshake_test.go | 4 +-- p2p/server.go | 64 +++++++++++++++++++++---------------------- p2p/server_test.go | 12 ++++---- 5 files changed, 59 insertions(+), 57 deletions(-) diff --git a/eth/backend.go b/eth/backend.go index 11e5c25e8..8aecfba5b 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -41,8 +41,8 @@ var ( discover.MustParseNode("enode://487611428e6c99a11a9795a6abe7b529e81315ca6aad66e2a2fc76e3adf263faba0d35466c2f8f68d561dbefa8878d4df5f1f2ddb1fbeab7f42ffb8cd328bd4a@5.1.83.226:30303"), } - // Path within to search for the trusted node list - trustedNodes = "trusted-nodes.json" + // Path within to search for the static node list + staticNodes = "static-nodes.json" ) type Config struct { @@ -102,23 +102,23 @@ func (cfg *Config) parseBootNodes() []*discover.Node { return ns } -// parseTrustedNodes parses a list of discovery node URLs either given literally, +// parseStaticNodes parses a list of discovery node URLs either given literally, // or loaded from a .json file. -func (cfg *Config) parseTrustedNodes() []*discover.Node { - // Short circuit if no trusted node config is present - path := filepath.Join(cfg.DataDir, trustedNodes) +func (cfg *Config) parseStaticNodes() []*discover.Node { + // Short circuit if no static node config is present + path := filepath.Join(cfg.DataDir, staticNodes) if _, err := os.Stat(path); err != nil { return nil } - // Load the trusted nodes from the config file + // Load the static nodes from the config file blob, err := ioutil.ReadFile(path) if err != nil { - glog.V(logger.Error).Infof("Failed to access trusted nodes: %v", err) + glog.V(logger.Error).Infof("Failed to access static nodes: %v", err) return nil } nodelist := []string{} if err := json.Unmarshal(blob, &nodelist); err != nil { - glog.V(logger.Error).Infof("Failed to load trusted nodes: %v", err) + glog.V(logger.Error).Infof("Failed to load static nodes: %v", err) return nil } // Interpret the list as a discovery node array @@ -129,7 +129,7 @@ func (cfg *Config) parseTrustedNodes() []*discover.Node { } node, err := discover.ParseNode(url) if err != nil { - glog.V(logger.Error).Infof("Trusted node URL %s: %v\n", url, err) + glog.V(logger.Error).Infof("Static node URL %s: %v\n", url, err) continue } nodes = append(nodes, node) @@ -288,7 +288,7 @@ func New(config *Config) (*Ethereum, error) { NAT: config.NAT, NoDial: !config.Dial, BootstrapNodes: config.parseBootNodes(), - TrustedNodes: config.parseTrustedNodes(), + StaticNodes: config.parseStaticNodes(), NodeDatabase: nodeDb, } if len(config.Port) > 0 { diff --git a/p2p/handshake.go b/p2p/handshake.go index 280b5068e..79395f23f 100644 --- a/p2p/handshake.go +++ b/p2p/handshake.go @@ -70,21 +70,21 @@ type protoHandshake struct { // If dial is non-nil, the connection the local node is the initiator. // If atcap is true, the connection will be disconnected with DiscTooManyPeers // after the key exchange. -func setupConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool, trust map[discover.NodeID]bool) (*conn, error) { +func setupConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool) (*conn, error) { if dial == nil { - return setupInboundConn(fd, prv, our, atcap, trust) + return setupInboundConn(fd, prv, our, atcap) } else { - return setupOutboundConn(fd, prv, our, dial, atcap, trust) + return setupOutboundConn(fd, prv, our, dial, atcap) } } -func setupInboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, atcap bool, trust map[discover.NodeID]bool) (*conn, error) { +func setupInboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, atcap bool) (*conn, error) { secrets, err := receiverEncHandshake(fd, prv, nil) if err != nil { return nil, fmt.Errorf("encryption handshake failed: %v", err) } rw := newRlpxFrameRW(fd, secrets) - if atcap && !trust[secrets.RemoteID] { + if atcap { SendItems(rw, discMsg, DiscTooManyPeers) return nil, errors.New("we have too many peers") } @@ -99,13 +99,13 @@ func setupInboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, a return &conn{rw, rhs}, nil } -func setupOutboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool, trust map[discover.NodeID]bool) (*conn, error) { +func setupOutboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool) (*conn, error) { secrets, err := initiatorEncHandshake(fd, prv, dial.ID, nil) if err != nil { return nil, fmt.Errorf("encryption handshake failed: %v", err) } rw := newRlpxFrameRW(fd, secrets) - if atcap && !trust[secrets.RemoteID] { + if atcap { SendItems(rw, discMsg, DiscTooManyPeers) return nil, errors.New("we have too many peers") } diff --git a/p2p/handshake_test.go b/p2p/handshake_test.go index 5e63e5c39..c22af7a9c 100644 --- a/p2p/handshake_test.go +++ b/p2p/handshake_test.go @@ -143,7 +143,7 @@ func TestSetupConn(t *testing.T) { done := make(chan struct{}) go func() { defer close(done) - conn0, err := setupConn(fd0, prv0, hs0, node1, false, nil) + conn0, err := setupConn(fd0, prv0, hs0, node1, false) if err != nil { t.Errorf("outbound side error: %v", err) return @@ -156,7 +156,7 @@ func TestSetupConn(t *testing.T) { } }() - conn1, err := setupConn(fd1, prv1, hs1, nil, false, nil) + conn1, err := setupConn(fd1, prv1, hs1, nil, false) if err != nil { t.Fatalf("inbound side error: %v", err) } diff --git a/p2p/server.go b/p2p/server.go index dbb2e5f9e..091bf0b2a 100644 --- a/p2p/server.go +++ b/p2p/server.go @@ -60,9 +60,9 @@ type Server struct { // with the rest of the network. BootstrapNodes []*discover.Node - // Trusted nodes are used as privileged connections which are always accepted - // and also always maintained. - TrustedNodes []*discover.Node + // Static nodes are used as pre-configured connections which are always + // maintained and re-connected on disconnects. + StaticNodes []*discover.Node // NodeDatabase is the path to the database containing the previously seen // live nodes in the network. @@ -100,11 +100,11 @@ type Server struct { ourHandshake *protoHandshake - lock sync.RWMutex // protects running, peers and the trust fields - running bool - peers map[discover.NodeID]*Peer - trusts map[discover.NodeID]*discover.Node // Map of currently trusted remote nodes - trustDial chan *discover.Node // Dial request channel reserved for the trusted nodes + lock sync.RWMutex // protects running, peers and the trust fields + running bool + peers map[discover.NodeID]*Peer + statics map[discover.NodeID]*discover.Node // Map of currently static remote nodes + staticDial chan *discover.Node // Dial request channel reserved for the static nodes ntab *discover.Table listener net.Listener @@ -114,7 +114,7 @@ type Server struct { peerWG sync.WaitGroup // active peer goroutines } -type setupFunc func(net.Conn, *ecdsa.PrivateKey, *protoHandshake, *discover.Node, bool, map[discover.NodeID]bool) (*conn, error) +type setupFunc func(net.Conn, *ecdsa.PrivateKey, *protoHandshake, *discover.Node, bool) (*conn, error) type newPeerHook func(*Peer) // Peers returns all connected peers. @@ -144,7 +144,7 @@ func (srv *Server) AddPeer(node *discover.Node) { srv.lock.Lock() defer srv.lock.Unlock() - srv.trusts[node.ID] = node + srv.statics[node.ID] = node } // Broadcast sends an RLP-encoded message to all connected peers. @@ -207,11 +207,11 @@ func (srv *Server) Start() (err error) { srv.peers = make(map[discover.NodeID]*Peer) // Create the current trust map, and the associated dialing channel - srv.trusts = make(map[discover.NodeID]*discover.Node) - for _, node := range srv.TrustedNodes { - srv.trusts[node.ID] = node + srv.statics = make(map[discover.NodeID]*discover.Node) + for _, node := range srv.StaticNodes { + srv.statics[node.ID] = node } - srv.trustDial = make(chan *discover.Node) + srv.staticDial = make(chan *discover.Node) if srv.setupFunc == nil { srv.setupFunc = setupConn @@ -246,8 +246,8 @@ func (srv *Server) Start() (err error) { if srv.NoDial && srv.ListenAddr == "" { glog.V(logger.Warn).Infoln("I will be kind-of useless, neither dialing nor listening.") } - // maintain the trusted peers - go srv.trustedNodesLoop() + // maintain the static peers + go srv.staticNodesLoop() srv.running = true return nil @@ -342,9 +342,9 @@ func (srv *Server) listenLoop() { } } -// trustedNodesLoop is responsible for periodically checking that trusted +// staticNodesLoop is responsible for periodically checking that static // connections are actually live, and requests dialing if not. -func (srv *Server) trustedNodesLoop() { +func (srv *Server) staticNodesLoop() { tick := time.Tick(trustedPeerCheckInterval) for { select { @@ -352,10 +352,10 @@ func (srv *Server) trustedNodesLoop() { return case <-tick: - // Collect all the non-connected trusted nodes + // Collect all the non-connected static nodes needed := []*discover.Node{} srv.lock.RLock() - for id, node := range srv.trusts { + for id, node := range srv.statics { if _, ok := srv.peers[id]; !ok { needed = append(needed, node) } @@ -364,9 +364,9 @@ func (srv *Server) trustedNodesLoop() { // Try to dial each of them (don't hang if server terminates) for _, node := range needed { - glog.V(logger.Debug).Infof("Dialing trusted peer %v", node) + glog.V(logger.Debug).Infof("Dialing static peer %v", node) select { - case srv.trustDial <- node: + case srv.staticDial <- node: case <-srv.quit: return } @@ -425,7 +425,7 @@ func (srv *Server) dialLoop() { // below MaxPeers. refresh.Reset(refreshPeersInterval) } - case dest := <-srv.trustDial: + case dest := <-srv.staticDial: dial(dest) case dests := <-findresults: for _, dest := range dests { @@ -469,17 +469,17 @@ func (srv *Server) startPeer(fd net.Conn, dest *discover.Node) { // the callers of startPeer added the peer to the wait group already. fd.SetDeadline(time.Now().Add(handshakeTimeout)) - // Check capacity and trust list + // Check capacity, but override for static nodes srv.lock.RLock() atcap := len(srv.peers) == srv.MaxPeers - - trust := make(map[discover.NodeID]bool) - for id, _ := range srv.trusts { - trust[id] = true + if dest != nil { + if _, ok := srv.statics[dest.ID]; ok { + atcap = false + } } srv.lock.RUnlock() - conn, err := srv.setupFunc(fd, srv.PrivateKey, srv.ourHandshake, dest, atcap, trust) + conn, err := srv.setupFunc(fd, srv.PrivateKey, srv.ourHandshake, dest, atcap) if err != nil { fd.Close() glog.V(logger.Debug).Infof("Handshake with %v failed: %v", fd.RemoteAddr(), err) @@ -535,14 +535,14 @@ func (srv *Server) addPeer(id discover.NodeID, p *Peer) (bool, DiscReason) { // checkPeer verifies whether a peer looks promising and should be allowed/kept // in the pool, or if it's of no use. func (srv *Server) checkPeer(id discover.NodeID) (bool, DiscReason) { - // First up, figure out if the peer is trusted - _, trusted := srv.trusts[id] + // First up, figure out if the peer is static + _, static := srv.statics[id] // Make sure the peer passes all required checks switch { case !srv.running: return false, DiscQuitting - case !trusted && len(srv.peers) >= srv.MaxPeers: + case !static && len(srv.peers) >= srv.MaxPeers: return false, DiscTooManyPeers case srv.peers[id] != nil: return false, DiscAlreadyConnected diff --git a/p2p/server_test.go b/p2p/server_test.go index 3e3fd6cc0..b48361235 100644 --- a/p2p/server_test.go +++ b/p2p/server_test.go @@ -22,7 +22,7 @@ func startTestServer(t *testing.T, pf newPeerHook) *Server { ListenAddr: "127.0.0.1:0", PrivateKey: newkey(), newPeerHook: pf, - setupFunc: func(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool, trust map[discover.NodeID]bool) (*conn, error) { + setupFunc: func(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool) (*conn, error) { id := randomID() rw := newRlpxFrameRW(fd, secrets{ MAC: zero16, @@ -102,7 +102,7 @@ func TestServerDial(t *testing.T) { // tell the server to connect tcpAddr := listener.Addr().(*net.TCPAddr) - srv.trustDial <- &discover.Node{IP: tcpAddr.IP, TCPPort: tcpAddr.Port} + srv.staticDial <- &discover.Node{IP: tcpAddr.IP, TCPPort: tcpAddr.Port} select { case conn := <-accepted: @@ -200,7 +200,7 @@ func TestServerDisconnectAtCap(t *testing.T) { // Run the handshakes just like a real peer would. key := newkey() hs := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)} - _, err = setupConn(conn, key, hs, srv.Self(), false, nil) + _, err = setupConn(conn, key, hs, srv.Self(), false) if i == nconns-1 { // When handling the last connection, the server should // disconnect immediately instead of running the protocol @@ -219,6 +219,7 @@ func TestServerDisconnectAtCap(t *testing.T) { } } +/* // Tests that trusted peers and can connect above max peer caps. func TestServerTrustedPeers(t *testing.T) { defer testlog(t).detach() @@ -250,7 +251,7 @@ func TestServerTrustedPeers(t *testing.T) { // Run the handshakes just like a real peer would, and wait for completion key := newkey() shake := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)} - if _, err = setupConn(conn, key, shake, server.Self(), false, nil); err != nil { + if _, err = setupConn(conn, key, shake, server.Self(), false); err != nil { t.Fatalf("conn %d: unexpected error: %v", i, err) } <-started @@ -269,7 +270,7 @@ func TestServerTrustedPeers(t *testing.T) { defer conn.Close() shake := &protoHandshake{Version: baseProtocolVersion, ID: trusted.ID} - if _, err = setupConn(conn, key, shake, server.Self(), false, nil); err != nil { + if _, err = setupConn(conn, key, shake, server.Self(), false); err != nil { t.Fatalf("trusted node: unexpected error: %v", err) } select { @@ -280,6 +281,7 @@ func TestServerTrustedPeers(t *testing.T) { t.Fatalf("trusted node timeout") } } +*/ func newkey() *ecdsa.PrivateKey { key, err := crypto.GenerateKey() From e82ddd9198f6c26f9aeba603d2e0fadd5a60bf96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Szil=C3=A1gyi?= Date: Thu, 30 Apr 2015 19:34:33 +0300 Subject: [PATCH 07/10] p2p: correct a leftover trusted -> static --- p2p/server.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/p2p/server.go b/p2p/server.go index 091bf0b2a..546b22744 100644 --- a/p2p/server.go +++ b/p2p/server.go @@ -18,9 +18,9 @@ import ( ) const ( - defaultDialTimeout = 10 * time.Second - refreshPeersInterval = 30 * time.Second - trustedPeerCheckInterval = 15 * time.Second + defaultDialTimeout = 10 * time.Second + refreshPeersInterval = 30 * time.Second + staticPeerCheckInterval = 15 * time.Second // This is the maximum number of inbound connection // that are allowed to linger between 'accepted' and @@ -345,7 +345,7 @@ func (srv *Server) listenLoop() { // staticNodesLoop is responsible for periodically checking that static // connections are actually live, and requests dialing if not. func (srv *Server) staticNodesLoop() { - tick := time.Tick(trustedPeerCheckInterval) + tick := time.Tick(staticPeerCheckInterval) for { select { case <-srv.quit: From 54db54931e10c37a6ef2cd3fca36a875b02140c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Szil=C3=A1gyi?= Date: Mon, 4 May 2015 13:08:42 +0300 Subject: [PATCH 08/10] p2p: add static node dialing test --- p2p/server.go | 33 ++++++++++------- p2p/server_test.go | 88 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+), 13 deletions(-) diff --git a/p2p/server.go b/p2p/server.go index 546b22744..3099190b6 100644 --- a/p2p/server.go +++ b/p2p/server.go @@ -100,11 +100,12 @@ type Server struct { ourHandshake *protoHandshake - lock sync.RWMutex // protects running, peers and the trust fields - running bool - peers map[discover.NodeID]*Peer - statics map[discover.NodeID]*discover.Node // Map of currently static remote nodes - staticDial chan *discover.Node // Dial request channel reserved for the static nodes + lock sync.RWMutex // protects running, peers and the trust fields + running bool + peers map[discover.NodeID]*Peer + staticNodes map[discover.NodeID]*discover.Node // Map of currently maintained static remote nodes + staticDial chan *discover.Node // Dial request channel reserved for the static nodes + staticCycle time.Duration // Overrides staticPeerCheckInterval, used for testing ntab *discover.Table listener net.Listener @@ -144,7 +145,7 @@ func (srv *Server) AddPeer(node *discover.Node) { srv.lock.Lock() defer srv.lock.Unlock() - srv.statics[node.ID] = node + srv.staticNodes[node.ID] = node } // Broadcast sends an RLP-encoded message to all connected peers. @@ -207,9 +208,9 @@ func (srv *Server) Start() (err error) { srv.peers = make(map[discover.NodeID]*Peer) // Create the current trust map, and the associated dialing channel - srv.statics = make(map[discover.NodeID]*discover.Node) + srv.staticNodes = make(map[discover.NodeID]*discover.Node) for _, node := range srv.StaticNodes { - srv.statics[node.ID] = node + srv.staticNodes[node.ID] = node } srv.staticDial = make(chan *discover.Node) @@ -345,17 +346,23 @@ func (srv *Server) listenLoop() { // staticNodesLoop is responsible for periodically checking that static // connections are actually live, and requests dialing if not. func (srv *Server) staticNodesLoop() { - tick := time.Tick(staticPeerCheckInterval) + // Create a default maintenance ticker, but override it requested + cycle := staticPeerCheckInterval + if srv.staticCycle != 0 { + cycle = srv.staticCycle + } + tick := time.NewTicker(cycle) + for { select { case <-srv.quit: return - case <-tick: + case <-tick.C: // Collect all the non-connected static nodes needed := []*discover.Node{} srv.lock.RLock() - for id, node := range srv.statics { + for id, node := range srv.staticNodes { if _, ok := srv.peers[id]; !ok { needed = append(needed, node) } @@ -473,7 +480,7 @@ func (srv *Server) startPeer(fd net.Conn, dest *discover.Node) { srv.lock.RLock() atcap := len(srv.peers) == srv.MaxPeers if dest != nil { - if _, ok := srv.statics[dest.ID]; ok { + if _, ok := srv.staticNodes[dest.ID]; ok { atcap = false } } @@ -536,7 +543,7 @@ func (srv *Server) addPeer(id discover.NodeID, p *Peer) (bool, DiscReason) { // in the pool, or if it's of no use. func (srv *Server) checkPeer(id discover.NodeID) (bool, DiscReason) { // First up, figure out if the peer is static - _, static := srv.statics[id] + _, static := srv.staticNodes[id] // Make sure the peer passes all required checks switch { diff --git a/p2p/server_test.go b/p2p/server_test.go index b48361235..606fa9386 100644 --- a/p2p/server_test.go +++ b/p2p/server_test.go @@ -219,6 +219,94 @@ func TestServerDisconnectAtCap(t *testing.T) { } } +// Tests that static peers are (re)connected, and done so even above max peers. +func TestServerStaticPeers(t *testing.T) { + defer testlog(t).detach() + + // Create a test server with limited connection slots + started := make(chan *Peer) + server := &Server{ + ListenAddr: "127.0.0.1:0", + PrivateKey: newkey(), + MaxPeers: 3, + newPeerHook: func(p *Peer) { started <- p }, + staticCycle: time.Second, + } + if err := server.Start(); err != nil { + t.Fatal(err) + } + defer server.Stop() + + // Fill up all the slots on the server + dialer := &net.Dialer{Deadline: time.Now().Add(3 * time.Second)} + for i := 0; i < server.MaxPeers; i++ { + // Establish a new connection + conn, err := dialer.Dial("tcp", server.ListenAddr) + if err != nil { + t.Fatalf("conn %d: dial error: %v", i, err) + } + defer conn.Close() + + // Run the handshakes just like a real peer would, and wait for completion + key := newkey() + shake := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)} + if _, err = setupConn(conn, key, shake, server.Self(), false); err != nil { + t.Fatalf("conn %d: unexpected error: %v", i, err) + } + <-started + } + // Open a TCP listener to accept static connections + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("failed to setup listener: %v", err) + } + defer listener.Close() + + connected := make(chan net.Conn) + go func() { + for i := 0; i < 3; i++ { + conn, err := listener.Accept() + if err == nil { + connected <- conn + } + } + }() + // Inject a static node and wait for a remote dial, then redial, then nothing + addr := listener.Addr().(*net.TCPAddr) + static := &discover.Node{ + ID: discover.PubkeyID(&newkey().PublicKey), + IP: addr.IP, + TCPPort: addr.Port, + } + server.AddPeer(static) + + select { + case conn := <-connected: + // Close the first connection, expect redial + conn.Close() + + case <-time.After(2 * server.staticCycle): + t.Fatalf("remote dial timeout") + } + + select { + case conn := <-connected: + // Keep the second connection, don't expect redial + defer conn.Close() + + case <-time.After(2 * server.staticCycle): + t.Fatalf("remote re-dial timeout") + } + + select { + case <-time.After(2 * server.staticCycle): + // Timeout as no dial occurred + + case <-connected: + t.Fatalf("connected node dialed") + } +} + /* // Tests that trusted peers and can connect above max peer caps. func TestServerTrustedPeers(t *testing.T) { From 2382da4179fa290582523f598e1be78469cdf274 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Szil=C3=A1gyi?= Date: Mon, 4 May 2015 13:11:43 +0300 Subject: [PATCH 09/10] cmd/mist: fix a stale error message --- cmd/mist/ui_lib.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/mist/ui_lib.go b/cmd/mist/ui_lib.go index a20205b03..bf5588010 100644 --- a/cmd/mist/ui_lib.go +++ b/cmd/mist/ui_lib.go @@ -105,7 +105,7 @@ func (ui *UiLib) Connect(button qml.Object) { func (ui *UiLib) ConnectToPeer(nodeURL string) { if err := ui.eth.AddPeer(nodeURL); err != nil { - guilogger.Infoln("TrustPeer error: " + err.Error()) + guilogger.Infoln("AddPeer error: " + err.Error()) } } From 4accc187d5cf6a100d6c10c0e0f35780f52871a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Szil=C3=A1gyi?= Date: Mon, 4 May 2015 13:59:51 +0300 Subject: [PATCH 10/10] eth, p2p: add trusted node list beside static list --- eth/backend.go | 24 ++++++++++++------------ p2p/handshake.go | 14 +++++++------- p2p/handshake_test.go | 4 ++-- p2p/server.go | 32 +++++++++++++++++++++----------- p2p/server_test.go | 36 +++++++++++++++++------------------- 5 files changed, 59 insertions(+), 51 deletions(-) diff --git a/eth/backend.go b/eth/backend.go index 8aecfba5b..983dd8e4f 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -41,8 +41,8 @@ var ( discover.MustParseNode("enode://487611428e6c99a11a9795a6abe7b529e81315ca6aad66e2a2fc76e3adf263faba0d35466c2f8f68d561dbefa8878d4df5f1f2ddb1fbeab7f42ffb8cd328bd4a@5.1.83.226:30303"), } - // Path within to search for the static node list - staticNodes = "static-nodes.json" + staticNodes = "static-nodes.json" // Path within to search for the static node list + trustedNodes = "trusted-nodes.json" // Path within to search for the trusted node list ) type Config struct { @@ -102,23 +102,22 @@ func (cfg *Config) parseBootNodes() []*discover.Node { return ns } -// parseStaticNodes parses a list of discovery node URLs either given literally, -// or loaded from a .json file. -func (cfg *Config) parseStaticNodes() []*discover.Node { - // Short circuit if no static node config is present - path := filepath.Join(cfg.DataDir, staticNodes) +// parseNodes parses a list of discovery node URLs loaded from a .json file. +func (cfg *Config) parseNodes(file string) []*discover.Node { + // Short circuit if no node config is present + path := filepath.Join(cfg.DataDir, file) if _, err := os.Stat(path); err != nil { return nil } - // Load the static nodes from the config file + // Load the nodes from the config file blob, err := ioutil.ReadFile(path) if err != nil { - glog.V(logger.Error).Infof("Failed to access static nodes: %v", err) + glog.V(logger.Error).Infof("Failed to access nodes: %v", err) return nil } nodelist := []string{} if err := json.Unmarshal(blob, &nodelist); err != nil { - glog.V(logger.Error).Infof("Failed to load static nodes: %v", err) + glog.V(logger.Error).Infof("Failed to load nodes: %v", err) return nil } // Interpret the list as a discovery node array @@ -129,7 +128,7 @@ func (cfg *Config) parseStaticNodes() []*discover.Node { } node, err := discover.ParseNode(url) if err != nil { - glog.V(logger.Error).Infof("Static node URL %s: %v\n", url, err) + glog.V(logger.Error).Infof("Node URL %s: %v\n", url, err) continue } nodes = append(nodes, node) @@ -288,7 +287,8 @@ func New(config *Config) (*Ethereum, error) { NAT: config.NAT, NoDial: !config.Dial, BootstrapNodes: config.parseBootNodes(), - StaticNodes: config.parseStaticNodes(), + StaticNodes: config.parseNodes(staticNodes), + TrustedNodes: config.parseNodes(trustedNodes), NodeDatabase: nodeDb, } if len(config.Port) > 0 { diff --git a/p2p/handshake.go b/p2p/handshake.go index 79395f23f..8e611cfd5 100644 --- a/p2p/handshake.go +++ b/p2p/handshake.go @@ -70,21 +70,21 @@ type protoHandshake struct { // If dial is non-nil, the connection the local node is the initiator. // If atcap is true, the connection will be disconnected with DiscTooManyPeers // after the key exchange. -func setupConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool) (*conn, error) { +func setupConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool, trusted map[discover.NodeID]bool) (*conn, error) { if dial == nil { - return setupInboundConn(fd, prv, our, atcap) + return setupInboundConn(fd, prv, our, atcap, trusted) } else { - return setupOutboundConn(fd, prv, our, dial, atcap) + return setupOutboundConn(fd, prv, our, dial, atcap, trusted) } } -func setupInboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, atcap bool) (*conn, error) { +func setupInboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, atcap bool, trusted map[discover.NodeID]bool) (*conn, error) { secrets, err := receiverEncHandshake(fd, prv, nil) if err != nil { return nil, fmt.Errorf("encryption handshake failed: %v", err) } rw := newRlpxFrameRW(fd, secrets) - if atcap { + if atcap && !trusted[secrets.RemoteID] { SendItems(rw, discMsg, DiscTooManyPeers) return nil, errors.New("we have too many peers") } @@ -99,13 +99,13 @@ func setupInboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, a return &conn{rw, rhs}, nil } -func setupOutboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool) (*conn, error) { +func setupOutboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool, trusted map[discover.NodeID]bool) (*conn, error) { secrets, err := initiatorEncHandshake(fd, prv, dial.ID, nil) if err != nil { return nil, fmt.Errorf("encryption handshake failed: %v", err) } rw := newRlpxFrameRW(fd, secrets) - if atcap { + if atcap && !trusted[secrets.RemoteID] { SendItems(rw, discMsg, DiscTooManyPeers) return nil, errors.New("we have too many peers") } diff --git a/p2p/handshake_test.go b/p2p/handshake_test.go index c22af7a9c..5e63e5c39 100644 --- a/p2p/handshake_test.go +++ b/p2p/handshake_test.go @@ -143,7 +143,7 @@ func TestSetupConn(t *testing.T) { done := make(chan struct{}) go func() { defer close(done) - conn0, err := setupConn(fd0, prv0, hs0, node1, false) + conn0, err := setupConn(fd0, prv0, hs0, node1, false, nil) if err != nil { t.Errorf("outbound side error: %v", err) return @@ -156,7 +156,7 @@ func TestSetupConn(t *testing.T) { } }() - conn1, err := setupConn(fd1, prv1, hs1, nil, false) + conn1, err := setupConn(fd1, prv1, hs1, nil, false, nil) if err != nil { t.Fatalf("inbound side error: %v", err) } diff --git a/p2p/server.go b/p2p/server.go index 3099190b6..959d61284 100644 --- a/p2p/server.go +++ b/p2p/server.go @@ -64,6 +64,10 @@ type Server struct { // maintained and re-connected on disconnects. StaticNodes []*discover.Node + // Trusted nodes are used as pre-configured connections which are always + // allowed to connect, even above the peer limit. + TrustedNodes []*discover.Node + // NodeDatabase is the path to the database containing the previously seen // live nodes in the network. NodeDatabase string @@ -100,12 +104,13 @@ type Server struct { ourHandshake *protoHandshake - lock sync.RWMutex // protects running, peers and the trust fields - running bool - peers map[discover.NodeID]*Peer - staticNodes map[discover.NodeID]*discover.Node // Map of currently maintained static remote nodes - staticDial chan *discover.Node // Dial request channel reserved for the static nodes - staticCycle time.Duration // Overrides staticPeerCheckInterval, used for testing + lock sync.RWMutex // protects running, peers and the trust fields + running bool + peers map[discover.NodeID]*Peer + staticNodes map[discover.NodeID]*discover.Node // Map of currently maintained static remote nodes + staticDial chan *discover.Node // Dial request channel reserved for the static nodes + staticCycle time.Duration // Overrides staticPeerCheckInterval, used for testing + trustedNodes map[discover.NodeID]bool // Set of currently trusted remote nodes ntab *discover.Table listener net.Listener @@ -115,7 +120,7 @@ type Server struct { peerWG sync.WaitGroup // active peer goroutines } -type setupFunc func(net.Conn, *ecdsa.PrivateKey, *protoHandshake, *discover.Node, bool) (*conn, error) +type setupFunc func(net.Conn, *ecdsa.PrivateKey, *protoHandshake, *discover.Node, bool, map[discover.NodeID]bool) (*conn, error) type newPeerHook func(*Peer) // Peers returns all connected peers. @@ -207,7 +212,11 @@ func (srv *Server) Start() (err error) { srv.quit = make(chan struct{}) srv.peers = make(map[discover.NodeID]*Peer) - // Create the current trust map, and the associated dialing channel + // Create the current trust maps, and the associated dialing channel + srv.trustedNodes = make(map[discover.NodeID]bool) + for _, node := range srv.TrustedNodes { + srv.trustedNodes[node.ID] = true + } srv.staticNodes = make(map[discover.NodeID]*discover.Node) for _, node := range srv.StaticNodes { srv.staticNodes[node.ID] = node @@ -486,7 +495,7 @@ func (srv *Server) startPeer(fd net.Conn, dest *discover.Node) { } srv.lock.RUnlock() - conn, err := srv.setupFunc(fd, srv.PrivateKey, srv.ourHandshake, dest, atcap) + conn, err := srv.setupFunc(fd, srv.PrivateKey, srv.ourHandshake, dest, atcap, srv.trustedNodes) if err != nil { fd.Close() glog.V(logger.Debug).Infof("Handshake with %v failed: %v", fd.RemoteAddr(), err) @@ -542,14 +551,15 @@ func (srv *Server) addPeer(id discover.NodeID, p *Peer) (bool, DiscReason) { // checkPeer verifies whether a peer looks promising and should be allowed/kept // in the pool, or if it's of no use. func (srv *Server) checkPeer(id discover.NodeID) (bool, DiscReason) { - // First up, figure out if the peer is static + // First up, figure out if the peer is static or trusted _, static := srv.staticNodes[id] + trusted := srv.trustedNodes[id] // Make sure the peer passes all required checks switch { case !srv.running: return false, DiscQuitting - case !static && len(srv.peers) >= srv.MaxPeers: + case !static && !trusted && len(srv.peers) >= srv.MaxPeers: return false, DiscTooManyPeers case srv.peers[id] != nil: return false, DiscAlreadyConnected diff --git a/p2p/server_test.go b/p2p/server_test.go index 606fa9386..5ee9c5ceb 100644 --- a/p2p/server_test.go +++ b/p2p/server_test.go @@ -22,7 +22,7 @@ func startTestServer(t *testing.T, pf newPeerHook) *Server { ListenAddr: "127.0.0.1:0", PrivateKey: newkey(), newPeerHook: pf, - setupFunc: func(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool) (*conn, error) { + setupFunc: func(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool, trusted map[discover.NodeID]bool) (*conn, error) { id := randomID() rw := newRlpxFrameRW(fd, secrets{ MAC: zero16, @@ -200,7 +200,7 @@ func TestServerDisconnectAtCap(t *testing.T) { // Run the handshakes just like a real peer would. key := newkey() hs := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)} - _, err = setupConn(conn, key, hs, srv.Self(), false) + _, err = setupConn(conn, key, hs, srv.Self(), false, srv.trustedNodes) if i == nconns-1 { // When handling the last connection, the server should // disconnect immediately instead of running the protocol @@ -250,7 +250,7 @@ func TestServerStaticPeers(t *testing.T) { // Run the handshakes just like a real peer would, and wait for completion key := newkey() shake := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)} - if _, err = setupConn(conn, key, shake, server.Self(), false); err != nil { + if _, err = setupConn(conn, key, shake, server.Self(), false, server.trustedNodes); err != nil { t.Fatalf("conn %d: unexpected error: %v", i, err) } <-started @@ -307,19 +307,24 @@ func TestServerStaticPeers(t *testing.T) { } } -/* // Tests that trusted peers and can connect above max peer caps. func TestServerTrustedPeers(t *testing.T) { defer testlog(t).detach() + // Create a trusted peer to accept connections from + key := newkey() + trusted := &discover.Node{ + ID: discover.PubkeyID(&key.PublicKey), + } // Create a test server with limited connection slots started := make(chan *Peer) server := &Server{ - ListenAddr: "127.0.0.1:0", - PrivateKey: newkey(), - MaxPeers: 3, - NoDial: true, - newPeerHook: func(p *Peer) { started <- p }, + ListenAddr: "127.0.0.1:0", + PrivateKey: newkey(), + MaxPeers: 3, + NoDial: true, + TrustedNodes: []*discover.Node{trusted}, + newPeerHook: func(p *Peer) { started <- p }, } if err := server.Start(); err != nil { t.Fatal(err) @@ -339,18 +344,12 @@ func TestServerTrustedPeers(t *testing.T) { // Run the handshakes just like a real peer would, and wait for completion key := newkey() shake := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)} - if _, err = setupConn(conn, key, shake, server.Self(), false); err != nil { + if _, err = setupConn(conn, key, shake, server.Self(), false, server.trustedNodes); err != nil { t.Fatalf("conn %d: unexpected error: %v", i, err) } <-started } - // Inject a trusted node and dial that (we'll connect from this end, don't need IP setup) - key := newkey() - trusted := &discover.Node{ - ID: discover.PubkeyID(&key.PublicKey), - } - server.AddPeer(trusted) - + // Dial from the trusted peer, ensure connection is accepted conn, err := dialer.Dial("tcp", server.ListenAddr) if err != nil { t.Fatalf("trusted node: dial error: %v", err) @@ -358,7 +357,7 @@ func TestServerTrustedPeers(t *testing.T) { defer conn.Close() shake := &protoHandshake{Version: baseProtocolVersion, ID: trusted.ID} - if _, err = setupConn(conn, key, shake, server.Self(), false); err != nil { + if _, err = setupConn(conn, key, shake, server.Self(), false, server.trustedNodes); err != nil { t.Fatalf("trusted node: unexpected error: %v", err) } select { @@ -369,7 +368,6 @@ func TestServerTrustedPeers(t *testing.T) { t.Fatalf("trusted node timeout") } } -*/ func newkey() *ecdsa.PrivateKey { key, err := crypto.GenerateKey()