mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-07-23 05:06:43 +00:00
Merge 19f2347472 into 3fef601903
This commit is contained in:
commit
237507a7bf
11 changed files with 372 additions and 45 deletions
|
|
@ -25,7 +25,7 @@ func (js *jsre) adminBindings() {
|
||||||
js.re.Set("admin", struct{}{})
|
js.re.Set("admin", struct{}{})
|
||||||
t, _ := js.re.Get("admin")
|
t, _ := js.re.Get("admin")
|
||||||
admin := t.Object()
|
admin := t.Object()
|
||||||
admin.Set("suggestPeer", js.suggestPeer)
|
admin.Set("trustPeer", js.trustPeer)
|
||||||
admin.Set("startRPC", js.startRPC)
|
admin.Set("startRPC", js.startRPC)
|
||||||
admin.Set("stopRPC", js.stopRPC)
|
admin.Set("stopRPC", js.stopRPC)
|
||||||
admin.Set("nodeInfo", js.nodeInfo)
|
admin.Set("nodeInfo", js.nodeInfo)
|
||||||
|
|
@ -243,13 +243,13 @@ func (js *jsre) stopRPC(call otto.FunctionCall) otto.Value {
|
||||||
return otto.FalseValue()
|
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()
|
nodeURL, err := call.Argument(0).ToString()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
return otto.FalseValue()
|
return otto.FalseValue()
|
||||||
}
|
}
|
||||||
err = js.ethereum.SuggestPeer(nodeURL)
|
err = js.ethereum.TrustPeer(nodeURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
return otto.FalseValue()
|
return otto.FalseValue()
|
||||||
|
|
|
||||||
|
|
@ -232,7 +232,7 @@ JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Conso
|
||||||
utils.IdentityFlag,
|
utils.IdentityFlag,
|
||||||
utils.UnlockedAccountFlag,
|
utils.UnlockedAccountFlag,
|
||||||
utils.PasswordFileFlag,
|
utils.PasswordFileFlag,
|
||||||
utils.BootnodesFlag,
|
utils.BootNodesFlag,
|
||||||
utils.DataDirFlag,
|
utils.DataDirFlag,
|
||||||
utils.BlockchainVersionFlag,
|
utils.BlockchainVersionFlag,
|
||||||
utils.JSpathFlag,
|
utils.JSpathFlag,
|
||||||
|
|
|
||||||
|
|
@ -69,7 +69,7 @@ func init() {
|
||||||
assetPathFlag,
|
assetPathFlag,
|
||||||
rpcCorsFlag,
|
rpcCorsFlag,
|
||||||
|
|
||||||
utils.BootnodesFlag,
|
utils.BootNodesFlag,
|
||||||
utils.DataDirFlag,
|
utils.DataDirFlag,
|
||||||
utils.ListenPortFlag,
|
utils.ListenPortFlag,
|
||||||
utils.LogFileFlag,
|
utils.LogFileFlag,
|
||||||
|
|
|
||||||
|
|
@ -104,8 +104,8 @@ func (ui *UiLib) Connect(button qml.Object) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ui *UiLib) ConnectToPeer(nodeURL string) {
|
func (ui *UiLib) ConnectToPeer(nodeURL string) {
|
||||||
if err := ui.eth.SuggestPeer(nodeURL); err != nil {
|
if err := ui.eth.TrustPeer(nodeURL); err != nil {
|
||||||
guilogger.Infoln("SuggestPeer error: " + err.Error())
|
guilogger.Infoln("TrustPeer error: " + err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -202,7 +202,7 @@ var (
|
||||||
Usage: "Network listening port",
|
Usage: "Network listening port",
|
||||||
Value: 30303,
|
Value: 30303,
|
||||||
}
|
}
|
||||||
BootnodesFlag = cli.StringFlag{
|
BootNodesFlag = cli.StringFlag{
|
||||||
Name: "bootnodes",
|
Name: "bootnodes",
|
||||||
Usage: "Space-separated enode URLs for p2p discovery bootstrap",
|
Usage: "Space-separated enode URLs for p2p discovery bootstrap",
|
||||||
Value: "",
|
Value: "",
|
||||||
|
|
@ -292,7 +292,7 @@ func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config {
|
||||||
NodeKey: GetNodeKey(ctx),
|
NodeKey: GetNodeKey(ctx),
|
||||||
Shh: ctx.GlobalBool(WhisperEnabledFlag.Name),
|
Shh: ctx.GlobalBool(WhisperEnabledFlag.Name),
|
||||||
Dial: true,
|
Dial: true,
|
||||||
BootNodes: ctx.GlobalString(BootnodesFlag.Name),
|
BootNodes: ctx.GlobalString(BootNodesFlag.Name),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,12 @@ package eth
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/ecdsa"
|
"crypto/ecdsa"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io/ioutil"
|
||||||
|
"os"
|
||||||
"path"
|
"path"
|
||||||
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
|
@ -36,6 +40,9 @@ var (
|
||||||
// ETH/DEV cpp-ethereum (poc-9.ethdev.com)
|
// ETH/DEV cpp-ethereum (poc-9.ethdev.com)
|
||||||
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 trusted node list
|
||||||
|
trustedNodes = "trusted-nodes.json"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
|
|
@ -56,8 +63,7 @@ type Config struct {
|
||||||
MaxPeers int
|
MaxPeers int
|
||||||
Port string
|
Port string
|
||||||
|
|
||||||
// This should be a space-separated list of
|
// Space-separated list of discovery node URLs
|
||||||
// discovery node URLs.
|
|
||||||
BootNodes string
|
BootNodes string
|
||||||
|
|
||||||
// This key is used to identify the node on the network.
|
// This key is used to identify the node on the network.
|
||||||
|
|
@ -96,6 +102,43 @@ func (cfg *Config) parseBootNodes() []*discover.Node {
|
||||||
return ns
|
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 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
|
||||||
|
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 nodelist {
|
||||||
|
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) {
|
func (cfg *Config) nodeKey() (*ecdsa.PrivateKey, error) {
|
||||||
// use explicit key from command line args if set
|
// use explicit key from command line args if set
|
||||||
if cfg.NodeKey != nil {
|
if cfg.NodeKey != nil {
|
||||||
|
|
@ -247,6 +290,7 @@ func New(config *Config) (*Ethereum, error) {
|
||||||
NAT: config.NAT,
|
NAT: config.NAT,
|
||||||
NoDial: !config.Dial,
|
NoDial: !config.Dial,
|
||||||
BootstrapNodes: config.parseBootNodes(),
|
BootstrapNodes: config.parseBootNodes(),
|
||||||
|
TrustedNodes: config.parseTrustedNodes(),
|
||||||
NodeDatabase: nodeDb,
|
NodeDatabase: nodeDb,
|
||||||
}
|
}
|
||||||
if len(config.Port) > 0 {
|
if len(config.Port) > 0 {
|
||||||
|
|
@ -442,12 +486,13 @@ func (s *Ethereum) StartForTest() {
|
||||||
s.txPool.Start()
|
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)
|
n, err := discover.ParseNode(nodeURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("invalid node URL: %v", err)
|
return fmt.Errorf("invalid node URL: %v", err)
|
||||||
}
|
}
|
||||||
self.net.SuggestPeer(n)
|
self.net.TrustPeer(n)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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, trust map[discover.NodeID]bool) (*conn, error) {
|
||||||
if dial == nil {
|
if dial == nil {
|
||||||
return setupInboundConn(fd, prv, our, atcap)
|
return setupInboundConn(fd, prv, our, atcap, trust)
|
||||||
} else {
|
} 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)
|
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 && !trust[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, trust 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 && !trust[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")
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -73,6 +73,7 @@ const (
|
||||||
DiscSelf
|
DiscSelf
|
||||||
DiscReadTimeout
|
DiscReadTimeout
|
||||||
DiscSubprotocolError
|
DiscSubprotocolError
|
||||||
|
DiscThrottled
|
||||||
)
|
)
|
||||||
|
|
||||||
var discReasonToString = [...]string{
|
var discReasonToString = [...]string{
|
||||||
|
|
@ -89,6 +90,7 @@ var discReasonToString = [...]string{
|
||||||
DiscSelf: "Connected to self",
|
DiscSelf: "Connected to self",
|
||||||
DiscReadTimeout: "Read timeout",
|
DiscReadTimeout: "Read timeout",
|
||||||
DiscSubprotocolError: "Subprotocol error",
|
DiscSubprotocolError: "Subprotocol error",
|
||||||
|
DiscThrottled: "Node throttled",
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d DiscReason) String() string {
|
func (d DiscReason) String() string {
|
||||||
|
|
|
||||||
146
p2p/server.go
146
p2p/server.go
|
|
@ -18,8 +18,10 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
defaultDialTimeout = 10 * time.Second
|
defaultDialTimeout = 10 * time.Second
|
||||||
refreshPeersInterval = 30 * time.Second
|
refreshPeersInterval = 30 * time.Second
|
||||||
|
trustedPeerCheckInterval = 15 * time.Second
|
||||||
|
dialFailureCooldown = 30 * time.Second
|
||||||
|
|
||||||
// This is the maximum number of inbound connection
|
// This is the maximum number of inbound connection
|
||||||
// that are allowed to linger between 'accepted' and
|
// that are allowed to linger between 'accepted' and
|
||||||
|
|
@ -59,6 +61,10 @@ type Server struct {
|
||||||
// with the rest of the network.
|
// with the rest of the network.
|
||||||
BootstrapNodes []*discover.Node
|
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
|
// 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
|
||||||
|
|
@ -95,20 +101,24 @@ type Server struct {
|
||||||
|
|
||||||
ourHandshake *protoHandshake
|
ourHandshake *protoHandshake
|
||||||
|
|
||||||
lock sync.RWMutex // protects running and peers
|
lock sync.RWMutex // protects running and peers
|
||||||
running bool
|
|
||||||
peers map[discover.NodeID]*Peer
|
running bool
|
||||||
|
peers map[discover.NodeID]*Peer // Currently active peer pool
|
||||||
|
throttle map[discover.NodeID]bool // List of recently failed connections
|
||||||
|
|
||||||
|
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
|
ntab *discover.Table
|
||||||
listener net.Listener
|
listener net.Listener
|
||||||
|
|
||||||
quit chan struct{}
|
quit chan struct{}
|
||||||
loopWG sync.WaitGroup // {dial,listen,nat}Loop
|
loopWG sync.WaitGroup // {dial,listen,nat}Loop
|
||||||
peerWG sync.WaitGroup // active peer goroutines
|
peerWG sync.WaitGroup // active peer goroutines
|
||||||
peerConnect chan *discover.Node
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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.
|
||||||
|
|
@ -131,10 +141,12 @@ func (srv *Server) PeerCount() int {
|
||||||
return n
|
return n
|
||||||
}
|
}
|
||||||
|
|
||||||
// SuggestPeer creates a connection to the given Node if it
|
// TrustPeer inserts a node into the list of privileged nodes.
|
||||||
// is not already connected.
|
func (srv *Server) TrustPeer(node *discover.Node) {
|
||||||
func (srv *Server) SuggestPeer(n *discover.Node) {
|
srv.lock.Lock()
|
||||||
srv.peerConnect <- n
|
defer srv.lock.Unlock()
|
||||||
|
|
||||||
|
srv.trusts[node.ID] = node
|
||||||
}
|
}
|
||||||
|
|
||||||
// Broadcast sends an RLP-encoded message to all connected peers.
|
// Broadcast sends an RLP-encoded message to all connected peers.
|
||||||
|
|
@ -195,7 +207,15 @@ 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)
|
||||||
srv.peerConnect = make(chan *discover.Node)
|
srv.throttle = make(map[discover.NodeID]bool)
|
||||||
|
|
||||||
|
// 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 {
|
if srv.setupFunc == nil {
|
||||||
srv.setupFunc = setupConn
|
srv.setupFunc = setupConn
|
||||||
}
|
}
|
||||||
|
|
@ -229,6 +249,8 @@ func (srv *Server) Start() (err error) {
|
||||||
if srv.NoDial && srv.ListenAddr == "" {
|
if srv.NoDial && srv.ListenAddr == "" {
|
||||||
glog.V(logger.Warn).Infoln("I will be kind-of useless, neither dialing nor listening.")
|
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
|
srv.running = true
|
||||||
return nil
|
return nil
|
||||||
|
|
@ -323,6 +345,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.Debug).Infof("Dialing trusted peer %v", node)
|
||||||
|
select {
|
||||||
|
case srv.trustDial <- node:
|
||||||
|
// Ok, dialing
|
||||||
|
|
||||||
|
case <-srv.quit:
|
||||||
|
// Terminating, return
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (srv *Server) dialLoop() {
|
func (srv *Server) dialLoop() {
|
||||||
var (
|
var (
|
||||||
dialed = make(chan *discover.Node)
|
dialed = make(chan *discover.Node)
|
||||||
|
|
@ -373,7 +434,7 @@ func (srv *Server) dialLoop() {
|
||||||
// below MaxPeers.
|
// below MaxPeers.
|
||||||
refresh.Reset(refreshPeersInterval)
|
refresh.Reset(refreshPeersInterval)
|
||||||
}
|
}
|
||||||
case dest := <-srv.peerConnect:
|
case dest := <-srv.trustDial:
|
||||||
dial(dest)
|
dial(dest)
|
||||||
case dests := <-findresults:
|
case dests := <-findresults:
|
||||||
for _, dest := range dests {
|
for _, dest := range dests {
|
||||||
|
|
@ -402,12 +463,34 @@ func (srv *Server) dialNode(dest *discover.Node) {
|
||||||
// dialNode, so we need to count it down again. startPeer also
|
// dialNode, so we need to count it down again. startPeer also
|
||||||
// does that when an error occurs.
|
// does that when an error occurs.
|
||||||
srv.peerWG.Done()
|
srv.peerWG.Done()
|
||||||
glog.V(logger.Detail).Infof("dial error: %v", err)
|
|
||||||
|
// Throttle the node to prevent hammering it with connections
|
||||||
|
glog.V(logger.Detail).Infof("Dialing %v failed: %v, throttling", dest, err)
|
||||||
|
srv.throttleNode(dest.ID)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
srv.startPeer(conn, dest)
|
srv.startPeer(conn, dest)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// throttleNode temporarily throttles a node, disabling both egress as well as
|
||||||
|
// ingress connections to/from that particular node.
|
||||||
|
func (srv *Server) throttleNode(id discover.NodeID) {
|
||||||
|
// Mark the node as throttled
|
||||||
|
srv.lock.Lock()
|
||||||
|
srv.throttle[id] = true
|
||||||
|
srv.lock.Unlock()
|
||||||
|
|
||||||
|
// Wait a while, after which discard the throttling
|
||||||
|
go func() {
|
||||||
|
<-time.After(dialFailureCooldown)
|
||||||
|
|
||||||
|
srv.lock.Lock()
|
||||||
|
delete(srv.throttle, id)
|
||||||
|
srv.lock.Unlock()
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
func (srv *Server) startPeer(fd net.Conn, dest *discover.Node) {
|
func (srv *Server) startPeer(fd net.Conn, dest *discover.Node) {
|
||||||
// TODO: handle/store session token
|
// TODO: handle/store session token
|
||||||
|
|
||||||
|
|
@ -416,10 +499,18 @@ func (srv *Server) startPeer(fd net.Conn, dest *discover.Node) {
|
||||||
// returns during that exchange need to call peerWG.Done because
|
// returns during that exchange need to call peerWG.Done because
|
||||||
// the callers of startPeer added the peer to the wait group already.
|
// the callers of startPeer added the peer to the wait group already.
|
||||||
fd.SetDeadline(time.Now().Add(handshakeTimeout))
|
fd.SetDeadline(time.Now().Add(handshakeTimeout))
|
||||||
|
|
||||||
|
// Check capacity and trust list
|
||||||
srv.lock.RLock()
|
srv.lock.RLock()
|
||||||
atcap := len(srv.peers) == srv.MaxPeers
|
atcap := len(srv.peers) == srv.MaxPeers
|
||||||
|
|
||||||
|
trust := make(map[discover.NodeID]bool)
|
||||||
|
for id, _ := range srv.trusts {
|
||||||
|
trust[id] = true
|
||||||
|
}
|
||||||
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, trust)
|
||||||
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)
|
||||||
|
|
@ -454,7 +545,11 @@ func (srv *Server) runPeer(p *Peer) {
|
||||||
srv.newPeerHook(p)
|
srv.newPeerHook(p)
|
||||||
}
|
}
|
||||||
discreason := p.run()
|
discreason := p.run()
|
||||||
|
|
||||||
|
// Drop the node, and throttle it to prevent hammering
|
||||||
srv.removePeer(p)
|
srv.removePeer(p)
|
||||||
|
srv.throttleNode(p.ID())
|
||||||
|
|
||||||
glog.V(logger.Debug).Infof("Removed %v (%v)\n", p, discreason)
|
glog.V(logger.Debug).Infof("Removed %v (%v)\n", p, discreason)
|
||||||
srvjslog.LogJson(&logger.P2PDisconnected{
|
srvjslog.LogJson(&logger.P2PDisconnected{
|
||||||
RemoteId: p.ID().String(),
|
RemoteId: p.ID().String(),
|
||||||
|
|
@ -472,16 +567,29 @@ func (srv *Server) addPeer(id discover.NodeID, p *Peer) (bool, DiscReason) {
|
||||||
return true, 0
|
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) {
|
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 {
|
switch {
|
||||||
case !srv.running:
|
case !srv.running:
|
||||||
return false, DiscQuitting
|
return false, DiscQuitting
|
||||||
case len(srv.peers) >= srv.MaxPeers:
|
|
||||||
|
case !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
|
||||||
|
|
||||||
case id == srv.ntab.Self().ID:
|
case id == srv.ntab.Self().ID:
|
||||||
return false, DiscSelf
|
return false, DiscSelf
|
||||||
|
|
||||||
|
case srv.throttle[id]:
|
||||||
|
return false, DiscThrottled
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return true, 0
|
return true, 0
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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, trust map[discover.NodeID]bool) (*conn, error) {
|
||||||
id := randomID()
|
id := randomID()
|
||||||
rw := newRlpxFrameRW(fd, secrets{
|
rw := newRlpxFrameRW(fd, secrets{
|
||||||
MAC: zero16,
|
MAC: zero16,
|
||||||
|
|
@ -80,7 +80,7 @@ func TestServerDial(t *testing.T) {
|
||||||
// run a one-shot TCP server to handle the connection.
|
// run a one-shot TCP server to handle the connection.
|
||||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("could not setup listener: %v")
|
t.Fatalf("could not setup listener: %v", err)
|
||||||
}
|
}
|
||||||
defer listener.Close()
|
defer listener.Close()
|
||||||
accepted := make(chan net.Conn)
|
accepted := make(chan net.Conn)
|
||||||
|
|
@ -102,7 +102,7 @@ func TestServerDial(t *testing.T) {
|
||||||
|
|
||||||
// tell the server to connect
|
// tell the server to connect
|
||||||
tcpAddr := listener.Addr().(*net.TCPAddr)
|
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 {
|
select {
|
||||||
case conn := <-accepted:
|
case conn := <-accepted:
|
||||||
|
|
@ -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, nil)
|
||||||
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
|
||||||
|
|
@ -219,6 +219,178 @@ 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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tests that a failed dial will temporarily throttle a peer.
|
||||||
|
func TestServerOutboundThrottling(t *testing.T) {
|
||||||
|
defer testlog(t).detach()
|
||||||
|
|
||||||
|
// Start a simple test server
|
||||||
|
server := startTestServer(t, nil)
|
||||||
|
defer server.Stop()
|
||||||
|
|
||||||
|
// Request a failing dial from the server and check throttling
|
||||||
|
node := &discover.Node{
|
||||||
|
ID: discover.PubkeyID(&newkey().PublicKey),
|
||||||
|
IP: []byte{127, 0, 0, 1},
|
||||||
|
TCPPort: 65535,
|
||||||
|
}
|
||||||
|
server.trustDial <- node
|
||||||
|
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
if throttle := server.throttle[node.ID]; !throttle {
|
||||||
|
t.Fatalf("throttling mismatch: have %v, want %v", throttle, true)
|
||||||
|
}
|
||||||
|
// Open a one shot TCP server to listen for valid dialing
|
||||||
|
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() {
|
||||||
|
conn, err := listener.Accept()
|
||||||
|
if err == nil {
|
||||||
|
conn.Close()
|
||||||
|
connected <- conn
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
|
||||||
|
// Request a re-dial from the server, make sure this also fails
|
||||||
|
addr := listener.Addr().(*net.TCPAddr)
|
||||||
|
node.IP, node.TCPPort = addr.IP, addr.Port
|
||||||
|
server.trustDial <- node
|
||||||
|
|
||||||
|
select {
|
||||||
|
case peer := <-connected:
|
||||||
|
t.Fatalf("throttled peer connected: %v", peer)
|
||||||
|
|
||||||
|
case <-time.After(100 * time.Millisecond):
|
||||||
|
// Ok, peer not accepted
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tests that a failed peer will get temporarily throttled.
|
||||||
|
func TestServerInboundThrottling(t *testing.T) {
|
||||||
|
defer testlog(t).detach()
|
||||||
|
|
||||||
|
// Start a test server and a peer sink for synchronization
|
||||||
|
started := make(chan *Peer)
|
||||||
|
server := &Server{
|
||||||
|
ListenAddr: "127.0.0.1:0",
|
||||||
|
PrivateKey: newkey(),
|
||||||
|
MaxPeers: 10,
|
||||||
|
NoDial: true,
|
||||||
|
newPeerHook: func(p *Peer) { started <- p },
|
||||||
|
}
|
||||||
|
if err := server.Start(); err != nil {
|
||||||
|
t.Fatal("failed to start test server: %v", err)
|
||||||
|
}
|
||||||
|
defer server.Stop()
|
||||||
|
|
||||||
|
// Create a new peer identity to check throttling with
|
||||||
|
dialer := &net.Dialer{Deadline: time.Now().Add(3 * time.Second)}
|
||||||
|
key := newkey()
|
||||||
|
|
||||||
|
// Connect with a new peer, run the handshake and disconnect
|
||||||
|
connection, err := dialer.Dial("tcp", server.ListenAddr)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to dial server: %v", err)
|
||||||
|
}
|
||||||
|
shake := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)}
|
||||||
|
if _, err = setupConn(connection, key, shake, server.Self(), false, nil); err != nil {
|
||||||
|
t.Fatalf("failed to run handshake: %v", err)
|
||||||
|
}
|
||||||
|
<-started
|
||||||
|
connection.Close()
|
||||||
|
server.peerWG.Wait()
|
||||||
|
|
||||||
|
// Check that throttling has been enabled
|
||||||
|
if throttle := server.throttle[shake.ID]; !throttle {
|
||||||
|
t.Fatalf("throttling mismatch: have %v, want %v", throttle, true)
|
||||||
|
}
|
||||||
|
// Try to reconnect with the same peer, run the handshake and verify throttling
|
||||||
|
connection, err = dialer.Dial("tcp", server.ListenAddr)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to re-dial server: %v", err)
|
||||||
|
}
|
||||||
|
defer connection.Close()
|
||||||
|
|
||||||
|
shake = &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)}
|
||||||
|
if _, err = setupConn(connection, key, shake, server.Self(), false, nil); err != nil {
|
||||||
|
t.Fatalf("failed to re-run handshake: %v", err)
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case peer := <-started:
|
||||||
|
t.Fatalf("throttled peer accepted: %v", peer)
|
||||||
|
|
||||||
|
case <-time.After(100 * time.Millisecond):
|
||||||
|
// Ok, peer not accepted
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func newkey() *ecdsa.PrivateKey {
|
func newkey() *ecdsa.PrivateKey {
|
||||||
key, err := crypto.GenerateKey()
|
key, err := crypto.GenerateKey()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue