localnode.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. // time needed to wait between two updates to the local ENR
  36. recordUpdateThrottle = time.Millisecond
  37. )
  38. // LocalNode produces the signed node record of a local node, i.e. a node run in the
  39. // current process. Setting ENR entries via the Set method updates the record. A new version
  40. // of the record is signed on demand when the Node method is called.
  41. type LocalNode struct {
  42. cur atomic.Value // holds a non-nil node pointer while the record is up-to-date
  43. id ID
  44. key *ecdsa.PrivateKey
  45. db *DB
  46. // everything below is protected by a lock
  47. mu sync.RWMutex
  48. seq uint64
  49. update time.Time // timestamp when the record was last updated
  50. entries map[string]enr.Entry
  51. endpoint4 lnEndpoint
  52. endpoint6 lnEndpoint
  53. }
  54. type lnEndpoint struct {
  55. track *netutil.IPTracker
  56. staticIP, fallbackIP net.IP
  57. fallbackUDP uint16 // port
  58. }
  59. // NewLocalNode creates a local node.
  60. func NewLocalNode(db *DB, key *ecdsa.PrivateKey) *LocalNode {
  61. ln := &LocalNode{
  62. id: PubkeyToIDV4(&key.PublicKey),
  63. db: db,
  64. key: key,
  65. entries: make(map[string]enr.Entry),
  66. endpoint4: lnEndpoint{
  67. track: netutil.NewIPTracker(iptrackWindow, iptrackContactWindow, iptrackMinStatements),
  68. },
  69. endpoint6: lnEndpoint{
  70. track: netutil.NewIPTracker(iptrackWindow, iptrackContactWindow, iptrackMinStatements),
  71. },
  72. }
  73. ln.seq = db.localSeq(ln.id)
  74. ln.update = time.Now()
  75. ln.cur.Store((*Node)(nil))
  76. return ln
  77. }
  78. // Database returns the node database associated with the local node.
  79. func (ln *LocalNode) Database() *DB {
  80. return ln.db
  81. }
  82. // Node returns the current version of the local node record.
  83. func (ln *LocalNode) Node() *Node {
  84. // If we have a valid record, return that
  85. n := ln.cur.Load().(*Node)
  86. if n != nil {
  87. return n
  88. }
  89. // Record was invalidated, sign a new copy.
  90. ln.mu.Lock()
  91. defer ln.mu.Unlock()
  92. // Double check the current record, since multiple goroutines might be waiting
  93. // on the write mutex.
  94. if n = ln.cur.Load().(*Node); n != nil {
  95. return n
  96. }
  97. // The initial sequence number is the current timestamp in milliseconds. To ensure
  98. // that the initial sequence number will always be higher than any previous sequence
  99. // number (assuming the clock is correct), we want to avoid updating the record faster
  100. // than once per ms. So we need to sleep here until the next possible update time has
  101. // arrived.
  102. lastChange := time.Since(ln.update)
  103. if lastChange < recordUpdateThrottle {
  104. time.Sleep(recordUpdateThrottle - lastChange)
  105. }
  106. ln.sign()
  107. ln.update = time.Now()
  108. return ln.cur.Load().(*Node)
  109. }
  110. // Seq returns the current sequence number of the local node record.
  111. func (ln *LocalNode) Seq() uint64 {
  112. ln.mu.Lock()
  113. defer ln.mu.Unlock()
  114. return ln.seq
  115. }
  116. // ID returns the local node ID.
  117. func (ln *LocalNode) ID() ID {
  118. return ln.id
  119. }
  120. // Set puts the given entry into the local record, overwriting any existing value.
  121. // Use Set*IP and SetFallbackUDP to set IP addresses and UDP port, otherwise they'll
  122. // be overwritten by the endpoint predictor.
  123. //
  124. // Since node record updates are throttled to one per second, Set is asynchronous.
  125. // Any update will be queued up and published when at least one second passes from
  126. // the last change.
  127. func (ln *LocalNode) Set(e enr.Entry) {
  128. ln.mu.Lock()
  129. defer ln.mu.Unlock()
  130. ln.set(e)
  131. }
  132. func (ln *LocalNode) set(e enr.Entry) {
  133. val, exists := ln.entries[e.ENRKey()]
  134. if !exists || !reflect.DeepEqual(val, e) {
  135. ln.entries[e.ENRKey()] = e
  136. ln.invalidate()
  137. }
  138. }
  139. // Delete removes the given entry from the local record.
  140. func (ln *LocalNode) Delete(e enr.Entry) {
  141. ln.mu.Lock()
  142. defer ln.mu.Unlock()
  143. ln.delete(e)
  144. }
  145. func (ln *LocalNode) delete(e enr.Entry) {
  146. _, exists := ln.entries[e.ENRKey()]
  147. if exists {
  148. delete(ln.entries, e.ENRKey())
  149. ln.invalidate()
  150. }
  151. }
  152. func (ln *LocalNode) endpointForIP(ip net.IP) *lnEndpoint {
  153. if ip.To4() != nil {
  154. return &ln.endpoint4
  155. }
  156. return &ln.endpoint6
  157. }
  158. // SetStaticIP sets the local IP to the given one unconditionally.
  159. // This disables endpoint prediction.
  160. func (ln *LocalNode) SetStaticIP(ip net.IP) {
  161. ln.mu.Lock()
  162. defer ln.mu.Unlock()
  163. ln.endpointForIP(ip).staticIP = ip
  164. ln.updateEndpoints()
  165. }
  166. // SetFallbackIP sets the last-resort IP address. This address is used
  167. // if no endpoint prediction can be made and no static IP is set.
  168. func (ln *LocalNode) SetFallbackIP(ip net.IP) {
  169. ln.mu.Lock()
  170. defer ln.mu.Unlock()
  171. ln.endpointForIP(ip).fallbackIP = ip
  172. ln.updateEndpoints()
  173. }
  174. // SetFallbackUDP sets the last-resort UDP-on-IPv4 port. This port is used
  175. // if no endpoint prediction can be made.
  176. func (ln *LocalNode) SetFallbackUDP(port int) {
  177. ln.mu.Lock()
  178. defer ln.mu.Unlock()
  179. ln.endpoint4.fallbackUDP = uint16(port)
  180. ln.endpoint6.fallbackUDP = uint16(port)
  181. ln.updateEndpoints()
  182. }
  183. // UDPEndpointStatement should be called whenever a statement about the local node's
  184. // UDP endpoint is received. It feeds the local endpoint predictor.
  185. func (ln *LocalNode) UDPEndpointStatement(fromaddr, endpoint *net.UDPAddr) {
  186. ln.mu.Lock()
  187. defer ln.mu.Unlock()
  188. ln.endpointForIP(endpoint.IP).track.AddStatement(fromaddr.String(), endpoint.String())
  189. ln.updateEndpoints()
  190. }
  191. // UDPContact should be called whenever the local node has announced itself to another node
  192. // via UDP. It feeds the local endpoint predictor.
  193. func (ln *LocalNode) UDPContact(toaddr *net.UDPAddr) {
  194. ln.mu.Lock()
  195. defer ln.mu.Unlock()
  196. ln.endpointForIP(toaddr.IP).track.AddContact(toaddr.String())
  197. ln.updateEndpoints()
  198. }
  199. // updateEndpoints updates the record with predicted endpoints.
  200. func (ln *LocalNode) updateEndpoints() {
  201. ip4, udp4 := ln.endpoint4.get()
  202. ip6, udp6 := ln.endpoint6.get()
  203. if ip4 != nil && !ip4.IsUnspecified() {
  204. ln.set(enr.IPv4(ip4))
  205. } else {
  206. ln.delete(enr.IPv4{})
  207. }
  208. if ip6 != nil && !ip6.IsUnspecified() {
  209. ln.set(enr.IPv6(ip6))
  210. } else {
  211. ln.delete(enr.IPv6{})
  212. }
  213. if udp4 != 0 {
  214. ln.set(enr.UDP(udp4))
  215. } else {
  216. ln.delete(enr.UDP(0))
  217. }
  218. if udp6 != 0 && udp6 != udp4 {
  219. ln.set(enr.UDP6(udp6))
  220. } else {
  221. ln.delete(enr.UDP6(0))
  222. }
  223. }
  224. // get returns the endpoint with highest precedence.
  225. func (e *lnEndpoint) get() (newIP net.IP, newPort uint16) {
  226. newPort = e.fallbackUDP
  227. if e.fallbackIP != nil {
  228. newIP = e.fallbackIP
  229. }
  230. if e.staticIP != nil {
  231. newIP = e.staticIP
  232. } else if ip, port := predictAddr(e.track); ip != nil {
  233. newIP = ip
  234. newPort = port
  235. }
  236. return newIP, newPort
  237. }
  238. // predictAddr wraps IPTracker.PredictEndpoint, converting from its string-based
  239. // endpoint representation to IP and port types.
  240. func predictAddr(t *netutil.IPTracker) (net.IP, uint16) {
  241. ep := t.PredictEndpoint()
  242. if ep == "" {
  243. return nil, 0
  244. }
  245. ipString, portString, _ := net.SplitHostPort(ep)
  246. ip := net.ParseIP(ipString)
  247. port, err := strconv.ParseUint(portString, 10, 16)
  248. if err != nil {
  249. return nil, 0
  250. }
  251. return ip, uint16(port)
  252. }
  253. func (ln *LocalNode) invalidate() {
  254. ln.cur.Store((*Node)(nil))
  255. }
  256. func (ln *LocalNode) sign() {
  257. if n := ln.cur.Load().(*Node); n != nil {
  258. return // no changes
  259. }
  260. var r enr.Record
  261. for _, e := range ln.entries {
  262. r.Set(e)
  263. }
  264. ln.bumpSeq()
  265. r.SetSeq(ln.seq)
  266. if err := SignV4(&r, ln.key); err != nil {
  267. panic(fmt.Errorf("enode: can't sign record: %v", err))
  268. }
  269. n, err := New(ValidSchemes, &r)
  270. if err != nil {
  271. panic(fmt.Errorf("enode: can't verify local record: %v", err))
  272. }
  273. ln.cur.Store(n)
  274. log.Info("New local node record", "seq", ln.seq, "id", n.ID(), "ip", n.IP(), "udp", n.UDP(), "tcp", n.TCP())
  275. }
  276. func (ln *LocalNode) bumpSeq() {
  277. ln.seq++
  278. ln.db.storeLocalSeq(ln.id, ln.seq)
  279. }
  280. // nowMilliseconds gives the current timestamp at millisecond precision.
  281. func nowMilliseconds() uint64 {
  282. ns := time.Now().UnixNano()
  283. if ns < 0 {
  284. return 0
  285. }
  286. return uint64(ns / 1000 / 1000)
  287. }