github.com/oskarth/go-ethereum@v1.6.8-0.20191013093314-dac24a9d3494/p2p/enode/localnode.go (about)

     1  // Copyright 2018 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package enode
    18  
    19  import (
    20  	"crypto/ecdsa"
    21  	"fmt"
    22  	"net"
    23  	"reflect"
    24  	"strconv"
    25  	"sync"
    26  	"sync/atomic"
    27  	"time"
    28  
    29  	"github.com/ethereum/go-ethereum/log"
    30  	"github.com/ethereum/go-ethereum/p2p/enr"
    31  	"github.com/ethereum/go-ethereum/p2p/netutil"
    32  )
    33  
    34  const (
    35  	// IP tracker configuration
    36  	iptrackMinStatements = 10
    37  	iptrackWindow        = 5 * time.Minute
    38  	iptrackContactWindow = 10 * time.Minute
    39  )
    40  
    41  // LocalNode produces the signed node record of a local node, i.e. a node run in the
    42  // current process. Setting ENR entries via the Set method updates the record. A new version
    43  // of the record is signed on demand when the Node method is called.
    44  type LocalNode struct {
    45  	cur atomic.Value // holds a non-nil node pointer while the record is up-to-date.
    46  	id  ID
    47  	key *ecdsa.PrivateKey
    48  	db  *DB
    49  
    50  	// everything below is protected by a lock
    51  	mu          sync.Mutex
    52  	seq         uint64
    53  	entries     map[string]enr.Entry
    54  	udpTrack    *netutil.IPTracker // predicts external UDP endpoint
    55  	staticIP    net.IP
    56  	fallbackIP  net.IP
    57  	fallbackUDP int
    58  }
    59  
    60  // NewLocalNode creates a local node.
    61  func NewLocalNode(db *DB, key *ecdsa.PrivateKey) *LocalNode {
    62  	ln := &LocalNode{
    63  		id:       PubkeyToIDV4(&key.PublicKey),
    64  		db:       db,
    65  		key:      key,
    66  		udpTrack: netutil.NewIPTracker(iptrackWindow, iptrackContactWindow, iptrackMinStatements),
    67  		entries:  make(map[string]enr.Entry),
    68  	}
    69  	ln.seq = db.localSeq(ln.id)
    70  	ln.invalidate()
    71  	return ln
    72  }
    73  
    74  // Database returns the node database associated with the local node.
    75  func (ln *LocalNode) Database() *DB {
    76  	return ln.db
    77  }
    78  
    79  // Node returns the current version of the local node record.
    80  func (ln *LocalNode) Node() *Node {
    81  	n := ln.cur.Load().(*Node)
    82  	if n != nil {
    83  		return n
    84  	}
    85  	// Record was invalidated, sign a new copy.
    86  	ln.mu.Lock()
    87  	defer ln.mu.Unlock()
    88  	ln.sign()
    89  	return ln.cur.Load().(*Node)
    90  }
    91  
    92  // ID returns the local node ID.
    93  func (ln *LocalNode) ID() ID {
    94  	return ln.id
    95  }
    96  
    97  // Set puts the given entry into the local record, overwriting
    98  // any existing value.
    99  func (ln *LocalNode) Set(e enr.Entry) {
   100  	ln.mu.Lock()
   101  	defer ln.mu.Unlock()
   102  
   103  	ln.set(e)
   104  }
   105  
   106  func (ln *LocalNode) set(e enr.Entry) {
   107  	val, exists := ln.entries[e.ENRKey()]
   108  	if !exists || !reflect.DeepEqual(val, e) {
   109  		ln.entries[e.ENRKey()] = e
   110  		ln.invalidate()
   111  	}
   112  }
   113  
   114  // Delete removes the given entry from the local record.
   115  func (ln *LocalNode) Delete(e enr.Entry) {
   116  	ln.mu.Lock()
   117  	defer ln.mu.Unlock()
   118  
   119  	ln.delete(e)
   120  }
   121  
   122  func (ln *LocalNode) delete(e enr.Entry) {
   123  	_, exists := ln.entries[e.ENRKey()]
   124  	if exists {
   125  		delete(ln.entries, e.ENRKey())
   126  		ln.invalidate()
   127  	}
   128  }
   129  
   130  // SetStaticIP sets the local IP to the given one unconditionally.
   131  // This disables endpoint prediction.
   132  func (ln *LocalNode) SetStaticIP(ip net.IP) {
   133  	ln.mu.Lock()
   134  	defer ln.mu.Unlock()
   135  
   136  	ln.staticIP = ip
   137  	ln.updateEndpoints()
   138  }
   139  
   140  // SetFallbackIP sets the last-resort IP address. This address is used
   141  // if no endpoint prediction can be made and no static IP is set.
   142  func (ln *LocalNode) SetFallbackIP(ip net.IP) {
   143  	ln.mu.Lock()
   144  	defer ln.mu.Unlock()
   145  
   146  	ln.fallbackIP = ip
   147  	ln.updateEndpoints()
   148  }
   149  
   150  // SetFallbackUDP sets the last-resort UDP port. This port is used
   151  // if no endpoint prediction can be made.
   152  func (ln *LocalNode) SetFallbackUDP(port int) {
   153  	ln.mu.Lock()
   154  	defer ln.mu.Unlock()
   155  
   156  	ln.fallbackUDP = port
   157  	ln.updateEndpoints()
   158  }
   159  
   160  // UDPEndpointStatement should be called whenever a statement about the local node's
   161  // UDP endpoint is received. It feeds the local endpoint predictor.
   162  func (ln *LocalNode) UDPEndpointStatement(fromaddr, endpoint *net.UDPAddr) {
   163  	ln.mu.Lock()
   164  	defer ln.mu.Unlock()
   165  
   166  	ln.udpTrack.AddStatement(fromaddr.String(), endpoint.String())
   167  	ln.updateEndpoints()
   168  }
   169  
   170  // UDPContact should be called whenever the local node has announced itself to another node
   171  // via UDP. It feeds the local endpoint predictor.
   172  func (ln *LocalNode) UDPContact(toaddr *net.UDPAddr) {
   173  	ln.mu.Lock()
   174  	defer ln.mu.Unlock()
   175  
   176  	ln.udpTrack.AddContact(toaddr.String())
   177  	ln.updateEndpoints()
   178  }
   179  
   180  func (ln *LocalNode) updateEndpoints() {
   181  	// Determine the endpoints.
   182  	newIP := ln.fallbackIP
   183  	newUDP := ln.fallbackUDP
   184  	if ln.staticIP != nil {
   185  		newIP = ln.staticIP
   186  	} else if ip, port := predictAddr(ln.udpTrack); ip != nil {
   187  		newIP = ip
   188  		newUDP = port
   189  	}
   190  
   191  	// Update the record.
   192  	if newIP != nil && !newIP.IsUnspecified() {
   193  		ln.set(enr.IP(newIP))
   194  		if newUDP != 0 {
   195  			ln.set(enr.UDP(newUDP))
   196  		} else {
   197  			ln.delete(enr.UDP(0))
   198  		}
   199  	} else {
   200  		ln.delete(enr.IP{})
   201  	}
   202  }
   203  
   204  // predictAddr wraps IPTracker.PredictEndpoint, converting from its string-based
   205  // endpoint representation to IP and port types.
   206  func predictAddr(t *netutil.IPTracker) (net.IP, int) {
   207  	ep := t.PredictEndpoint()
   208  	if ep == "" {
   209  		return nil, 0
   210  	}
   211  	ipString, portString, _ := net.SplitHostPort(ep)
   212  	ip := net.ParseIP(ipString)
   213  	port, _ := strconv.Atoi(portString)
   214  	return ip, port
   215  }
   216  
   217  func (ln *LocalNode) invalidate() {
   218  	ln.cur.Store((*Node)(nil))
   219  }
   220  
   221  func (ln *LocalNode) sign() {
   222  	if n := ln.cur.Load().(*Node); n != nil {
   223  		return // no changes
   224  	}
   225  
   226  	var r enr.Record
   227  	for _, e := range ln.entries {
   228  		r.Set(e)
   229  	}
   230  	ln.bumpSeq()
   231  	r.SetSeq(ln.seq)
   232  	if err := SignV4(&r, ln.key); err != nil {
   233  		panic(fmt.Errorf("enode: can't sign record: %v", err))
   234  	}
   235  	n, err := New(ValidSchemes, &r)
   236  	if err != nil {
   237  		panic(fmt.Errorf("enode: can't verify local record: %v", err))
   238  	}
   239  	ln.cur.Store(n)
   240  	log.Info("New local node record", "seq", ln.seq, "id", n.ID(), "ip", n.IP(), "udp", n.UDP(), "tcp", n.TCP())
   241  }
   242  
   243  func (ln *LocalNode) bumpSeq() {
   244  	ln.seq++
   245  	ln.db.storeLocalSeq(ln.id, ln.seq)
   246  }