2016-11-02 22:17:50 +01:00
|
|
|
// Copyright (c) 2013-2016 The btcsuite developers
|
2018-06-03 10:27:33 +02:00
|
|
|
// Copyright (c) 2015-2018 The Decred developers
|
2013-08-06 23:55:22 +02:00
|
|
|
// Use of this source code is governed by an ISC
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2014-07-06 08:04:24 +02:00
|
|
|
package addrmgr
|
2013-08-06 23:55:22 +02:00
|
|
|
|
|
|
|
import (
|
2013-08-01 19:00:14 +02:00
|
|
|
"container/list"
|
2013-09-17 18:24:15 +02:00
|
|
|
crand "crypto/rand" // for seeding
|
2013-11-28 01:11:16 +01:00
|
|
|
"encoding/base32"
|
2013-09-17 18:24:15 +02:00
|
|
|
"encoding/binary"
|
2013-08-01 19:00:14 +02:00
|
|
|
"encoding/json"
|
2013-09-17 18:24:15 +02:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2013-08-01 19:00:14 +02:00
|
|
|
"math/rand"
|
2013-08-06 23:55:22 +02:00
|
|
|
"net"
|
2013-08-01 19:00:14 +02:00
|
|
|
"os"
|
2013-09-12 21:19:10 +02:00
|
|
|
"path/filepath"
|
2013-08-06 23:55:22 +02:00
|
|
|
"strconv"
|
2013-11-28 01:11:16 +01:00
|
|
|
"strings"
|
2013-08-06 23:55:22 +02:00
|
|
|
"sync"
|
2013-10-03 01:33:42 +02:00
|
|
|
"sync/atomic"
|
2013-08-06 23:55:22 +02:00
|
|
|
"time"
|
2014-07-02 15:50:08 +02:00
|
|
|
|
2016-08-08 21:04:33 +02:00
|
|
|
"github.com/btcsuite/btcd/chaincfg/chainhash"
|
2015-02-05 22:16:39 +01:00
|
|
|
"github.com/btcsuite/btcd/wire"
|
2013-08-06 23:55:22 +02:00
|
|
|
)
|
|
|
|
|
2014-07-11 02:03:34 +02:00
|
|
|
// AddrManager provides a concurrency safe address manager for caching potential
|
|
|
|
// peers on the bitcoin network.
|
|
|
|
type AddrManager struct {
|
|
|
|
mtx sync.Mutex
|
2014-07-11 02:28:30 +02:00
|
|
|
peersFile string
|
2014-07-11 02:03:34 +02:00
|
|
|
lookupFunc func(string) ([]net.IP, error)
|
|
|
|
rand *rand.Rand
|
|
|
|
key [32]byte
|
2015-01-28 16:44:56 +01:00
|
|
|
addrIndex map[string]*KnownAddress // address key to ka for all addrs.
|
|
|
|
addrNew [newBucketCount]map[string]*KnownAddress
|
2014-07-11 02:03:34 +02:00
|
|
|
addrTried [triedBucketCount]*list.List
|
|
|
|
started int32
|
|
|
|
shutdown int32
|
|
|
|
wg sync.WaitGroup
|
|
|
|
quit chan struct{}
|
|
|
|
nTried int
|
|
|
|
nNew int
|
|
|
|
lamtx sync.Mutex
|
|
|
|
localAddresses map[string]*localAddress
|
|
|
|
}
|
|
|
|
|
|
|
|
type serializedKnownAddress struct {
|
|
|
|
Addr string
|
|
|
|
Src string
|
|
|
|
Attempts int
|
|
|
|
TimeStamp int64
|
|
|
|
LastAttempt int64
|
|
|
|
LastSuccess int64
|
|
|
|
// no refcount or tried, that is available from context.
|
|
|
|
}
|
|
|
|
|
|
|
|
type serializedAddrManager struct {
|
|
|
|
Version int
|
|
|
|
Key [32]byte
|
|
|
|
Addresses []*serializedKnownAddress
|
|
|
|
NewBuckets [newBucketCount][]string // string is NetAddressKey
|
|
|
|
TriedBuckets [triedBucketCount][]string
|
|
|
|
}
|
|
|
|
|
|
|
|
type localAddress struct {
|
2015-02-05 22:16:39 +01:00
|
|
|
na *wire.NetAddress
|
2014-07-11 02:03:34 +02:00
|
|
|
score AddressPriority
|
|
|
|
}
|
|
|
|
|
2014-09-08 21:19:47 +02:00
|
|
|
// AddressPriority type is used to describe the hierarchy of local address
|
2014-07-11 02:03:34 +02:00
|
|
|
// discovery methods.
|
|
|
|
type AddressPriority int
|
|
|
|
|
|
|
|
const (
|
|
|
|
// InterfacePrio signifies the address is on a local interface
|
|
|
|
InterfacePrio AddressPriority = iota
|
|
|
|
|
2014-09-08 21:19:47 +02:00
|
|
|
// BoundPrio signifies the address has been explicitly bounded to.
|
2014-07-11 02:03:34 +02:00
|
|
|
BoundPrio
|
|
|
|
|
|
|
|
// UpnpPrio signifies the address was obtained from UPnP.
|
|
|
|
UpnpPrio
|
|
|
|
|
|
|
|
// HTTPPrio signifies the address was obtained from an external HTTP service.
|
|
|
|
HTTPPrio
|
|
|
|
|
|
|
|
// ManualPrio signifies the address was provided by --externalip.
|
|
|
|
ManualPrio
|
|
|
|
)
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
const (
|
2013-09-12 21:19:10 +02:00
|
|
|
// needAddressThreshold is the number of addresses under which the
|
|
|
|
// address manager will claim to need more addresses.
|
|
|
|
needAddressThreshold = 1000
|
|
|
|
|
2013-08-01 19:00:14 +02:00
|
|
|
// dumpAddressInterval is the interval used to dump the address
|
|
|
|
// cache to disk for future use.
|
2014-07-06 15:47:42 +02:00
|
|
|
dumpAddressInterval = time.Minute * 10
|
2013-08-01 19:00:14 +02:00
|
|
|
|
|
|
|
// triedBucketSize is the maximum number of addresses in each
|
|
|
|
// tried address bucket.
|
2015-04-06 17:45:57 +02:00
|
|
|
triedBucketSize = 256
|
2013-08-01 19:00:14 +02:00
|
|
|
|
2013-09-17 18:24:15 +02:00
|
|
|
// triedBucketCount is the number of buckets we split tried
|
|
|
|
// addresses over.
|
|
|
|
triedBucketCount = 64
|
|
|
|
|
2013-08-01 19:00:14 +02:00
|
|
|
// newBucketSize is the maximum number of addresses in each new address
|
|
|
|
// bucket.
|
|
|
|
newBucketSize = 64
|
|
|
|
|
2014-09-08 21:19:47 +02:00
|
|
|
// newBucketCount is the number of buckets that we spread new addresses
|
2013-09-17 18:24:15 +02:00
|
|
|
// over.
|
2015-04-06 17:45:57 +02:00
|
|
|
newBucketCount = 1024
|
2013-09-17 18:24:15 +02:00
|
|
|
|
2014-09-08 21:19:47 +02:00
|
|
|
// triedBucketsPerGroup is the number of tried buckets over which an
|
2013-09-17 18:24:15 +02:00
|
|
|
// address group will be spread.
|
2015-04-06 17:45:57 +02:00
|
|
|
triedBucketsPerGroup = 8
|
2013-09-17 18:24:15 +02:00
|
|
|
|
|
|
|
// newBucketsPerGroup is the number of new buckets over which an
|
|
|
|
// source address group will be spread.
|
2015-04-06 17:45:57 +02:00
|
|
|
newBucketsPerGroup = 64
|
2013-09-17 18:24:15 +02:00
|
|
|
|
|
|
|
// newBucketsPerAddress is the number of buckets a frequently seen new
|
|
|
|
// address may end up in.
|
2015-04-06 17:45:57 +02:00
|
|
|
newBucketsPerAddress = 8
|
2013-09-17 18:24:15 +02:00
|
|
|
|
2013-08-01 19:00:14 +02:00
|
|
|
// numMissingDays is the number of days before which we assume an
|
|
|
|
// address has vanished if we have not seen it announced in that long.
|
|
|
|
numMissingDays = 30
|
|
|
|
|
|
|
|
// numRetries is the number of tried without a single success before
|
|
|
|
// we assume an address is bad.
|
|
|
|
numRetries = 3
|
|
|
|
|
|
|
|
// maxFailures is the maximum number of failures we will accept without
|
|
|
|
// a success before considering an address bad.
|
|
|
|
maxFailures = 10
|
|
|
|
|
|
|
|
// minBadDays is the number of days since the last success before we
|
|
|
|
// will consider evicting an address.
|
|
|
|
minBadDays = 7
|
2013-09-17 18:24:15 +02:00
|
|
|
|
|
|
|
// getAddrMax is the most addresses that we will send in response
|
|
|
|
// to a getAddr (in practise the most addresses we will return from a
|
|
|
|
// call to AddressCache()).
|
|
|
|
getAddrMax = 2500
|
|
|
|
|
|
|
|
// getAddrPercent is the percentage of total addresses known that we
|
|
|
|
// will share with a call to AddressCache.
|
|
|
|
getAddrPercent = 23
|
|
|
|
|
|
|
|
// serialisationVersion is the current version of the on-disk format.
|
|
|
|
serialisationVersion = 1
|
2013-08-06 23:55:22 +02:00
|
|
|
)
|
|
|
|
|
2014-07-06 08:04:24 +02:00
|
|
|
// updateAddress is a helper function to either update an address already known
|
|
|
|
// to the address manager, or to add the address if not already known.
|
2015-02-05 22:16:39 +01:00
|
|
|
func (a *AddrManager) updateAddress(netAddr, srcAddr *wire.NetAddress) {
|
2014-07-06 08:04:24 +02:00
|
|
|
// Filter out non-routable addresses. Note that non-routable
|
|
|
|
// also includes invalid and local addresses.
|
2014-07-06 15:47:42 +02:00
|
|
|
if !IsRoutable(netAddr) {
|
2014-07-06 08:04:24 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
addr := NetAddressKey(netAddr)
|
|
|
|
ka := a.find(netAddr)
|
|
|
|
if ka != nil {
|
2016-11-16 00:43:43 +01:00
|
|
|
// TODO: only update addresses periodically.
|
2014-07-06 08:04:24 +02:00
|
|
|
// Update the last seen time and services.
|
|
|
|
// note that to prevent causing excess garbage on getaddr
|
|
|
|
// messages the netaddresses in addrmaanger are *immutable*,
|
|
|
|
// if we need to change them then we replace the pointer with a
|
|
|
|
// new copy so that we don't have to copy every na for getaddr.
|
|
|
|
if netAddr.Timestamp.After(ka.na.Timestamp) ||
|
|
|
|
(ka.na.Services&netAddr.Services) !=
|
|
|
|
netAddr.Services {
|
|
|
|
|
|
|
|
naCopy := *ka.na
|
|
|
|
naCopy.Timestamp = netAddr.Timestamp
|
|
|
|
naCopy.AddService(netAddr.Services)
|
|
|
|
ka.na = &naCopy
|
|
|
|
}
|
|
|
|
|
|
|
|
// If already in tried, we have nothing to do here.
|
|
|
|
if ka.tried {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Already at our max?
|
|
|
|
if ka.refs == newBucketsPerAddress {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// The more entries we have, the less likely we are to add more.
|
2014-09-08 21:19:47 +02:00
|
|
|
// likelihood is 2N.
|
2014-07-06 08:04:24 +02:00
|
|
|
factor := int32(2 * ka.refs)
|
|
|
|
if a.rand.Int31n(factor) != 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// Make a copy of the net address to avoid races since it is
|
|
|
|
// updated elsewhere in the addrmanager code and would otherwise
|
|
|
|
// change the actual netaddress on the peer.
|
|
|
|
netAddrCopy := *netAddr
|
2015-01-28 16:44:56 +01:00
|
|
|
ka = &KnownAddress{na: &netAddrCopy, srcAddr: srcAddr}
|
2014-07-06 08:04:24 +02:00
|
|
|
a.addrIndex[addr] = ka
|
|
|
|
a.nNew++
|
|
|
|
// XXX time penalty?
|
|
|
|
}
|
|
|
|
|
|
|
|
bucket := a.getNewBucket(netAddr, srcAddr)
|
|
|
|
|
|
|
|
// Already exists?
|
|
|
|
if _, ok := a.addrNew[bucket][addr]; ok {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Enforce max addresses.
|
|
|
|
if len(a.addrNew[bucket]) > newBucketSize {
|
2014-07-11 02:03:34 +02:00
|
|
|
log.Tracef("new bucket is full, expiring old")
|
2014-07-06 08:04:24 +02:00
|
|
|
a.expireNew(bucket)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add to new bucket.
|
|
|
|
ka.refs++
|
|
|
|
a.addrNew[bucket][addr] = ka
|
|
|
|
|
|
|
|
log.Tracef("Added new address %s for a total of %d addresses", addr,
|
|
|
|
a.nTried+a.nNew)
|
|
|
|
}
|
|
|
|
|
2013-08-01 19:00:14 +02:00
|
|
|
// expireNew makes space in the new buckets by expiring the really bad entries.
|
|
|
|
// If no bad entries are available we look at a few and remove the oldest.
|
2013-09-17 18:24:15 +02:00
|
|
|
func (a *AddrManager) expireNew(bucket int) {
|
2013-08-01 19:00:14 +02:00
|
|
|
// First see if there are any entries that are so bad we can just throw
|
|
|
|
// them away. otherwise we throw away the oldest entry in the cache.
|
|
|
|
// Bitcoind here chooses four random and just throws the oldest of
|
|
|
|
// those away, but we keep track of oldest in the initial traversal and
|
2013-09-17 18:24:15 +02:00
|
|
|
// use that information instead.
|
2015-01-28 16:44:56 +01:00
|
|
|
var oldest *KnownAddress
|
2013-09-17 18:24:15 +02:00
|
|
|
for k, v := range a.addrNew[bucket] {
|
2014-07-11 02:03:34 +02:00
|
|
|
if v.isBad() {
|
2014-07-06 08:04:24 +02:00
|
|
|
log.Tracef("expiring bad address %v", k)
|
2013-09-17 18:24:15 +02:00
|
|
|
delete(a.addrNew[bucket], k)
|
|
|
|
v.refs--
|
|
|
|
if v.refs == 0 {
|
2013-10-14 22:56:23 +02:00
|
|
|
a.nNew--
|
2013-09-17 18:24:15 +02:00
|
|
|
delete(a.addrIndex, k)
|
|
|
|
}
|
2014-07-11 02:03:34 +02:00
|
|
|
continue
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
|
|
|
if oldest == nil {
|
|
|
|
oldest = v
|
|
|
|
} else if !v.na.Timestamp.After(oldest.na.Timestamp) {
|
|
|
|
oldest = v
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if oldest != nil {
|
|
|
|
key := NetAddressKey(oldest.na)
|
2014-07-06 08:04:24 +02:00
|
|
|
log.Tracef("expiring oldest address %v", key)
|
2013-08-01 19:00:14 +02:00
|
|
|
|
2013-09-17 18:24:15 +02:00
|
|
|
delete(a.addrNew[bucket], key)
|
|
|
|
oldest.refs--
|
|
|
|
if oldest.refs == 0 {
|
2013-10-14 22:56:23 +02:00
|
|
|
a.nNew--
|
2013-09-17 18:24:15 +02:00
|
|
|
delete(a.addrIndex, key)
|
|
|
|
}
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// pickTried selects an address from the tried bucket to be evicted.
|
2013-09-17 18:24:15 +02:00
|
|
|
// We just choose the eldest. Bitcoind selects 4 random entries and throws away
|
|
|
|
// the older of them.
|
|
|
|
func (a *AddrManager) pickTried(bucket int) *list.Element {
|
2015-01-28 16:44:56 +01:00
|
|
|
var oldest *KnownAddress
|
2013-08-01 19:00:14 +02:00
|
|
|
var oldestElem *list.Element
|
2013-09-17 18:24:15 +02:00
|
|
|
for e := a.addrTried[bucket].Front(); e != nil; e = e.Next() {
|
2015-01-28 16:44:56 +01:00
|
|
|
ka := e.Value.(*KnownAddress)
|
2013-08-01 19:00:14 +02:00
|
|
|
if oldest == nil || oldest.na.Timestamp.After(ka.na.Timestamp) {
|
|
|
|
oldestElem = e
|
|
|
|
oldest = ka
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
return oldestElem
|
|
|
|
}
|
|
|
|
|
2015-02-05 22:16:39 +01:00
|
|
|
func (a *AddrManager) getNewBucket(netAddr, srcAddr *wire.NetAddress) int {
|
2013-09-17 18:24:15 +02:00
|
|
|
// bitcoind:
|
2014-09-08 21:19:47 +02:00
|
|
|
// doublesha256(key + sourcegroup + int64(doublesha256(key + group + sourcegroup))%bucket_per_source_group) % num_new_buckets
|
2013-09-17 18:24:15 +02:00
|
|
|
|
|
|
|
data1 := []byte{}
|
|
|
|
data1 = append(data1, a.key[:]...)
|
|
|
|
data1 = append(data1, []byte(GroupKey(netAddr))...)
|
|
|
|
data1 = append(data1, []byte(GroupKey(srcAddr))...)
|
2016-08-08 21:04:33 +02:00
|
|
|
hash1 := chainhash.DoubleHashB(data1)
|
2013-09-17 18:24:15 +02:00
|
|
|
hash64 := binary.LittleEndian.Uint64(hash1)
|
|
|
|
hash64 %= newBucketsPerGroup
|
2014-06-05 01:41:54 +02:00
|
|
|
var hashbuf [8]byte
|
|
|
|
binary.LittleEndian.PutUint64(hashbuf[:], hash64)
|
2013-09-17 18:24:15 +02:00
|
|
|
data2 := []byte{}
|
|
|
|
data2 = append(data2, a.key[:]...)
|
|
|
|
data2 = append(data2, GroupKey(srcAddr)...)
|
2014-06-05 01:41:54 +02:00
|
|
|
data2 = append(data2, hashbuf[:]...)
|
2013-09-17 18:24:15 +02:00
|
|
|
|
2016-08-08 21:04:33 +02:00
|
|
|
hash2 := chainhash.DoubleHashB(data2)
|
2013-09-17 18:24:15 +02:00
|
|
|
return int(binary.LittleEndian.Uint64(hash2) % newBucketCount)
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
|
|
|
|
2015-02-05 22:16:39 +01:00
|
|
|
func (a *AddrManager) getTriedBucket(netAddr *wire.NetAddress) int {
|
2013-09-17 18:24:15 +02:00
|
|
|
// bitcoind hashes this as:
|
|
|
|
// doublesha256(key + group + truncate_to_64bits(doublesha256(key)) % buckets_per_group) % num_buckets
|
|
|
|
data1 := []byte{}
|
|
|
|
data1 = append(data1, a.key[:]...)
|
|
|
|
data1 = append(data1, []byte(NetAddressKey(netAddr))...)
|
2016-08-08 21:04:33 +02:00
|
|
|
hash1 := chainhash.DoubleHashB(data1)
|
2013-09-17 18:24:15 +02:00
|
|
|
hash64 := binary.LittleEndian.Uint64(hash1)
|
|
|
|
hash64 %= triedBucketsPerGroup
|
2014-06-05 01:41:54 +02:00
|
|
|
var hashbuf [8]byte
|
|
|
|
binary.LittleEndian.PutUint64(hashbuf[:], hash64)
|
2013-09-17 18:24:15 +02:00
|
|
|
data2 := []byte{}
|
|
|
|
data2 = append(data2, a.key[:]...)
|
|
|
|
data2 = append(data2, GroupKey(netAddr)...)
|
2014-06-05 01:41:54 +02:00
|
|
|
data2 = append(data2, hashbuf[:]...)
|
2013-09-17 18:24:15 +02:00
|
|
|
|
2016-08-08 21:04:33 +02:00
|
|
|
hash2 := chainhash.DoubleHashB(data2)
|
2013-09-17 18:24:15 +02:00
|
|
|
return int(binary.LittleEndian.Uint64(hash2) % triedBucketCount)
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// addressHandler is the main handler for the address manager. It must be run
|
|
|
|
// as a goroutine.
|
|
|
|
func (a *AddrManager) addressHandler() {
|
|
|
|
dumpAddressTicker := time.NewTicker(dumpAddressInterval)
|
2014-12-04 01:20:19 +01:00
|
|
|
defer dumpAddressTicker.Stop()
|
2013-08-06 23:55:22 +02:00
|
|
|
out:
|
2013-10-03 01:33:42 +02:00
|
|
|
for {
|
2013-08-06 23:55:22 +02:00
|
|
|
select {
|
|
|
|
case <-dumpAddressTicker.C:
|
2013-10-03 01:33:42 +02:00
|
|
|
a.savePeers()
|
2013-08-06 23:55:22 +02:00
|
|
|
|
|
|
|
case <-a.quit:
|
|
|
|
break out
|
|
|
|
}
|
|
|
|
}
|
2013-10-03 01:33:42 +02:00
|
|
|
a.savePeers()
|
2013-08-06 23:55:22 +02:00
|
|
|
a.wg.Done()
|
2014-07-06 08:04:24 +02:00
|
|
|
log.Trace("Address handler done")
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
2013-08-01 19:00:14 +02:00
|
|
|
// savePeers saves all the known addresses to a file so they can be read back
|
|
|
|
// in at next run.
|
|
|
|
func (a *AddrManager) savePeers() {
|
2013-10-02 21:27:08 +02:00
|
|
|
a.mtx.Lock()
|
|
|
|
defer a.mtx.Unlock()
|
2014-07-11 02:23:31 +02:00
|
|
|
|
2013-09-17 18:24:15 +02:00
|
|
|
// First we make a serialisable datastructure so we can encode it to
|
|
|
|
// json.
|
2014-07-06 15:47:42 +02:00
|
|
|
sam := new(serializedAddrManager)
|
2013-09-17 18:24:15 +02:00
|
|
|
sam.Version = serialisationVersion
|
|
|
|
copy(sam.Key[:], a.key[:])
|
|
|
|
|
2014-07-06 15:47:42 +02:00
|
|
|
sam.Addresses = make([]*serializedKnownAddress, len(a.addrIndex))
|
2013-09-17 18:24:15 +02:00
|
|
|
i := 0
|
|
|
|
for k, v := range a.addrIndex {
|
2014-07-06 15:47:42 +02:00
|
|
|
ska := new(serializedKnownAddress)
|
2013-09-17 18:24:15 +02:00
|
|
|
ska.Addr = k
|
|
|
|
ska.TimeStamp = v.na.Timestamp.Unix()
|
|
|
|
ska.Src = NetAddressKey(v.srcAddr)
|
|
|
|
ska.Attempts = v.attempts
|
|
|
|
ska.LastAttempt = v.lastattempt.Unix()
|
|
|
|
ska.LastSuccess = v.lastsuccess.Unix()
|
|
|
|
// Tried and refs are implicit in the rest of the structure
|
|
|
|
// and will be worked out from context on unserialisation.
|
|
|
|
sam.Addresses[i] = ska
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
for i := range a.addrNew {
|
|
|
|
sam.NewBuckets[i] = make([]string, len(a.addrNew[i]))
|
|
|
|
j := 0
|
|
|
|
for k := range a.addrNew[i] {
|
|
|
|
sam.NewBuckets[i][j] = k
|
|
|
|
j++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for i := range a.addrTried {
|
|
|
|
sam.TriedBuckets[i] = make([]string, a.addrTried[i].Len())
|
|
|
|
j := 0
|
|
|
|
for e := a.addrTried[i].Front(); e != nil; e = e.Next() {
|
2015-01-28 16:44:56 +01:00
|
|
|
ka := e.Value.(*KnownAddress)
|
2013-09-17 18:24:15 +02:00
|
|
|
sam.TriedBuckets[i][j] = NetAddressKey(ka.na)
|
|
|
|
j++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-07-11 02:28:30 +02:00
|
|
|
w, err := os.Create(a.peersFile)
|
2013-08-01 19:00:14 +02:00
|
|
|
if err != nil {
|
2014-08-28 17:49:49 +02:00
|
|
|
log.Errorf("Error opening file %s: %v", a.peersFile, err)
|
2013-10-12 18:45:38 +02:00
|
|
|
return
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
|
|
|
enc := json.NewEncoder(w)
|
|
|
|
defer w.Close()
|
2014-07-03 20:33:56 +02:00
|
|
|
if err := enc.Encode(&sam); err != nil {
|
2014-07-11 02:28:30 +02:00
|
|
|
log.Errorf("Failed to encode file %s: %v", a.peersFile, err)
|
2014-07-03 20:33:56 +02:00
|
|
|
return
|
|
|
|
}
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// loadPeers loads the known address from the saved file. If empty, missing, or
|
|
|
|
// malformed file, just don't load anything and start fresh
|
|
|
|
func (a *AddrManager) loadPeers() {
|
2013-10-02 21:27:08 +02:00
|
|
|
a.mtx.Lock()
|
|
|
|
defer a.mtx.Unlock()
|
|
|
|
|
2014-07-11 02:28:30 +02:00
|
|
|
err := a.deserializePeers(a.peersFile)
|
2013-09-17 18:24:15 +02:00
|
|
|
if err != nil {
|
2014-07-11 02:28:30 +02:00
|
|
|
log.Errorf("Failed to parse file %s: %v", a.peersFile, err)
|
2013-09-17 18:24:15 +02:00
|
|
|
// if it is invalid we nuke the old one unconditionally.
|
2014-07-11 02:28:30 +02:00
|
|
|
err = os.Remove(a.peersFile)
|
2013-09-17 18:24:15 +02:00
|
|
|
if err != nil {
|
2014-07-11 02:28:30 +02:00
|
|
|
log.Warnf("Failed to remove corrupt peers file %s: %v",
|
|
|
|
a.peersFile, err)
|
2013-09-17 18:24:15 +02:00
|
|
|
}
|
|
|
|
a.reset()
|
|
|
|
return
|
|
|
|
}
|
2014-07-11 02:28:30 +02:00
|
|
|
log.Infof("Loaded %d addresses from file '%s'", a.numAddresses(), a.peersFile)
|
2013-09-17 18:24:15 +02:00
|
|
|
}
|
|
|
|
|
2014-07-06 15:47:42 +02:00
|
|
|
func (a *AddrManager) deserializePeers(filePath string) error {
|
2013-09-17 18:24:15 +02:00
|
|
|
|
2013-09-12 21:19:10 +02:00
|
|
|
_, err := os.Stat(filePath)
|
2013-08-01 19:00:14 +02:00
|
|
|
if os.IsNotExist(err) {
|
2013-10-02 16:25:43 +02:00
|
|
|
return nil
|
2013-09-17 18:24:15 +02:00
|
|
|
}
|
|
|
|
r, err := os.Open(filePath)
|
|
|
|
if err != nil {
|
2013-10-04 07:37:15 +02:00
|
|
|
return fmt.Errorf("%s error opening file: %v", filePath, err)
|
2013-09-17 18:24:15 +02:00
|
|
|
}
|
|
|
|
defer r.Close()
|
|
|
|
|
2014-07-06 15:47:42 +02:00
|
|
|
var sam serializedAddrManager
|
2013-09-17 18:24:15 +02:00
|
|
|
dec := json.NewDecoder(r)
|
|
|
|
err = dec.Decode(&sam)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error reading %s: %v", filePath, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if sam.Version != serialisationVersion {
|
2014-07-06 15:47:42 +02:00
|
|
|
return fmt.Errorf("unknown version %v in serialized "+
|
2013-09-17 18:24:15 +02:00
|
|
|
"addrmanager", sam.Version)
|
|
|
|
}
|
|
|
|
copy(a.key[:], sam.Key[:])
|
|
|
|
|
|
|
|
for _, v := range sam.Addresses {
|
2015-01-28 16:44:56 +01:00
|
|
|
ka := new(KnownAddress)
|
2014-07-06 15:47:42 +02:00
|
|
|
ka.na, err = a.DeserializeNetAddress(v.Addr)
|
2013-08-01 19:00:14 +02:00
|
|
|
if err != nil {
|
2014-07-06 15:47:42 +02:00
|
|
|
return fmt.Errorf("failed to deserialize netaddress "+
|
2013-09-17 18:24:15 +02:00
|
|
|
"%s: %v", v.Addr, err)
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
2014-07-06 15:47:42 +02:00
|
|
|
ka.srcAddr, err = a.DeserializeNetAddress(v.Src)
|
2013-08-01 19:00:14 +02:00
|
|
|
if err != nil {
|
2014-07-06 15:47:42 +02:00
|
|
|
return fmt.Errorf("failed to deserialize netaddress "+
|
2013-09-17 18:24:15 +02:00
|
|
|
"%s: %v", v.Src, err)
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
2013-09-17 18:24:15 +02:00
|
|
|
ka.attempts = v.Attempts
|
|
|
|
ka.lastattempt = time.Unix(v.LastAttempt, 0)
|
|
|
|
ka.lastsuccess = time.Unix(v.LastSuccess, 0)
|
|
|
|
a.addrIndex[NetAddressKey(ka.na)] = ka
|
|
|
|
}
|
|
|
|
|
|
|
|
for i := range sam.NewBuckets {
|
|
|
|
for _, val := range sam.NewBuckets[i] {
|
|
|
|
ka, ok := a.addrIndex[val]
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("newbucket contains %s but "+
|
|
|
|
"none in address list", val)
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
2013-09-17 18:24:15 +02:00
|
|
|
|
|
|
|
if ka.refs == 0 {
|
|
|
|
a.nNew++
|
|
|
|
}
|
|
|
|
ka.refs++
|
|
|
|
a.addrNew[i][val] = ka
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
|
|
|
}
|
2013-09-17 18:24:15 +02:00
|
|
|
for i := range sam.TriedBuckets {
|
|
|
|
for _, val := range sam.TriedBuckets[i] {
|
|
|
|
ka, ok := a.addrIndex[val]
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("Newbucket contains %s but "+
|
|
|
|
"none in address list", val)
|
|
|
|
}
|
|
|
|
|
|
|
|
ka.tried = true
|
|
|
|
a.nTried++
|
|
|
|
a.addrTried[i].PushBack(ka)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Sanity checking.
|
|
|
|
for k, v := range a.addrIndex {
|
|
|
|
if v.refs == 0 && !v.tried {
|
|
|
|
return fmt.Errorf("address %s after serialisation "+
|
|
|
|
"with no references", k)
|
|
|
|
}
|
|
|
|
|
|
|
|
if v.refs > 0 && v.tried {
|
|
|
|
return fmt.Errorf("address %s after serialisation "+
|
|
|
|
"which is both new and tried!", k)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-02-05 22:16:39 +01:00
|
|
|
// DeserializeNetAddress converts a given address string to a *wire.NetAddress
|
|
|
|
func (a *AddrManager) DeserializeNetAddress(addr string) (*wire.NetAddress, error) {
|
2013-09-17 18:24:15 +02:00
|
|
|
host, portStr, err := net.SplitHostPort(addr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
port, err := strconv.ParseUint(portStr, 10, 16)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2013-11-28 19:37:37 +01:00
|
|
|
|
2015-02-05 22:16:39 +01:00
|
|
|
return a.HostToNetAddress(host, uint16(port), wire.SFNodeNetwork)
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
// Start begins the core address handler which manages a pool of known
|
|
|
|
// addresses, timeouts, and interval based writes.
|
|
|
|
func (a *AddrManager) Start() {
|
|
|
|
// Already started?
|
2013-10-03 01:33:42 +02:00
|
|
|
if atomic.AddInt32(&a.started, 1) != 1 {
|
2013-08-06 23:55:22 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-07-06 08:04:24 +02:00
|
|
|
log.Trace("Starting address manager")
|
2013-08-06 23:55:22 +02:00
|
|
|
|
2013-08-01 19:00:14 +02:00
|
|
|
// Load peers we already know about from file.
|
|
|
|
a.loadPeers()
|
2013-10-03 01:33:42 +02:00
|
|
|
|
|
|
|
// Start the address ticker to save addresses periodically.
|
2014-07-11 02:23:31 +02:00
|
|
|
a.wg.Add(1)
|
2013-10-03 01:33:42 +02:00
|
|
|
go a.addressHandler()
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Stop gracefully shuts down the address manager by stopping the main handler.
|
|
|
|
func (a *AddrManager) Stop() error {
|
2013-10-03 01:33:42 +02:00
|
|
|
if atomic.AddInt32(&a.shutdown, 1) != 1 {
|
2014-07-06 08:04:24 +02:00
|
|
|
log.Warnf("Address manager is already in the process of " +
|
2013-08-06 23:55:22 +02:00
|
|
|
"shutting down")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-07-06 08:04:24 +02:00
|
|
|
log.Infof("Address manager shutting down")
|
2013-10-03 01:33:42 +02:00
|
|
|
close(a.quit)
|
2013-08-06 23:55:22 +02:00
|
|
|
a.wg.Wait()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddAddresses adds new addresses to the address manager. It enforces a max
|
|
|
|
// number of addresses and silently ignores duplicate addresses. It is
|
|
|
|
// safe for concurrent access.
|
2015-02-05 22:16:39 +01:00
|
|
|
func (a *AddrManager) AddAddresses(addrs []*wire.NetAddress, srcAddr *wire.NetAddress) {
|
2014-07-11 02:23:31 +02:00
|
|
|
a.mtx.Lock()
|
|
|
|
defer a.mtx.Unlock()
|
|
|
|
|
2013-08-01 19:00:14 +02:00
|
|
|
for _, na := range addrs {
|
2013-09-17 18:24:15 +02:00
|
|
|
a.updateAddress(na, srcAddr)
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// AddAddress adds a new address to the address manager. It enforces a max
|
|
|
|
// number of addresses and silently ignores duplicate addresses. It is
|
|
|
|
// safe for concurrent access.
|
2015-02-05 22:16:39 +01:00
|
|
|
func (a *AddrManager) AddAddress(addr, srcAddr *wire.NetAddress) {
|
2014-07-11 02:23:31 +02:00
|
|
|
a.mtx.Lock()
|
|
|
|
defer a.mtx.Unlock()
|
|
|
|
|
|
|
|
a.updateAddress(addr, srcAddr)
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// AddAddressByIP adds an address where we are given an ip:port and not a
|
2015-02-05 22:16:39 +01:00
|
|
|
// wire.NetAddress.
|
2014-07-10 03:24:06 +02:00
|
|
|
func (a *AddrManager) AddAddressByIP(addrIP string) error {
|
2013-08-01 19:00:14 +02:00
|
|
|
// Split IP and port
|
|
|
|
addr, portStr, err := net.SplitHostPort(addrIP)
|
|
|
|
if err != nil {
|
2014-07-10 03:24:06 +02:00
|
|
|
return err
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
2015-02-05 22:16:39 +01:00
|
|
|
// Put it in wire.Netaddress
|
2016-12-06 20:48:02 +01:00
|
|
|
ip := net.ParseIP(addr)
|
|
|
|
if ip == nil {
|
2014-07-10 03:24:06 +02:00
|
|
|
return fmt.Errorf("invalid ip address %s", addr)
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
|
|
|
port, err := strconv.ParseUint(portStr, 10, 0)
|
|
|
|
if err != nil {
|
2014-07-10 03:24:06 +02:00
|
|
|
return fmt.Errorf("invalid port %s: %v", portStr, err)
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
2016-12-06 20:48:02 +01:00
|
|
|
na := wire.NewNetAddressIPPort(ip, uint16(port), 0)
|
|
|
|
a.AddAddress(na, na) // XXX use correct src address
|
2014-07-10 03:24:06 +02:00
|
|
|
return nil
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
2014-07-11 02:23:31 +02:00
|
|
|
// NumAddresses returns the number of addresses known to the address manager.
|
|
|
|
func (a *AddrManager) numAddresses() int {
|
|
|
|
return a.nTried + a.nNew
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// NumAddresses returns the number of addresses known to the address manager.
|
|
|
|
func (a *AddrManager) NumAddresses() int {
|
2013-08-01 19:00:14 +02:00
|
|
|
a.mtx.Lock()
|
|
|
|
defer a.mtx.Unlock()
|
2013-08-06 23:55:22 +02:00
|
|
|
|
2014-07-11 02:23:31 +02:00
|
|
|
return a.numAddresses()
|
|
|
|
}
|
|
|
|
|
|
|
|
// NeedMoreAddresses returns whether or not the address manager needs more
|
|
|
|
// addresses.
|
|
|
|
func (a *AddrManager) NeedMoreAddresses() bool {
|
|
|
|
a.mtx.Lock()
|
|
|
|
defer a.mtx.Unlock()
|
|
|
|
|
|
|
|
return a.numAddresses() < needAddressThreshold
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// AddressCache returns the current address cache. It must be treated as
|
2013-08-01 19:00:14 +02:00
|
|
|
// read-only (but since it is a copy now, this is not as dangerous).
|
2015-02-05 22:16:39 +01:00
|
|
|
func (a *AddrManager) AddressCache() []*wire.NetAddress {
|
2013-08-01 19:00:14 +02:00
|
|
|
a.mtx.Lock()
|
|
|
|
defer a.mtx.Unlock()
|
2016-09-26 19:16:40 +02:00
|
|
|
|
|
|
|
addrIndexLen := len(a.addrIndex)
|
|
|
|
if addrIndexLen == 0 {
|
2013-09-17 18:24:15 +02:00
|
|
|
return nil
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
|
|
|
|
2016-09-26 19:16:40 +02:00
|
|
|
allAddr := make([]*wire.NetAddress, 0, addrIndexLen)
|
2013-09-17 18:24:15 +02:00
|
|
|
// Iteration order is undefined here, but we randomise it anyway.
|
|
|
|
for _, v := range a.addrIndex {
|
2016-09-26 19:16:40 +02:00
|
|
|
allAddr = append(allAddr, v.na)
|
2013-09-17 18:24:15 +02:00
|
|
|
}
|
|
|
|
|
2016-09-26 19:16:40 +02:00
|
|
|
numAddresses := addrIndexLen * getAddrPercent / 100
|
2013-09-17 18:24:15 +02:00
|
|
|
if numAddresses > getAddrMax {
|
|
|
|
numAddresses = getAddrMax
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
|
|
|
|
2014-04-23 16:16:31 +02:00
|
|
|
// Fisher-Yates shuffle the array. We only need to do the first
|
|
|
|
// `numAddresses' since we are throwing the rest.
|
|
|
|
for i := 0; i < numAddresses; i++ {
|
|
|
|
// pick a number between current index and the end
|
2016-09-26 19:16:40 +02:00
|
|
|
j := rand.Intn(addrIndexLen-i) + i
|
2014-04-23 16:16:31 +02:00
|
|
|
allAddr[i], allAddr[j] = allAddr[j], allAddr[i]
|
|
|
|
}
|
|
|
|
|
2013-09-17 18:24:15 +02:00
|
|
|
// slice off the limit we are willing to share.
|
2016-09-26 19:16:40 +02:00
|
|
|
return allAddr[0:numAddresses]
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
|
|
|
|
2013-09-17 18:24:15 +02:00
|
|
|
// reset resets the address manager by reinitialising the random source
|
|
|
|
// and allocating fresh empty bucket storage.
|
|
|
|
func (a *AddrManager) reset() {
|
2013-08-01 19:00:14 +02:00
|
|
|
|
2015-01-28 16:44:56 +01:00
|
|
|
a.addrIndex = make(map[string]*KnownAddress)
|
2013-08-01 19:00:14 +02:00
|
|
|
|
2013-09-17 18:24:15 +02:00
|
|
|
// fill key with bytes from a good random source.
|
|
|
|
io.ReadFull(crand.Reader, a.key[:])
|
|
|
|
for i := range a.addrNew {
|
2015-01-28 16:44:56 +01:00
|
|
|
a.addrNew[i] = make(map[string]*KnownAddress)
|
2013-09-17 18:24:15 +02:00
|
|
|
}
|
|
|
|
for i := range a.addrTried {
|
|
|
|
a.addrTried[i] = list.New()
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
|
|
|
|
2017-05-30 16:59:51 +02:00
|
|
|
// HostToNetAddress returns a netaddress given a host address. If the address
|
|
|
|
// is a Tor .onion address this will be taken care of. Else if the host is
|
|
|
|
// not an IP address it will be resolved (via Tor if required).
|
2015-02-05 22:16:39 +01:00
|
|
|
func (a *AddrManager) HostToNetAddress(host string, port uint16, services wire.ServiceFlag) (*wire.NetAddress, error) {
|
2017-05-30 16:59:51 +02:00
|
|
|
// Tor address is 16 char base32 + ".onion"
|
2013-11-28 01:11:16 +01:00
|
|
|
var ip net.IP
|
|
|
|
if len(host) == 22 && host[16:] == ".onion" {
|
|
|
|
// go base32 encoding uses capitals (as does the rfc
|
2017-05-30 16:59:51 +02:00
|
|
|
// but Tor and bitcoind tend to user lowercase, so we switch
|
2013-11-28 01:11:16 +01:00
|
|
|
// case here.
|
|
|
|
data, err := base32.StdEncoding.DecodeString(
|
|
|
|
strings.ToUpper(host[:16]))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
prefix := []byte{0xfd, 0x87, 0xd8, 0x7e, 0xeb, 0x43}
|
|
|
|
ip = net.IP(append(prefix, data...))
|
|
|
|
} else if ip = net.ParseIP(host); ip == nil {
|
2014-07-06 08:04:24 +02:00
|
|
|
ips, err := a.lookupFunc(host)
|
2013-11-28 01:11:16 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if len(ips) == 0 {
|
2014-07-02 16:25:42 +02:00
|
|
|
return nil, fmt.Errorf("no addresses found for %s", host)
|
2013-11-28 01:11:16 +01:00
|
|
|
}
|
|
|
|
ip = ips[0]
|
|
|
|
}
|
|
|
|
|
2015-02-05 22:16:39 +01:00
|
|
|
return wire.NewNetAddressIPPort(ip, port, services), nil
|
2013-11-28 01:11:16 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// ipString returns a string for the ip from the provided NetAddress. If the
|
2017-05-30 16:59:51 +02:00
|
|
|
// ip is in the range used for Tor addresses then it will be transformed into
|
2014-09-08 21:19:47 +02:00
|
|
|
// the relevant .onion address.
|
2015-02-05 22:16:39 +01:00
|
|
|
func ipString(na *wire.NetAddress) string {
|
2014-07-06 15:47:42 +02:00
|
|
|
if IsOnionCatTor(na) {
|
2017-05-30 16:59:51 +02:00
|
|
|
// We know now that na.IP is long enough.
|
2013-11-28 01:11:16 +01:00
|
|
|
base32 := base32.StdEncoding.EncodeToString(na.IP[6:])
|
|
|
|
return strings.ToLower(base32) + ".onion"
|
|
|
|
}
|
2014-07-11 02:23:31 +02:00
|
|
|
|
2014-07-02 16:25:42 +02:00
|
|
|
return na.IP.String()
|
2013-11-28 01:11:16 +01:00
|
|
|
}
|
|
|
|
|
2013-08-06 23:55:22 +02:00
|
|
|
// NetAddressKey returns a string key in the form of ip:port for IPv4 addresses
|
|
|
|
// or [ip]:port for IPv6 addresses.
|
2015-02-05 22:16:39 +01:00
|
|
|
func NetAddressKey(na *wire.NetAddress) string {
|
2013-08-06 23:55:22 +02:00
|
|
|
port := strconv.FormatUint(uint64(na.Port), 10)
|
2014-07-11 02:23:31 +02:00
|
|
|
|
|
|
|
return net.JoinHostPort(ipString(na), port)
|
2013-08-06 23:55:22 +02:00
|
|
|
}
|
2013-08-01 19:00:14 +02:00
|
|
|
|
|
|
|
// GetAddress returns a single address that should be routable. It picks a
|
|
|
|
// random one from the possible addresses with preference given to ones that
|
|
|
|
// have not been used recently and should not pick 'close' addresses
|
|
|
|
// consecutively.
|
2016-11-21 15:56:46 +01:00
|
|
|
func (a *AddrManager) GetAddress() *KnownAddress {
|
2013-08-01 19:00:14 +02:00
|
|
|
// Protect concurrent access.
|
|
|
|
a.mtx.Lock()
|
|
|
|
defer a.mtx.Unlock()
|
|
|
|
|
2014-07-11 02:23:31 +02:00
|
|
|
if a.numAddresses() == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-04-06 18:13:00 +02:00
|
|
|
// Use a 50% chance for choosing between tried and new table entries.
|
|
|
|
if a.nTried > 0 && (a.nNew == 0 || a.rand.Intn(2) == 0) {
|
2013-08-01 19:00:14 +02:00
|
|
|
// Tried entry.
|
|
|
|
large := 1 << 30
|
|
|
|
factor := 1.0
|
|
|
|
for {
|
2013-09-17 18:24:15 +02:00
|
|
|
// pick a random bucket.
|
|
|
|
bucket := a.rand.Intn(len(a.addrTried))
|
|
|
|
if a.addrTried[bucket].Len() == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2013-08-01 19:00:14 +02:00
|
|
|
// Pick a random entry in the list
|
2013-09-17 18:24:15 +02:00
|
|
|
e := a.addrTried[bucket].Front()
|
|
|
|
for i :=
|
|
|
|
a.rand.Int63n(int64(a.addrTried[bucket].Len())); i > 0; i-- {
|
2013-08-01 19:00:14 +02:00
|
|
|
e = e.Next()
|
|
|
|
}
|
2015-01-28 16:44:56 +01:00
|
|
|
ka := e.Value.(*KnownAddress)
|
2013-08-01 19:00:14 +02:00
|
|
|
randval := a.rand.Intn(large)
|
2014-07-11 02:03:34 +02:00
|
|
|
if float64(randval) < (factor * ka.chance() * float64(large)) {
|
2014-07-06 08:04:24 +02:00
|
|
|
log.Tracef("Selected %v from tried bucket",
|
2013-11-21 19:03:56 +01:00
|
|
|
NetAddressKey(ka.na))
|
2013-08-01 19:00:14 +02:00
|
|
|
return ka
|
|
|
|
}
|
|
|
|
factor *= 1.2
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// new node.
|
|
|
|
// XXX use a closure/function to avoid repeating this.
|
|
|
|
large := 1 << 30
|
|
|
|
factor := 1.0
|
|
|
|
for {
|
2013-09-17 18:24:15 +02:00
|
|
|
// Pick a random bucket.
|
|
|
|
bucket := a.rand.Intn(len(a.addrNew))
|
|
|
|
if len(a.addrNew[bucket]) == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
// Then, a random entry in it.
|
2015-01-28 16:44:56 +01:00
|
|
|
var ka *KnownAddress
|
2013-09-17 18:24:15 +02:00
|
|
|
nth := a.rand.Intn(len(a.addrNew[bucket]))
|
|
|
|
for _, value := range a.addrNew[bucket] {
|
|
|
|
if nth == 0 {
|
|
|
|
ka = value
|
|
|
|
}
|
|
|
|
nth--
|
|
|
|
}
|
2013-08-01 19:00:14 +02:00
|
|
|
randval := a.rand.Intn(large)
|
2014-07-11 02:03:34 +02:00
|
|
|
if float64(randval) < (factor * ka.chance() * float64(large)) {
|
2014-07-06 08:04:24 +02:00
|
|
|
log.Tracef("Selected %v from new bucket",
|
2013-08-01 19:00:14 +02:00
|
|
|
NetAddressKey(ka.na))
|
|
|
|
return ka
|
|
|
|
}
|
|
|
|
factor *= 1.2
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-02-05 22:16:39 +01:00
|
|
|
func (a *AddrManager) find(addr *wire.NetAddress) *KnownAddress {
|
2013-08-01 19:00:14 +02:00
|
|
|
return a.addrIndex[NetAddressKey(addr)]
|
|
|
|
}
|
|
|
|
|
2014-07-06 15:47:42 +02:00
|
|
|
// Attempt increases the given address' attempt counter and updates
|
|
|
|
// the last attempt time.
|
2015-02-05 22:16:39 +01:00
|
|
|
func (a *AddrManager) Attempt(addr *wire.NetAddress) {
|
2013-08-01 19:00:14 +02:00
|
|
|
a.mtx.Lock()
|
|
|
|
defer a.mtx.Unlock()
|
|
|
|
|
|
|
|
// find address.
|
|
|
|
// Surely address will be in tried by now?
|
|
|
|
ka := a.find(addr)
|
|
|
|
if ka == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// set last tried time to now
|
|
|
|
ka.attempts++
|
|
|
|
ka.lastattempt = time.Now()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Connected Marks the given address as currently connected and working at the
|
|
|
|
// current time. The address must already be known to AddrManager else it will
|
|
|
|
// be ignored.
|
2015-02-05 22:16:39 +01:00
|
|
|
func (a *AddrManager) Connected(addr *wire.NetAddress) {
|
2013-08-01 19:00:14 +02:00
|
|
|
a.mtx.Lock()
|
|
|
|
defer a.mtx.Unlock()
|
|
|
|
|
|
|
|
ka := a.find(addr)
|
|
|
|
if ka == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update the time as long as it has been 20 minutes since last we did
|
|
|
|
// so.
|
|
|
|
now := time.Now()
|
|
|
|
if now.After(ka.na.Timestamp.Add(time.Minute * 20)) {
|
2014-04-18 15:49:43 +02:00
|
|
|
// ka.na is immutable, so replace it.
|
|
|
|
naCopy := *ka.na
|
|
|
|
naCopy.Timestamp = time.Now()
|
|
|
|
ka.na = &naCopy
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-09-12 21:19:10 +02:00
|
|
|
// Good marks the given address as good. To be called after a successful
|
2014-09-08 21:19:47 +02:00
|
|
|
// connection and version exchange. If the address is unknown to the address
|
2013-08-01 19:00:14 +02:00
|
|
|
// manager it will be ignored.
|
2015-02-05 22:16:39 +01:00
|
|
|
func (a *AddrManager) Good(addr *wire.NetAddress) {
|
2013-08-01 19:00:14 +02:00
|
|
|
a.mtx.Lock()
|
|
|
|
defer a.mtx.Unlock()
|
|
|
|
|
|
|
|
ka := a.find(addr)
|
|
|
|
if ka == nil {
|
|
|
|
return
|
|
|
|
}
|
2015-03-17 18:05:11 +01:00
|
|
|
|
|
|
|
// ka.Timestamp is not updated here to avoid leaking information
|
|
|
|
// about currently connected peers.
|
2013-08-01 19:00:14 +02:00
|
|
|
now := time.Now()
|
|
|
|
ka.lastsuccess = now
|
|
|
|
ka.lastattempt = now
|
|
|
|
ka.attempts = 0
|
|
|
|
|
|
|
|
// move to tried set, optionally evicting other addresses if neeed.
|
|
|
|
if ka.tried {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// ok, need to move it to tried.
|
|
|
|
|
2013-09-17 18:24:15 +02:00
|
|
|
// remove from all new buckets.
|
|
|
|
// record one of the buckets in question and call it the `first'
|
2013-08-01 19:00:14 +02:00
|
|
|
addrKey := NetAddressKey(addr)
|
2013-09-17 18:24:15 +02:00
|
|
|
oldBucket := -1
|
|
|
|
for i := range a.addrNew {
|
2016-02-25 18:17:12 +01:00
|
|
|
// we check for existence so we can record the first one
|
2013-09-17 18:24:15 +02:00
|
|
|
if _, ok := a.addrNew[i][addrKey]; ok {
|
|
|
|
delete(a.addrNew[i], addrKey)
|
|
|
|
ka.refs--
|
|
|
|
if oldBucket == -1 {
|
|
|
|
oldBucket = i
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
a.nNew--
|
2013-08-01 19:00:14 +02:00
|
|
|
|
2013-09-17 18:24:15 +02:00
|
|
|
if oldBucket == -1 {
|
|
|
|
// What? wasn't in a bucket after all.... Panic?
|
2013-08-01 19:00:14 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-09-17 18:24:15 +02:00
|
|
|
bucket := a.getTriedBucket(ka.na)
|
|
|
|
|
|
|
|
// Room in this tried bucket?
|
|
|
|
if a.addrTried[bucket].Len() < triedBucketSize {
|
|
|
|
ka.tried = true
|
|
|
|
a.addrTried[bucket].PushBack(ka)
|
|
|
|
a.nTried++
|
|
|
|
return
|
|
|
|
}
|
2013-08-01 19:00:14 +02:00
|
|
|
|
2013-09-17 18:24:15 +02:00
|
|
|
// No room, we have to evict something else.
|
|
|
|
entry := a.pickTried(bucket)
|
2015-01-28 16:44:56 +01:00
|
|
|
rmka := entry.Value.(*KnownAddress)
|
2013-08-01 19:00:14 +02:00
|
|
|
|
2013-09-17 18:24:15 +02:00
|
|
|
// First bucket it would have been put in.
|
|
|
|
newBucket := a.getNewBucket(rmka.na, rmka.srcAddr)
|
2013-08-01 19:00:14 +02:00
|
|
|
|
2013-09-17 18:24:15 +02:00
|
|
|
// If no room in the original bucket, we put it in a bucket we just
|
|
|
|
// freed up a space in.
|
|
|
|
if len(a.addrNew[newBucket]) >= newBucketSize {
|
|
|
|
newBucket = oldBucket
|
|
|
|
}
|
|
|
|
|
|
|
|
// replace with ka in list.
|
|
|
|
ka.tried = true
|
2013-08-01 19:00:14 +02:00
|
|
|
entry.Value = ka
|
|
|
|
|
|
|
|
rmka.tried = false
|
2013-09-17 18:24:15 +02:00
|
|
|
rmka.refs++
|
|
|
|
|
|
|
|
// We don't touch a.nTried here since the number of tried stays the same
|
|
|
|
// but we decemented new above, raise it again since we're putting
|
|
|
|
// something back.
|
|
|
|
a.nNew++
|
2013-08-01 19:00:14 +02:00
|
|
|
|
2013-09-17 18:24:15 +02:00
|
|
|
rmkey := NetAddressKey(rmka.na)
|
2014-07-06 08:04:24 +02:00
|
|
|
log.Tracef("Replacing %s with %s in tried", rmkey, addrKey)
|
2013-08-01 19:00:14 +02:00
|
|
|
|
2013-09-17 18:24:15 +02:00
|
|
|
// We made sure there is space here just above.
|
|
|
|
a.addrNew[newBucket][rmkey] = rmka
|
2013-08-01 19:00:14 +02:00
|
|
|
}
|
|
|
|
|
2018-06-03 10:27:33 +02:00
|
|
|
// SetServices sets the services for the giiven address to the provided value.
|
|
|
|
func (a *AddrManager) SetServices(addr *wire.NetAddress, services wire.ServiceFlag) {
|
|
|
|
a.mtx.Lock()
|
|
|
|
defer a.mtx.Unlock()
|
|
|
|
|
|
|
|
ka := a.find(addr)
|
|
|
|
if ka == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update the services if needed.
|
|
|
|
if ka.na.Services != services {
|
|
|
|
// ka.na is immutable, so replace it.
|
|
|
|
naCopy := *ka.na
|
|
|
|
naCopy.Services = services
|
|
|
|
ka.na = &naCopy
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-07-06 08:04:24 +02:00
|
|
|
// AddLocalAddress adds na to the list of known local addresses to advertise
|
2013-11-26 01:40:16 +01:00
|
|
|
// with the given priority.
|
2015-02-05 22:16:39 +01:00
|
|
|
func (a *AddrManager) AddLocalAddress(na *wire.NetAddress, priority AddressPriority) error {
|
2014-07-06 15:47:42 +02:00
|
|
|
if !IsRoutable(na) {
|
|
|
|
return fmt.Errorf("address %s is not routable", na.IP)
|
2013-11-26 01:40:16 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
a.lamtx.Lock()
|
|
|
|
defer a.lamtx.Unlock()
|
|
|
|
|
|
|
|
key := NetAddressKey(na)
|
|
|
|
la, ok := a.localAddresses[key]
|
|
|
|
if !ok || la.score < priority {
|
|
|
|
if ok {
|
|
|
|
la.score = priority + 1
|
|
|
|
} else {
|
|
|
|
a.localAddresses[key] = &localAddress{
|
|
|
|
na: na,
|
|
|
|
score: priority,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2014-07-06 15:47:42 +02:00
|
|
|
return nil
|
2013-11-26 01:40:16 +01:00
|
|
|
}
|
|
|
|
|
2014-07-06 15:47:42 +02:00
|
|
|
// getReachabilityFrom returns the relative reachability of the provided local
|
|
|
|
// address to the provided remote address.
|
2015-02-05 22:16:39 +01:00
|
|
|
func getReachabilityFrom(localAddr, remoteAddr *wire.NetAddress) int {
|
2013-11-26 01:40:16 +01:00
|
|
|
const (
|
|
|
|
Unreachable = 0
|
|
|
|
Default = iota
|
|
|
|
Teredo
|
2014-07-02 16:25:42 +02:00
|
|
|
Ipv6Weak
|
2013-11-26 01:40:16 +01:00
|
|
|
Ipv4
|
2014-07-02 16:25:42 +02:00
|
|
|
Ipv6Strong
|
2013-11-26 01:40:16 +01:00
|
|
|
Private
|
|
|
|
)
|
2014-07-02 16:25:42 +02:00
|
|
|
|
2014-07-06 15:47:42 +02:00
|
|
|
if !IsRoutable(remoteAddr) {
|
2013-11-26 01:40:16 +01:00
|
|
|
return Unreachable
|
2014-07-02 16:25:42 +02:00
|
|
|
}
|
|
|
|
|
2014-07-06 15:47:42 +02:00
|
|
|
if IsOnionCatTor(remoteAddr) {
|
|
|
|
if IsOnionCatTor(localAddr) {
|
2013-11-26 01:40:16 +01:00
|
|
|
return Private
|
2014-07-02 16:25:42 +02:00
|
|
|
}
|
|
|
|
|
2014-07-06 15:47:42 +02:00
|
|
|
if IsRoutable(localAddr) && IsIPv4(localAddr) {
|
2013-11-26 01:40:16 +01:00
|
|
|
return Ipv4
|
|
|
|
}
|
2014-07-02 16:25:42 +02:00
|
|
|
|
|
|
|
return Default
|
|
|
|
}
|
|
|
|
|
2014-07-06 15:47:42 +02:00
|
|
|
if IsRFC4380(remoteAddr) {
|
|
|
|
if !IsRoutable(localAddr) {
|
2013-11-26 01:40:16 +01:00
|
|
|
return Default
|
2014-07-02 16:25:42 +02:00
|
|
|
}
|
|
|
|
|
2014-07-06 15:47:42 +02:00
|
|
|
if IsRFC4380(localAddr) {
|
2013-11-26 01:40:16 +01:00
|
|
|
return Teredo
|
2014-07-02 16:25:42 +02:00
|
|
|
}
|
|
|
|
|
2014-07-06 15:47:42 +02:00
|
|
|
if IsIPv4(localAddr) {
|
2013-11-26 01:40:16 +01:00
|
|
|
return Ipv4
|
|
|
|
}
|
2014-07-02 16:25:42 +02:00
|
|
|
|
|
|
|
return Ipv6Weak
|
|
|
|
}
|
|
|
|
|
2014-07-06 15:47:42 +02:00
|
|
|
if IsIPv4(remoteAddr) {
|
|
|
|
if IsRoutable(localAddr) && IsIPv4(localAddr) {
|
2013-11-26 01:40:16 +01:00
|
|
|
return Ipv4
|
|
|
|
}
|
2014-07-06 15:47:42 +02:00
|
|
|
return Unreachable
|
2013-11-26 01:40:16 +01:00
|
|
|
}
|
2014-07-02 16:25:42 +02:00
|
|
|
|
|
|
|
/* ipv6 */
|
|
|
|
var tunnelled bool
|
|
|
|
// Is our v6 is tunnelled?
|
2014-07-06 15:47:42 +02:00
|
|
|
if IsRFC3964(localAddr) || IsRFC6052(localAddr) || IsRFC6145(localAddr) {
|
2014-07-02 16:25:42 +02:00
|
|
|
tunnelled = true
|
|
|
|
}
|
|
|
|
|
2014-07-06 15:47:42 +02:00
|
|
|
if !IsRoutable(localAddr) {
|
2014-07-02 16:25:42 +02:00
|
|
|
return Default
|
|
|
|
}
|
|
|
|
|
2014-07-06 15:47:42 +02:00
|
|
|
if IsRFC4380(localAddr) {
|
2014-07-02 16:25:42 +02:00
|
|
|
return Teredo
|
|
|
|
}
|
|
|
|
|
2014-07-06 15:47:42 +02:00
|
|
|
if IsIPv4(localAddr) {
|
2014-07-02 16:25:42 +02:00
|
|
|
return Ipv4
|
|
|
|
}
|
|
|
|
|
|
|
|
if tunnelled {
|
|
|
|
// only prioritise ipv6 if we aren't tunnelling it.
|
|
|
|
return Ipv6Weak
|
|
|
|
}
|
|
|
|
|
|
|
|
return Ipv6Strong
|
2013-11-26 01:40:16 +01:00
|
|
|
}
|
|
|
|
|
2014-07-06 15:47:42 +02:00
|
|
|
// GetBestLocalAddress returns the most appropriate local address to use
|
|
|
|
// for the given remote address.
|
2015-02-05 22:16:39 +01:00
|
|
|
func (a *AddrManager) GetBestLocalAddress(remoteAddr *wire.NetAddress) *wire.NetAddress {
|
2013-11-26 01:40:16 +01:00
|
|
|
a.lamtx.Lock()
|
|
|
|
defer a.lamtx.Unlock()
|
|
|
|
|
|
|
|
bestreach := 0
|
2014-07-06 15:47:42 +02:00
|
|
|
var bestscore AddressPriority
|
2015-02-05 22:16:39 +01:00
|
|
|
var bestAddress *wire.NetAddress
|
2013-11-26 01:40:16 +01:00
|
|
|
for _, la := range a.localAddresses {
|
2014-07-06 15:47:42 +02:00
|
|
|
reach := getReachabilityFrom(la.na, remoteAddr)
|
2013-11-26 01:40:16 +01:00
|
|
|
if reach > bestreach ||
|
|
|
|
(reach == bestreach && la.score > bestscore) {
|
|
|
|
bestreach = reach
|
|
|
|
bestscore = la.score
|
2014-07-06 15:47:42 +02:00
|
|
|
bestAddress = la.na
|
2013-11-26 01:40:16 +01:00
|
|
|
}
|
|
|
|
}
|
2014-07-06 15:47:42 +02:00
|
|
|
if bestAddress != nil {
|
|
|
|
log.Debugf("Suggesting address %s:%d for %s:%d", bestAddress.IP,
|
|
|
|
bestAddress.Port, remoteAddr.IP, remoteAddr.Port)
|
2013-11-26 01:40:16 +01:00
|
|
|
} else {
|
2014-07-06 15:47:42 +02:00
|
|
|
log.Debugf("No worthy address for %s:%d", remoteAddr.IP,
|
|
|
|
remoteAddr.Port)
|
|
|
|
|
2013-11-26 01:40:16 +01:00
|
|
|
// Send something unroutable if nothing suitable.
|
2016-12-06 20:48:02 +01:00
|
|
|
var ip net.IP
|
2014-07-06 15:47:42 +02:00
|
|
|
if !IsIPv4(remoteAddr) && !IsOnionCatTor(remoteAddr) {
|
2016-12-06 20:48:02 +01:00
|
|
|
ip = net.IPv6zero
|
2014-07-06 15:47:42 +02:00
|
|
|
} else {
|
2016-12-06 20:48:02 +01:00
|
|
|
ip = net.IPv4zero
|
2014-07-06 15:47:42 +02:00
|
|
|
}
|
2016-10-19 01:54:55 +02:00
|
|
|
services := wire.SFNodeNetwork | wire.SFNodeWitness | wire.SFNodeBloom
|
|
|
|
bestAddress = wire.NewNetAddressIPPort(ip, 0, services)
|
2013-11-26 01:40:16 +01:00
|
|
|
}
|
|
|
|
|
2014-07-06 15:47:42 +02:00
|
|
|
return bestAddress
|
2013-11-26 01:40:16 +01:00
|
|
|
}
|
2014-07-06 08:04:24 +02:00
|
|
|
|
|
|
|
// New returns a new bitcoin address manager.
|
|
|
|
// Use Start to begin processing asynchronous address updates.
|
|
|
|
func New(dataDir string, lookupFunc func(string) ([]net.IP, error)) *AddrManager {
|
|
|
|
am := AddrManager{
|
2014-07-11 02:28:30 +02:00
|
|
|
peersFile: filepath.Join(dataDir, "peers.json"),
|
2014-07-06 08:04:24 +02:00
|
|
|
lookupFunc: lookupFunc,
|
|
|
|
rand: rand.New(rand.NewSource(time.Now().UnixNano())),
|
|
|
|
quit: make(chan struct{}),
|
|
|
|
localAddresses: make(map[string]*localAddress),
|
|
|
|
}
|
|
|
|
am.reset()
|
|
|
|
return &am
|
|
|
|
}
|