eth, p2p: add trusted node list beside static list

This commit is contained in:
Péter Szilágyi 2015-05-04 13:59:51 +03:00
parent 2382da4179
commit 4accc187d5
5 changed files with 59 additions and 51 deletions

View File

@ -41,8 +41,8 @@ var (
discover.MustParseNode("enode://487611428e6c99a11a9795a6abe7b529e81315ca6aad66e2a2fc76e3adf263faba0d35466c2f8f68d561dbefa8878d4df5f1f2ddb1fbeab7f42ffb8cd328bd4a@5.1.83.226:30303"), discover.MustParseNode("enode://487611428e6c99a11a9795a6abe7b529e81315ca6aad66e2a2fc76e3adf263faba0d35466c2f8f68d561dbefa8878d4df5f1f2ddb1fbeab7f42ffb8cd328bd4a@5.1.83.226:30303"),
} }
// Path within <datadir> to search for the static node list staticNodes = "static-nodes.json" // Path within <datadir> to search for the static node list
staticNodes = "static-nodes.json" trustedNodes = "trusted-nodes.json" // Path within <datadir> to search for the trusted node list
) )
type Config struct { type Config struct {
@ -102,23 +102,22 @@ func (cfg *Config) parseBootNodes() []*discover.Node {
return ns return ns
} }
// parseStaticNodes parses a list of discovery node URLs either given literally, // parseNodes parses a list of discovery node URLs loaded from a .json file.
// or loaded from a .json file. func (cfg *Config) parseNodes(file string) []*discover.Node {
func (cfg *Config) parseStaticNodes() []*discover.Node { // Short circuit if no node config is present
// Short circuit if no static node config is present path := filepath.Join(cfg.DataDir, file)
path := filepath.Join(cfg.DataDir, staticNodes)
if _, err := os.Stat(path); err != nil { if _, err := os.Stat(path); err != nil {
return nil return nil
} }
// Load the static nodes from the config file // Load the nodes from the config file
blob, err := ioutil.ReadFile(path) blob, err := ioutil.ReadFile(path)
if err != nil { 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 return nil
} }
nodelist := []string{} nodelist := []string{}
if err := json.Unmarshal(blob, &nodelist); err != nil { 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 return nil
} }
// Interpret the list as a discovery node array // Interpret the list as a discovery node array
@ -129,7 +128,7 @@ func (cfg *Config) parseStaticNodes() []*discover.Node {
} }
node, err := discover.ParseNode(url) node, err := discover.ParseNode(url)
if err != nil { 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 continue
} }
nodes = append(nodes, node) nodes = append(nodes, node)
@ -288,7 +287,8 @@ func New(config *Config) (*Ethereum, error) {
NAT: config.NAT, NAT: config.NAT,
NoDial: !config.Dial, NoDial: !config.Dial,
BootstrapNodes: config.parseBootNodes(), BootstrapNodes: config.parseBootNodes(),
StaticNodes: config.parseStaticNodes(), StaticNodes: config.parseNodes(staticNodes),
TrustedNodes: config.parseNodes(trustedNodes),
NodeDatabase: nodeDb, NodeDatabase: nodeDb,
} }
if len(config.Port) > 0 { if len(config.Port) > 0 {

View File

@ -70,21 +70,21 @@ type protoHandshake struct {
// If dial is non-nil, the connection the local node is the initiator. // If dial is non-nil, the connection the local node is the initiator.
// If atcap is true, the connection will be disconnected with DiscTooManyPeers // If atcap is true, the connection will be disconnected with DiscTooManyPeers
// after the key exchange. // 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 { if dial == nil {
return setupInboundConn(fd, prv, our, atcap) return setupInboundConn(fd, prv, our, atcap, trusted)
} else { } 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) secrets, err := receiverEncHandshake(fd, prv, nil)
if err != nil { if err != nil {
return nil, fmt.Errorf("encryption handshake failed: %v", err) return nil, fmt.Errorf("encryption handshake failed: %v", err)
} }
rw := newRlpxFrameRW(fd, secrets) rw := newRlpxFrameRW(fd, secrets)
if atcap { if atcap && !trusted[secrets.RemoteID] {
SendItems(rw, discMsg, DiscTooManyPeers) SendItems(rw, discMsg, DiscTooManyPeers)
return nil, errors.New("we have too many peers") 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 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) secrets, err := initiatorEncHandshake(fd, prv, dial.ID, nil)
if err != nil { if err != nil {
return nil, fmt.Errorf("encryption handshake failed: %v", err) return nil, fmt.Errorf("encryption handshake failed: %v", err)
} }
rw := newRlpxFrameRW(fd, secrets) rw := newRlpxFrameRW(fd, secrets)
if atcap { if atcap && !trusted[secrets.RemoteID] {
SendItems(rw, discMsg, DiscTooManyPeers) SendItems(rw, discMsg, DiscTooManyPeers)
return nil, errors.New("we have too many peers") return nil, errors.New("we have too many peers")
} }

View File

@ -143,7 +143,7 @@ func TestSetupConn(t *testing.T) {
done := make(chan struct{}) done := make(chan struct{})
go func() { go func() {
defer close(done) defer close(done)
conn0, err := setupConn(fd0, prv0, hs0, node1, false) conn0, err := setupConn(fd0, prv0, hs0, node1, false, nil)
if err != nil { if err != nil {
t.Errorf("outbound side error: %v", err) t.Errorf("outbound side error: %v", err)
return 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 { if err != nil {
t.Fatalf("inbound side error: %v", err) t.Fatalf("inbound side error: %v", err)
} }

View File

@ -64,6 +64,10 @@ type Server struct {
// maintained and re-connected on disconnects. // maintained and re-connected on disconnects.
StaticNodes []*discover.Node 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 // NodeDatabase is the path to the database containing the previously seen
// live nodes in the network. // live nodes in the network.
NodeDatabase string NodeDatabase string
@ -106,6 +110,7 @@ type Server struct {
staticNodes map[discover.NodeID]*discover.Node // Map of currently maintained static remote nodes 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 staticDial chan *discover.Node // Dial request channel reserved for the static nodes
staticCycle time.Duration // Overrides staticPeerCheckInterval, used for testing staticCycle time.Duration // Overrides staticPeerCheckInterval, used for testing
trustedNodes map[discover.NodeID]bool // Set of currently trusted remote nodes
ntab *discover.Table ntab *discover.Table
listener net.Listener listener net.Listener
@ -115,7 +120,7 @@ type Server struct {
peerWG sync.WaitGroup // active peer goroutines 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) type newPeerHook func(*Peer)
// Peers returns all connected peers. // Peers returns all connected peers.
@ -207,7 +212,11 @@ func (srv *Server) Start() (err error) {
srv.quit = make(chan struct{}) srv.quit = make(chan struct{})
srv.peers = make(map[discover.NodeID]*Peer) 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) srv.staticNodes = make(map[discover.NodeID]*discover.Node)
for _, node := range srv.StaticNodes { for _, node := range srv.StaticNodes {
srv.staticNodes[node.ID] = node srv.staticNodes[node.ID] = node
@ -486,7 +495,7 @@ func (srv *Server) startPeer(fd net.Conn, dest *discover.Node) {
} }
srv.lock.RUnlock() 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 { if err != nil {
fd.Close() fd.Close()
glog.V(logger.Debug).Infof("Handshake with %v failed: %v", fd.RemoteAddr(), err) 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 // checkPeer verifies whether a peer looks promising and should be allowed/kept
// in the pool, or if it's of no use. // in the pool, or if it's of no use.
func (srv *Server) checkPeer(id discover.NodeID) (bool, DiscReason) { 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] _, static := srv.staticNodes[id]
trusted := srv.trustedNodes[id]
// Make sure the peer passes all required checks // Make sure the peer passes all required checks
switch { switch {
case !srv.running: case !srv.running:
return false, DiscQuitting return false, DiscQuitting
case !static && len(srv.peers) >= srv.MaxPeers: case !static && !trusted && len(srv.peers) >= srv.MaxPeers:
return false, DiscTooManyPeers return false, DiscTooManyPeers
case srv.peers[id] != nil: case srv.peers[id] != nil:
return false, DiscAlreadyConnected return false, DiscAlreadyConnected

View File

@ -22,7 +22,7 @@ func startTestServer(t *testing.T, pf newPeerHook) *Server {
ListenAddr: "127.0.0.1:0", ListenAddr: "127.0.0.1:0",
PrivateKey: newkey(), PrivateKey: newkey(),
newPeerHook: pf, 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() id := randomID()
rw := newRlpxFrameRW(fd, secrets{ rw := newRlpxFrameRW(fd, secrets{
MAC: zero16, MAC: zero16,
@ -200,7 +200,7 @@ func TestServerDisconnectAtCap(t *testing.T) {
// Run the handshakes just like a real peer would. // Run the handshakes just like a real peer would.
key := newkey() key := newkey()
hs := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)} 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 { if i == nconns-1 {
// When handling the last connection, the server should // When handling the last connection, the server should
// disconnect immediately instead of running the protocol // 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 // Run the handshakes just like a real peer would, and wait for completion
key := newkey() key := newkey()
shake := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)} 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) t.Fatalf("conn %d: unexpected error: %v", i, err)
} }
<-started <-started
@ -307,11 +307,15 @@ func TestServerStaticPeers(t *testing.T) {
} }
} }
/*
// Tests that trusted peers and can connect above max peer caps. // Tests that trusted peers and can connect above max peer caps.
func TestServerTrustedPeers(t *testing.T) { func TestServerTrustedPeers(t *testing.T) {
defer testlog(t).detach() 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 // Create a test server with limited connection slots
started := make(chan *Peer) started := make(chan *Peer)
server := &Server{ server := &Server{
@ -319,6 +323,7 @@ func TestServerTrustedPeers(t *testing.T) {
PrivateKey: newkey(), PrivateKey: newkey(),
MaxPeers: 3, MaxPeers: 3,
NoDial: true, NoDial: true,
TrustedNodes: []*discover.Node{trusted},
newPeerHook: func(p *Peer) { started <- p }, newPeerHook: func(p *Peer) { started <- p },
} }
if err := server.Start(); err != nil { if err := server.Start(); err != nil {
@ -339,18 +344,12 @@ func TestServerTrustedPeers(t *testing.T) {
// Run the handshakes just like a real peer would, and wait for completion // Run the handshakes just like a real peer would, and wait for completion
key := newkey() key := newkey()
shake := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)} 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) t.Fatalf("conn %d: unexpected error: %v", i, err)
} }
<-started <-started
} }
// Inject a trusted node and dial that (we'll connect from this end, don't need IP setup) // Dial from the trusted peer, ensure connection is accepted
key := newkey()
trusted := &discover.Node{
ID: discover.PubkeyID(&key.PublicKey),
}
server.AddPeer(trusted)
conn, err := dialer.Dial("tcp", server.ListenAddr) conn, err := dialer.Dial("tcp", server.ListenAddr)
if err != nil { if err != nil {
t.Fatalf("trusted node: dial error: %v", err) t.Fatalf("trusted node: dial error: %v", err)
@ -358,7 +357,7 @@ func TestServerTrustedPeers(t *testing.T) {
defer conn.Close() defer conn.Close()
shake := &protoHandshake{Version: baseProtocolVersion, ID: trusted.ID} 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) t.Fatalf("trusted node: unexpected error: %v", err)
} }
select { select {
@ -369,7 +368,6 @@ func TestServerTrustedPeers(t *testing.T) {
t.Fatalf("trusted node timeout") t.Fatalf("trusted node timeout")
} }
} }
*/
func newkey() *ecdsa.PrivateKey { func newkey() *ecdsa.PrivateKey {
key, err := crypto.GenerateKey() key, err := crypto.GenerateKey()