You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

816 lines
20 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. // Modified for Tendermint
  2. // Originally Copyright (c) 2013-2014 Conformal Systems LLC.
  3. // https://github.com/conformal/btcd/blob/master/LICENSE
  4. package p2p
  5. import (
  6. "encoding/binary"
  7. "encoding/json"
  8. "fmt"
  9. "math"
  10. "math/rand"
  11. "net"
  12. "os"
  13. "sync"
  14. "sync/atomic"
  15. "time"
  16. . "github.com/tendermint/tendermint/common"
  17. )
  18. const (
  19. // addresses under which the address manager will claim to need more addresses.
  20. needAddressThreshold = 1000
  21. // interval used to dump the address cache to disk for future use.
  22. dumpAddressInterval = time.Minute * 2
  23. // max addresses in each old address bucket.
  24. oldBucketSize = 64
  25. // buckets we split old addresses over.
  26. oldBucketCount = 64
  27. // max addresses in each new address bucket.
  28. newBucketSize = 64
  29. // buckets that we spread new addresses over.
  30. newBucketCount = 256
  31. // old buckets over which an address group will be spread.
  32. oldBucketsPerGroup = 4
  33. // new buckets over which an source address group will be spread.
  34. newBucketsPerGroup = 32
  35. // buckets a frequently seen new address may end up in.
  36. maxNewBucketsPerAddress = 4
  37. // days before which we assume an address has vanished
  38. // if we have not seen it announced in that long.
  39. numMissingDays = 30
  40. // tries without a single success before we assume an address is bad.
  41. numRetries = 3
  42. // max failures we will accept without a success before considering an address bad.
  43. maxFailures = 10
  44. // days since the last success before we will consider evicting an address.
  45. minBadDays = 7
  46. // % of total addresses known returned by GetSelection.
  47. getSelectionPercent = 23
  48. // min addresses that must be returned by GetSelection. Useful for bootstrapping.
  49. minGetSelection = 32
  50. // max addresses returned by GetSelection
  51. maxGetSelection = 2500
  52. // current version of the on-disk format.
  53. serializationVersion = 1
  54. )
  55. /* AddrBook - concurrency safe peer address manager */
  56. type AddrBook struct {
  57. filePath string
  58. mtx sync.Mutex
  59. rand *rand.Rand
  60. key string
  61. ourAddrs map[string]*NetAddress
  62. addrLookup map[string]*knownAddress // new & old
  63. addrNew []map[string]*knownAddress
  64. addrOld []map[string]*knownAddress
  65. started uint32
  66. stopped uint32
  67. wg sync.WaitGroup
  68. quit chan struct{}
  69. nOld int
  70. nNew int
  71. }
  72. const (
  73. bucketTypeNew = 0x01
  74. bucketTypeOld = 0x02
  75. )
  76. // Use Start to begin processing asynchronous address updates.
  77. func NewAddrBook(filePath string) *AddrBook {
  78. am := AddrBook{
  79. rand: rand.New(rand.NewSource(time.Now().UnixNano())),
  80. ourAddrs: make(map[string]*NetAddress),
  81. addrLookup: make(map[string]*knownAddress),
  82. quit: make(chan struct{}),
  83. filePath: filePath,
  84. }
  85. am.init()
  86. return &am
  87. }
  88. // When modifying this, don't forget to update loadFromFile()
  89. func (a *AddrBook) init() {
  90. a.key = CRandHex(24) // 24/2 * 8 = 96 bits
  91. // New addr buckets
  92. a.addrNew = make([]map[string]*knownAddress, newBucketCount)
  93. for i := range a.addrNew {
  94. a.addrNew[i] = make(map[string]*knownAddress)
  95. }
  96. // Old addr buckets
  97. a.addrOld = make([]map[string]*knownAddress, oldBucketCount)
  98. for i := range a.addrOld {
  99. a.addrOld[i] = make(map[string]*knownAddress)
  100. }
  101. }
  102. func (a *AddrBook) Start() {
  103. if atomic.CompareAndSwapUint32(&a.started, 0, 1) {
  104. log.Info("Starting address manager")
  105. a.loadFromFile(a.filePath)
  106. a.wg.Add(1)
  107. go a.saveRoutine()
  108. }
  109. }
  110. func (a *AddrBook) Stop() {
  111. if atomic.CompareAndSwapUint32(&a.stopped, 0, 1) {
  112. log.Info("Stopping address manager")
  113. close(a.quit)
  114. a.wg.Wait()
  115. }
  116. }
  117. func (a *AddrBook) AddOurAddress(addr *NetAddress) {
  118. a.mtx.Lock()
  119. defer a.mtx.Unlock()
  120. a.ourAddrs[addr.String()] = addr
  121. }
  122. func (a *AddrBook) OurAddresses() []*NetAddress {
  123. addrs := []*NetAddress{}
  124. for _, addr := range a.ourAddrs {
  125. addrs = append(addrs, addr)
  126. }
  127. return addrs
  128. }
  129. func (a *AddrBook) AddAddress(addr *NetAddress, src *NetAddress) {
  130. a.mtx.Lock()
  131. defer a.mtx.Unlock()
  132. a.addAddress(addr, src)
  133. }
  134. func (a *AddrBook) NeedMoreAddrs() bool {
  135. return a.Size() < needAddressThreshold
  136. }
  137. func (a *AddrBook) Size() int {
  138. a.mtx.Lock()
  139. defer a.mtx.Unlock()
  140. return a.size()
  141. }
  142. func (a *AddrBook) size() int {
  143. return a.nNew + a.nOld
  144. }
  145. // Pick an address to connect to with new/old bias.
  146. func (a *AddrBook) PickAddress(newBias int) *NetAddress {
  147. a.mtx.Lock()
  148. defer a.mtx.Unlock()
  149. if a.size() == 0 {
  150. return nil
  151. }
  152. if newBias > 100 {
  153. newBias = 100
  154. }
  155. if newBias < 0 {
  156. newBias = 0
  157. }
  158. // Bias between new and old addresses.
  159. oldCorrelation := math.Sqrt(float64(a.nOld)) * (100.0 - float64(newBias))
  160. newCorrelation := math.Sqrt(float64(a.nNew)) * float64(newBias)
  161. if (newCorrelation+oldCorrelation)*a.rand.Float64() < oldCorrelation {
  162. // pick random Old bucket.
  163. var bucket map[string]*knownAddress = nil
  164. for len(bucket) == 0 {
  165. bucket = a.addrOld[a.rand.Intn(len(a.addrOld))]
  166. }
  167. // pick a random ka from bucket.
  168. randIndex := a.rand.Intn(len(bucket))
  169. for _, ka := range bucket {
  170. if randIndex == 0 {
  171. return ka.Addr
  172. }
  173. randIndex--
  174. }
  175. panic("Should not happen")
  176. } else {
  177. // pick random New bucket.
  178. var bucket map[string]*knownAddress = nil
  179. for len(bucket) == 0 {
  180. bucket = a.addrNew[a.rand.Intn(len(a.addrNew))]
  181. }
  182. // pick a random ka from bucket.
  183. randIndex := a.rand.Intn(len(bucket))
  184. for _, ka := range bucket {
  185. if randIndex == 0 {
  186. return ka.Addr
  187. }
  188. randIndex--
  189. }
  190. panic("Should not happen")
  191. }
  192. return nil
  193. }
  194. func (a *AddrBook) MarkGood(addr *NetAddress) {
  195. a.mtx.Lock()
  196. defer a.mtx.Unlock()
  197. ka := a.addrLookup[addr.String()]
  198. if ka == nil {
  199. return
  200. }
  201. ka.markGood()
  202. if ka.isNew() {
  203. a.moveToOld(ka)
  204. }
  205. }
  206. func (a *AddrBook) MarkAttempt(addr *NetAddress) {
  207. a.mtx.Lock()
  208. defer a.mtx.Unlock()
  209. ka := a.addrLookup[addr.String()]
  210. if ka == nil {
  211. return
  212. }
  213. ka.markAttempt()
  214. }
  215. func (a *AddrBook) MarkBad(addr *NetAddress) {
  216. a.mtx.Lock()
  217. defer a.mtx.Unlock()
  218. ka := a.addrLookup[addr.String()]
  219. if ka == nil {
  220. return
  221. }
  222. // We currently just eject the address.
  223. // In the future, consider blacklisting.
  224. a.removeFromAllBuckets(ka)
  225. }
  226. /* Peer exchange */
  227. // GetSelection randomly selects some addresses (old & new). Suitable for peer-exchange protocols.
  228. func (a *AddrBook) GetSelection() []*NetAddress {
  229. a.mtx.Lock()
  230. defer a.mtx.Unlock()
  231. if a.size() == 0 {
  232. return nil
  233. }
  234. allAddr := make([]*NetAddress, a.size())
  235. i := 0
  236. for _, v := range a.addrLookup {
  237. allAddr[i] = v.Addr
  238. i++
  239. }
  240. numAddresses := MaxInt(
  241. MinInt(minGetSelection, len(allAddr)),
  242. len(allAddr)*getSelectionPercent/100)
  243. numAddresses = MinInt(maxGetSelection, numAddresses)
  244. // Fisher-Yates shuffle the array. We only need to do the first
  245. // `numAddresses' since we are throwing the rest.
  246. for i := 0; i < numAddresses; i++ {
  247. // pick a number between current index and the end
  248. j := rand.Intn(len(allAddr)-i) + i
  249. allAddr[i], allAddr[j] = allAddr[j], allAddr[i]
  250. }
  251. // slice off the limit we are willing to share.
  252. return allAddr[:numAddresses]
  253. }
  254. /* Loading & Saving */
  255. type addrBookJSON struct {
  256. Key string
  257. Addrs []*knownAddress
  258. }
  259. func (a *AddrBook) saveToFile(filePath string) {
  260. // Compile Addrs
  261. addrs := []*knownAddress{}
  262. for _, ka := range a.addrLookup {
  263. addrs = append(addrs, ka)
  264. }
  265. aJSON := &addrBookJSON{
  266. Key: a.key,
  267. Addrs: addrs,
  268. }
  269. w, err := os.Create(filePath)
  270. if err != nil {
  271. log.Error("Error opening file: ", filePath, err)
  272. return
  273. }
  274. defer w.Close()
  275. jsonBytes, err := json.MarshalIndent(aJSON, "", "\t")
  276. _, err = w.Write(jsonBytes)
  277. if err != nil {
  278. log.Error("Failed to save AddrBook to file %v: %v", filePath, err)
  279. }
  280. }
  281. func (a *AddrBook) loadFromFile(filePath string) {
  282. // If doesn't exist, do nothing.
  283. _, err := os.Stat(filePath)
  284. if os.IsNotExist(err) {
  285. return
  286. }
  287. // Load addrBookJSON{}
  288. r, err := os.Open(filePath)
  289. if err != nil {
  290. panic(fmt.Errorf("Error opening file %s: %v", filePath, err))
  291. }
  292. defer r.Close()
  293. aJSON := &addrBookJSON{}
  294. dec := json.NewDecoder(r)
  295. err = dec.Decode(aJSON)
  296. if err != nil {
  297. panic(fmt.Errorf("Error reading file %s: %v", filePath, err))
  298. }
  299. // Restore all the fields...
  300. // Restore the key
  301. a.key = aJSON.Key
  302. // Restore .addrNew & .addrOld
  303. for _, ka := range aJSON.Addrs {
  304. for _, bucketIndex := range ka.Buckets {
  305. bucket := a.getBucket(ka.BucketType, bucketIndex)
  306. bucket[ka.Addr.String()] = ka
  307. }
  308. a.addrLookup[ka.Addr.String()] = ka
  309. if ka.BucketType == bucketTypeNew {
  310. a.nNew++
  311. } else {
  312. a.nOld++
  313. }
  314. }
  315. }
  316. /* Private methods */
  317. func (a *AddrBook) saveRoutine() {
  318. dumpAddressTicker := time.NewTicker(dumpAddressInterval)
  319. out:
  320. for {
  321. select {
  322. case <-dumpAddressTicker.C:
  323. log.Debug("Saving book to file (%v)", a.Size())
  324. a.saveToFile(a.filePath)
  325. case <-a.quit:
  326. break out
  327. }
  328. }
  329. dumpAddressTicker.Stop()
  330. a.saveToFile(a.filePath)
  331. a.wg.Done()
  332. log.Info("Address handler done")
  333. }
  334. func (a *AddrBook) getBucket(bucketType byte, bucketIdx int) map[string]*knownAddress {
  335. switch bucketType {
  336. case bucketTypeNew:
  337. return a.addrNew[bucketIdx]
  338. case bucketTypeOld:
  339. return a.addrOld[bucketIdx]
  340. default:
  341. panic("Should not happen")
  342. }
  343. }
  344. // Adds ka to new bucket. Returns false if it couldn't do it cuz buckets full.
  345. // NOTE: currently it always returns true.
  346. func (a *AddrBook) addToNewBucket(ka *knownAddress, bucketIdx int) bool {
  347. // Sanity check
  348. if ka.isOld() {
  349. log.Warning("Cannot add address already in old bucket to a new bucket: %v", ka)
  350. return false
  351. }
  352. addrStr := ka.Addr.String()
  353. bucket := a.getBucket(bucketTypeNew, bucketIdx)
  354. // Already exists?
  355. if _, ok := bucket[addrStr]; ok {
  356. return true
  357. }
  358. // Enforce max addresses.
  359. if len(bucket) > newBucketSize {
  360. log.Info("new bucket is full, expiring old ")
  361. a.expireNew(bucketIdx)
  362. }
  363. // Add to bucket.
  364. bucket[addrStr] = ka
  365. if ka.addBucketRef(bucketIdx) == 1 {
  366. a.nNew++
  367. }
  368. // Ensure in addrLookup
  369. a.addrLookup[addrStr] = ka
  370. return true
  371. }
  372. // Adds ka to old bucket. Returns false if it couldn't do it cuz buckets full.
  373. func (a *AddrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool {
  374. // Sanity check
  375. if ka.isNew() {
  376. log.Warning("Cannot add new address to old bucket: %v", ka)
  377. return false
  378. }
  379. if len(ka.Buckets) != 0 {
  380. log.Warning("Cannot add already old address to another old bucket: %v", ka)
  381. return false
  382. }
  383. addrStr := ka.Addr.String()
  384. bucket := a.getBucket(bucketTypeNew, bucketIdx)
  385. // Already exists?
  386. if _, ok := bucket[addrStr]; ok {
  387. return true
  388. }
  389. // Enforce max addresses.
  390. if len(bucket) > oldBucketSize {
  391. return false
  392. }
  393. // Add to bucket.
  394. bucket[addrStr] = ka
  395. if ka.addBucketRef(bucketIdx) == 1 {
  396. a.nOld++
  397. }
  398. // Ensure in addrLookup
  399. a.addrLookup[addrStr] = ka
  400. return true
  401. }
  402. func (a *AddrBook) removeFromBucket(ka *knownAddress, bucketType byte, bucketIdx int) {
  403. if ka.BucketType != bucketType {
  404. log.Warning("Bucket type mismatch: %v", ka)
  405. return
  406. }
  407. bucket := a.getBucket(bucketType, bucketIdx)
  408. delete(bucket, ka.Addr.String())
  409. if ka.removeBucketRef(bucketIdx) == 0 {
  410. if bucketType == bucketTypeNew {
  411. a.nNew--
  412. } else {
  413. a.nOld--
  414. }
  415. delete(a.addrLookup, ka.Addr.String())
  416. }
  417. }
  418. func (a *AddrBook) removeFromAllBuckets(ka *knownAddress) {
  419. for _, bucketIdx := range ka.Buckets {
  420. bucket := a.getBucket(ka.BucketType, bucketIdx)
  421. delete(bucket, ka.Addr.String())
  422. }
  423. ka.Buckets = nil
  424. if ka.BucketType == bucketTypeNew {
  425. a.nNew--
  426. } else {
  427. a.nOld--
  428. }
  429. delete(a.addrLookup, ka.Addr.String())
  430. }
  431. func (a *AddrBook) pickOldest(bucketType byte, bucketIdx int) *knownAddress {
  432. bucket := a.getBucket(bucketType, bucketIdx)
  433. var oldest *knownAddress
  434. for _, ka := range bucket {
  435. if oldest == nil || ka.LastAttempt.Before(oldest.LastAttempt) {
  436. oldest = ka
  437. }
  438. }
  439. return oldest
  440. }
  441. func (a *AddrBook) addAddress(addr, src *NetAddress) {
  442. if !addr.Routable() {
  443. log.Warning("Cannot add non-routable address %v", addr)
  444. return
  445. }
  446. if _, ok := a.ourAddrs[addr.String()]; ok {
  447. // Ignore our own listener address.
  448. return
  449. }
  450. ka := a.addrLookup[addr.String()]
  451. if ka != nil {
  452. // Already old.
  453. if ka.isOld() {
  454. return
  455. }
  456. // Already in max new buckets.
  457. if len(ka.Buckets) == maxNewBucketsPerAddress {
  458. return
  459. }
  460. // The more entries we have, the less likely we are to add more.
  461. factor := int32(2 * len(ka.Buckets))
  462. if a.rand.Int31n(factor) != 0 {
  463. return
  464. }
  465. } else {
  466. ka = newKnownAddress(addr, src)
  467. }
  468. bucket := a.calcNewBucket(addr, src)
  469. a.addToNewBucket(ka, bucket)
  470. log.Info("Added new address %s for a total of %d addresses", addr, a.size())
  471. }
  472. // Make space in the new buckets by expiring the really bad entries.
  473. // If no bad entries are available we remove the oldest.
  474. func (a *AddrBook) expireNew(bucketIdx int) {
  475. for addrStr, ka := range a.addrNew[bucketIdx] {
  476. // If an entry is bad, throw it away
  477. if ka.isBad() {
  478. log.Info("expiring bad address %v", addrStr)
  479. a.removeFromBucket(ka, bucketTypeNew, bucketIdx)
  480. return
  481. }
  482. }
  483. // If we haven't thrown out a bad entry, throw out the oldest entry
  484. oldest := a.pickOldest(bucketTypeNew, bucketIdx)
  485. a.removeFromBucket(oldest, bucketTypeNew, bucketIdx)
  486. }
  487. // Promotes an address from new to old.
  488. // TODO: Move to old probabilistically.
  489. // The better a node is, the less likely it should be evicted from an old bucket.
  490. func (a *AddrBook) moveToOld(ka *knownAddress) {
  491. // Sanity check
  492. if ka.isOld() {
  493. log.Warning("Cannot promote address that is already old %v", ka)
  494. return
  495. }
  496. if len(ka.Buckets) == 0 {
  497. log.Warning("Cannot promote address that isn't in any new buckets %v", ka)
  498. return
  499. }
  500. // Remember one of the buckets in which ka is in.
  501. freedBucket := ka.Buckets[0]
  502. // Remove from all (new) buckets.
  503. a.removeFromAllBuckets(ka)
  504. // It's officially old now.
  505. ka.BucketType = bucketTypeOld
  506. // Try to add it to its oldBucket destination.
  507. oldBucketIdx := a.calcOldBucket(ka.Addr)
  508. added := a.addToOldBucket(ka, oldBucketIdx)
  509. if !added {
  510. // No room, must evict something
  511. oldest := a.pickOldest(bucketTypeOld, oldBucketIdx)
  512. a.removeFromBucket(oldest, bucketTypeOld, oldBucketIdx)
  513. // Find new bucket to put oldest in
  514. newBucketIdx := a.calcNewBucket(oldest.Addr, oldest.Src)
  515. added := a.addToNewBucket(oldest, newBucketIdx)
  516. // No space in newBucket either, just put it in freedBucket from above.
  517. if !added {
  518. added := a.addToNewBucket(oldest, freedBucket)
  519. if !added {
  520. log.Warning("Could not migrate oldest %v to freedBucket %v", oldest, freedBucket)
  521. }
  522. }
  523. // Finally, add to bucket again.
  524. added = a.addToOldBucket(ka, oldBucketIdx)
  525. if !added {
  526. log.Warning("Could not re-add ka %v to oldBucketIdx %v", ka, oldBucketIdx)
  527. }
  528. }
  529. }
  530. // doublesha256(key + sourcegroup +
  531. // int64(doublesha256(key + group + sourcegroup))%bucket_per_source_group) % num_new_buckes
  532. func (a *AddrBook) calcNewBucket(addr, src *NetAddress) int {
  533. data1 := []byte{}
  534. data1 = append(data1, []byte(a.key)...)
  535. data1 = append(data1, []byte(groupKey(addr))...)
  536. data1 = append(data1, []byte(groupKey(src))...)
  537. hash1 := doubleSha256(data1)
  538. hash64 := binary.LittleEndian.Uint64(hash1)
  539. hash64 %= newBucketsPerGroup
  540. var hashbuf [8]byte
  541. binary.LittleEndian.PutUint64(hashbuf[:], hash64)
  542. data2 := []byte{}
  543. data2 = append(data2, []byte(a.key)...)
  544. data2 = append(data2, groupKey(src)...)
  545. data2 = append(data2, hashbuf[:]...)
  546. hash2 := doubleSha256(data2)
  547. return int(binary.LittleEndian.Uint64(hash2) % newBucketCount)
  548. }
  549. // doublesha256(key + group + truncate_to_64bits(doublesha256(key + addr))%buckets_per_group) % num_buckets
  550. func (a *AddrBook) calcOldBucket(addr *NetAddress) int {
  551. data1 := []byte{}
  552. data1 = append(data1, []byte(a.key)...)
  553. data1 = append(data1, []byte(addr.String())...)
  554. hash1 := doubleSha256(data1)
  555. hash64 := binary.LittleEndian.Uint64(hash1)
  556. hash64 %= oldBucketsPerGroup
  557. var hashbuf [8]byte
  558. binary.LittleEndian.PutUint64(hashbuf[:], hash64)
  559. data2 := []byte{}
  560. data2 = append(data2, []byte(a.key)...)
  561. data2 = append(data2, groupKey(addr)...)
  562. data2 = append(data2, hashbuf[:]...)
  563. hash2 := doubleSha256(data2)
  564. return int(binary.LittleEndian.Uint64(hash2) % oldBucketCount)
  565. }
  566. // Return a string representing the network group of this address.
  567. // This is the /16 for IPv6, the /32 (/36 for he.net) for IPv6, the string
  568. // "local" for a local address and the string "unroutable for an unroutable
  569. // address.
  570. func groupKey(na *NetAddress) string {
  571. if na.Local() {
  572. return "local"
  573. }
  574. if !na.Routable() {
  575. return "unroutable"
  576. }
  577. if ipv4 := na.IP.To4(); ipv4 != nil {
  578. return (&net.IPNet{IP: na.IP, Mask: net.CIDRMask(16, 32)}).String()
  579. }
  580. if na.RFC6145() || na.RFC6052() {
  581. // last four bytes are the ip address
  582. ip := net.IP(na.IP[12:16])
  583. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  584. }
  585. if na.RFC3964() {
  586. ip := net.IP(na.IP[2:7])
  587. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  588. }
  589. if na.RFC4380() {
  590. // teredo tunnels have the last 4 bytes as the v4 address XOR
  591. // 0xff.
  592. ip := net.IP(make([]byte, 4))
  593. for i, byte := range na.IP[12:16] {
  594. ip[i] = byte ^ 0xff
  595. }
  596. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  597. }
  598. // OK, so now we know ourselves to be a IPv6 address.
  599. // bitcoind uses /32 for everything, except for Hurricane Electric's
  600. // (he.net) IP range, which it uses /36 for.
  601. bits := 32
  602. heNet := &net.IPNet{IP: net.ParseIP("2001:470::"),
  603. Mask: net.CIDRMask(32, 128)}
  604. if heNet.Contains(na.IP) {
  605. bits = 36
  606. }
  607. return (&net.IPNet{IP: na.IP, Mask: net.CIDRMask(bits, 128)}).String()
  608. }
  609. //-----------------------------------------------------------------------------
  610. /*
  611. knownAddress
  612. tracks information about a known network address that is used
  613. to determine how viable an address is.
  614. */
  615. type knownAddress struct {
  616. Addr *NetAddress
  617. Src *NetAddress
  618. Attempts uint32
  619. LastAttempt time.Time
  620. LastSuccess time.Time
  621. BucketType byte
  622. Buckets []int
  623. }
  624. func newKnownAddress(addr *NetAddress, src *NetAddress) *knownAddress {
  625. return &knownAddress{
  626. Addr: addr,
  627. Src: src,
  628. Attempts: 0,
  629. LastAttempt: time.Now(),
  630. BucketType: bucketTypeNew,
  631. Buckets: nil,
  632. }
  633. }
  634. func (ka *knownAddress) isOld() bool {
  635. return ka.BucketType == bucketTypeOld
  636. }
  637. func (ka *knownAddress) isNew() bool {
  638. return ka.BucketType == bucketTypeNew
  639. }
  640. func (ka *knownAddress) markAttempt() {
  641. now := time.Now()
  642. ka.LastAttempt = now
  643. ka.Attempts += 1
  644. }
  645. func (ka *knownAddress) markGood() {
  646. now := time.Now()
  647. ka.LastAttempt = now
  648. ka.Attempts = 0
  649. ka.LastSuccess = now
  650. }
  651. func (ka *knownAddress) addBucketRef(bucketIdx int) int {
  652. for _, bucket := range ka.Buckets {
  653. if bucket == bucketIdx {
  654. log.Warning("Bucket already exists in ka.Buckets: %v", ka)
  655. return -1
  656. }
  657. }
  658. ka.Buckets = append(ka.Buckets, bucketIdx)
  659. return len(ka.Buckets)
  660. }
  661. func (ka *knownAddress) removeBucketRef(bucketIdx int) int {
  662. buckets := []int{}
  663. for _, bucket := range ka.Buckets {
  664. if bucket != bucketIdx {
  665. buckets = append(buckets, bucket)
  666. }
  667. }
  668. if len(buckets) != len(ka.Buckets)-1 {
  669. log.Warning("bucketIdx not found in ka.Buckets: %v", ka)
  670. return -1
  671. }
  672. ka.Buckets = buckets
  673. return len(ka.Buckets)
  674. }
  675. /*
  676. An address is bad if the address in question has not been tried in the last
  677. minute and meets one of the following criteria:
  678. 1) It claims to be from the future
  679. 2) It hasn't been seen in over a month
  680. 3) It has failed at least three times and never succeeded
  681. 4) It has failed ten times in the last week
  682. All addresses that meet these criteria are assumed to be worthless and not
  683. worth keeping hold of.
  684. */
  685. func (ka *knownAddress) isBad() bool {
  686. // Has been attempted in the last minute --> good
  687. if ka.LastAttempt.Before(time.Now().Add(-1 * time.Minute)) {
  688. return false
  689. }
  690. // Over a month old?
  691. if ka.LastAttempt.After(time.Now().Add(-1 * numMissingDays * time.Hour * 24)) {
  692. return true
  693. }
  694. // Never succeeded?
  695. if ka.LastSuccess.IsZero() && ka.Attempts >= numRetries {
  696. return true
  697. }
  698. // Hasn't succeeded in too long?
  699. if ka.LastSuccess.Before(time.Now().Add(-1*minBadDays*time.Hour*24)) &&
  700. ka.Attempts >= maxFailures {
  701. return true
  702. }
  703. return false
  704. }