client.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. // Copyright 2019 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 dnsdisc
  17. import (
  18. "bytes"
  19. "context"
  20. "errors"
  21. "fmt"
  22. "math/rand"
  23. "net"
  24. "strings"
  25. "sync"
  26. "time"
  27. "github.com/ethereum/go-ethereum/common/mclock"
  28. "github.com/ethereum/go-ethereum/crypto"
  29. "github.com/ethereum/go-ethereum/log"
  30. "github.com/ethereum/go-ethereum/p2p/enode"
  31. "github.com/ethereum/go-ethereum/p2p/enr"
  32. lru "github.com/hashicorp/golang-lru"
  33. "golang.org/x/sync/singleflight"
  34. "golang.org/x/time/rate"
  35. )
  36. // Client discovers nodes by querying DNS servers.
  37. type Client struct {
  38. cfg Config
  39. clock mclock.Clock
  40. entries *lru.Cache
  41. ratelimit *rate.Limiter
  42. singleflight singleflight.Group
  43. }
  44. // Config holds configuration options for the client.
  45. type Config struct {
  46. Timeout time.Duration // timeout used for DNS lookups (default 5s)
  47. RecheckInterval time.Duration // time between tree root update checks (default 30min)
  48. CacheLimit int // maximum number of cached records (default 1000)
  49. RateLimit float64 // maximum DNS requests / second (default 3)
  50. ValidSchemes enr.IdentityScheme // acceptable ENR identity schemes (default enode.ValidSchemes)
  51. Resolver Resolver // the DNS resolver to use (defaults to system DNS)
  52. Logger log.Logger // destination of client log messages (defaults to root logger)
  53. }
  54. // Resolver is a DNS resolver that can query TXT records.
  55. type Resolver interface {
  56. LookupTXT(ctx context.Context, domain string) ([]string, error)
  57. }
  58. func (cfg Config) withDefaults() Config {
  59. const (
  60. defaultTimeout = 5 * time.Second
  61. defaultRecheck = 30 * time.Minute
  62. defaultRateLimit = 3
  63. defaultCache = 1000
  64. )
  65. if cfg.Timeout == 0 {
  66. cfg.Timeout = defaultTimeout
  67. }
  68. if cfg.RecheckInterval == 0 {
  69. cfg.RecheckInterval = defaultRecheck
  70. }
  71. if cfg.CacheLimit == 0 {
  72. cfg.CacheLimit = defaultCache
  73. }
  74. if cfg.RateLimit == 0 {
  75. cfg.RateLimit = defaultRateLimit
  76. }
  77. if cfg.ValidSchemes == nil {
  78. cfg.ValidSchemes = enode.ValidSchemes
  79. }
  80. if cfg.Resolver == nil {
  81. cfg.Resolver = new(net.Resolver)
  82. }
  83. if cfg.Logger == nil {
  84. cfg.Logger = log.Root()
  85. }
  86. return cfg
  87. }
  88. // NewClient creates a client.
  89. func NewClient(cfg Config) *Client {
  90. cfg = cfg.withDefaults()
  91. cache, err := lru.New(cfg.CacheLimit)
  92. if err != nil {
  93. panic(err)
  94. }
  95. rlimit := rate.NewLimiter(rate.Limit(cfg.RateLimit), 10)
  96. return &Client{
  97. cfg: cfg,
  98. entries: cache,
  99. clock: mclock.System{},
  100. ratelimit: rlimit,
  101. }
  102. }
  103. // SyncTree downloads the entire node tree at the given URL.
  104. func (c *Client) SyncTree(url string) (*Tree, error) {
  105. le, err := parseLink(url)
  106. if err != nil {
  107. return nil, fmt.Errorf("invalid enrtree URL: %v", err)
  108. }
  109. ct := newClientTree(c, new(linkCache), le)
  110. t := &Tree{entries: make(map[string]entry)}
  111. if err := ct.syncAll(t.entries); err != nil {
  112. return nil, err
  113. }
  114. t.root = ct.root
  115. return t, nil
  116. }
  117. // NewIterator creates an iterator that visits all nodes at the
  118. // given tree URLs.
  119. func (c *Client) NewIterator(urls ...string) (enode.Iterator, error) {
  120. it := c.newRandomIterator()
  121. for _, url := range urls {
  122. if err := it.addTree(url); err != nil {
  123. return nil, err
  124. }
  125. }
  126. return it, nil
  127. }
  128. // resolveRoot retrieves a root entry via DNS.
  129. func (c *Client) resolveRoot(ctx context.Context, loc *linkEntry) (rootEntry, error) {
  130. e, err, _ := c.singleflight.Do(loc.str, func() (interface{}, error) {
  131. txts, err := c.cfg.Resolver.LookupTXT(ctx, loc.domain)
  132. c.cfg.Logger.Trace("Updating DNS discovery root", "tree", loc.domain, "err", err)
  133. if err != nil {
  134. return rootEntry{}, err
  135. }
  136. for _, txt := range txts {
  137. if strings.HasPrefix(txt, rootPrefix) {
  138. return parseAndVerifyRoot(txt, loc)
  139. }
  140. }
  141. return rootEntry{}, nameError{loc.domain, errNoRoot}
  142. })
  143. return e.(rootEntry), err
  144. }
  145. func parseAndVerifyRoot(txt string, loc *linkEntry) (rootEntry, error) {
  146. e, err := parseRoot(txt)
  147. if err != nil {
  148. return e, err
  149. }
  150. if !e.verifySignature(loc.pubkey) {
  151. return e, entryError{typ: "root", err: errInvalidSig}
  152. }
  153. return e, nil
  154. }
  155. // resolveEntry retrieves an entry from the cache or fetches it from the network
  156. // if it isn't cached.
  157. func (c *Client) resolveEntry(ctx context.Context, domain, hash string) (entry, error) {
  158. // The rate limit always applies, even when the result might be cached. This is
  159. // important because it avoids hot-spinning in consumers of node iterators created on
  160. // this client.
  161. if err := c.ratelimit.Wait(ctx); err != nil {
  162. return nil, err
  163. }
  164. cacheKey := truncateHash(hash)
  165. if e, ok := c.entries.Get(cacheKey); ok {
  166. return e.(entry), nil
  167. }
  168. ei, err, _ := c.singleflight.Do(cacheKey, func() (interface{}, error) {
  169. e, err := c.doResolveEntry(ctx, domain, hash)
  170. if err != nil {
  171. return nil, err
  172. }
  173. c.entries.Add(cacheKey, e)
  174. return e, nil
  175. })
  176. e, _ := ei.(entry)
  177. return e, err
  178. }
  179. // doResolveEntry fetches an entry via DNS.
  180. func (c *Client) doResolveEntry(ctx context.Context, domain, hash string) (entry, error) {
  181. wantHash, err := b32format.DecodeString(hash)
  182. if err != nil {
  183. return nil, fmt.Errorf("invalid base32 hash")
  184. }
  185. name := hash + "." + domain
  186. txts, err := c.cfg.Resolver.LookupTXT(ctx, hash+"."+domain)
  187. c.cfg.Logger.Trace("DNS discovery lookup", "name", name, "err", err)
  188. if err != nil {
  189. return nil, err
  190. }
  191. for _, txt := range txts {
  192. e, err := parseEntry(txt, c.cfg.ValidSchemes)
  193. if errors.Is(err, errUnknownEntry) {
  194. continue
  195. }
  196. if !bytes.HasPrefix(crypto.Keccak256([]byte(txt)), wantHash) {
  197. err = nameError{name, errHashMismatch}
  198. } else if err != nil {
  199. err = nameError{name, err}
  200. }
  201. return e, err
  202. }
  203. return nil, nameError{name, errNoEntry}
  204. }
  205. // randomIterator traverses a set of trees and returns nodes found in them.
  206. type randomIterator struct {
  207. cur *enode.Node
  208. ctx context.Context
  209. cancelFn context.CancelFunc
  210. c *Client
  211. mu sync.Mutex
  212. lc linkCache // tracks tree dependencies
  213. trees map[string]*clientTree // all trees
  214. // buffers for syncableTrees
  215. syncableList []*clientTree
  216. disabledList []*clientTree
  217. }
  218. func (c *Client) newRandomIterator() *randomIterator {
  219. ctx, cancel := context.WithCancel(context.Background())
  220. return &randomIterator{
  221. c: c,
  222. ctx: ctx,
  223. cancelFn: cancel,
  224. trees: make(map[string]*clientTree),
  225. }
  226. }
  227. // Node returns the current node.
  228. func (it *randomIterator) Node() *enode.Node {
  229. return it.cur
  230. }
  231. // Close closes the iterator.
  232. func (it *randomIterator) Close() {
  233. it.cancelFn()
  234. it.mu.Lock()
  235. defer it.mu.Unlock()
  236. it.trees = nil
  237. }
  238. // Next moves the iterator to the next node.
  239. func (it *randomIterator) Next() bool {
  240. it.cur = it.nextNode()
  241. return it.cur != nil
  242. }
  243. // addTree adds an enrtree:// URL to the iterator.
  244. func (it *randomIterator) addTree(url string) error {
  245. le, err := parseLink(url)
  246. if err != nil {
  247. return fmt.Errorf("invalid enrtree URL: %v", err)
  248. }
  249. it.lc.addLink("", le.str)
  250. return nil
  251. }
  252. // nextNode syncs random tree entries until it finds a node.
  253. func (it *randomIterator) nextNode() *enode.Node {
  254. for {
  255. ct := it.pickTree()
  256. if ct == nil {
  257. return nil
  258. }
  259. n, err := ct.syncRandom(it.ctx)
  260. if err != nil {
  261. if errors.Is(err, it.ctx.Err()) {
  262. return nil // context canceled.
  263. }
  264. it.c.cfg.Logger.Debug("Error in DNS random node sync", "tree", ct.loc.domain, "err", err)
  265. continue
  266. }
  267. if n != nil {
  268. return n
  269. }
  270. }
  271. }
  272. // pickTree returns a random tree to sync from.
  273. func (it *randomIterator) pickTree() *clientTree {
  274. it.mu.Lock()
  275. defer it.mu.Unlock()
  276. // First check if iterator was closed.
  277. // Need to do this here to avoid nil map access in rebuildTrees.
  278. if it.trees == nil {
  279. return nil
  280. }
  281. // Rebuild the trees map if any links have changed.
  282. if it.lc.changed {
  283. it.rebuildTrees()
  284. it.lc.changed = false
  285. }
  286. for {
  287. canSync, trees := it.syncableTrees()
  288. switch {
  289. case canSync:
  290. // Pick a random tree.
  291. return trees[rand.Intn(len(trees))]
  292. case len(trees) > 0:
  293. // No sync action can be performed on any tree right now. The only meaningful
  294. // thing to do is waiting for any root record to get updated.
  295. if !it.waitForRootUpdates(trees) {
  296. // Iterator was closed while waiting.
  297. return nil
  298. }
  299. default:
  300. // There are no trees left, the iterator was closed.
  301. return nil
  302. }
  303. }
  304. }
  305. // syncableTrees finds trees on which any meaningful sync action can be performed.
  306. func (it *randomIterator) syncableTrees() (canSync bool, trees []*clientTree) {
  307. // Resize tree lists.
  308. it.syncableList = it.syncableList[:0]
  309. it.disabledList = it.disabledList[:0]
  310. // Partition them into the two lists.
  311. for _, ct := range it.trees {
  312. if ct.canSyncRandom() {
  313. it.syncableList = append(it.syncableList, ct)
  314. } else {
  315. it.disabledList = append(it.disabledList, ct)
  316. }
  317. }
  318. if len(it.syncableList) > 0 {
  319. return true, it.syncableList
  320. }
  321. return false, it.disabledList
  322. }
  323. // waitForRootUpdates waits for the closest scheduled root check time on the given trees.
  324. func (it *randomIterator) waitForRootUpdates(trees []*clientTree) bool {
  325. var minTree *clientTree
  326. var nextCheck mclock.AbsTime
  327. for _, ct := range trees {
  328. check := ct.nextScheduledRootCheck()
  329. if minTree == nil || check < nextCheck {
  330. minTree = ct
  331. nextCheck = check
  332. }
  333. }
  334. sleep := nextCheck.Sub(it.c.clock.Now())
  335. it.c.cfg.Logger.Debug("DNS iterator waiting for root updates", "sleep", sleep, "tree", minTree.loc.domain)
  336. timeout := it.c.clock.NewTimer(sleep)
  337. defer timeout.Stop()
  338. select {
  339. case <-timeout.C():
  340. return true
  341. case <-it.ctx.Done():
  342. return false // Iterator was closed.
  343. }
  344. }
  345. // rebuildTrees rebuilds the 'trees' map.
  346. func (it *randomIterator) rebuildTrees() {
  347. // Delete removed trees.
  348. for loc := range it.trees {
  349. if !it.lc.isReferenced(loc) {
  350. delete(it.trees, loc)
  351. }
  352. }
  353. // Add new trees.
  354. for loc := range it.lc.backrefs {
  355. if it.trees[loc] == nil {
  356. link, _ := parseLink(linkPrefix + loc)
  357. it.trees[loc] = newClientTree(it.c, &it.lc, link)
  358. }
  359. }
  360. }