github.com/btcsuite/btcd@v0.24.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/btcsuite/btcd/chaincfg/chainhash"
    27  	"github.com/btcsuite/btcd/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.NetAddressV2
    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.NetAddressV2) {
   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.NetAddressV2) 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.NetAddressV2) 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.NetAddressV2, 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.NetAddressV2, srcAddr *wire.NetAddressV2) {
   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.NetAddressV2) {
   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.NetAddressV2FromBytes(time.Now(), 0, ip, uint16(port))
   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.NetAddressV2 {
   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.NetAddressV2 {
   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.NetAddressV2, 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,
   726  	services wire.ServiceFlag) (*wire.NetAddressV2, error) {
   727  
   728  	var (
   729  		na *wire.NetAddressV2
   730  		ip net.IP
   731  	)
   732  
   733  	// Tor v2 address is 16 char base32 + ".onion"
   734  	if len(host) == wire.TorV2EncodedSize && host[wire.TorV2EncodedSize-6:] == ".onion" {
   735  		// go base32 encoding uses capitals (as does the rfc
   736  		// but Tor and bitcoind tend to user lowercase, so we switch
   737  		// case here.
   738  		data, err := base32.StdEncoding.DecodeString(
   739  			strings.ToUpper(host[:wire.TorV2EncodedSize-6]))
   740  		if err != nil {
   741  			return nil, err
   742  		}
   743  
   744  		na = wire.NetAddressV2FromBytes(
   745  			time.Now(), services, data, port,
   746  		)
   747  	} else if len(host) == wire.TorV3EncodedSize && host[wire.TorV3EncodedSize-6:] == ".onion" {
   748  		// Tor v3 addresses are 56 base32 characters with the 6 byte
   749  		// onion suffix.
   750  		data, err := base32.StdEncoding.DecodeString(
   751  			strings.ToUpper(host[:wire.TorV3EncodedSize-6]),
   752  		)
   753  		if err != nil {
   754  			return nil, err
   755  		}
   756  
   757  		// The first 32 bytes is the ed25519 public key and is enough
   758  		// to reconstruct the .onion address.
   759  		na = wire.NetAddressV2FromBytes(
   760  			time.Now(), services, data[:wire.TorV3Size], port,
   761  		)
   762  	} else if ip = net.ParseIP(host); ip == nil {
   763  		ips, err := a.lookupFunc(host)
   764  		if err != nil {
   765  			return nil, err
   766  		}
   767  		if len(ips) == 0 {
   768  			return nil, fmt.Errorf("no addresses found for %s", host)
   769  		}
   770  		ip = ips[0]
   771  
   772  		na = wire.NetAddressV2FromBytes(time.Now(), services, ip, port)
   773  	} else {
   774  		// This is an non-nil IP address that was parsed in the else if
   775  		// above.
   776  		na = wire.NetAddressV2FromBytes(time.Now(), services, ip, port)
   777  	}
   778  
   779  	return na, nil
   780  }
   781  
   782  // NetAddressKey returns a string key in the form of ip:port for IPv4 addresses
   783  // or [ip]:port for IPv6 addresses. It also handles onion v2 and v3 addresses.
   784  func NetAddressKey(na *wire.NetAddressV2) string {
   785  	port := strconv.FormatUint(uint64(na.Port), 10)
   786  
   787  	return net.JoinHostPort(na.Addr.String(), port)
   788  }
   789  
   790  // GetAddress returns a single address that should be routable.  It picks a
   791  // random one from the possible addresses with preference given to ones that
   792  // have not been used recently and should not pick 'close' addresses
   793  // consecutively.
   794  func (a *AddrManager) GetAddress() *KnownAddress {
   795  	// Protect concurrent access.
   796  	a.mtx.Lock()
   797  	defer a.mtx.Unlock()
   798  
   799  	if a.numAddresses() == 0 {
   800  		return nil
   801  	}
   802  
   803  	// Use a 50% chance for choosing between tried and new table entries.
   804  	if a.nTried > 0 && (a.nNew == 0 || a.rand.Intn(2) == 0) {
   805  		// Tried entry.
   806  		large := 1 << 30
   807  		factor := 1.0
   808  		for {
   809  			// pick a random bucket.
   810  			bucket := a.rand.Intn(len(a.addrTried))
   811  			if a.addrTried[bucket].Len() == 0 {
   812  				continue
   813  			}
   814  
   815  			// Pick a random entry in the list
   816  			e := a.addrTried[bucket].Front()
   817  			for i :=
   818  				a.rand.Int63n(int64(a.addrTried[bucket].Len())); i > 0; i-- {
   819  				e = e.Next()
   820  			}
   821  			ka := e.Value.(*KnownAddress)
   822  			randval := a.rand.Intn(large)
   823  			if float64(randval) < (factor * ka.chance() * float64(large)) {
   824  				log.Tracef("Selected %v from tried bucket",
   825  					NetAddressKey(ka.na))
   826  				return ka
   827  			}
   828  			factor *= 1.2
   829  		}
   830  	} else {
   831  		// new node.
   832  		// XXX use a closure/function to avoid repeating this.
   833  		large := 1 << 30
   834  		factor := 1.0
   835  		for {
   836  			// Pick a random bucket.
   837  			bucket := a.rand.Intn(len(a.addrNew))
   838  			if len(a.addrNew[bucket]) == 0 {
   839  				continue
   840  			}
   841  			// Then, a random entry in it.
   842  			var ka *KnownAddress
   843  			nth := a.rand.Intn(len(a.addrNew[bucket]))
   844  			for _, value := range a.addrNew[bucket] {
   845  				if nth == 0 {
   846  					ka = value
   847  				}
   848  				nth--
   849  			}
   850  			randval := a.rand.Intn(large)
   851  			if float64(randval) < (factor * ka.chance() * float64(large)) {
   852  				log.Tracef("Selected %v from new bucket",
   853  					NetAddressKey(ka.na))
   854  				return ka
   855  			}
   856  			factor *= 1.2
   857  		}
   858  	}
   859  }
   860  
   861  func (a *AddrManager) find(addr *wire.NetAddressV2) *KnownAddress {
   862  	return a.addrIndex[NetAddressKey(addr)]
   863  }
   864  
   865  // Attempt increases the given address' attempt counter and updates
   866  // the last attempt time.
   867  func (a *AddrManager) Attempt(addr *wire.NetAddressV2) {
   868  	a.mtx.Lock()
   869  	defer a.mtx.Unlock()
   870  
   871  	// find address.
   872  	// Surely address will be in tried by now?
   873  	ka := a.find(addr)
   874  	if ka == nil {
   875  		return
   876  	}
   877  	// set last tried time to now
   878  	now := time.Now()
   879  	ka.mtx.Lock()
   880  	ka.attempts++
   881  	ka.lastattempt = now
   882  	ka.mtx.Unlock()
   883  }
   884  
   885  // Connected Marks the given address as currently connected and working at the
   886  // current time.  The address must already be known to AddrManager else it will
   887  // be ignored.
   888  func (a *AddrManager) Connected(addr *wire.NetAddressV2) {
   889  	a.mtx.Lock()
   890  	defer a.mtx.Unlock()
   891  
   892  	ka := a.find(addr)
   893  	if ka == nil {
   894  		return
   895  	}
   896  
   897  	// Update the time as long as it has been 20 minutes since last we did
   898  	// so.
   899  	now := time.Now()
   900  	if now.After(ka.na.Timestamp.Add(time.Minute * 20)) {
   901  		// ka.na is immutable, so replace it.
   902  		naCopy := *ka.na
   903  		naCopy.Timestamp = time.Now()
   904  		ka.mtx.Lock()
   905  		ka.na = &naCopy
   906  		ka.mtx.Unlock()
   907  	}
   908  }
   909  
   910  // Good marks the given address as good.  To be called after a successful
   911  // connection and version exchange.  If the address is unknown to the address
   912  // manager it will be ignored.
   913  func (a *AddrManager) Good(addr *wire.NetAddressV2) {
   914  	a.mtx.Lock()
   915  	defer a.mtx.Unlock()
   916  
   917  	ka := a.find(addr)
   918  	if ka == nil {
   919  		return
   920  	}
   921  
   922  	// ka.Timestamp is not updated here to avoid leaking information
   923  	// about currently connected peers.
   924  	now := time.Now()
   925  	ka.mtx.Lock()
   926  	ka.lastsuccess = now
   927  	ka.lastattempt = now
   928  	ka.attempts = 0
   929  	ka.mtx.Unlock() // tried and refs synchronized via a.mtx
   930  
   931  	// move to tried set, optionally evicting other addresses if need.
   932  	if ka.tried {
   933  		return
   934  	}
   935  
   936  	// ok, need to move it to tried.
   937  
   938  	// remove from all new buckets.
   939  	// record one of the buckets in question and call it the `first'
   940  	addrKey := NetAddressKey(addr)
   941  	oldBucket := -1
   942  	for i := range a.addrNew {
   943  		// we check for existence so we can record the first one
   944  		if _, ok := a.addrNew[i][addrKey]; ok {
   945  			delete(a.addrNew[i], addrKey)
   946  			ka.refs--
   947  			if oldBucket == -1 {
   948  				oldBucket = i
   949  			}
   950  		}
   951  	}
   952  	a.nNew--
   953  
   954  	if oldBucket == -1 {
   955  		// What? wasn't in a bucket after all.... Panic?
   956  		return
   957  	}
   958  
   959  	bucket := a.getTriedBucket(ka.na)
   960  
   961  	// Room in this tried bucket?
   962  	if a.addrTried[bucket].Len() < triedBucketSize {
   963  		ka.tried = true
   964  		a.addrTried[bucket].PushBack(ka)
   965  		a.nTried++
   966  		return
   967  	}
   968  
   969  	// No room, we have to evict something else.
   970  	entry := a.pickTried(bucket)
   971  	rmka := entry.Value.(*KnownAddress)
   972  
   973  	// First bucket it would have been put in.
   974  	newBucket := a.getNewBucket(rmka.na, rmka.srcAddr)
   975  
   976  	// If no room in the original bucket, we put it in a bucket we just
   977  	// freed up a space in.
   978  	if len(a.addrNew[newBucket]) >= newBucketSize {
   979  		newBucket = oldBucket
   980  	}
   981  
   982  	// replace with ka in list.
   983  	ka.tried = true
   984  	entry.Value = ka
   985  
   986  	rmka.tried = false
   987  	rmka.refs++
   988  
   989  	// We don't touch a.nTried here since the number of tried stays the same
   990  	// but we decemented new above, raise it again since we're putting
   991  	// something back.
   992  	a.nNew++
   993  
   994  	rmkey := NetAddressKey(rmka.na)
   995  	log.Tracef("Replacing %s with %s in tried", rmkey, addrKey)
   996  
   997  	// We made sure there is space here just above.
   998  	a.addrNew[newBucket][rmkey] = rmka
   999  }
  1000  
  1001  // SetServices sets the services for the giiven address to the provided value.
  1002  func (a *AddrManager) SetServices(addr *wire.NetAddressV2, services wire.ServiceFlag) {
  1003  	a.mtx.Lock()
  1004  	defer a.mtx.Unlock()
  1005  
  1006  	ka := a.find(addr)
  1007  	if ka == nil {
  1008  		return
  1009  	}
  1010  
  1011  	// Update the services if needed.
  1012  	if ka.na.Services != services {
  1013  		// ka.na is immutable, so replace it.
  1014  		naCopy := *ka.na
  1015  		naCopy.Services = services
  1016  		ka.mtx.Lock()
  1017  		ka.na = &naCopy
  1018  		ka.mtx.Unlock()
  1019  	}
  1020  }
  1021  
  1022  // AddLocalAddress adds na to the list of known local addresses to advertise
  1023  // with the given priority.
  1024  func (a *AddrManager) AddLocalAddress(na *wire.NetAddressV2, priority AddressPriority) error {
  1025  	if !IsRoutable(na) {
  1026  		return fmt.Errorf(
  1027  			"address %s is not routable", na.Addr.String(),
  1028  		)
  1029  	}
  1030  
  1031  	a.lamtx.Lock()
  1032  	defer a.lamtx.Unlock()
  1033  
  1034  	key := NetAddressKey(na)
  1035  	la, ok := a.localAddresses[key]
  1036  	if !ok || la.score < priority {
  1037  		if ok {
  1038  			la.score = priority + 1
  1039  		} else {
  1040  			a.localAddresses[key] = &localAddress{
  1041  				na:    na,
  1042  				score: priority,
  1043  			}
  1044  		}
  1045  	}
  1046  	return nil
  1047  }
  1048  
  1049  // getReachabilityFrom returns the relative reachability of the provided local
  1050  // address to the provided remote address.
  1051  func getReachabilityFrom(localAddr, remoteAddr *wire.NetAddressV2) int {
  1052  	const (
  1053  		Unreachable = 0
  1054  		Default     = iota
  1055  		Teredo
  1056  		Ipv6Weak
  1057  		Ipv4
  1058  		Ipv6Strong
  1059  		Private
  1060  	)
  1061  
  1062  	if !IsRoutable(remoteAddr) {
  1063  		return Unreachable
  1064  	}
  1065  
  1066  	if remoteAddr.IsTorV3() {
  1067  		if localAddr.IsTorV3() {
  1068  			return Private
  1069  		}
  1070  
  1071  		lna := localAddr.ToLegacy()
  1072  		if IsOnionCatTor(lna) {
  1073  			// Modern v3 clients should not be able to connect to
  1074  			// deprecated v2 hidden services.
  1075  			return Unreachable
  1076  		}
  1077  
  1078  		if IsRoutable(localAddr) && IsIPv4(lna) {
  1079  			return Ipv4
  1080  		}
  1081  
  1082  		return Default
  1083  	}
  1084  
  1085  	// We can't be sure if the remote party can actually connect to this
  1086  	// address or not.
  1087  	if localAddr.IsTorV3() {
  1088  		return Default
  1089  	}
  1090  
  1091  	// Convert the V2 addresses into legacy to access the network
  1092  	// functions.
  1093  	remoteLna := remoteAddr.ToLegacy()
  1094  	localLna := localAddr.ToLegacy()
  1095  
  1096  	if IsOnionCatTor(remoteLna) {
  1097  		if IsOnionCatTor(localLna) {
  1098  			return Private
  1099  		}
  1100  
  1101  		if IsRoutable(localAddr) && IsIPv4(localLna) {
  1102  			return Ipv4
  1103  		}
  1104  
  1105  		return Default
  1106  	}
  1107  
  1108  	if IsRFC4380(remoteLna) {
  1109  		if !IsRoutable(localAddr) {
  1110  			return Default
  1111  		}
  1112  
  1113  		if IsRFC4380(localLna) {
  1114  			return Teredo
  1115  		}
  1116  
  1117  		if IsIPv4(localLna) {
  1118  			return Ipv4
  1119  		}
  1120  
  1121  		return Ipv6Weak
  1122  	}
  1123  
  1124  	if IsIPv4(remoteLna) {
  1125  		if IsRoutable(localAddr) && IsIPv4(localLna) {
  1126  			return Ipv4
  1127  		}
  1128  		return Unreachable
  1129  	}
  1130  
  1131  	/* ipv6 */
  1132  	var tunnelled bool
  1133  	// Is our v6 is tunnelled?
  1134  	if IsRFC3964(localLna) || IsRFC6052(localLna) || IsRFC6145(localLna) {
  1135  		tunnelled = true
  1136  	}
  1137  
  1138  	if !IsRoutable(localAddr) {
  1139  		return Default
  1140  	}
  1141  
  1142  	if IsRFC4380(localLna) {
  1143  		return Teredo
  1144  	}
  1145  
  1146  	if IsIPv4(localLna) {
  1147  		return Ipv4
  1148  	}
  1149  
  1150  	if tunnelled {
  1151  		// only prioritise ipv6 if we aren't tunnelling it.
  1152  		return Ipv6Weak
  1153  	}
  1154  
  1155  	return Ipv6Strong
  1156  }
  1157  
  1158  // GetBestLocalAddress returns the most appropriate local address to use
  1159  // for the given remote address.
  1160  func (a *AddrManager) GetBestLocalAddress(remoteAddr *wire.NetAddressV2) *wire.NetAddressV2 {
  1161  	a.lamtx.Lock()
  1162  	defer a.lamtx.Unlock()
  1163  
  1164  	bestreach := 0
  1165  	var bestscore AddressPriority
  1166  	var bestAddress *wire.NetAddressV2
  1167  	for _, la := range a.localAddresses {
  1168  		reach := getReachabilityFrom(la.na, remoteAddr)
  1169  		if reach > bestreach ||
  1170  			(reach == bestreach && la.score > bestscore) {
  1171  			bestreach = reach
  1172  			bestscore = la.score
  1173  			bestAddress = la.na
  1174  		}
  1175  	}
  1176  	if bestAddress != nil {
  1177  		log.Debugf("Suggesting address %s:%d for %s:%d",
  1178  			bestAddress.Addr.String(), bestAddress.Port,
  1179  			remoteAddr.Addr.String(), remoteAddr.Port)
  1180  	} else {
  1181  		log.Debugf("No worthy address for %s:%d",
  1182  			remoteAddr.Addr.String(), remoteAddr.Port)
  1183  
  1184  		// Send something unroutable if nothing suitable.
  1185  		var ip net.IP
  1186  		if remoteAddr.IsTorV3() {
  1187  			ip = net.IPv4zero
  1188  		} else {
  1189  			remoteLna := remoteAddr.ToLegacy()
  1190  			if !IsIPv4(remoteLna) && !IsOnionCatTor(remoteLna) {
  1191  				ip = net.IPv6zero
  1192  			} else {
  1193  				ip = net.IPv4zero
  1194  			}
  1195  		}
  1196  		services := wire.SFNodeNetwork | wire.SFNodeWitness | wire.SFNodeBloom
  1197  		bestAddress = wire.NetAddressV2FromBytes(
  1198  			time.Now(), services, ip, 0,
  1199  		)
  1200  	}
  1201  
  1202  	return bestAddress
  1203  }
  1204  
  1205  // New returns a new bitcoin address manager.
  1206  // Use Start to begin processing asynchronous address updates.
  1207  func New(dataDir string, lookupFunc func(string) ([]net.IP, error)) *AddrManager {
  1208  	am := AddrManager{
  1209  		peersFile:      filepath.Join(dataDir, "peers.json"),
  1210  		lookupFunc:     lookupFunc,
  1211  		rand:           rand.New(rand.NewSource(time.Now().UnixNano())),
  1212  		quit:           make(chan struct{}),
  1213  		localAddresses: make(map[string]*localAddress),
  1214  		version:        serialisationVersion,
  1215  	}
  1216  	am.reset()
  1217  	return &am
  1218  }