gitlab.com/SiaPrime/SiaPrime@v1.4.1/modules/renter/hostdb/randomhosts.go (about) 1 package hostdb 2 3 import ( 4 "gitlab.com/NebulousLabs/errors" 5 6 "gitlab.com/SiaPrime/SiaPrime/modules" 7 "gitlab.com/SiaPrime/SiaPrime/modules/renter/hostdb/hosttree" 8 "gitlab.com/SiaPrime/SiaPrime/types" 9 ) 10 11 // RandomHosts implements the HostDB interface's RandomHosts() method. It takes 12 // a number of hosts to return, and a slice of netaddresses to ignore, and 13 // returns a slice of entries. If the IP violation check was disabled, the 14 // addressBlacklist is ignored. 15 func (hdb *HostDB) RandomHosts(n int, blacklist, addressBlacklist []types.SiaPublicKey) ([]modules.HostDBEntry, error) { 16 hdb.mu.RLock() 17 initialScanComplete := hdb.initialScanComplete 18 ipCheckDisabled := !hdb.IPViolationsCheck() 19 hdb.mu.RUnlock() 20 if !initialScanComplete { 21 return []modules.HostDBEntry{}, ErrInitialScanIncomplete 22 } 23 if ipCheckDisabled { 24 return hdb.filteredTree.SelectRandom(n, blacklist, nil), nil 25 } 26 return hdb.filteredTree.SelectRandom(n, blacklist, addressBlacklist), nil 27 } 28 29 // RandomHostsWithAllowance works as RandomHosts but uses a temporary hosttree 30 // created from the specified allowance. This is a very expensive call and 31 // should be used with caution. 32 func (hdb *HostDB) RandomHostsWithAllowance(n int, blacklist, addressBlacklist []types.SiaPublicKey, allowance modules.Allowance) ([]modules.HostDBEntry, error) { 33 hdb.mu.RLock() 34 initialScanComplete := hdb.initialScanComplete 35 filteredHosts := hdb.filteredHosts 36 filterType := hdb.filterMode 37 hdb.mu.RUnlock() 38 if !initialScanComplete { 39 return []modules.HostDBEntry{}, ErrInitialScanIncomplete 40 } 41 // Create a temporary hosttree from the given allowance. 42 ht := hosttree.New(hdb.managedCalculateHostWeightFn(allowance), hdb.deps.Resolver()) 43 44 // Insert all known hosts. 45 var insertErrs error 46 allHosts := hdb.hostTree.All() 47 isWhitelist := filterType == modules.HostDBActiveWhitelist 48 for _, host := range allHosts { 49 // Filter out listed hosts 50 _, ok := filteredHosts[host.PublicKey.String()] 51 if isWhitelist != ok { 52 continue 53 } 54 if err := ht.Insert(host); err != nil { 55 insertErrs = errors.Compose(insertErrs, err) 56 } 57 } 58 59 // Select hosts from the temporary hosttree. 60 return ht.SelectRandom(n, blacklist, addressBlacklist), insertErrs 61 }