github.com/palcoin-project/palcd@v1.0.0/addrmgr/addrmanager.go (about) 1 // Copyright (c) 2013-2016 The btcsuite developers 2 // Copyright (c) 2015-2018 The Decred developers 3 // Use of this source code is governed by an ISC 4 // license that can be found in the LICENSE file. 5 6 package addrmgr 7 8 import ( 9 "container/list" 10 crand "crypto/rand" // for seeding 11 "encoding/base32" 12 "encoding/binary" 13 "encoding/json" 14 "fmt" 15 "io" 16 "math/rand" 17 "net" 18 "os" 19 "path/filepath" 20 "strconv" 21 "strings" 22 "sync" 23 "sync/atomic" 24 "time" 25 26 "github.com/palcoin-project/palcd/chaincfg/chainhash" 27 "github.com/palcoin-project/palcd/wire" 28 ) 29 30 // AddrManager provides a concurrency safe address manager for caching potential 31 // peers on the bitcoin network. 32 type AddrManager struct { 33 mtx sync.RWMutex 34 peersFile string 35 lookupFunc func(string) ([]net.IP, error) 36 rand *rand.Rand 37 key [32]byte 38 addrIndex map[string]*KnownAddress // address key to ka for all addrs. 39 addrNew [newBucketCount]map[string]*KnownAddress 40 addrTried [triedBucketCount]*list.List 41 started int32 42 shutdown int32 43 wg sync.WaitGroup 44 quit chan struct{} 45 nTried int 46 nNew int 47 lamtx sync.Mutex 48 localAddresses map[string]*localAddress 49 version int 50 } 51 52 type serializedKnownAddress struct { 53 Addr string 54 Src string 55 Attempts int 56 TimeStamp int64 57 LastAttempt int64 58 LastSuccess int64 59 Services wire.ServiceFlag 60 SrcServices wire.ServiceFlag 61 // no refcount or tried, that is available from context. 62 } 63 64 type serializedAddrManager struct { 65 Version int 66 Key [32]byte 67 Addresses []*serializedKnownAddress 68 NewBuckets [newBucketCount][]string // string is NetAddressKey 69 TriedBuckets [triedBucketCount][]string 70 } 71 72 type localAddress struct { 73 na *wire.NetAddress 74 score AddressPriority 75 } 76 77 // AddressPriority type is used to describe the hierarchy of local address 78 // discovery methods. 79 type AddressPriority int 80 81 const ( 82 // InterfacePrio signifies the address is on a local interface 83 InterfacePrio AddressPriority = iota 84 85 // BoundPrio signifies the address has been explicitly bounded to. 86 BoundPrio 87 88 // UpnpPrio signifies the address was obtained from UPnP. 89 UpnpPrio 90 91 // HTTPPrio signifies the address was obtained from an external HTTP service. 92 HTTPPrio 93 94 // ManualPrio signifies the address was provided by --externalip. 95 ManualPrio 96 ) 97 98 const ( 99 // needAddressThreshold is the number of addresses under which the 100 // address manager will claim to need more addresses. 101 needAddressThreshold = 1000 102 103 // dumpAddressInterval is the interval used to dump the address 104 // cache to disk for future use. 105 dumpAddressInterval = time.Minute * 10 106 107 // triedBucketSize is the maximum number of addresses in each 108 // tried address bucket. 109 triedBucketSize = 256 110 111 // triedBucketCount is the number of buckets we split tried 112 // addresses over. 113 triedBucketCount = 64 114 115 // newBucketSize is the maximum number of addresses in each new address 116 // bucket. 117 newBucketSize = 64 118 119 // newBucketCount is the number of buckets that we spread new addresses 120 // over. 121 newBucketCount = 1024 122 123 // triedBucketsPerGroup is the number of tried buckets over which an 124 // address group will be spread. 125 triedBucketsPerGroup = 8 126 127 // newBucketsPerGroup is the number of new buckets over which an 128 // source address group will be spread. 129 newBucketsPerGroup = 64 130 131 // newBucketsPerAddress is the number of buckets a frequently seen new 132 // address may end up in. 133 newBucketsPerAddress = 8 134 135 // numMissingDays is the number of days before which we assume an 136 // address has vanished if we have not seen it announced in that long. 137 numMissingDays = 30 138 139 // numRetries is the number of tried without a single success before 140 // we assume an address is bad. 141 numRetries = 3 142 143 // maxFailures is the maximum number of failures we will accept without 144 // a success before considering an address bad. 145 maxFailures = 10 146 147 // minBadDays is the number of days since the last success before we 148 // will consider evicting an address. 149 minBadDays = 7 150 151 // getAddrMax is the most addresses that we will send in response 152 // to a getAddr (in practise the most addresses we will return from a 153 // call to AddressCache()). 154 getAddrMax = 2500 155 156 // getAddrPercent is the percentage of total addresses known that we 157 // will share with a call to AddressCache. 158 getAddrPercent = 23 159 160 // serialisationVersion is the current version of the on-disk format. 161 serialisationVersion = 2 162 ) 163 164 // updateAddress is a helper function to either update an address already known 165 // to the address manager, or to add the address if not already known. 166 func (a *AddrManager) updateAddress(netAddr, srcAddr *wire.NetAddress) { 167 // Filter out non-routable addresses. Note that non-routable 168 // also includes invalid and local addresses. 169 if !IsRoutable(netAddr) { 170 return 171 } 172 173 addr := NetAddressKey(netAddr) 174 ka := a.find(netAddr) 175 if ka != nil { 176 // TODO: only update addresses periodically. 177 // Update the last seen time and services. 178 // note that to prevent causing excess garbage on getaddr 179 // messages the netaddresses in addrmaanger are *immutable*, 180 // if we need to change them then we replace the pointer with a 181 // new copy so that we don't have to copy every na for getaddr. 182 if netAddr.Timestamp.After(ka.na.Timestamp) || 183 (ka.na.Services&netAddr.Services) != 184 netAddr.Services { 185 186 naCopy := *ka.na 187 naCopy.Timestamp = netAddr.Timestamp 188 naCopy.AddService(netAddr.Services) 189 ka.na = &naCopy 190 } 191 192 // If already in tried, we have nothing to do here. 193 if ka.tried { 194 return 195 } 196 197 // Already at our max? 198 if ka.refs == newBucketsPerAddress { 199 return 200 } 201 202 // The more entries we have, the less likely we are to add more. 203 // likelihood is 2N. 204 factor := int32(2 * ka.refs) 205 if a.rand.Int31n(factor) != 0 { 206 return 207 } 208 } else { 209 // Make a copy of the net address to avoid races since it is 210 // updated elsewhere in the addrmanager code and would otherwise 211 // change the actual netaddress on the peer. 212 netAddrCopy := *netAddr 213 ka = &KnownAddress{na: &netAddrCopy, srcAddr: srcAddr} 214 a.addrIndex[addr] = ka 215 a.nNew++ 216 // XXX time penalty? 217 } 218 219 bucket := a.getNewBucket(netAddr, srcAddr) 220 221 // Already exists? 222 if _, ok := a.addrNew[bucket][addr]; ok { 223 return 224 } 225 226 // Enforce max addresses. 227 if len(a.addrNew[bucket]) > newBucketSize { 228 log.Tracef("new bucket is full, expiring old") 229 a.expireNew(bucket) 230 } 231 232 // Add to new bucket. 233 ka.refs++ 234 a.addrNew[bucket][addr] = ka 235 236 log.Tracef("Added new address %s for a total of %d addresses", addr, 237 a.nTried+a.nNew) 238 } 239 240 // expireNew makes space in the new buckets by expiring the really bad entries. 241 // If no bad entries are available we look at a few and remove the oldest. 242 func (a *AddrManager) expireNew(bucket int) { 243 // First see if there are any entries that are so bad we can just throw 244 // them away. otherwise we throw away the oldest entry in the cache. 245 // Bitcoind here chooses four random and just throws the oldest of 246 // those away, but we keep track of oldest in the initial traversal and 247 // use that information instead. 248 var oldest *KnownAddress 249 for k, v := range a.addrNew[bucket] { 250 if v.isBad() { 251 log.Tracef("expiring bad address %v", k) 252 delete(a.addrNew[bucket], k) 253 v.refs-- 254 if v.refs == 0 { 255 a.nNew-- 256 delete(a.addrIndex, k) 257 } 258 continue 259 } 260 if oldest == nil { 261 oldest = v 262 } else if !v.na.Timestamp.After(oldest.na.Timestamp) { 263 oldest = v 264 } 265 } 266 267 if oldest != nil { 268 key := NetAddressKey(oldest.na) 269 log.Tracef("expiring oldest address %v", key) 270 271 delete(a.addrNew[bucket], key) 272 oldest.refs-- 273 if oldest.refs == 0 { 274 a.nNew-- 275 delete(a.addrIndex, key) 276 } 277 } 278 } 279 280 // pickTried selects an address from the tried bucket to be evicted. 281 // We just choose the eldest. Bitcoind selects 4 random entries and throws away 282 // the older of them. 283 func (a *AddrManager) pickTried(bucket int) *list.Element { 284 var oldest *KnownAddress 285 var oldestElem *list.Element 286 for e := a.addrTried[bucket].Front(); e != nil; e = e.Next() { 287 ka := e.Value.(*KnownAddress) 288 if oldest == nil || oldest.na.Timestamp.After(ka.na.Timestamp) { 289 oldestElem = e 290 oldest = ka 291 } 292 293 } 294 return oldestElem 295 } 296 297 func (a *AddrManager) getNewBucket(netAddr, srcAddr *wire.NetAddress) int { 298 // bitcoind: 299 // doublesha256(key + sourcegroup + int64(doublesha256(key + group + sourcegroup))%bucket_per_source_group) % num_new_buckets 300 301 data1 := []byte{} 302 data1 = append(data1, a.key[:]...) 303 data1 = append(data1, []byte(GroupKey(netAddr))...) 304 data1 = append(data1, []byte(GroupKey(srcAddr))...) 305 hash1 := chainhash.DoubleHashB(data1) 306 hash64 := binary.LittleEndian.Uint64(hash1) 307 hash64 %= newBucketsPerGroup 308 var hashbuf [8]byte 309 binary.LittleEndian.PutUint64(hashbuf[:], hash64) 310 data2 := []byte{} 311 data2 = append(data2, a.key[:]...) 312 data2 = append(data2, GroupKey(srcAddr)...) 313 data2 = append(data2, hashbuf[:]...) 314 315 hash2 := chainhash.DoubleHashB(data2) 316 return int(binary.LittleEndian.Uint64(hash2) % newBucketCount) 317 } 318 319 func (a *AddrManager) getTriedBucket(netAddr *wire.NetAddress) int { 320 // bitcoind hashes this as: 321 // doublesha256(key + group + truncate_to_64bits(doublesha256(key)) % buckets_per_group) % num_buckets 322 data1 := []byte{} 323 data1 = append(data1, a.key[:]...) 324 data1 = append(data1, []byte(NetAddressKey(netAddr))...) 325 hash1 := chainhash.DoubleHashB(data1) 326 hash64 := binary.LittleEndian.Uint64(hash1) 327 hash64 %= triedBucketsPerGroup 328 var hashbuf [8]byte 329 binary.LittleEndian.PutUint64(hashbuf[:], hash64) 330 data2 := []byte{} 331 data2 = append(data2, a.key[:]...) 332 data2 = append(data2, GroupKey(netAddr)...) 333 data2 = append(data2, hashbuf[:]...) 334 335 hash2 := chainhash.DoubleHashB(data2) 336 return int(binary.LittleEndian.Uint64(hash2) % triedBucketCount) 337 } 338 339 // addressHandler is the main handler for the address manager. It must be run 340 // as a goroutine. 341 func (a *AddrManager) addressHandler() { 342 dumpAddressTicker := time.NewTicker(dumpAddressInterval) 343 defer dumpAddressTicker.Stop() 344 out: 345 for { 346 select { 347 case <-dumpAddressTicker.C: 348 a.savePeers() 349 350 case <-a.quit: 351 break out 352 } 353 } 354 a.savePeers() 355 a.wg.Done() 356 log.Trace("Address handler done") 357 } 358 359 // savePeers saves all the known addresses to a file so they can be read back 360 // in at next run. 361 func (a *AddrManager) savePeers() { 362 a.mtx.Lock() 363 defer a.mtx.Unlock() 364 365 // First we make a serialisable datastructure so we can encode it to 366 // json. 367 sam := new(serializedAddrManager) 368 sam.Version = a.version 369 copy(sam.Key[:], a.key[:]) 370 371 sam.Addresses = make([]*serializedKnownAddress, len(a.addrIndex)) 372 i := 0 373 for k, v := range a.addrIndex { 374 ska := new(serializedKnownAddress) 375 ska.Addr = k 376 ska.TimeStamp = v.na.Timestamp.Unix() 377 ska.Src = NetAddressKey(v.srcAddr) 378 ska.Attempts = v.attempts 379 ska.LastAttempt = v.lastattempt.Unix() 380 ska.LastSuccess = v.lastsuccess.Unix() 381 if a.version > 1 { 382 ska.Services = v.na.Services 383 ska.SrcServices = v.srcAddr.Services 384 } 385 // Tried and refs are implicit in the rest of the structure 386 // and will be worked out from context on unserialisation. 387 sam.Addresses[i] = ska 388 i++ 389 } 390 for i := range a.addrNew { 391 sam.NewBuckets[i] = make([]string, len(a.addrNew[i])) 392 j := 0 393 for k := range a.addrNew[i] { 394 sam.NewBuckets[i][j] = k 395 j++ 396 } 397 } 398 for i := range a.addrTried { 399 sam.TriedBuckets[i] = make([]string, a.addrTried[i].Len()) 400 j := 0 401 for e := a.addrTried[i].Front(); e != nil; e = e.Next() { 402 ka := e.Value.(*KnownAddress) 403 sam.TriedBuckets[i][j] = NetAddressKey(ka.na) 404 j++ 405 } 406 } 407 408 w, err := os.Create(a.peersFile) 409 if err != nil { 410 log.Errorf("Error opening file %s: %v", a.peersFile, err) 411 return 412 } 413 enc := json.NewEncoder(w) 414 defer w.Close() 415 if err := enc.Encode(&sam); err != nil { 416 log.Errorf("Failed to encode file %s: %v", a.peersFile, err) 417 return 418 } 419 } 420 421 // loadPeers loads the known address from the saved file. If empty, missing, or 422 // malformed file, just don't load anything and start fresh 423 func (a *AddrManager) loadPeers() { 424 a.mtx.Lock() 425 defer a.mtx.Unlock() 426 427 err := a.deserializePeers(a.peersFile) 428 if err != nil { 429 log.Errorf("Failed to parse file %s: %v", a.peersFile, err) 430 // if it is invalid we nuke the old one unconditionally. 431 err = os.Remove(a.peersFile) 432 if err != nil { 433 log.Warnf("Failed to remove corrupt peers file %s: %v", 434 a.peersFile, err) 435 } 436 a.reset() 437 return 438 } 439 log.Infof("Loaded %d addresses from file '%s'", a.numAddresses(), a.peersFile) 440 } 441 442 func (a *AddrManager) deserializePeers(filePath string) error { 443 444 _, err := os.Stat(filePath) 445 if os.IsNotExist(err) { 446 return nil 447 } 448 r, err := os.Open(filePath) 449 if err != nil { 450 return fmt.Errorf("%s error opening file: %v", filePath, err) 451 } 452 defer r.Close() 453 454 var sam serializedAddrManager 455 dec := json.NewDecoder(r) 456 err = dec.Decode(&sam) 457 if err != nil { 458 return fmt.Errorf("error reading %s: %v", filePath, err) 459 } 460 461 // Since decoding JSON is backwards compatible (i.e., only decodes 462 // fields it understands), we'll only return an error upon seeing a 463 // version past our latest supported version. 464 if sam.Version > serialisationVersion { 465 return fmt.Errorf("unknown version %v in serialized "+ 466 "addrmanager", sam.Version) 467 } 468 469 copy(a.key[:], sam.Key[:]) 470 471 for _, v := range sam.Addresses { 472 ka := new(KnownAddress) 473 474 // The first version of the serialized address manager was not 475 // aware of the service bits associated with this address, so 476 // we'll assign a default of SFNodeNetwork to it. 477 if sam.Version == 1 { 478 v.Services = wire.SFNodeNetwork 479 } 480 ka.na, err = a.DeserializeNetAddress(v.Addr, v.Services) 481 if err != nil { 482 return fmt.Errorf("failed to deserialize netaddress "+ 483 "%s: %v", v.Addr, err) 484 } 485 486 // The first version of the serialized address manager was not 487 // aware of the service bits associated with the source address, 488 // so we'll assign a default of SFNodeNetwork to it. 489 if sam.Version == 1 { 490 v.SrcServices = wire.SFNodeNetwork 491 } 492 ka.srcAddr, err = a.DeserializeNetAddress(v.Src, v.SrcServices) 493 if err != nil { 494 return fmt.Errorf("failed to deserialize netaddress "+ 495 "%s: %v", v.Src, err) 496 } 497 498 ka.attempts = v.Attempts 499 ka.lastattempt = time.Unix(v.LastAttempt, 0) 500 ka.lastsuccess = time.Unix(v.LastSuccess, 0) 501 a.addrIndex[NetAddressKey(ka.na)] = ka 502 } 503 504 for i := range sam.NewBuckets { 505 for _, val := range sam.NewBuckets[i] { 506 ka, ok := a.addrIndex[val] 507 if !ok { 508 return fmt.Errorf("newbucket contains %s but "+ 509 "none in address list", val) 510 } 511 512 if ka.refs == 0 { 513 a.nNew++ 514 } 515 ka.refs++ 516 a.addrNew[i][val] = ka 517 } 518 } 519 for i := range sam.TriedBuckets { 520 for _, val := range sam.TriedBuckets[i] { 521 ka, ok := a.addrIndex[val] 522 if !ok { 523 return fmt.Errorf("Newbucket contains %s but "+ 524 "none in address list", val) 525 } 526 527 ka.tried = true 528 a.nTried++ 529 a.addrTried[i].PushBack(ka) 530 } 531 } 532 533 // Sanity checking. 534 for k, v := range a.addrIndex { 535 if v.refs == 0 && !v.tried { 536 return fmt.Errorf("address %s after serialisation "+ 537 "with no references", k) 538 } 539 540 if v.refs > 0 && v.tried { 541 return fmt.Errorf("address %s after serialisation "+ 542 "which is both new and tried!", k) 543 } 544 } 545 546 return nil 547 } 548 549 // DeserializeNetAddress converts a given address string to a *wire.NetAddress. 550 func (a *AddrManager) DeserializeNetAddress(addr string, 551 services wire.ServiceFlag) (*wire.NetAddress, error) { 552 553 host, portStr, err := net.SplitHostPort(addr) 554 if err != nil { 555 return nil, err 556 } 557 port, err := strconv.ParseUint(portStr, 10, 16) 558 if err != nil { 559 return nil, err 560 } 561 562 return a.HostToNetAddress(host, uint16(port), services) 563 } 564 565 // Start begins the core address handler which manages a pool of known 566 // addresses, timeouts, and interval based writes. 567 func (a *AddrManager) Start() { 568 // Already started? 569 if atomic.AddInt32(&a.started, 1) != 1 { 570 return 571 } 572 573 log.Trace("Starting address manager") 574 575 // Load peers we already know about from file. 576 a.loadPeers() 577 578 // Start the address ticker to save addresses periodically. 579 a.wg.Add(1) 580 go a.addressHandler() 581 } 582 583 // Stop gracefully shuts down the address manager by stopping the main handler. 584 func (a *AddrManager) Stop() error { 585 if atomic.AddInt32(&a.shutdown, 1) != 1 { 586 log.Warnf("Address manager is already in the process of " + 587 "shutting down") 588 return nil 589 } 590 591 log.Infof("Address manager shutting down") 592 close(a.quit) 593 a.wg.Wait() 594 return nil 595 } 596 597 // AddAddresses adds new addresses to the address manager. It enforces a max 598 // number of addresses and silently ignores duplicate addresses. It is 599 // safe for concurrent access. 600 func (a *AddrManager) AddAddresses(addrs []*wire.NetAddress, srcAddr *wire.NetAddress) { 601 a.mtx.Lock() 602 defer a.mtx.Unlock() 603 604 for _, na := range addrs { 605 a.updateAddress(na, srcAddr) 606 } 607 } 608 609 // AddAddress adds a new address to the address manager. It enforces a max 610 // number of addresses and silently ignores duplicate addresses. It is 611 // safe for concurrent access. 612 func (a *AddrManager) AddAddress(addr, srcAddr *wire.NetAddress) { 613 a.mtx.Lock() 614 defer a.mtx.Unlock() 615 616 a.updateAddress(addr, srcAddr) 617 } 618 619 // AddAddressByIP adds an address where we are given an ip:port and not a 620 // wire.NetAddress. 621 func (a *AddrManager) AddAddressByIP(addrIP string) error { 622 // Split IP and port 623 addr, portStr, err := net.SplitHostPort(addrIP) 624 if err != nil { 625 return err 626 } 627 // Put it in wire.Netaddress 628 ip := net.ParseIP(addr) 629 if ip == nil { 630 return fmt.Errorf("invalid ip address %s", addr) 631 } 632 port, err := strconv.ParseUint(portStr, 10, 0) 633 if err != nil { 634 return fmt.Errorf("invalid port %s: %v", portStr, err) 635 } 636 na := wire.NewNetAddressIPPort(ip, uint16(port), 0) 637 a.AddAddress(na, na) // XXX use correct src address 638 return nil 639 } 640 641 // NumAddresses returns the number of addresses known to the address manager. 642 func (a *AddrManager) numAddresses() int { 643 return a.nTried + a.nNew 644 } 645 646 // NumAddresses returns the number of addresses known to the address manager. 647 func (a *AddrManager) NumAddresses() int { 648 a.mtx.RLock() 649 defer a.mtx.RUnlock() 650 651 return a.numAddresses() 652 } 653 654 // NeedMoreAddresses returns whether or not the address manager needs more 655 // addresses. 656 func (a *AddrManager) NeedMoreAddresses() bool { 657 a.mtx.RLock() 658 defer a.mtx.RUnlock() 659 660 return a.numAddresses() < needAddressThreshold 661 } 662 663 // AddressCache returns the current address cache. It must be treated as 664 // read-only (but since it is a copy now, this is not as dangerous). 665 func (a *AddrManager) AddressCache() []*wire.NetAddress { 666 allAddr := a.getAddresses() 667 668 numAddresses := len(allAddr) * getAddrPercent / 100 669 if numAddresses > getAddrMax { 670 numAddresses = getAddrMax 671 } 672 673 // Fisher-Yates shuffle the array. We only need to do the first 674 // `numAddresses' since we are throwing the rest. 675 for i := 0; i < numAddresses; i++ { 676 // pick a number between current index and the end 677 j := rand.Intn(len(allAddr)-i) + i 678 allAddr[i], allAddr[j] = allAddr[j], allAddr[i] 679 } 680 681 // slice off the limit we are willing to share. 682 return allAddr[0:numAddresses] 683 } 684 685 // getAddresses returns all of the addresses currently found within the 686 // manager's address cache. 687 func (a *AddrManager) getAddresses() []*wire.NetAddress { 688 a.mtx.RLock() 689 defer a.mtx.RUnlock() 690 691 addrIndexLen := len(a.addrIndex) 692 if addrIndexLen == 0 { 693 return nil 694 } 695 696 addrs := make([]*wire.NetAddress, 0, addrIndexLen) 697 for _, v := range a.addrIndex { 698 addrs = append(addrs, v.na) 699 } 700 701 return addrs 702 } 703 704 // reset resets the address manager by reinitialising the random source 705 // and allocating fresh empty bucket storage. 706 func (a *AddrManager) reset() { 707 708 a.addrIndex = make(map[string]*KnownAddress) 709 710 // fill key with bytes from a good random source. 711 io.ReadFull(crand.Reader, a.key[:]) 712 for i := range a.addrNew { 713 a.addrNew[i] = make(map[string]*KnownAddress) 714 } 715 for i := range a.addrTried { 716 a.addrTried[i] = list.New() 717 } 718 } 719 720 // HostToNetAddress returns a netaddress given a host address. If the address 721 // is a Tor .onion address this will be taken care of. Else if the host is 722 // not an IP address it will be resolved (via Tor if required). 723 func (a *AddrManager) HostToNetAddress(host string, port uint16, services wire.ServiceFlag) (*wire.NetAddress, error) { 724 // Tor address is 16 char base32 + ".onion" 725 var ip net.IP 726 if len(host) == 22 && host[16:] == ".onion" { 727 // go base32 encoding uses capitals (as does the rfc 728 // but Tor and bitcoind tend to user lowercase, so we switch 729 // case here. 730 data, err := base32.StdEncoding.DecodeString( 731 strings.ToUpper(host[:16])) 732 if err != nil { 733 return nil, err 734 } 735 prefix := []byte{0xfd, 0x87, 0xd8, 0x7e, 0xeb, 0x43} 736 ip = net.IP(append(prefix, data...)) 737 } else if ip = net.ParseIP(host); ip == nil { 738 ips, err := a.lookupFunc(host) 739 if err != nil { 740 return nil, err 741 } 742 if len(ips) == 0 { 743 return nil, fmt.Errorf("no addresses found for %s", host) 744 } 745 ip = ips[0] 746 } 747 748 return wire.NewNetAddressIPPort(ip, port, services), nil 749 } 750 751 // ipString returns a string for the ip from the provided NetAddress. If the 752 // ip is in the range used for Tor addresses then it will be transformed into 753 // the relevant .onion address. 754 func ipString(na *wire.NetAddress) string { 755 if IsOnionCatTor(na) { 756 // We know now that na.IP is long enough. 757 base32 := base32.StdEncoding.EncodeToString(na.IP[6:]) 758 return strings.ToLower(base32) + ".onion" 759 } 760 761 return na.IP.String() 762 } 763 764 // NetAddressKey returns a string key in the form of ip:port for IPv4 addresses 765 // or [ip]:port for IPv6 addresses. 766 func NetAddressKey(na *wire.NetAddress) string { 767 port := strconv.FormatUint(uint64(na.Port), 10) 768 769 return net.JoinHostPort(ipString(na), port) 770 } 771 772 // GetAddress returns a single address that should be routable. It picks a 773 // random one from the possible addresses with preference given to ones that 774 // have not been used recently and should not pick 'close' addresses 775 // consecutively. 776 func (a *AddrManager) GetAddress() *KnownAddress { 777 // Protect concurrent access. 778 a.mtx.Lock() 779 defer a.mtx.Unlock() 780 781 if a.numAddresses() == 0 { 782 return nil 783 } 784 785 // Use a 50% chance for choosing between tried and new table entries. 786 if a.nTried > 0 && (a.nNew == 0 || a.rand.Intn(2) == 0) { 787 // Tried entry. 788 large := 1 << 30 789 factor := 1.0 790 for { 791 // pick a random bucket. 792 bucket := a.rand.Intn(len(a.addrTried)) 793 if a.addrTried[bucket].Len() == 0 { 794 continue 795 } 796 797 // Pick a random entry in the list 798 e := a.addrTried[bucket].Front() 799 for i := 800 a.rand.Int63n(int64(a.addrTried[bucket].Len())); i > 0; i-- { 801 e = e.Next() 802 } 803 ka := e.Value.(*KnownAddress) 804 randval := a.rand.Intn(large) 805 if float64(randval) < (factor * ka.chance() * float64(large)) { 806 log.Tracef("Selected %v from tried bucket", 807 NetAddressKey(ka.na)) 808 return ka 809 } 810 factor *= 1.2 811 } 812 } else { 813 // new node. 814 // XXX use a closure/function to avoid repeating this. 815 large := 1 << 30 816 factor := 1.0 817 for { 818 // Pick a random bucket. 819 bucket := a.rand.Intn(len(a.addrNew)) 820 if len(a.addrNew[bucket]) == 0 { 821 continue 822 } 823 // Then, a random entry in it. 824 var ka *KnownAddress 825 nth := a.rand.Intn(len(a.addrNew[bucket])) 826 for _, value := range a.addrNew[bucket] { 827 if nth == 0 { 828 ka = value 829 } 830 nth-- 831 } 832 randval := a.rand.Intn(large) 833 if float64(randval) < (factor * ka.chance() * float64(large)) { 834 log.Tracef("Selected %v from new bucket", 835 NetAddressKey(ka.na)) 836 return ka 837 } 838 factor *= 1.2 839 } 840 } 841 } 842 843 func (a *AddrManager) find(addr *wire.NetAddress) *KnownAddress { 844 return a.addrIndex[NetAddressKey(addr)] 845 } 846 847 // Attempt increases the given address' attempt counter and updates 848 // the last attempt time. 849 func (a *AddrManager) Attempt(addr *wire.NetAddress) { 850 a.mtx.Lock() 851 defer a.mtx.Unlock() 852 853 // find address. 854 // Surely address will be in tried by now? 855 ka := a.find(addr) 856 if ka == nil { 857 return 858 } 859 // set last tried time to now 860 ka.attempts++ 861 ka.lastattempt = time.Now() 862 } 863 864 // Connected Marks the given address as currently connected and working at the 865 // current time. The address must already be known to AddrManager else it will 866 // be ignored. 867 func (a *AddrManager) Connected(addr *wire.NetAddress) { 868 a.mtx.Lock() 869 defer a.mtx.Unlock() 870 871 ka := a.find(addr) 872 if ka == nil { 873 return 874 } 875 876 // Update the time as long as it has been 20 minutes since last we did 877 // so. 878 now := time.Now() 879 if now.After(ka.na.Timestamp.Add(time.Minute * 20)) { 880 // ka.na is immutable, so replace it. 881 naCopy := *ka.na 882 naCopy.Timestamp = time.Now() 883 ka.na = &naCopy 884 } 885 } 886 887 // Good marks the given address as good. To be called after a successful 888 // connection and version exchange. If the address is unknown to the address 889 // manager it will be ignored. 890 func (a *AddrManager) Good(addr *wire.NetAddress) { 891 a.mtx.Lock() 892 defer a.mtx.Unlock() 893 894 ka := a.find(addr) 895 if ka == nil { 896 return 897 } 898 899 // ka.Timestamp is not updated here to avoid leaking information 900 // about currently connected peers. 901 now := time.Now() 902 ka.lastsuccess = now 903 ka.lastattempt = now 904 ka.attempts = 0 905 906 // move to tried set, optionally evicting other addresses if neeed. 907 if ka.tried { 908 return 909 } 910 911 // ok, need to move it to tried. 912 913 // remove from all new buckets. 914 // record one of the buckets in question and call it the `first' 915 addrKey := NetAddressKey(addr) 916 oldBucket := -1 917 for i := range a.addrNew { 918 // we check for existence so we can record the first one 919 if _, ok := a.addrNew[i][addrKey]; ok { 920 delete(a.addrNew[i], addrKey) 921 ka.refs-- 922 if oldBucket == -1 { 923 oldBucket = i 924 } 925 } 926 } 927 a.nNew-- 928 929 if oldBucket == -1 { 930 // What? wasn't in a bucket after all.... Panic? 931 return 932 } 933 934 bucket := a.getTriedBucket(ka.na) 935 936 // Room in this tried bucket? 937 if a.addrTried[bucket].Len() < triedBucketSize { 938 ka.tried = true 939 a.addrTried[bucket].PushBack(ka) 940 a.nTried++ 941 return 942 } 943 944 // No room, we have to evict something else. 945 entry := a.pickTried(bucket) 946 rmka := entry.Value.(*KnownAddress) 947 948 // First bucket it would have been put in. 949 newBucket := a.getNewBucket(rmka.na, rmka.srcAddr) 950 951 // If no room in the original bucket, we put it in a bucket we just 952 // freed up a space in. 953 if len(a.addrNew[newBucket]) >= newBucketSize { 954 newBucket = oldBucket 955 } 956 957 // replace with ka in list. 958 ka.tried = true 959 entry.Value = ka 960 961 rmka.tried = false 962 rmka.refs++ 963 964 // We don't touch a.nTried here since the number of tried stays the same 965 // but we decemented new above, raise it again since we're putting 966 // something back. 967 a.nNew++ 968 969 rmkey := NetAddressKey(rmka.na) 970 log.Tracef("Replacing %s with %s in tried", rmkey, addrKey) 971 972 // We made sure there is space here just above. 973 a.addrNew[newBucket][rmkey] = rmka 974 } 975 976 // SetServices sets the services for the giiven address to the provided value. 977 func (a *AddrManager) SetServices(addr *wire.NetAddress, services wire.ServiceFlag) { 978 a.mtx.Lock() 979 defer a.mtx.Unlock() 980 981 ka := a.find(addr) 982 if ka == nil { 983 return 984 } 985 986 // Update the services if needed. 987 if ka.na.Services != services { 988 // ka.na is immutable, so replace it. 989 naCopy := *ka.na 990 naCopy.Services = services 991 ka.na = &naCopy 992 } 993 } 994 995 // AddLocalAddress adds na to the list of known local addresses to advertise 996 // with the given priority. 997 func (a *AddrManager) AddLocalAddress(na *wire.NetAddress, priority AddressPriority) error { 998 if !IsRoutable(na) { 999 return fmt.Errorf("address %s is not routable", na.IP) 1000 } 1001 1002 a.lamtx.Lock() 1003 defer a.lamtx.Unlock() 1004 1005 key := NetAddressKey(na) 1006 la, ok := a.localAddresses[key] 1007 if !ok || la.score < priority { 1008 if ok { 1009 la.score = priority + 1 1010 } else { 1011 a.localAddresses[key] = &localAddress{ 1012 na: na, 1013 score: priority, 1014 } 1015 } 1016 } 1017 return nil 1018 } 1019 1020 // getReachabilityFrom returns the relative reachability of the provided local 1021 // address to the provided remote address. 1022 func getReachabilityFrom(localAddr, remoteAddr *wire.NetAddress) int { 1023 const ( 1024 Unreachable = 0 1025 Default = iota 1026 Teredo 1027 Ipv6Weak 1028 Ipv4 1029 Ipv6Strong 1030 Private 1031 ) 1032 1033 if !IsRoutable(remoteAddr) { 1034 return Unreachable 1035 } 1036 1037 if IsOnionCatTor(remoteAddr) { 1038 if IsOnionCatTor(localAddr) { 1039 return Private 1040 } 1041 1042 if IsRoutable(localAddr) && IsIPv4(localAddr) { 1043 return Ipv4 1044 } 1045 1046 return Default 1047 } 1048 1049 if IsRFC4380(remoteAddr) { 1050 if !IsRoutable(localAddr) { 1051 return Default 1052 } 1053 1054 if IsRFC4380(localAddr) { 1055 return Teredo 1056 } 1057 1058 if IsIPv4(localAddr) { 1059 return Ipv4 1060 } 1061 1062 return Ipv6Weak 1063 } 1064 1065 if IsIPv4(remoteAddr) { 1066 if IsRoutable(localAddr) && IsIPv4(localAddr) { 1067 return Ipv4 1068 } 1069 return Unreachable 1070 } 1071 1072 /* ipv6 */ 1073 var tunnelled bool 1074 // Is our v6 is tunnelled? 1075 if IsRFC3964(localAddr) || IsRFC6052(localAddr) || IsRFC6145(localAddr) { 1076 tunnelled = true 1077 } 1078 1079 if !IsRoutable(localAddr) { 1080 return Default 1081 } 1082 1083 if IsRFC4380(localAddr) { 1084 return Teredo 1085 } 1086 1087 if IsIPv4(localAddr) { 1088 return Ipv4 1089 } 1090 1091 if tunnelled { 1092 // only prioritise ipv6 if we aren't tunnelling it. 1093 return Ipv6Weak 1094 } 1095 1096 return Ipv6Strong 1097 } 1098 1099 // GetBestLocalAddress returns the most appropriate local address to use 1100 // for the given remote address. 1101 func (a *AddrManager) GetBestLocalAddress(remoteAddr *wire.NetAddress) *wire.NetAddress { 1102 a.lamtx.Lock() 1103 defer a.lamtx.Unlock() 1104 1105 bestreach := 0 1106 var bestscore AddressPriority 1107 var bestAddress *wire.NetAddress 1108 for _, la := range a.localAddresses { 1109 reach := getReachabilityFrom(la.na, remoteAddr) 1110 if reach > bestreach || 1111 (reach == bestreach && la.score > bestscore) { 1112 bestreach = reach 1113 bestscore = la.score 1114 bestAddress = la.na 1115 } 1116 } 1117 if bestAddress != nil { 1118 log.Debugf("Suggesting address %s:%d for %s:%d", bestAddress.IP, 1119 bestAddress.Port, remoteAddr.IP, remoteAddr.Port) 1120 } else { 1121 log.Debugf("No worthy address for %s:%d", remoteAddr.IP, 1122 remoteAddr.Port) 1123 1124 // Send something unroutable if nothing suitable. 1125 var ip net.IP 1126 if !IsIPv4(remoteAddr) && !IsOnionCatTor(remoteAddr) { 1127 ip = net.IPv6zero 1128 } else { 1129 ip = net.IPv4zero 1130 } 1131 services := wire.SFNodeNetwork | wire.SFNodeWitness | wire.SFNodeBloom 1132 bestAddress = wire.NewNetAddressIPPort(ip, 0, services) 1133 } 1134 1135 return bestAddress 1136 } 1137 1138 // New returns a new bitcoin address manager. 1139 // Use Start to begin processing asynchronous address updates. 1140 func New(dataDir string, lookupFunc func(string) ([]net.IP, error)) *AddrManager { 1141 am := AddrManager{ 1142 peersFile: filepath.Join(dataDir, "peers.json"), 1143 lookupFunc: lookupFunc, 1144 rand: rand.New(rand.NewSource(time.Now().UnixNano())), 1145 quit: make(chan struct{}), 1146 localAddresses: make(map[string]*localAddress), 1147 version: serialisationVersion, 1148 } 1149 am.reset() 1150 return &am 1151 }