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