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.

809 lines
20 KiB

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