Skip to content

Commit 4accc18

Browse files
committed
eth, p2p: add trusted node list beside static list
1 parent 2382da4 commit 4accc18

File tree

5 files changed

+59
-51
lines changed

5 files changed

+59
-51
lines changed

eth/backend.go

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,8 @@ var (
4141
discover.MustParseNode("enode://487611428e6c99a11a9795a6abe7b529e81315ca6aad66e2a2fc76e3adf263faba0d35466c2f8f68d561dbefa8878d4df5f1f2ddb1fbeab7f42ffb8cd328bd4a@5.1.83.226:30303"),
4242
}
4343

44-
// Path within <datadir> to search for the static node list
45-
staticNodes = "static-nodes.json"
44+
staticNodes = "static-nodes.json" // Path within <datadir> to search for the static node list
45+
trustedNodes = "trusted-nodes.json" // Path within <datadir> to search for the trusted node list
4646
)
4747

4848
type Config struct {
@@ -102,23 +102,22 @@ func (cfg *Config) parseBootNodes() []*discover.Node {
102102
return ns
103103
}
104104

105-
// parseStaticNodes parses a list of discovery node URLs either given literally,
106-
// or loaded from a .json file.
107-
func (cfg *Config) parseStaticNodes() []*discover.Node {
108-
// Short circuit if no static node config is present
109-
path := filepath.Join(cfg.DataDir, staticNodes)
105+
// parseNodes parses a list of discovery node URLs loaded from a .json file.
106+
func (cfg *Config) parseNodes(file string) []*discover.Node {
107+
// Short circuit if no node config is present
108+
path := filepath.Join(cfg.DataDir, file)
110109
if _, err := os.Stat(path); err != nil {
111110
return nil
112111
}
113-
// Load the static nodes from the config file
112+
// Load the nodes from the config file
114113
blob, err := ioutil.ReadFile(path)
115114
if err != nil {
116-
glog.V(logger.Error).Infof("Failed to access static nodes: %v", err)
115+
glog.V(logger.Error).Infof("Failed to access nodes: %v", err)
117116
return nil
118117
}
119118
nodelist := []string{}
120119
if err := json.Unmarshal(blob, &nodelist); err != nil {
121-
glog.V(logger.Error).Infof("Failed to load static nodes: %v", err)
120+
glog.V(logger.Error).Infof("Failed to load nodes: %v", err)
122121
return nil
123122
}
124123
// Interpret the list as a discovery node array
@@ -129,7 +128,7 @@ func (cfg *Config) parseStaticNodes() []*discover.Node {
129128
}
130129
node, err := discover.ParseNode(url)
131130
if err != nil {
132-
glog.V(logger.Error).Infof("Static node URL %s: %v\n", url, err)
131+
glog.V(logger.Error).Infof("Node URL %s: %v\n", url, err)
133132
continue
134133
}
135134
nodes = append(nodes, node)
@@ -288,7 +287,8 @@ func New(config *Config) (*Ethereum, error) {
288287
NAT: config.NAT,
289288
NoDial: !config.Dial,
290289
BootstrapNodes: config.parseBootNodes(),
291-
StaticNodes: config.parseStaticNodes(),
290+
StaticNodes: config.parseNodes(staticNodes),
291+
TrustedNodes: config.parseNodes(trustedNodes),
292292
NodeDatabase: nodeDb,
293293
}
294294
if len(config.Port) > 0 {

p2p/handshake.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -70,21 +70,21 @@ type protoHandshake struct {
7070
// If dial is non-nil, the connection the local node is the initiator.
7171
// If atcap is true, the connection will be disconnected with DiscTooManyPeers
7272
// after the key exchange.
73-
func setupConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool) (*conn, error) {
73+
func setupConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool, trusted map[discover.NodeID]bool) (*conn, error) {
7474
if dial == nil {
75-
return setupInboundConn(fd, prv, our, atcap)
75+
return setupInboundConn(fd, prv, our, atcap, trusted)
7676
} else {
77-
return setupOutboundConn(fd, prv, our, dial, atcap)
77+
return setupOutboundConn(fd, prv, our, dial, atcap, trusted)
7878
}
7979
}
8080

81-
func setupInboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, atcap bool) (*conn, error) {
81+
func setupInboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, atcap bool, trusted map[discover.NodeID]bool) (*conn, error) {
8282
secrets, err := receiverEncHandshake(fd, prv, nil)
8383
if err != nil {
8484
return nil, fmt.Errorf("encryption handshake failed: %v", err)
8585
}
8686
rw := newRlpxFrameRW(fd, secrets)
87-
if atcap {
87+
if atcap && !trusted[secrets.RemoteID] {
8888
SendItems(rw, discMsg, DiscTooManyPeers)
8989
return nil, errors.New("we have too many peers")
9090
}
@@ -99,13 +99,13 @@ func setupInboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, a
9999
return &conn{rw, rhs}, nil
100100
}
101101

102-
func setupOutboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool) (*conn, error) {
102+
func setupOutboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool, trusted map[discover.NodeID]bool) (*conn, error) {
103103
secrets, err := initiatorEncHandshake(fd, prv, dial.ID, nil)
104104
if err != nil {
105105
return nil, fmt.Errorf("encryption handshake failed: %v", err)
106106
}
107107
rw := newRlpxFrameRW(fd, secrets)
108-
if atcap {
108+
if atcap && !trusted[secrets.RemoteID] {
109109
SendItems(rw, discMsg, DiscTooManyPeers)
110110
return nil, errors.New("we have too many peers")
111111
}

p2p/handshake_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ func TestSetupConn(t *testing.T) {
143143
done := make(chan struct{})
144144
go func() {
145145
defer close(done)
146-
conn0, err := setupConn(fd0, prv0, hs0, node1, false)
146+
conn0, err := setupConn(fd0, prv0, hs0, node1, false, nil)
147147
if err != nil {
148148
t.Errorf("outbound side error: %v", err)
149149
return
@@ -156,7 +156,7 @@ func TestSetupConn(t *testing.T) {
156156
}
157157
}()
158158

159-
conn1, err := setupConn(fd1, prv1, hs1, nil, false)
159+
conn1, err := setupConn(fd1, prv1, hs1, nil, false, nil)
160160
if err != nil {
161161
t.Fatalf("inbound side error: %v", err)
162162
}

p2p/server.go

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,10 @@ type Server struct {
6464
// maintained and re-connected on disconnects.
6565
StaticNodes []*discover.Node
6666

67+
// Trusted nodes are used as pre-configured connections which are always
68+
// allowed to connect, even above the peer limit.
69+
TrustedNodes []*discover.Node
70+
6771
// NodeDatabase is the path to the database containing the previously seen
6872
// live nodes in the network.
6973
NodeDatabase string
@@ -100,12 +104,13 @@ type Server struct {
100104

101105
ourHandshake *protoHandshake
102106

103-
lock sync.RWMutex // protects running, peers and the trust fields
104-
running bool
105-
peers map[discover.NodeID]*Peer
106-
staticNodes map[discover.NodeID]*discover.Node // Map of currently maintained static remote nodes
107-
staticDial chan *discover.Node // Dial request channel reserved for the static nodes
108-
staticCycle time.Duration // Overrides staticPeerCheckInterval, used for testing
107+
lock sync.RWMutex // protects running, peers and the trust fields
108+
running bool
109+
peers map[discover.NodeID]*Peer
110+
staticNodes map[discover.NodeID]*discover.Node // Map of currently maintained static remote nodes
111+
staticDial chan *discover.Node // Dial request channel reserved for the static nodes
112+
staticCycle time.Duration // Overrides staticPeerCheckInterval, used for testing
113+
trustedNodes map[discover.NodeID]bool // Set of currently trusted remote nodes
109114

110115
ntab *discover.Table
111116
listener net.Listener
@@ -115,7 +120,7 @@ type Server struct {
115120
peerWG sync.WaitGroup // active peer goroutines
116121
}
117122

118-
type setupFunc func(net.Conn, *ecdsa.PrivateKey, *protoHandshake, *discover.Node, bool) (*conn, error)
123+
type setupFunc func(net.Conn, *ecdsa.PrivateKey, *protoHandshake, *discover.Node, bool, map[discover.NodeID]bool) (*conn, error)
119124
type newPeerHook func(*Peer)
120125

121126
// Peers returns all connected peers.
@@ -207,7 +212,11 @@ func (srv *Server) Start() (err error) {
207212
srv.quit = make(chan struct{})
208213
srv.peers = make(map[discover.NodeID]*Peer)
209214

210-
// Create the current trust map, and the associated dialing channel
215+
// Create the current trust maps, and the associated dialing channel
216+
srv.trustedNodes = make(map[discover.NodeID]bool)
217+
for _, node := range srv.TrustedNodes {
218+
srv.trustedNodes[node.ID] = true
219+
}
211220
srv.staticNodes = make(map[discover.NodeID]*discover.Node)
212221
for _, node := range srv.StaticNodes {
213222
srv.staticNodes[node.ID] = node
@@ -486,7 +495,7 @@ func (srv *Server) startPeer(fd net.Conn, dest *discover.Node) {
486495
}
487496
srv.lock.RUnlock()
488497

489-
conn, err := srv.setupFunc(fd, srv.PrivateKey, srv.ourHandshake, dest, atcap)
498+
conn, err := srv.setupFunc(fd, srv.PrivateKey, srv.ourHandshake, dest, atcap, srv.trustedNodes)
490499
if err != nil {
491500
fd.Close()
492501
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) {
542551
// checkPeer verifies whether a peer looks promising and should be allowed/kept
543552
// in the pool, or if it's of no use.
544553
func (srv *Server) checkPeer(id discover.NodeID) (bool, DiscReason) {
545-
// First up, figure out if the peer is static
554+
// First up, figure out if the peer is static or trusted
546555
_, static := srv.staticNodes[id]
556+
trusted := srv.trustedNodes[id]
547557

548558
// Make sure the peer passes all required checks
549559
switch {
550560
case !srv.running:
551561
return false, DiscQuitting
552-
case !static && len(srv.peers) >= srv.MaxPeers:
562+
case !static && !trusted && len(srv.peers) >= srv.MaxPeers:
553563
return false, DiscTooManyPeers
554564
case srv.peers[id] != nil:
555565
return false, DiscAlreadyConnected

p2p/server_test.go

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ func startTestServer(t *testing.T, pf newPeerHook) *Server {
2222
ListenAddr: "127.0.0.1:0",
2323
PrivateKey: newkey(),
2424
newPeerHook: pf,
25-
setupFunc: func(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool) (*conn, error) {
25+
setupFunc: func(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool, trusted map[discover.NodeID]bool) (*conn, error) {
2626
id := randomID()
2727
rw := newRlpxFrameRW(fd, secrets{
2828
MAC: zero16,
@@ -200,7 +200,7 @@ func TestServerDisconnectAtCap(t *testing.T) {
200200
// Run the handshakes just like a real peer would.
201201
key := newkey()
202202
hs := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)}
203-
_, err = setupConn(conn, key, hs, srv.Self(), false)
203+
_, err = setupConn(conn, key, hs, srv.Self(), false, srv.trustedNodes)
204204
if i == nconns-1 {
205205
// When handling the last connection, the server should
206206
// disconnect immediately instead of running the protocol
@@ -250,7 +250,7 @@ func TestServerStaticPeers(t *testing.T) {
250250
// Run the handshakes just like a real peer would, and wait for completion
251251
key := newkey()
252252
shake := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)}
253-
if _, err = setupConn(conn, key, shake, server.Self(), false); err != nil {
253+
if _, err = setupConn(conn, key, shake, server.Self(), false, server.trustedNodes); err != nil {
254254
t.Fatalf("conn %d: unexpected error: %v", i, err)
255255
}
256256
<-started
@@ -307,19 +307,24 @@ func TestServerStaticPeers(t *testing.T) {
307307
}
308308
}
309309

310-
/*
311310
// Tests that trusted peers and can connect above max peer caps.
312311
func TestServerTrustedPeers(t *testing.T) {
313312
defer testlog(t).detach()
314313

314+
// Create a trusted peer to accept connections from
315+
key := newkey()
316+
trusted := &discover.Node{
317+
ID: discover.PubkeyID(&key.PublicKey),
318+
}
315319
// Create a test server with limited connection slots
316320
started := make(chan *Peer)
317321
server := &Server{
318-
ListenAddr: "127.0.0.1:0",
319-
PrivateKey: newkey(),
320-
MaxPeers: 3,
321-
NoDial: true,
322-
newPeerHook: func(p *Peer) { started <- p },
322+
ListenAddr: "127.0.0.1:0",
323+
PrivateKey: newkey(),
324+
MaxPeers: 3,
325+
NoDial: true,
326+
TrustedNodes: []*discover.Node{trusted},
327+
newPeerHook: func(p *Peer) { started <- p },
323328
}
324329
if err := server.Start(); err != nil {
325330
t.Fatal(err)
@@ -339,26 +344,20 @@ func TestServerTrustedPeers(t *testing.T) {
339344
// Run the handshakes just like a real peer would, and wait for completion
340345
key := newkey()
341346
shake := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)}
342-
if _, err = setupConn(conn, key, shake, server.Self(), false); err != nil {
347+
if _, err = setupConn(conn, key, shake, server.Self(), false, server.trustedNodes); err != nil {
343348
t.Fatalf("conn %d: unexpected error: %v", i, err)
344349
}
345350
<-started
346351
}
347-
// Inject a trusted node and dial that (we'll connect from this end, don't need IP setup)
348-
key := newkey()
349-
trusted := &discover.Node{
350-
ID: discover.PubkeyID(&key.PublicKey),
351-
}
352-
server.AddPeer(trusted)
353-
352+
// Dial from the trusted peer, ensure connection is accepted
354353
conn, err := dialer.Dial("tcp", server.ListenAddr)
355354
if err != nil {
356355
t.Fatalf("trusted node: dial error: %v", err)
357356
}
358357
defer conn.Close()
359358

360359
shake := &protoHandshake{Version: baseProtocolVersion, ID: trusted.ID}
361-
if _, err = setupConn(conn, key, shake, server.Self(), false); err != nil {
360+
if _, err = setupConn(conn, key, shake, server.Self(), false, server.trustedNodes); err != nil {
362361
t.Fatalf("trusted node: unexpected error: %v", err)
363362
}
364363
select {
@@ -369,7 +368,6 @@ func TestServerTrustedPeers(t *testing.T) {
369368
t.Fatalf("trusted node timeout")
370369
}
371370
}
372-
*/
373371

374372
func newkey() *ecdsa.PrivateKey {
375373
key, err := crypto.GenerateKey()

0 commit comments

Comments
 (0)