github.com/DFWallet/tendermint-cosmos@v0.0.2/p2p/pex/addrbook.go (about) 1 // Modified for Tendermint 2 // Originally Copyright (c) 2013-2014 Conformal Systems LLC. 3 // https://github.com/conformal/btcd/blob/master/LICENSE 4 5 package pex 6 7 import ( 8 crand "crypto/rand" 9 "encoding/binary" 10 "fmt" 11 "math" 12 "math/rand" 13 "net" 14 "sync" 15 "time" 16 17 "github.com/minio/highwayhash" 18 19 "github.com/DFWallet/tendermint-cosmos/crypto" 20 tmmath "github.com/DFWallet/tendermint-cosmos/libs/math" 21 tmrand "github.com/DFWallet/tendermint-cosmos/libs/rand" 22 "github.com/DFWallet/tendermint-cosmos/libs/service" 23 tmsync "github.com/DFWallet/tendermint-cosmos/libs/sync" 24 "github.com/DFWallet/tendermint-cosmos/p2p" 25 ) 26 27 const ( 28 bucketTypeNew = 0x01 29 bucketTypeOld = 0x02 30 ) 31 32 // AddrBook is an address book used for tracking peers 33 // so we can gossip about them to others and select 34 // peers to dial. 35 // TODO: break this up? 36 type AddrBook interface { 37 service.Service 38 39 // Add our own addresses so we don't later add ourselves 40 AddOurAddress(*p2p.NetAddress) 41 // Check if it is our address 42 OurAddress(*p2p.NetAddress) bool 43 44 AddPrivateIDs([]string) 45 46 // Add and remove an address 47 AddAddress(addr *p2p.NetAddress, src *p2p.NetAddress) error 48 RemoveAddress(*p2p.NetAddress) 49 50 // Check if the address is in the book 51 HasAddress(*p2p.NetAddress) bool 52 53 // Do we need more peers? 54 NeedMoreAddrs() bool 55 // Is Address Book Empty? Answer should not depend on being in your own 56 // address book, or private peers 57 Empty() bool 58 59 // Pick an address to dial 60 PickAddress(biasTowardsNewAddrs int) *p2p.NetAddress 61 62 // Mark address 63 MarkGood(p2p.ID) 64 MarkAttempt(*p2p.NetAddress) 65 MarkBad(*p2p.NetAddress, time.Duration) // Move peer to bad peers list 66 // Add bad peers back to addrBook 67 ReinstateBadPeers() 68 69 IsGood(*p2p.NetAddress) bool 70 IsBanned(*p2p.NetAddress) bool 71 72 // Send a selection of addresses to peers 73 GetSelection() []*p2p.NetAddress 74 // Send a selection of addresses with bias 75 GetSelectionWithBias(biasTowardsNewAddrs int) []*p2p.NetAddress 76 77 Size() int 78 79 // Persist to disk 80 Save() 81 } 82 83 var _ AddrBook = (*addrBook)(nil) 84 85 // addrBook - concurrency safe peer address manager. 86 // Implements AddrBook. 87 type addrBook struct { 88 service.BaseService 89 90 // accessed concurrently 91 mtx tmsync.Mutex 92 rand *tmrand.Rand 93 ourAddrs map[string]struct{} 94 privateIDs map[p2p.ID]struct{} 95 addrLookup map[p2p.ID]*knownAddress // new & old 96 badPeers map[p2p.ID]*knownAddress // blacklisted peers 97 bucketsOld []map[string]*knownAddress 98 bucketsNew []map[string]*knownAddress 99 nOld int 100 nNew int 101 102 // immutable after creation 103 filePath string 104 key string // random prefix for bucket placement 105 routabilityStrict bool 106 hashKey []byte 107 108 wg sync.WaitGroup 109 } 110 111 func newHashKey() []byte { 112 result := make([]byte, highwayhash.Size) 113 crand.Read(result) //nolint:errcheck // ignore error 114 return result 115 } 116 117 // NewAddrBook creates a new address book. 118 // Use Start to begin processing asynchronous address updates. 119 func NewAddrBook(filePath string, routabilityStrict bool) AddrBook { 120 am := &addrBook{ 121 rand: tmrand.NewRand(), 122 ourAddrs: make(map[string]struct{}), 123 privateIDs: make(map[p2p.ID]struct{}), 124 addrLookup: make(map[p2p.ID]*knownAddress), 125 badPeers: make(map[p2p.ID]*knownAddress), 126 filePath: filePath, 127 routabilityStrict: routabilityStrict, 128 hashKey: newHashKey(), 129 } 130 am.init() 131 am.BaseService = *service.NewBaseService(nil, "AddrBook", am) 132 return am 133 } 134 135 // Initialize the buckets. 136 // When modifying this, don't forget to update loadFromFile() 137 func (a *addrBook) init() { 138 a.key = crypto.CRandHex(24) // 24/2 * 8 = 96 bits 139 // New addr buckets 140 a.bucketsNew = make([]map[string]*knownAddress, newBucketCount) 141 for i := range a.bucketsNew { 142 a.bucketsNew[i] = make(map[string]*knownAddress) 143 } 144 // Old addr buckets 145 a.bucketsOld = make([]map[string]*knownAddress, oldBucketCount) 146 for i := range a.bucketsOld { 147 a.bucketsOld[i] = make(map[string]*knownAddress) 148 } 149 } 150 151 // OnStart implements Service. 152 func (a *addrBook) OnStart() error { 153 if err := a.BaseService.OnStart(); err != nil { 154 return err 155 } 156 a.loadFromFile(a.filePath) 157 158 // wg.Add to ensure that any invocation of .Wait() 159 // later on will wait for saveRoutine to terminate. 160 a.wg.Add(1) 161 go a.saveRoutine() 162 163 return nil 164 } 165 166 // OnStop implements Service. 167 func (a *addrBook) OnStop() { 168 a.BaseService.OnStop() 169 } 170 171 func (a *addrBook) Wait() { 172 a.wg.Wait() 173 } 174 175 func (a *addrBook) FilePath() string { 176 return a.filePath 177 } 178 179 //------------------------------------------------------- 180 181 // AddOurAddress one of our addresses. 182 func (a *addrBook) AddOurAddress(addr *p2p.NetAddress) { 183 a.mtx.Lock() 184 defer a.mtx.Unlock() 185 186 a.Logger.Info("Add our address to book", "addr", addr) 187 a.ourAddrs[addr.String()] = struct{}{} 188 } 189 190 // OurAddress returns true if it is our address. 191 func (a *addrBook) OurAddress(addr *p2p.NetAddress) bool { 192 a.mtx.Lock() 193 defer a.mtx.Unlock() 194 195 _, ok := a.ourAddrs[addr.String()] 196 return ok 197 } 198 199 func (a *addrBook) AddPrivateIDs(ids []string) { 200 a.mtx.Lock() 201 defer a.mtx.Unlock() 202 203 for _, id := range ids { 204 a.privateIDs[p2p.ID(id)] = struct{}{} 205 } 206 } 207 208 // AddAddress implements AddrBook 209 // Add address to a "new" bucket. If it's already in one, only add it probabilistically. 210 // Returns error if the addr is non-routable. Does not add self. 211 // NOTE: addr must not be nil 212 func (a *addrBook) AddAddress(addr *p2p.NetAddress, src *p2p.NetAddress) error { 213 a.mtx.Lock() 214 defer a.mtx.Unlock() 215 216 return a.addAddress(addr, src) 217 } 218 219 // RemoveAddress implements AddrBook - removes the address from the book. 220 func (a *addrBook) RemoveAddress(addr *p2p.NetAddress) { 221 a.mtx.Lock() 222 defer a.mtx.Unlock() 223 224 a.removeAddress(addr) 225 } 226 227 // IsGood returns true if peer was ever marked as good and haven't 228 // done anything wrong since then. 229 func (a *addrBook) IsGood(addr *p2p.NetAddress) bool { 230 a.mtx.Lock() 231 defer a.mtx.Unlock() 232 233 return a.addrLookup[addr.ID].isOld() 234 } 235 236 // IsBanned returns true if the peer is currently banned 237 func (a *addrBook) IsBanned(addr *p2p.NetAddress) bool { 238 a.mtx.Lock() 239 _, ok := a.badPeers[addr.ID] 240 a.mtx.Unlock() 241 242 return ok 243 } 244 245 // HasAddress returns true if the address is in the book. 246 func (a *addrBook) HasAddress(addr *p2p.NetAddress) bool { 247 a.mtx.Lock() 248 defer a.mtx.Unlock() 249 250 ka := a.addrLookup[addr.ID] 251 return ka != nil 252 } 253 254 // NeedMoreAddrs implements AddrBook - returns true if there are not have enough addresses in the book. 255 func (a *addrBook) NeedMoreAddrs() bool { 256 return a.Size() < needAddressThreshold 257 } 258 259 // Empty implements AddrBook - returns true if there are no addresses in the address book. 260 // Does not count the peer appearing in its own address book, or private peers. 261 func (a *addrBook) Empty() bool { 262 return a.Size() == 0 263 } 264 265 // PickAddress implements AddrBook. It picks an address to connect to. 266 // The address is picked randomly from an old or new bucket according 267 // to the biasTowardsNewAddrs argument, which must be between [0, 100] (or else is truncated to that range) 268 // and determines how biased we are to pick an address from a new bucket. 269 // PickAddress returns nil if the AddrBook is empty or if we try to pick 270 // from an empty bucket. 271 func (a *addrBook) PickAddress(biasTowardsNewAddrs int) *p2p.NetAddress { 272 a.mtx.Lock() 273 defer a.mtx.Unlock() 274 275 bookSize := a.size() 276 if bookSize <= 0 { 277 if bookSize < 0 { 278 panic(fmt.Sprintf("Addrbook size %d (new: %d + old: %d) is less than 0", a.nNew+a.nOld, a.nNew, a.nOld)) 279 } 280 return nil 281 } 282 if biasTowardsNewAddrs > 100 { 283 biasTowardsNewAddrs = 100 284 } 285 if biasTowardsNewAddrs < 0 { 286 biasTowardsNewAddrs = 0 287 } 288 289 // Bias between new and old addresses. 290 oldCorrelation := math.Sqrt(float64(a.nOld)) * (100.0 - float64(biasTowardsNewAddrs)) 291 newCorrelation := math.Sqrt(float64(a.nNew)) * float64(biasTowardsNewAddrs) 292 293 // pick a random peer from a random bucket 294 var bucket map[string]*knownAddress 295 pickFromOldBucket := (newCorrelation+oldCorrelation)*a.rand.Float64() < oldCorrelation 296 if (pickFromOldBucket && a.nOld == 0) || 297 (!pickFromOldBucket && a.nNew == 0) { 298 return nil 299 } 300 // loop until we pick a random non-empty bucket 301 for len(bucket) == 0 { 302 if pickFromOldBucket { 303 bucket = a.bucketsOld[a.rand.Intn(len(a.bucketsOld))] 304 } else { 305 bucket = a.bucketsNew[a.rand.Intn(len(a.bucketsNew))] 306 } 307 } 308 // pick a random index and loop over the map to return that index 309 randIndex := a.rand.Intn(len(bucket)) 310 for _, ka := range bucket { 311 if randIndex == 0 { 312 return ka.Addr 313 } 314 randIndex-- 315 } 316 return nil 317 } 318 319 // MarkGood implements AddrBook - it marks the peer as good and 320 // moves it into an "old" bucket. 321 func (a *addrBook) MarkGood(id p2p.ID) { 322 a.mtx.Lock() 323 defer a.mtx.Unlock() 324 325 ka := a.addrLookup[id] 326 if ka == nil { 327 return 328 } 329 ka.markGood() 330 if ka.isNew() { 331 if err := a.moveToOld(ka); err != nil { 332 a.Logger.Error("Error moving address to old", "err", err) 333 } 334 } 335 } 336 337 // MarkAttempt implements AddrBook - it marks that an attempt was made to connect to the address. 338 func (a *addrBook) MarkAttempt(addr *p2p.NetAddress) { 339 a.mtx.Lock() 340 defer a.mtx.Unlock() 341 342 ka := a.addrLookup[addr.ID] 343 if ka == nil { 344 return 345 } 346 ka.markAttempt() 347 } 348 349 // MarkBad implements AddrBook. Kicks address out from book, places 350 // the address in the badPeers pool. 351 func (a *addrBook) MarkBad(addr *p2p.NetAddress, banTime time.Duration) { 352 a.mtx.Lock() 353 defer a.mtx.Unlock() 354 355 if a.addBadPeer(addr, banTime) { 356 a.removeAddress(addr) 357 } 358 } 359 360 // ReinstateBadPeers removes bad peers from ban list and places them into a new 361 // bucket. 362 func (a *addrBook) ReinstateBadPeers() { 363 a.mtx.Lock() 364 defer a.mtx.Unlock() 365 366 for _, ka := range a.badPeers { 367 if ka.isBanned() { 368 continue 369 } 370 371 bucket, err := a.calcNewBucket(ka.Addr, ka.Src) 372 if err != nil { 373 a.Logger.Error("Failed to calculate new bucket (bad peer won't be reinstantiated)", 374 "addr", ka.Addr, "err", err) 375 continue 376 } 377 378 if err := a.addToNewBucket(ka, bucket); err != nil { 379 a.Logger.Error("Error adding peer to new bucket", "err", err) 380 } 381 delete(a.badPeers, ka.ID()) 382 383 a.Logger.Info("Reinstated address", "addr", ka.Addr) 384 } 385 } 386 387 // GetSelection implements AddrBook. 388 // It randomly selects some addresses (old & new). Suitable for peer-exchange protocols. 389 // Must never return a nil address. 390 func (a *addrBook) GetSelection() []*p2p.NetAddress { 391 a.mtx.Lock() 392 defer a.mtx.Unlock() 393 394 bookSize := a.size() 395 if bookSize <= 0 { 396 if bookSize < 0 { 397 panic(fmt.Sprintf("Addrbook size %d (new: %d + old: %d) is less than 0", a.nNew+a.nOld, a.nNew, a.nOld)) 398 } 399 return nil 400 } 401 402 numAddresses := tmmath.MaxInt( 403 tmmath.MinInt(minGetSelection, bookSize), 404 bookSize*getSelectionPercent/100) 405 numAddresses = tmmath.MinInt(maxGetSelection, numAddresses) 406 407 // XXX: instead of making a list of all addresses, shuffling, and slicing a random chunk, 408 // could we just select a random numAddresses of indexes? 409 allAddr := make([]*p2p.NetAddress, bookSize) 410 i := 0 411 for _, ka := range a.addrLookup { 412 allAddr[i] = ka.Addr 413 i++ 414 } 415 416 // Fisher-Yates shuffle the array. We only need to do the first 417 // `numAddresses' since we are throwing the rest. 418 for i := 0; i < numAddresses; i++ { 419 // pick a number between current index and the end 420 j := tmrand.Intn(len(allAddr)-i) + i 421 allAddr[i], allAddr[j] = allAddr[j], allAddr[i] 422 } 423 424 // slice off the limit we are willing to share. 425 return allAddr[:numAddresses] 426 } 427 428 func percentageOfNum(p, n int) int { 429 return int(math.Round((float64(p) / float64(100)) * float64(n))) 430 } 431 432 // GetSelectionWithBias implements AddrBook. 433 // It randomly selects some addresses (old & new). Suitable for peer-exchange protocols. 434 // Must never return a nil address. 435 // 436 // Each address is picked randomly from an old or new bucket according to the 437 // biasTowardsNewAddrs argument, which must be between [0, 100] (or else is truncated to 438 // that range) and determines how biased we are to pick an address from a new 439 // bucket. 440 func (a *addrBook) GetSelectionWithBias(biasTowardsNewAddrs int) []*p2p.NetAddress { 441 a.mtx.Lock() 442 defer a.mtx.Unlock() 443 444 bookSize := a.size() 445 if bookSize <= 0 { 446 if bookSize < 0 { 447 panic(fmt.Sprintf("Addrbook size %d (new: %d + old: %d) is less than 0", a.nNew+a.nOld, a.nNew, a.nOld)) 448 } 449 return nil 450 } 451 452 if biasTowardsNewAddrs > 100 { 453 biasTowardsNewAddrs = 100 454 } 455 if biasTowardsNewAddrs < 0 { 456 biasTowardsNewAddrs = 0 457 } 458 459 numAddresses := tmmath.MaxInt( 460 tmmath.MinInt(minGetSelection, bookSize), 461 bookSize*getSelectionPercent/100) 462 numAddresses = tmmath.MinInt(maxGetSelection, numAddresses) 463 464 // number of new addresses that, if possible, should be in the beginning of the selection 465 // if there are no enough old addrs, will choose new addr instead. 466 numRequiredNewAdd := tmmath.MaxInt(percentageOfNum(biasTowardsNewAddrs, numAddresses), numAddresses-a.nOld) 467 selection := a.randomPickAddresses(bucketTypeNew, numRequiredNewAdd) 468 selection = append(selection, a.randomPickAddresses(bucketTypeOld, numAddresses-len(selection))...) 469 return selection 470 } 471 472 //------------------------------------------------ 473 474 // Size returns the number of addresses in the book. 475 func (a *addrBook) Size() int { 476 a.mtx.Lock() 477 defer a.mtx.Unlock() 478 479 return a.size() 480 } 481 482 func (a *addrBook) size() int { 483 return a.nNew + a.nOld 484 } 485 486 //---------------------------------------------------------- 487 488 // Save persists the address book to disk. 489 func (a *addrBook) Save() { 490 a.saveToFile(a.filePath) // thread safe 491 } 492 493 func (a *addrBook) saveRoutine() { 494 defer a.wg.Done() 495 496 saveFileTicker := time.NewTicker(dumpAddressInterval) 497 out: 498 for { 499 select { 500 case <-saveFileTicker.C: 501 a.saveToFile(a.filePath) 502 case <-a.Quit(): 503 break out 504 } 505 } 506 saveFileTicker.Stop() 507 a.saveToFile(a.filePath) 508 } 509 510 //---------------------------------------------------------- 511 512 func (a *addrBook) getBucket(bucketType byte, bucketIdx int) map[string]*knownAddress { 513 switch bucketType { 514 case bucketTypeNew: 515 return a.bucketsNew[bucketIdx] 516 case bucketTypeOld: 517 return a.bucketsOld[bucketIdx] 518 default: 519 panic("Invalid bucket type") 520 } 521 } 522 523 // Adds ka to new bucket. Returns false if it couldn't do it cuz buckets full. 524 // NOTE: currently it always returns true. 525 func (a *addrBook) addToNewBucket(ka *knownAddress, bucketIdx int) error { 526 // Consistency check to ensure we don't add an already known address 527 if ka.isOld() { 528 return errAddrBookOldAddressNewBucket{ka.Addr, bucketIdx} 529 } 530 531 addrStr := ka.Addr.String() 532 bucket := a.getBucket(bucketTypeNew, bucketIdx) 533 534 // Already exists? 535 if _, ok := bucket[addrStr]; ok { 536 return nil 537 } 538 539 // Enforce max addresses. 540 if len(bucket) > newBucketSize { 541 a.Logger.Info("new bucket is full, expiring new") 542 a.expireNew(bucketIdx) 543 } 544 545 // Add to bucket. 546 bucket[addrStr] = ka 547 // increment nNew if the peer doesnt already exist in a bucket 548 if ka.addBucketRef(bucketIdx) == 1 { 549 a.nNew++ 550 } 551 552 // Add it to addrLookup 553 a.addrLookup[ka.ID()] = ka 554 return nil 555 } 556 557 // Adds ka to old bucket. Returns false if it couldn't do it cuz buckets full. 558 func (a *addrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool { 559 // Sanity check 560 if ka.isNew() { 561 a.Logger.Error(fmt.Sprintf("Cannot add new address to old bucket: %v", ka)) 562 return false 563 } 564 if len(ka.Buckets) != 0 { 565 a.Logger.Error(fmt.Sprintf("Cannot add already old address to another old bucket: %v", ka)) 566 return false 567 } 568 569 addrStr := ka.Addr.String() 570 bucket := a.getBucket(bucketTypeOld, bucketIdx) 571 572 // Already exists? 573 if _, ok := bucket[addrStr]; ok { 574 return true 575 } 576 577 // Enforce max addresses. 578 if len(bucket) > oldBucketSize { 579 return false 580 } 581 582 // Add to bucket. 583 bucket[addrStr] = ka 584 if ka.addBucketRef(bucketIdx) == 1 { 585 a.nOld++ 586 } 587 588 // Ensure in addrLookup 589 a.addrLookup[ka.ID()] = ka 590 591 return true 592 } 593 594 func (a *addrBook) removeFromBucket(ka *knownAddress, bucketType byte, bucketIdx int) { 595 if ka.BucketType != bucketType { 596 a.Logger.Error(fmt.Sprintf("Bucket type mismatch: %v", ka)) 597 return 598 } 599 bucket := a.getBucket(bucketType, bucketIdx) 600 delete(bucket, ka.Addr.String()) 601 if ka.removeBucketRef(bucketIdx) == 0 { 602 if bucketType == bucketTypeNew { 603 a.nNew-- 604 } else { 605 a.nOld-- 606 } 607 delete(a.addrLookup, ka.ID()) 608 } 609 } 610 611 func (a *addrBook) removeFromAllBuckets(ka *knownAddress) { 612 for _, bucketIdx := range ka.Buckets { 613 bucket := a.getBucket(ka.BucketType, bucketIdx) 614 delete(bucket, ka.Addr.String()) 615 } 616 ka.Buckets = nil 617 if ka.BucketType == bucketTypeNew { 618 a.nNew-- 619 } else { 620 a.nOld-- 621 } 622 delete(a.addrLookup, ka.ID()) 623 } 624 625 //---------------------------------------------------------- 626 627 func (a *addrBook) pickOldest(bucketType byte, bucketIdx int) *knownAddress { 628 bucket := a.getBucket(bucketType, bucketIdx) 629 var oldest *knownAddress 630 for _, ka := range bucket { 631 if oldest == nil || ka.LastAttempt.Before(oldest.LastAttempt) { 632 oldest = ka 633 } 634 } 635 return oldest 636 } 637 638 // adds the address to a "new" bucket. if its already in one, 639 // it only adds it probabilistically 640 func (a *addrBook) addAddress(addr, src *p2p.NetAddress) error { 641 if addr == nil || src == nil { 642 return ErrAddrBookNilAddr{addr, src} 643 } 644 645 if err := addr.Valid(); err != nil { 646 return ErrAddrBookInvalidAddr{Addr: addr, AddrErr: err} 647 } 648 649 if _, ok := a.badPeers[addr.ID]; ok { 650 return ErrAddressBanned{addr} 651 } 652 653 if _, ok := a.privateIDs[addr.ID]; ok { 654 return ErrAddrBookPrivate{addr} 655 } 656 657 if _, ok := a.privateIDs[src.ID]; ok { 658 return ErrAddrBookPrivateSrc{src} 659 } 660 661 // TODO: we should track ourAddrs by ID and by IP:PORT and refuse both. 662 if _, ok := a.ourAddrs[addr.String()]; ok { 663 return ErrAddrBookSelf{addr} 664 } 665 666 if a.routabilityStrict && !addr.Routable() { 667 return ErrAddrBookNonRoutable{addr} 668 } 669 670 ka := a.addrLookup[addr.ID] 671 if ka != nil { 672 // If its already old and the address ID's are the same, ignore it. 673 // Thereby avoiding issues with a node on the network attempting to change 674 // the IP of a known node ID. (Which could yield an eclipse attack on the node) 675 if ka.isOld() && ka.Addr.ID == addr.ID { 676 return nil 677 } 678 // Already in max new buckets. 679 if len(ka.Buckets) == maxNewBucketsPerAddress { 680 return nil 681 } 682 // The more entries we have, the less likely we are to add more. 683 factor := int32(2 * len(ka.Buckets)) 684 if a.rand.Int31n(factor) != 0 { 685 return nil 686 } 687 } else { 688 ka = newKnownAddress(addr, src) 689 } 690 691 bucket, err := a.calcNewBucket(addr, src) 692 if err != nil { 693 return err 694 } 695 return a.addToNewBucket(ka, bucket) 696 } 697 698 func (a *addrBook) randomPickAddresses(bucketType byte, num int) []*p2p.NetAddress { 699 var buckets []map[string]*knownAddress 700 switch bucketType { 701 case bucketTypeNew: 702 buckets = a.bucketsNew 703 case bucketTypeOld: 704 buckets = a.bucketsOld 705 default: 706 panic("unexpected bucketType") 707 } 708 total := 0 709 for _, bucket := range buckets { 710 total += len(bucket) 711 } 712 addresses := make([]*knownAddress, 0, total) 713 for _, bucket := range buckets { 714 for _, ka := range bucket { 715 addresses = append(addresses, ka) 716 } 717 } 718 selection := make([]*p2p.NetAddress, 0, num) 719 chosenSet := make(map[string]bool, num) 720 rand.Shuffle(total, func(i, j int) { 721 addresses[i], addresses[j] = addresses[j], addresses[i] 722 }) 723 for _, addr := range addresses { 724 if chosenSet[addr.Addr.String()] { 725 continue 726 } 727 chosenSet[addr.Addr.String()] = true 728 selection = append(selection, addr.Addr) 729 if len(selection) >= num { 730 return selection 731 } 732 } 733 return selection 734 } 735 736 // Make space in the new buckets by expiring the really bad entries. 737 // If no bad entries are available we remove the oldest. 738 func (a *addrBook) expireNew(bucketIdx int) { 739 for addrStr, ka := range a.bucketsNew[bucketIdx] { 740 // If an entry is bad, throw it away 741 if ka.isBad() { 742 a.Logger.Info(fmt.Sprintf("expiring bad address %v", addrStr)) 743 a.removeFromBucket(ka, bucketTypeNew, bucketIdx) 744 return 745 } 746 } 747 748 // If we haven't thrown out a bad entry, throw out the oldest entry 749 oldest := a.pickOldest(bucketTypeNew, bucketIdx) 750 a.removeFromBucket(oldest, bucketTypeNew, bucketIdx) 751 } 752 753 // Promotes an address from new to old. If the destination bucket is full, 754 // demote the oldest one to a "new" bucket. 755 // TODO: Demote more probabilistically? 756 func (a *addrBook) moveToOld(ka *knownAddress) error { 757 // Sanity check 758 if ka.isOld() { 759 a.Logger.Error(fmt.Sprintf("Cannot promote address that is already old %v", ka)) 760 return nil 761 } 762 if len(ka.Buckets) == 0 { 763 a.Logger.Error(fmt.Sprintf("Cannot promote address that isn't in any new buckets %v", ka)) 764 return nil 765 } 766 767 // Remove from all (new) buckets. 768 a.removeFromAllBuckets(ka) 769 // It's officially old now. 770 ka.BucketType = bucketTypeOld 771 772 // Try to add it to its oldBucket destination. 773 oldBucketIdx, err := a.calcOldBucket(ka.Addr) 774 if err != nil { 775 return err 776 } 777 added := a.addToOldBucket(ka, oldBucketIdx) 778 if !added { 779 // No room; move the oldest to a new bucket 780 oldest := a.pickOldest(bucketTypeOld, oldBucketIdx) 781 a.removeFromBucket(oldest, bucketTypeOld, oldBucketIdx) 782 newBucketIdx, err := a.calcNewBucket(oldest.Addr, oldest.Src) 783 if err != nil { 784 return err 785 } 786 if err := a.addToNewBucket(oldest, newBucketIdx); err != nil { 787 a.Logger.Error("Error adding peer to old bucket", "err", err) 788 } 789 790 // Finally, add our ka to old bucket again. 791 added = a.addToOldBucket(ka, oldBucketIdx) 792 if !added { 793 a.Logger.Error(fmt.Sprintf("Could not re-add ka %v to oldBucketIdx %v", ka, oldBucketIdx)) 794 } 795 } 796 return nil 797 } 798 799 func (a *addrBook) removeAddress(addr *p2p.NetAddress) { 800 ka := a.addrLookup[addr.ID] 801 if ka == nil { 802 return 803 } 804 a.Logger.Info("Remove address from book", "addr", addr) 805 a.removeFromAllBuckets(ka) 806 } 807 808 func (a *addrBook) addBadPeer(addr *p2p.NetAddress, banTime time.Duration) bool { 809 // check it exists in addrbook 810 ka := a.addrLookup[addr.ID] 811 // check address is not already there 812 if ka == nil { 813 return false 814 } 815 816 if _, alreadyBadPeer := a.badPeers[addr.ID]; !alreadyBadPeer { 817 // add to bad peer list 818 ka.ban(banTime) 819 a.badPeers[addr.ID] = ka 820 a.Logger.Info("Add address to blacklist", "addr", addr) 821 } 822 return true 823 } 824 825 //--------------------------------------------------------------------- 826 // calculate bucket placements 827 828 // hash(key + sourcegroup + int64(hash(key + group + sourcegroup)) % bucket_per_group) % num_new_buckets 829 func (a *addrBook) calcNewBucket(addr, src *p2p.NetAddress) (int, error) { 830 data1 := []byte{} 831 data1 = append(data1, []byte(a.key)...) 832 data1 = append(data1, []byte(a.groupKey(addr))...) 833 data1 = append(data1, []byte(a.groupKey(src))...) 834 hash1, err := a.hash(data1) 835 if err != nil { 836 return 0, err 837 } 838 hash64 := binary.BigEndian.Uint64(hash1) 839 hash64 %= newBucketsPerGroup 840 var hashbuf [8]byte 841 binary.BigEndian.PutUint64(hashbuf[:], hash64) 842 data2 := []byte{} 843 data2 = append(data2, []byte(a.key)...) 844 data2 = append(data2, a.groupKey(src)...) 845 data2 = append(data2, hashbuf[:]...) 846 847 hash2, err := a.hash(data2) 848 if err != nil { 849 return 0, err 850 } 851 result := int(binary.BigEndian.Uint64(hash2) % newBucketCount) 852 return result, nil 853 } 854 855 // hash(key + group + int64(hash(key + addr)) % buckets_per_group) % num_old_buckets 856 func (a *addrBook) calcOldBucket(addr *p2p.NetAddress) (int, error) { 857 data1 := []byte{} 858 data1 = append(data1, []byte(a.key)...) 859 data1 = append(data1, []byte(addr.String())...) 860 hash1, err := a.hash(data1) 861 if err != nil { 862 return 0, err 863 } 864 hash64 := binary.BigEndian.Uint64(hash1) 865 hash64 %= oldBucketsPerGroup 866 var hashbuf [8]byte 867 binary.BigEndian.PutUint64(hashbuf[:], hash64) 868 data2 := []byte{} 869 data2 = append(data2, []byte(a.key)...) 870 data2 = append(data2, a.groupKey(addr)...) 871 data2 = append(data2, hashbuf[:]...) 872 873 hash2, err := a.hash(data2) 874 if err != nil { 875 return 0, err 876 } 877 result := int(binary.BigEndian.Uint64(hash2) % oldBucketCount) 878 return result, nil 879 } 880 881 // Return a string representing the network group of this address. 882 // This is the /16 for IPv4 (e.g. 1.2.0.0), the /32 (/36 for he.net) for IPv6, the string 883 // "local" for a local address and the string "unroutable" for an unroutable 884 // address. 885 func (a *addrBook) groupKey(na *p2p.NetAddress) string { 886 return groupKeyFor(na, a.routabilityStrict) 887 } 888 889 func groupKeyFor(na *p2p.NetAddress, routabilityStrict bool) string { 890 if routabilityStrict && na.Local() { 891 return "local" 892 } 893 if routabilityStrict && !na.Routable() { 894 return "unroutable" 895 } 896 897 if ipv4 := na.IP.To4(); ipv4 != nil { 898 return na.IP.Mask(net.CIDRMask(16, 32)).String() 899 } 900 901 if na.RFC6145() || na.RFC6052() { 902 // last four bytes are the ip address 903 ip := na.IP[12:16] 904 return ip.Mask(net.CIDRMask(16, 32)).String() 905 } 906 907 if na.RFC3964() { 908 ip := na.IP[2:6] 909 return ip.Mask(net.CIDRMask(16, 32)).String() 910 } 911 912 if na.RFC4380() { 913 // teredo tunnels have the last 4 bytes as the v4 address XOR 914 // 0xff. 915 ip := net.IP(make([]byte, 4)) 916 for i, byte := range na.IP[12:16] { 917 ip[i] = byte ^ 0xff 918 } 919 return ip.Mask(net.CIDRMask(16, 32)).String() 920 } 921 922 if na.OnionCatTor() { 923 // group is keyed off the first 4 bits of the actual onion key. 924 return fmt.Sprintf("tor:%d", na.IP[6]&((1<<4)-1)) 925 } 926 927 // OK, so now we know ourselves to be a IPv6 address. 928 // bitcoind uses /32 for everything, except for Hurricane Electric's 929 // (he.net) IP range, which it uses /36 for. 930 bits := 32 931 heNet := &net.IPNet{IP: net.ParseIP("2001:470::"), Mask: net.CIDRMask(32, 128)} 932 if heNet.Contains(na.IP) { 933 bits = 36 934 } 935 ipv6Mask := net.CIDRMask(bits, 128) 936 return na.IP.Mask(ipv6Mask).String() 937 } 938 939 func (a *addrBook) hash(b []byte) ([]byte, error) { 940 hasher, err := highwayhash.New64(a.hashKey) 941 if err != nil { 942 return nil, err 943 } 944 hasher.Write(b) 945 return hasher.Sum(nil), nil 946 }