Changeset View
Changeset View
Standalone View
Standalone View
src/avalanche/peermanager.cpp
// Copyright (c) 2020 The Bitcoin developers | // Copyright (c) 2020 The Bitcoin developers | ||||
// Distributed under the MIT software license, see the accompanying | // Distributed under the MIT software license, see the accompanying | ||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php. | // file COPYING or http://www.opensource.org/licenses/mit-license.php. | ||||
#include <avalanche/peermanager.h> | #include <avalanche/peermanager.h> | ||||
#include <random.h> | #include <random.h> | ||||
void PeerManager::addPeer(uint64_t score) { | void PeerManager::addPeer(uint64_t score) { | ||||
const uint64_t start = slotCount; | const uint64_t start = slotCount; | ||||
const uint64_t stop = start + score; | const uint64_t stop = start + score; | ||||
slots.emplace_back(start, stop); | slots.emplace_back(start, stop); | ||||
slotCount = stop; | slotCount = stop; | ||||
} | } | ||||
void PeerManager::rescorePeer(size_t i, uint64_t score) { | |||||
assert(i < slots.size()); | |||||
const uint64_t start = slots[i].start; | |||||
const uint64_t stop = start + score; | |||||
// If this is the last element, we can extend/shrink easily. | |||||
if (i + 1 == slots.size()) { | |||||
slots[i].stop = stop; | |||||
slotCount = stop; | |||||
return; | |||||
} | |||||
const uint64_t nextStart = slots[i + 1].start; | |||||
// We can extend in place. | |||||
if (stop <= nextStart) { | |||||
fragmentation += (slots[i].stop - stop); | |||||
slots[i].stop = stop; | |||||
return; | |||||
} | |||||
// So we remove and insert a new entry. | |||||
addPeer(score); | |||||
removePeer(i); | |||||
} | |||||
size_t PeerManager::selectPeer() const { | size_t PeerManager::selectPeer() const { | ||||
if (slots.empty()) { | if (slots.empty()) { | ||||
return NO_PEER; | return NO_PEER; | ||||
} | } | ||||
const uint64_t max = slotCount; | const uint64_t max = slotCount; | ||||
while (true) { | while (true) { | ||||
size_t i = selectPeerImpl(slots, GetRand(max), max); | size_t i = selectPeerImpl(slots, GetRand(max), max); | ||||
▲ Show 20 Lines • Show All 57 Lines • Show Last 20 Lines |