localnode.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. package enode
  17. import (
  18. "crypto/ecdsa"
  19. "fmt"
  20. "net"
  21. "reflect"
  22. "strconv"
  23. "sync"
  24. "sync/atomic"
  25. "time"
  26. "github.com/ethereum/go-ethereum/log"
  27. "github.com/ethereum/go-ethereum/p2p/enr"
  28. "github.com/ethereum/go-ethereum/p2p/netutil"
  29. )
  30. const (
  31. // IP tracker configuration
  32. iptrackMinStatements = 10
  33. iptrackWindow = 5 * time.Minute
  34. iptrackContactWindow = 10 * time.Minute
  35. )
  36. // LocalNode produces the signed node record of a local node, i.e. a node run in the
  37. // current process. Setting ENR entries via the Set method updates the record. A new version
  38. // of the record is signed on demand when the Node method is called.
  39. type LocalNode struct {
  40. cur atomic.Value // holds a non-nil node pointer while the record is up-to-date.
  41. id ID
  42. key *ecdsa.PrivateKey
  43. db *DB
  44. // everything below is protected by a lock
  45. mu sync.Mutex
  46. seq uint64
  47. entries map[string]enr.Entry
  48. endpoint4 lnEndpoint
  49. endpoint6 lnEndpoint
  50. }
  51. type lnEndpoint struct {
  52. track *netutil.IPTracker
  53. staticIP, fallbackIP net.IP
  54. fallbackUDP int
  55. }
  56. // NewLocalNode creates a local node.
  57. func NewLocalNode(db *DB, key *ecdsa.PrivateKey) *LocalNode {
  58. ln := &LocalNode{
  59. id: PubkeyToIDV4(&key.PublicKey),
  60. db: db,
  61. key: key,
  62. entries: make(map[string]enr.Entry),
  63. endpoint4: lnEndpoint{
  64. track: netutil.NewIPTracker(iptrackWindow, iptrackContactWindow, iptrackMinStatements),
  65. },
  66. endpoint6: lnEndpoint{
  67. track: netutil.NewIPTracker(iptrackWindow, iptrackContactWindow, iptrackMinStatements),
  68. },
  69. }
  70. ln.seq = db.localSeq(ln.id)
  71. ln.invalidate()
  72. return ln
  73. }
  74. // Database returns the node database associated with the local node.
  75. func (ln *LocalNode) Database() *DB {
  76. return ln.db
  77. }
  78. // Node returns the current version of the local node record.
  79. func (ln *LocalNode) Node() *Node {
  80. n := ln.cur.Load().(*Node)
  81. if n != nil {
  82. return n
  83. }
  84. // Record was invalidated, sign a new copy.
  85. ln.mu.Lock()
  86. defer ln.mu.Unlock()
  87. ln.sign()
  88. return ln.cur.Load().(*Node)
  89. }
  90. // Seq returns the current sequence number of the local node record.
  91. func (ln *LocalNode) Seq() uint64 {
  92. ln.mu.Lock()
  93. defer ln.mu.Unlock()
  94. return ln.seq
  95. }
  96. // ID returns the local node ID.
  97. func (ln *LocalNode) ID() ID {
  98. return ln.id
  99. }
  100. // Set puts the given entry into the local record, overwriting any existing value.
  101. // Use Set*IP and SetFallbackUDP to set IP addresses and UDP port, otherwise they'll
  102. // be overwritten by the endpoint predictor.
  103. func (ln *LocalNode) Set(e enr.Entry) {
  104. ln.mu.Lock()
  105. defer ln.mu.Unlock()
  106. ln.set(e)
  107. }
  108. func (ln *LocalNode) set(e enr.Entry) {
  109. val, exists := ln.entries[e.ENRKey()]
  110. if !exists || !reflect.DeepEqual(val, e) {
  111. ln.entries[e.ENRKey()] = e
  112. ln.invalidate()
  113. }
  114. }
  115. // Delete removes the given entry from the local record.
  116. func (ln *LocalNode) Delete(e enr.Entry) {
  117. ln.mu.Lock()
  118. defer ln.mu.Unlock()
  119. ln.delete(e)
  120. }
  121. func (ln *LocalNode) delete(e enr.Entry) {
  122. _, exists := ln.entries[e.ENRKey()]
  123. if exists {
  124. delete(ln.entries, e.ENRKey())
  125. ln.invalidate()
  126. }
  127. }
  128. func (ln *LocalNode) endpointForIP(ip net.IP) *lnEndpoint {
  129. if ip.To4() != nil {
  130. return &ln.endpoint4
  131. }
  132. return &ln.endpoint6
  133. }
  134. // SetStaticIP sets the local IP to the given one unconditionally.
  135. // This disables endpoint prediction.
  136. func (ln *LocalNode) SetStaticIP(ip net.IP) {
  137. ln.mu.Lock()
  138. defer ln.mu.Unlock()
  139. ln.endpointForIP(ip).staticIP = ip
  140. ln.updateEndpoints()
  141. }
  142. // SetFallbackIP sets the last-resort IP address. This address is used
  143. // if no endpoint prediction can be made and no static IP is set.
  144. func (ln *LocalNode) SetFallbackIP(ip net.IP) {
  145. ln.mu.Lock()
  146. defer ln.mu.Unlock()
  147. ln.endpointForIP(ip).fallbackIP = ip
  148. ln.updateEndpoints()
  149. }
  150. // SetFallbackUDP sets the last-resort UDP-on-IPv4 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. ln.endpoint4.fallbackUDP = port
  156. ln.endpoint6.fallbackUDP = port
  157. ln.updateEndpoints()
  158. }
  159. // UDPEndpointStatement should be called whenever a statement about the local node's
  160. // UDP endpoint is received. It feeds the local endpoint predictor.
  161. func (ln *LocalNode) UDPEndpointStatement(fromaddr, endpoint *net.UDPAddr) {
  162. ln.mu.Lock()
  163. defer ln.mu.Unlock()
  164. ln.endpointForIP(endpoint.IP).track.AddStatement(fromaddr.String(), endpoint.String())
  165. ln.updateEndpoints()
  166. }
  167. // UDPContact should be called whenever the local node has announced itself to another node
  168. // via UDP. It feeds the local endpoint predictor.
  169. func (ln *LocalNode) UDPContact(toaddr *net.UDPAddr) {
  170. ln.mu.Lock()
  171. defer ln.mu.Unlock()
  172. ln.endpointForIP(toaddr.IP).track.AddContact(toaddr.String())
  173. ln.updateEndpoints()
  174. }
  175. // updateEndpoints updates the record with predicted endpoints.
  176. func (ln *LocalNode) updateEndpoints() {
  177. ip4, udp4 := ln.endpoint4.get()
  178. ip6, udp6 := ln.endpoint6.get()
  179. if ip4 != nil && !ip4.IsUnspecified() {
  180. ln.set(enr.IPv4(ip4))
  181. } else {
  182. ln.delete(enr.IPv4{})
  183. }
  184. if ip6 != nil && !ip6.IsUnspecified() {
  185. ln.set(enr.IPv6(ip6))
  186. } else {
  187. ln.delete(enr.IPv6{})
  188. }
  189. if udp4 != 0 {
  190. ln.set(enr.UDP(udp4))
  191. } else {
  192. ln.delete(enr.UDP(0))
  193. }
  194. if udp6 != 0 && udp6 != udp4 {
  195. ln.set(enr.UDP6(udp6))
  196. } else {
  197. ln.delete(enr.UDP6(0))
  198. }
  199. }
  200. // get returns the endpoint with highest precedence.
  201. func (e *lnEndpoint) get() (newIP net.IP, newPort int) {
  202. newPort = e.fallbackUDP
  203. if e.fallbackIP != nil {
  204. newIP = e.fallbackIP
  205. }
  206. if e.staticIP != nil {
  207. newIP = e.staticIP
  208. } else if ip, port := predictAddr(e.track); ip != nil {
  209. newIP = ip
  210. newPort = port
  211. }
  212. return newIP, newPort
  213. }
  214. // predictAddr wraps IPTracker.PredictEndpoint, converting from its string-based
  215. // endpoint representation to IP and port types.
  216. func predictAddr(t *netutil.IPTracker) (net.IP, int) {
  217. ep := t.PredictEndpoint()
  218. if ep == "" {
  219. return nil, 0
  220. }
  221. ipString, portString, _ := net.SplitHostPort(ep)
  222. ip := net.ParseIP(ipString)
  223. port, _ := strconv.Atoi(portString)
  224. return ip, port
  225. }
  226. func (ln *LocalNode) invalidate() {
  227. ln.cur.Store((*Node)(nil))
  228. }
  229. func (ln *LocalNode) sign() {
  230. if n := ln.cur.Load().(*Node); n != nil {
  231. return // no changes
  232. }
  233. var r enr.Record
  234. for _, e := range ln.entries {
  235. r.Set(e)
  236. }
  237. ln.bumpSeq()
  238. r.SetSeq(ln.seq)
  239. if err := SignV4(&r, ln.key); err != nil {
  240. panic(fmt.Errorf("enode: can't sign record: %v", err))
  241. }
  242. n, err := New(ValidSchemes, &r)
  243. if err != nil {
  244. panic(fmt.Errorf("enode: can't verify local record: %v", err))
  245. }
  246. ln.cur.Store(n)
  247. log.Info("New local node record", "seq", ln.seq, "id", n.ID(), "ip", n.IP(), "udp", n.UDP(), "tcp", n.TCP())
  248. }
  249. func (ln *LocalNode) bumpSeq() {
  250. ln.seq++
  251. ln.db.storeLocalSeq(ln.id, ln.seq)
  252. }