2021-03-26 06:52:01 +00:00
|
|
|
# beacon_chain
|
|
|
|
# Copyright (c) 2018-2021 Status Research & Development GmbH
|
|
|
|
# Licensed and distributed under either of
|
|
|
|
# * MIT license (license terms in the root directory or at https://opensource.org/licenses/MIT).
|
|
|
|
# * Apache v2 license (license terms in the root directory or at https://www.apache.org/licenses/LICENSE-2.0).
|
|
|
|
# at your option. This file may not be copied, modified, or distributed except according to those terms.
|
|
|
|
|
|
|
|
{.push raises: [Defect].}
|
|
|
|
|
2021-12-16 14:57:16 +00:00
|
|
|
import std/[options, heapqueue, tables, strutils, sequtils, algorithm]
|
2020-06-03 13:52:02 +00:00
|
|
|
import stew/results, chronos, chronicles
|
2021-08-12 13:08:20 +00:00
|
|
|
import
|
2021-12-16 14:57:16 +00:00
|
|
|
../spec/datatypes/[phase0, altair, merge],
|
2021-08-12 13:08:20 +00:00
|
|
|
../spec/eth2_apis/rpc_types,
|
|
|
|
../spec/[helpers, forks],
|
2021-12-08 21:15:29 +00:00
|
|
|
../networking/[peer_pool, eth2_network],
|
2021-12-16 14:57:16 +00:00
|
|
|
../beacon_clock,
|
2021-12-08 21:15:29 +00:00
|
|
|
./peer_scores, ./sync_queue
|
2021-08-12 13:08:20 +00:00
|
|
|
|
2021-12-16 14:57:16 +00:00
|
|
|
export phase0, altair, merge, chronos, chronicles, results,
|
|
|
|
helpers, peer_scores, sync_queue, forks
|
2020-01-21 18:30:21 +00:00
|
|
|
|
2020-01-22 12:47:55 +00:00
|
|
|
logScope:
|
|
|
|
topics = "syncman"
|
2020-01-21 18:30:21 +00:00
|
|
|
|
2020-04-23 15:31:00 +00:00
|
|
|
const
|
2020-11-26 08:19:27 +00:00
|
|
|
SyncWorkersCount* = 10
|
2020-09-11 12:46:01 +00:00
|
|
|
## Number of sync workers to spawn
|
|
|
|
|
2020-09-23 15:58:02 +00:00
|
|
|
StatusUpdateInterval* = chronos.minutes(1)
|
|
|
|
## Minimum time between two subsequent calls to update peer's status
|
|
|
|
|
2020-10-08 12:50:48 +00:00
|
|
|
StatusExpirationTime* = chronos.minutes(2)
|
|
|
|
## Time time it takes for the peer's status information to expire.
|
|
|
|
|
2020-01-21 18:30:21 +00:00
|
|
|
type
|
2020-09-11 12:46:01 +00:00
|
|
|
SyncWorkerStatus* {.pure.} = enum
|
2021-12-16 14:57:16 +00:00
|
|
|
Sleeping, WaitingPeer, UpdatingStatus, Requesting, Downloading, Queueing,
|
|
|
|
Processing
|
2020-09-11 12:46:01 +00:00
|
|
|
|
|
|
|
SyncWorker*[A, B] = object
|
|
|
|
future: Future[void]
|
|
|
|
status: SyncWorkerStatus
|
|
|
|
|
2020-04-20 14:59:18 +00:00
|
|
|
SyncManager*[A, B] = ref object
|
|
|
|
pool: PeerPool[A, B]
|
|
|
|
responseTimeout: chronos.Duration
|
|
|
|
sleepTime: chronos.Duration
|
|
|
|
maxStatusAge: uint64
|
|
|
|
maxHeadAge: uint64
|
|
|
|
toleranceValue: uint64
|
|
|
|
getLocalHeadSlot: GetSlotCallback
|
|
|
|
getLocalWallSlot: GetSlotCallback
|
2021-12-16 14:57:16 +00:00
|
|
|
getSafeSlot: GetSlotCallback
|
|
|
|
getFirstSlot: GetSlotCallback
|
|
|
|
getLastSlot: GetSlotCallback
|
2020-09-11 12:46:01 +00:00
|
|
|
workers: array[SyncWorkersCount, SyncWorker[A, B]]
|
|
|
|
notInSyncEvent: AsyncEvent
|
|
|
|
rangeAge: uint64
|
2020-04-23 15:31:00 +00:00
|
|
|
chunkSize: uint64
|
2020-05-19 12:08:50 +00:00
|
|
|
queue: SyncQueue[A]
|
2020-08-10 07:15:50 +00:00
|
|
|
syncFut: Future[void]
|
2021-12-16 14:57:16 +00:00
|
|
|
blockVerifier: BlockVerifier
|
2020-06-03 08:46:29 +00:00
|
|
|
inProgress*: bool
|
2020-10-27 09:25:28 +00:00
|
|
|
insSyncSpeed*: float
|
|
|
|
avgSyncSpeed*: float
|
2020-09-11 12:46:01 +00:00
|
|
|
syncStatus*: string
|
2021-12-16 14:57:16 +00:00
|
|
|
direction: SyncQueueKind
|
2020-05-19 12:08:50 +00:00
|
|
|
|
|
|
|
SyncMoment* = object
|
|
|
|
stamp*: chronos.Moment
|
2021-12-16 14:57:16 +00:00
|
|
|
slots*: uint64
|
2020-05-28 05:02:28 +00:00
|
|
|
|
2020-01-21 18:30:21 +00:00
|
|
|
SyncManagerError* = object of CatchableError
|
2021-07-15 19:01:07 +00:00
|
|
|
BeaconBlocksRes* = NetRes[seq[ForkedSignedBeaconBlock]]
|
2020-04-20 14:59:18 +00:00
|
|
|
|
2021-12-16 14:57:16 +00:00
|
|
|
proc now*(sm: typedesc[SyncMoment], slots: uint64): SyncMoment {.inline.} =
|
|
|
|
SyncMoment(stamp: now(chronos.Moment), slots: slots)
|
2020-05-19 12:08:50 +00:00
|
|
|
|
|
|
|
proc speed*(start, finish: SyncMoment): float {.inline.} =
|
|
|
|
## Returns number of slots per second.
|
2021-12-16 14:57:16 +00:00
|
|
|
if finish.slots <= start.slots or finish.stamp <= start.stamp:
|
|
|
|
0.0 # replays for example
|
2020-05-19 12:08:50 +00:00
|
|
|
else:
|
2021-12-16 14:57:16 +00:00
|
|
|
let
|
|
|
|
slots = float(finish.slots - start.slots)
|
|
|
|
dur = toFloatSeconds(finish.stamp - start.stamp)
|
|
|
|
slots / dur
|
|
|
|
|
|
|
|
proc initQueue[A, B](man: SyncManager[A, B]) =
|
|
|
|
man.queue = SyncQueue.init(A, man.direction, man.getFirstSlot(),
|
|
|
|
man.getLastSlot(), man.chunkSize,
|
|
|
|
man.getSafeSlot, man.blockVerifier, 1)
|
2020-05-19 12:08:50 +00:00
|
|
|
|
2020-01-21 18:30:21 +00:00
|
|
|
proc newSyncManager*[A, B](pool: PeerPool[A, B],
|
2021-12-16 14:57:16 +00:00
|
|
|
direction: SyncQueueKind,
|
2020-04-20 14:59:18 +00:00
|
|
|
getLocalHeadSlotCb: GetSlotCallback,
|
|
|
|
getLocalWallSlotCb: GetSlotCallback,
|
2020-07-06 12:53:48 +00:00
|
|
|
getFinalizedSlotCb: GetSlotCallback,
|
2021-12-16 14:57:16 +00:00
|
|
|
getBackfillSlotCb: GetSlotCallback,
|
|
|
|
blockVerifier: BlockVerifier,
|
2020-04-20 14:59:18 +00:00
|
|
|
maxStatusAge = uint64(SLOTS_PER_EPOCH * 4),
|
2020-06-07 15:36:24 +00:00
|
|
|
maxHeadAge = uint64(SLOTS_PER_EPOCH * 1),
|
2020-04-20 14:59:18 +00:00
|
|
|
sleepTime = (int(SLOTS_PER_EPOCH) *
|
|
|
|
int(SECONDS_PER_SLOT)).seconds,
|
|
|
|
chunkSize = uint64(SLOTS_PER_EPOCH),
|
2021-12-16 14:57:16 +00:00
|
|
|
toleranceValue = uint64(1)
|
2020-04-20 14:59:18 +00:00
|
|
|
): SyncManager[A, B] =
|
2021-12-16 14:57:16 +00:00
|
|
|
let (getFirstSlot, getLastSlot, getSafeSlot) = case direction
|
|
|
|
of SyncQueueKind.Forward:
|
|
|
|
(getLocalHeadSlotCb, getLocalWallSlotCb, getFinalizedSlotCb)
|
|
|
|
of SyncQueueKind.Backward:
|
|
|
|
(getBackfillSlotCb, GetSlotCallback(proc(): Slot = Slot(0)), getBackfillSlotCb)
|
2020-05-19 12:08:50 +00:00
|
|
|
|
2020-04-20 14:59:18 +00:00
|
|
|
result = SyncManager[A, B](
|
|
|
|
pool: pool,
|
|
|
|
maxStatusAge: maxStatusAge,
|
|
|
|
getLocalHeadSlot: getLocalHeadSlotCb,
|
|
|
|
getLocalWallSlot: getLocalWallSlotCb,
|
2021-12-16 14:57:16 +00:00
|
|
|
getSafeSlot: getSafeSlot,
|
|
|
|
getFirstSlot: getFirstSlot,
|
|
|
|
getLastSlot: getLastSlot,
|
2020-04-20 14:59:18 +00:00
|
|
|
maxHeadAge: maxHeadAge,
|
|
|
|
sleepTime: sleepTime,
|
2020-04-23 15:31:00 +00:00
|
|
|
chunkSize: chunkSize,
|
2021-12-16 14:57:16 +00:00
|
|
|
blockVerifier: blockVerifier,
|
2020-09-11 12:46:01 +00:00
|
|
|
notInSyncEvent: newAsyncEvent(),
|
2021-12-16 14:57:16 +00:00
|
|
|
direction: direction
|
2020-04-20 14:59:18 +00:00
|
|
|
)
|
2021-12-16 14:57:16 +00:00
|
|
|
result.initQueue()
|
2020-04-20 14:59:18 +00:00
|
|
|
|
|
|
|
proc getBlocks*[A, B](man: SyncManager[A, B], peer: A,
|
2020-05-12 22:37:07 +00:00
|
|
|
req: SyncRequest): Future[BeaconBlocksRes] {.async.} =
|
2020-04-20 14:59:18 +00:00
|
|
|
mixin beaconBlocksByRange, getScore, `==`
|
|
|
|
doAssert(not(req.isEmpty()), "Request must not be empty!")
|
|
|
|
debug "Requesting blocks from peer", peer = peer,
|
|
|
|
slot = req.slot, slot_count = req.count, step = req.step,
|
2020-07-25 06:12:23 +00:00
|
|
|
peer_score = peer.getScore(), peer_speed = peer.netKbps(),
|
2021-12-16 14:57:16 +00:00
|
|
|
direction = man.direction, topics = "syncman"
|
2021-07-15 19:01:07 +00:00
|
|
|
if peer.useSyncV2():
|
|
|
|
var workFut = awaitne beaconBlocksByRange_v2(peer, req.slot, req.count, req.step)
|
|
|
|
if workFut.failed():
|
|
|
|
debug "Error, while waiting getBlocks response", peer = peer,
|
|
|
|
slot = req.slot, slot_count = req.count, step = req.step,
|
|
|
|
errMsg = workFut.readError().msg, peer_speed = peer.netKbps(),
|
2021-12-16 14:57:16 +00:00
|
|
|
direction = man.direction, topics = "syncman"
|
2021-07-15 19:01:07 +00:00
|
|
|
else:
|
|
|
|
let res = workFut.read()
|
|
|
|
if res.isErr:
|
|
|
|
debug "Error, while reading getBlocks response",
|
|
|
|
peer = peer, slot = req.slot, count = req.count,
|
|
|
|
step = req.step, peer_speed = peer.netKbps(),
|
2021-12-16 14:57:16 +00:00
|
|
|
direction = man.direction, topics = "syncman", error = $res.error()
|
2021-07-15 19:01:07 +00:00
|
|
|
result = res
|
2020-01-21 18:30:21 +00:00
|
|
|
else:
|
2021-07-15 19:01:07 +00:00
|
|
|
var workFut = awaitne beaconBlocksByRange(peer, req.slot, req.count, req.step)
|
|
|
|
if workFut.failed():
|
|
|
|
debug "Error, while waiting getBlocks response", peer = peer,
|
|
|
|
slot = req.slot, slot_count = req.count, step = req.step,
|
|
|
|
errMsg = workFut.readError().msg, peer_speed = peer.netKbps(),
|
2021-12-16 14:57:16 +00:00
|
|
|
direction = man.direction, topics = "syncman"
|
2021-07-15 19:01:07 +00:00
|
|
|
else:
|
|
|
|
let res = workFut.read()
|
|
|
|
if res.isErr:
|
|
|
|
debug "Error, while reading getBlocks response",
|
|
|
|
peer = peer, slot = req.slot, count = req.count,
|
|
|
|
step = req.step, peer_speed = peer.netKbps(),
|
|
|
|
topics = "syncman", error = $res.error()
|
|
|
|
result = res.map() do (blcks: seq[phase0.SignedBeaconBlock]) -> auto: blcks.mapIt(ForkedSignedBeaconBlock.init(it))
|
2020-04-20 14:59:18 +00:00
|
|
|
|
|
|
|
template headAge(): uint64 =
|
|
|
|
wallSlot - headSlot
|
|
|
|
|
2020-09-23 15:58:02 +00:00
|
|
|
template peerStatusAge(): Duration =
|
|
|
|
Moment.now() - peer.state(BeaconSync).statusLastTime
|
|
|
|
|
2020-09-21 16:02:27 +00:00
|
|
|
proc syncStep[A, B](man: SyncManager[A, B], index: int, peer: A) {.async.} =
|
|
|
|
let wallSlot = man.getLocalWallSlot()
|
|
|
|
let headSlot = man.getLocalHeadSlot()
|
|
|
|
var peerSlot = peer.getHeadSlot()
|
|
|
|
|
|
|
|
debug "Peer's syncing status", wall_clock_slot = wallSlot,
|
|
|
|
remote_head_slot = peerSlot, local_head_slot = headSlot,
|
|
|
|
peer_score = peer.getScore(), peer = peer, index = index,
|
2021-12-16 14:57:16 +00:00
|
|
|
peer_speed = peer.netKbps(), direction = man.direction,
|
|
|
|
topics = "syncman"
|
2020-09-21 16:02:27 +00:00
|
|
|
|
|
|
|
# Check if peer's head slot is bigger than our wall clock slot.
|
|
|
|
if peerSlot > wallSlot + man.toleranceValue:
|
2021-12-16 14:57:16 +00:00
|
|
|
peer.updateScore(PeerScoreHeadTooNew)
|
|
|
|
|
|
|
|
warn "Peer reports a head newer than our wall clock - clock out of sync?",
|
2020-09-21 16:02:27 +00:00
|
|
|
wall_clock_slot = wallSlot, remote_head_slot = peerSlot,
|
|
|
|
local_head_slot = headSlot, peer = peer, index = index,
|
|
|
|
tolerance_value = man.toleranceValue, peer_speed = peer.netKbps(),
|
2021-12-16 14:57:16 +00:00
|
|
|
peer_score = peer.getScore(), direction = man.direction,
|
|
|
|
topics = "syncman"
|
2020-09-21 16:02:27 +00:00
|
|
|
return
|
2020-09-11 12:46:01 +00:00
|
|
|
|
2020-09-21 16:02:27 +00:00
|
|
|
# Check if we need to update peer's status information
|
2020-10-08 12:50:48 +00:00
|
|
|
if peerStatusAge >= StatusExpirationTime:
|
2020-09-21 16:02:27 +00:00
|
|
|
# Peer's status information is very old, its time to update it
|
|
|
|
man.workers[index].status = SyncWorkerStatus.UpdatingStatus
|
2020-10-01 18:56:42 +00:00
|
|
|
trace "Updating peer's status information", wall_clock_slot = wallSlot,
|
2020-09-21 16:02:27 +00:00
|
|
|
remote_head_slot = peerSlot, local_head_slot = headSlot,
|
|
|
|
peer = peer, peer_score = peer.getScore(), index = index,
|
2021-12-16 14:57:16 +00:00
|
|
|
peer_speed = peer.netKbps(), direction = man.direction,
|
|
|
|
topics = "syncman"
|
2020-09-11 12:46:01 +00:00
|
|
|
|
|
|
|
try:
|
2020-09-21 16:02:27 +00:00
|
|
|
let res = await peer.updateStatus()
|
|
|
|
if not(res):
|
|
|
|
peer.updateScore(PeerScoreNoStatus)
|
|
|
|
debug "Failed to get remote peer's status, exiting", peer = peer,
|
|
|
|
peer_score = peer.getScore(), peer_head_slot = peerSlot,
|
2021-12-16 14:57:16 +00:00
|
|
|
peer_speed = peer.netKbps(), index = index,
|
|
|
|
direction = man.direction, topics = "syncman"
|
2020-09-21 16:02:27 +00:00
|
|
|
return
|
|
|
|
except CatchableError as exc:
|
|
|
|
debug "Unexpected exception while updating peer's status",
|
|
|
|
peer = peer, peer_score = peer.getScore(),
|
|
|
|
peer_head_slot = peerSlot, peer_speed = peer.netKbps(),
|
2021-12-16 14:57:16 +00:00
|
|
|
index = index, errMsg = exc.msg, direction = man.direction,
|
|
|
|
topics = "syncman"
|
2020-09-21 16:02:27 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
let newPeerSlot = peer.getHeadSlot()
|
|
|
|
if peerSlot >= newPeerSlot:
|
|
|
|
peer.updateScore(PeerScoreStaleStatus)
|
|
|
|
debug "Peer's status information is stale",
|
|
|
|
wall_clock_slot = wallSlot, remote_old_head_slot = peerSlot,
|
|
|
|
local_head_slot = headSlot, remote_new_head_slot = newPeerSlot,
|
|
|
|
peer = peer, peer_score = peer.getScore(), index = index,
|
2021-12-16 14:57:16 +00:00
|
|
|
peer_speed = peer.netKbps(), direction = man.direction,
|
|
|
|
topics = "syncman"
|
2020-09-21 16:02:27 +00:00
|
|
|
else:
|
|
|
|
debug "Peer's status information updated", wall_clock_slot = wallSlot,
|
|
|
|
remote_old_head_slot = peerSlot, local_head_slot = headSlot,
|
|
|
|
remote_new_head_slot = newPeerSlot, peer = peer,
|
|
|
|
peer_score = peer.getScore(), peer_speed = peer.netKbps(),
|
2021-12-16 14:57:16 +00:00
|
|
|
index = index, direction = man.direction, topics = "syncman"
|
2020-09-21 16:02:27 +00:00
|
|
|
peer.updateScore(PeerScoreGoodStatus)
|
|
|
|
peerSlot = newPeerSlot
|
|
|
|
|
2020-09-23 15:58:02 +00:00
|
|
|
if headAge <= man.maxHeadAge:
|
2020-10-01 18:56:42 +00:00
|
|
|
info "We are in sync with network", wall_clock_slot = wallSlot,
|
2020-09-21 16:02:27 +00:00
|
|
|
remote_head_slot = peerSlot, local_head_slot = headSlot,
|
|
|
|
peer = peer, peer_score = peer.getScore(), index = index,
|
|
|
|
peer_speed = peer.netKbps(), topics = "syncman"
|
2020-09-23 15:58:02 +00:00
|
|
|
# We clear SyncManager's `notInSyncEvent` so all the workers will become
|
|
|
|
# sleeping soon.
|
|
|
|
man.notInSyncEvent.clear()
|
|
|
|
return
|
|
|
|
|
2020-09-24 12:14:29 +00:00
|
|
|
if headSlot >= peerSlot - man.maxHeadAge:
|
2020-10-01 18:56:42 +00:00
|
|
|
debug "We are in sync with peer; refreshing peer's status information",
|
2020-09-23 15:58:02 +00:00
|
|
|
wall_clock_slot = wallSlot, remote_head_slot = peerSlot,
|
|
|
|
local_head_slot = headSlot, peer = peer, peer_score = peer.getScore(),
|
2021-12-16 14:57:16 +00:00
|
|
|
index = index, peer_speed = peer.netKbps(), direction = man.direction,
|
|
|
|
topics = "syncman"
|
2020-09-23 15:58:02 +00:00
|
|
|
|
2020-09-24 12:14:29 +00:00
|
|
|
man.workers[index].status = SyncWorkerStatus.UpdatingStatus
|
|
|
|
|
2020-09-23 15:58:02 +00:00
|
|
|
if peerStatusAge <= StatusUpdateInterval:
|
|
|
|
await sleepAsync(StatusUpdateInterval - peerStatusAge)
|
|
|
|
|
|
|
|
try:
|
|
|
|
let res = await peer.updateStatus()
|
|
|
|
if not(res):
|
|
|
|
peer.updateScore(PeerScoreNoStatus)
|
|
|
|
debug "Failed to get remote peer's status, exiting", peer = peer,
|
|
|
|
peer_score = peer.getScore(), peer_head_slot = peerSlot,
|
2021-12-16 14:57:16 +00:00
|
|
|
peer_speed = peer.netKbps(), index = index,
|
|
|
|
direction = man.direction, topics = "syncman"
|
2020-09-23 15:58:02 +00:00
|
|
|
return
|
|
|
|
except CatchableError as exc:
|
|
|
|
debug "Unexpected exception while updating peer's status",
|
|
|
|
peer = peer, peer_score = peer.getScore(),
|
|
|
|
peer_head_slot = peerSlot, peer_speed = peer.netKbps(),
|
2021-12-16 14:57:16 +00:00
|
|
|
index = index, errMsg = exc.msg, direction = man.direction,
|
|
|
|
topics = "syncman"
|
2020-09-23 15:58:02 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
let newPeerSlot = peer.getHeadSlot()
|
|
|
|
if peerSlot >= newPeerSlot:
|
|
|
|
peer.updateScore(PeerScoreStaleStatus)
|
|
|
|
debug "Peer's status information is stale",
|
|
|
|
wall_clock_slot = wallSlot, remote_old_head_slot = peerSlot,
|
|
|
|
local_head_slot = headSlot, remote_new_head_slot = newPeerSlot,
|
|
|
|
peer = peer, peer_score = peer.getScore(), index = index,
|
2021-12-16 14:57:16 +00:00
|
|
|
peer_speed = peer.netKbps(), direction = man.direction,
|
|
|
|
topics = "syncman"
|
2020-09-23 15:58:02 +00:00
|
|
|
else:
|
2020-10-30 12:33:52 +00:00
|
|
|
# This is not very good solution because we should not discriminate and/or
|
|
|
|
# penalize peers which are in sync process too, but their latest head is
|
|
|
|
# lower then our latest head. We should keep connections with such peers
|
|
|
|
# (so this peers are able to get in sync using our data), but we should
|
|
|
|
# not use this peers for syncing because this peers are useless for us.
|
|
|
|
# Right now we decreasing peer's score a bit, so it will not be
|
|
|
|
# disconnected due to low peer's score, but new fresh peers could replace
|
|
|
|
# peers with low latest head.
|
|
|
|
if headSlot >= newPeerSlot - man.maxHeadAge:
|
|
|
|
# Peer's head slot is still lower then ours.
|
|
|
|
debug "Peer's head slot is lower then local head slot",
|
|
|
|
wall_clock_slot = wallSlot, remote_old_head_slot = peerSlot,
|
|
|
|
local_head_slot = headSlot, remote_new_head_slot = newPeerSlot,
|
|
|
|
peer = peer, peer_score = peer.getScore(),
|
2021-12-16 14:57:16 +00:00
|
|
|
peer_speed = peer.netKbps(), index = index,
|
|
|
|
direction = man.direction, topics = "syncman"
|
2020-10-30 12:33:52 +00:00
|
|
|
peer.updateScore(PeerScoreUseless)
|
|
|
|
else:
|
|
|
|
debug "Peer's status information updated", wall_clock_slot = wallSlot,
|
|
|
|
remote_old_head_slot = peerSlot, local_head_slot = headSlot,
|
|
|
|
remote_new_head_slot = newPeerSlot, peer = peer,
|
|
|
|
peer_score = peer.getScore(), peer_speed = peer.netKbps(),
|
2021-12-16 14:57:16 +00:00
|
|
|
index = index, direction = man.direction, topics = "syncman"
|
2020-10-30 12:33:52 +00:00
|
|
|
peer.updateScore(PeerScoreGoodStatus)
|
|
|
|
peerSlot = newPeerSlot
|
2020-09-23 15:58:02 +00:00
|
|
|
|
2020-09-21 16:02:27 +00:00
|
|
|
return
|
2020-04-20 14:59:18 +00:00
|
|
|
|
2021-12-16 14:57:16 +00:00
|
|
|
# We updating SyncQueue's last slot all the time
|
|
|
|
man.queue.updateLastSlot(man.getLastSlot())
|
|
|
|
|
2020-09-21 16:02:27 +00:00
|
|
|
man.workers[index].status = SyncWorkerStatus.Requesting
|
|
|
|
let req = man.queue.pop(peerSlot, peer)
|
|
|
|
if req.isEmpty():
|
|
|
|
# SyncQueue could return empty request in 2 cases:
|
|
|
|
# 1. There no more slots in SyncQueue to download (we are synced, but
|
|
|
|
# our ``notInSyncEvent`` is not yet cleared).
|
|
|
|
# 2. Current peer's known head slot is too low to satisfy request.
|
|
|
|
#
|
|
|
|
# To avoid endless loop we going to wait for RESP_TIMEOUT time here.
|
|
|
|
# This time is enough for all pending requests to finish and it is also
|
|
|
|
# enough for main sync loop to clear ``notInSyncEvent``.
|
|
|
|
debug "Empty request received from queue, exiting", peer = peer,
|
|
|
|
local_head_slot = headSlot, remote_head_slot = peerSlot,
|
|
|
|
queue_input_slot = man.queue.inpSlot,
|
|
|
|
queue_output_slot = man.queue.outSlot,
|
2021-12-08 21:15:29 +00:00
|
|
|
queue_last_slot = man.queue.finalSlot,
|
2020-09-21 16:02:27 +00:00
|
|
|
peer_speed = peer.netKbps(), peer_score = peer.getScore(),
|
2021-12-16 14:57:16 +00:00
|
|
|
index = index, direction = man.direction, topics = "syncman"
|
2020-09-21 16:02:27 +00:00
|
|
|
await sleepAsync(RESP_TIMEOUT)
|
|
|
|
return
|
2020-04-23 15:31:00 +00:00
|
|
|
|
2020-09-21 16:02:27 +00:00
|
|
|
debug "Creating new request for peer", wall_clock_slot = wallSlot,
|
|
|
|
remote_head_slot = peerSlot, local_head_slot = headSlot,
|
|
|
|
request_slot = req.slot, request_count = req.count,
|
|
|
|
request_step = req.step, peer = peer, peer_speed = peer.netKbps(),
|
2021-12-16 14:57:16 +00:00
|
|
|
peer_score = peer.getScore(), index = index,
|
|
|
|
direction = man.direction, topics = "syncman"
|
2020-09-21 16:02:27 +00:00
|
|
|
|
|
|
|
man.workers[index].status = SyncWorkerStatus.Downloading
|
2020-04-20 14:59:18 +00:00
|
|
|
|
2020-09-21 16:02:27 +00:00
|
|
|
try:
|
|
|
|
let blocks = await man.getBlocks(peer, req)
|
|
|
|
if blocks.isOk:
|
|
|
|
let data = blocks.get()
|
|
|
|
let smap = getShortMap(req, data)
|
|
|
|
debug "Received blocks on request", blocks_count = len(data),
|
|
|
|
blocks_map = smap, request_slot = req.slot,
|
|
|
|
request_count = req.count, request_step = req.step,
|
|
|
|
peer = peer, peer_score = peer.getScore(),
|
2021-12-16 14:57:16 +00:00
|
|
|
peer_speed = peer.netKbps(), index = index,
|
|
|
|
direction = man.direction, topics = "syncman"
|
2020-09-21 16:02:27 +00:00
|
|
|
|
|
|
|
if not(checkResponse(req, data)):
|
|
|
|
peer.updateScore(PeerScoreBadResponse)
|
|
|
|
warn "Received blocks sequence is not in requested range",
|
|
|
|
blocks_count = len(data), blocks_map = smap,
|
|
|
|
request_slot = req.slot, request_count = req.count,
|
|
|
|
request_step = req.step, peer = peer,
|
|
|
|
peer_score = peer.getScore(), peer_speed = peer.netKbps(),
|
2021-12-16 14:57:16 +00:00
|
|
|
index = index, direction = man.direction, topics = "syncman"
|
2020-09-21 16:02:27 +00:00
|
|
|
return
|
2020-01-21 18:30:21 +00:00
|
|
|
|
2020-09-21 16:02:27 +00:00
|
|
|
# Scoring will happen in `syncUpdate`.
|
2021-12-16 14:57:16 +00:00
|
|
|
man.workers[index].status = SyncWorkerStatus.Queueing
|
|
|
|
await man.queue.push(req, data, proc() =
|
|
|
|
man.workers[index].status = SyncWorkerStatus.Processing)
|
2020-09-21 16:02:27 +00:00
|
|
|
else:
|
|
|
|
peer.updateScore(PeerScoreNoBlocks)
|
|
|
|
man.queue.push(req)
|
|
|
|
debug "Failed to receive blocks on request",
|
|
|
|
request_slot = req.slot, request_count = req.count,
|
|
|
|
request_step = req.step, peer = peer, index = index,
|
|
|
|
peer_score = peer.getScore(), peer_speed = peer.netKbps(),
|
2021-12-16 14:57:16 +00:00
|
|
|
direction = man.direction, topics = "syncman"
|
2020-09-21 16:02:27 +00:00
|
|
|
return
|
2020-01-21 18:30:21 +00:00
|
|
|
|
2020-09-21 16:02:27 +00:00
|
|
|
except CatchableError as exc:
|
|
|
|
debug "Unexpected exception while receiving blocks",
|
2020-04-20 14:59:18 +00:00
|
|
|
request_slot = req.slot, request_count = req.count,
|
2020-09-21 16:02:27 +00:00
|
|
|
request_step = req.step, peer = peer, index = index,
|
|
|
|
peer_score = peer.getScore(), peer_speed = peer.netKbps(),
|
2021-12-16 14:57:16 +00:00
|
|
|
errMsg = exc.msg, direction = man.direction, topics = "syncman"
|
2020-09-21 16:02:27 +00:00
|
|
|
return
|
2020-01-21 18:30:21 +00:00
|
|
|
|
2020-09-21 16:02:27 +00:00
|
|
|
proc syncWorker[A, B](man: SyncManager[A, B], index: int) {.async.} =
|
|
|
|
mixin getKey, getScore, getHeadSlot
|
|
|
|
|
2021-12-16 14:57:16 +00:00
|
|
|
debug "Starting syncing worker",
|
|
|
|
index = index, direction = man.direction, topics = "syncman"
|
2020-09-21 16:02:27 +00:00
|
|
|
|
|
|
|
while true:
|
|
|
|
man.workers[index].status = SyncWorkerStatus.Sleeping
|
|
|
|
# This event is going to be set until we are not in sync with network
|
|
|
|
await man.notInSyncEvent.wait()
|
|
|
|
man.workers[index].status = SyncWorkerStatus.WaitingPeer
|
|
|
|
let peer = await man.pool.acquire()
|
|
|
|
await man.syncStep(index, peer)
|
|
|
|
man.pool.release(peer)
|
2020-09-11 12:46:01 +00:00
|
|
|
|
|
|
|
proc getWorkersStats[A, B](man: SyncManager[A, B]): tuple[map: string,
|
|
|
|
sleeping: int,
|
|
|
|
waiting: int,
|
|
|
|
pending: int] =
|
|
|
|
var map = newString(len(man.workers))
|
|
|
|
var sleeping, waiting, pending: int
|
|
|
|
for i in 0 ..< len(man.workers):
|
|
|
|
var ch: char
|
|
|
|
case man.workers[i].status
|
|
|
|
of SyncWorkerStatus.Sleeping:
|
|
|
|
ch = 's'
|
|
|
|
inc(sleeping)
|
|
|
|
of SyncWorkerStatus.WaitingPeer:
|
|
|
|
ch = 'w'
|
|
|
|
inc(waiting)
|
|
|
|
of SyncWorkerStatus.UpdatingStatus:
|
|
|
|
ch = 'U'
|
|
|
|
inc(pending)
|
|
|
|
of SyncWorkerStatus.Requesting:
|
|
|
|
ch = 'R'
|
|
|
|
inc(pending)
|
|
|
|
of SyncWorkerStatus.Downloading:
|
|
|
|
ch = 'D'
|
|
|
|
inc(pending)
|
2021-12-16 14:57:16 +00:00
|
|
|
of SyncWorkerStatus.Queueing:
|
|
|
|
ch = 'Q'
|
|
|
|
inc(pending)
|
2020-09-11 12:46:01 +00:00
|
|
|
of SyncWorkerStatus.Processing:
|
|
|
|
ch = 'P'
|
|
|
|
inc(pending)
|
|
|
|
map[i] = ch
|
|
|
|
(map, sleeping, waiting, pending)
|
2020-01-21 18:30:21 +00:00
|
|
|
|
2020-11-10 13:47:26 +00:00
|
|
|
proc guardTask[A, B](man: SyncManager[A, B]) {.async.} =
|
|
|
|
var pending: array[SyncWorkersCount, Future[void]]
|
|
|
|
|
|
|
|
# Starting all the synchronization workers.
|
|
|
|
for i in 0 ..< len(man.workers):
|
|
|
|
let future = syncWorker[A, B](man, i)
|
|
|
|
man.workers[i].future = future
|
|
|
|
pending[i] = future
|
|
|
|
|
|
|
|
# Wait for synchronization worker's failure and replace it with new one.
|
|
|
|
while true:
|
|
|
|
let failFuture = await one(pending)
|
|
|
|
let index = pending.find(failFuture)
|
|
|
|
if failFuture.failed():
|
|
|
|
warn "Synchronization worker stopped working unexpectedly with an error",
|
2021-12-16 14:57:16 +00:00
|
|
|
index = index, errMsg = failFuture.error.msg, direction = man.direction
|
2020-11-10 13:47:26 +00:00
|
|
|
else:
|
|
|
|
warn "Synchronization worker stopped working unexpectedly without error",
|
2021-12-16 14:57:16 +00:00
|
|
|
index = index, direction = man.direction
|
2020-11-10 13:47:26 +00:00
|
|
|
|
|
|
|
let future = syncWorker[A, B](man, index)
|
|
|
|
man.workers[index].future = future
|
|
|
|
pending[index] = future
|
|
|
|
|
2020-11-12 11:16:51 +00:00
|
|
|
proc toTimeLeftString(d: Duration): string =
|
2021-12-16 14:57:16 +00:00
|
|
|
if d == InfiniteDuration:
|
|
|
|
"--h--m"
|
2020-11-12 11:16:51 +00:00
|
|
|
else:
|
2021-12-16 14:57:16 +00:00
|
|
|
var v = d
|
|
|
|
var res = ""
|
|
|
|
let ndays = chronos.days(v)
|
|
|
|
if ndays > 0:
|
|
|
|
res = res & (if ndays < 10: "0" & $ndays else: $ndays) & "d"
|
|
|
|
v = v - chronos.days(ndays)
|
|
|
|
|
|
|
|
let nhours = chronos.hours(v)
|
|
|
|
if nhours > 0:
|
|
|
|
res = res & (if nhours < 10: "0" & $nhours else: $nhours) & "h"
|
|
|
|
v = v - chronos.hours(nhours)
|
|
|
|
else:
|
|
|
|
res = res & "00h"
|
2020-11-12 11:16:51 +00:00
|
|
|
|
2021-12-16 14:57:16 +00:00
|
|
|
let nmins = chronos.minutes(v)
|
|
|
|
if nmins > 0:
|
|
|
|
res = res & (if nmins < 10: "0" & $nmins else: $nmins) & "m"
|
|
|
|
v = v - chronos.minutes(nmins)
|
|
|
|
else:
|
|
|
|
res = res & "00m"
|
|
|
|
res
|
2020-11-12 11:16:51 +00:00
|
|
|
|
2020-08-10 07:15:50 +00:00
|
|
|
proc syncLoop[A, B](man: SyncManager[A, B]) {.async.} =
|
2020-04-20 14:59:18 +00:00
|
|
|
mixin getKey, getScore
|
2020-10-27 09:25:28 +00:00
|
|
|
var pauseTime = 0
|
2020-01-21 18:30:21 +00:00
|
|
|
|
2020-11-10 13:47:26 +00:00
|
|
|
asyncSpawn man.guardTask()
|
2020-01-21 18:30:21 +00:00
|
|
|
|
2020-09-11 12:46:01 +00:00
|
|
|
debug "Synchronization loop started", topics = "syncman"
|
|
|
|
|
2020-10-27 09:25:28 +00:00
|
|
|
proc averageSpeedTask() {.async.} =
|
|
|
|
while true:
|
2021-12-16 14:57:16 +00:00
|
|
|
# Reset sync speeds between each loss-of-sync event
|
|
|
|
man.avgSyncSpeed = 0
|
|
|
|
man.insSyncSpeed = 0
|
|
|
|
|
|
|
|
await man.notInSyncEvent.wait()
|
|
|
|
|
|
|
|
# Give the node time to connect to peers and get the sync process started
|
|
|
|
await sleepAsync(seconds(SECONDS_PER_SLOT.int64))
|
|
|
|
|
|
|
|
var
|
|
|
|
stamp = SyncMoment.now(man.queue.progress())
|
|
|
|
syncCount = 0
|
|
|
|
|
|
|
|
while man.inProgress:
|
|
|
|
await sleepAsync(seconds(SECONDS_PER_SLOT.int64))
|
|
|
|
|
|
|
|
let
|
|
|
|
newStamp = SyncMoment.now(man.queue.progress())
|
|
|
|
slotsPerSec = speed(stamp, newStamp)
|
|
|
|
|
|
|
|
syncCount += 1
|
|
|
|
|
|
|
|
man.insSyncSpeed = slotsPerSec
|
|
|
|
man.avgSyncSpeed =
|
|
|
|
man.avgSyncSpeed + (slotsPerSec - man.avgSyncSpeed) / float(syncCount)
|
|
|
|
|
|
|
|
stamp = newStamp
|
2020-10-27 09:25:28 +00:00
|
|
|
|
|
|
|
asyncSpawn averageSpeedTask()
|
2020-05-19 12:08:50 +00:00
|
|
|
|
2020-04-20 14:59:18 +00:00
|
|
|
while true:
|
2020-06-14 09:45:53 +00:00
|
|
|
let wallSlot = man.getLocalWallSlot()
|
|
|
|
let headSlot = man.getLocalHeadSlot()
|
2020-04-20 14:59:18 +00:00
|
|
|
|
2020-09-11 12:46:01 +00:00
|
|
|
let (map, sleeping, waiting, pending) = man.getWorkersStats()
|
2020-04-23 15:31:00 +00:00
|
|
|
|
2020-10-27 09:25:28 +00:00
|
|
|
debug "Current syncing state", workers_map = map,
|
2020-09-11 12:46:01 +00:00
|
|
|
sleeping_workers_count = sleeping,
|
|
|
|
waiting_workers_count = waiting,
|
|
|
|
pending_workers_count = pending,
|
|
|
|
wall_head_slot = wallSlot, local_head_slot = headSlot,
|
2020-10-27 09:25:28 +00:00
|
|
|
pause_time = $chronos.seconds(pauseTime),
|
|
|
|
avg_sync_speed = man.avgSyncSpeed, ins_sync_speed = man.insSyncSpeed,
|
2021-12-16 14:57:16 +00:00
|
|
|
direction = man.direction, topics = "syncman"
|
|
|
|
|
|
|
|
let
|
|
|
|
progress = float(man.queue.progress())
|
|
|
|
total = float(man.queue.total())
|
|
|
|
remaining = total - progress
|
|
|
|
done = if total > 0.0: progress / total else: 1.0
|
|
|
|
timeleft =
|
|
|
|
if man.avgSyncSpeed >= 0.001:
|
|
|
|
Duration.fromFloatSeconds(remaining / man.avgSyncSpeed)
|
|
|
|
else: InfiniteDuration
|
2020-04-20 14:59:18 +00:00
|
|
|
|
2020-09-11 12:46:01 +00:00
|
|
|
# Update status string
|
2021-12-16 14:57:16 +00:00
|
|
|
man.syncStatus = timeLeft.toTimeLeftString() & " (" &
|
|
|
|
(done * 100).formatBiggestFloat(ffDecimal, 2) & "%) " &
|
|
|
|
man.avgSyncSpeed.formatBiggestFloat(ffDecimal, 4) &
|
|
|
|
"slots/s (" & map & ":" & $man.queue.outSlot & ")"
|
2020-05-19 12:08:50 +00:00
|
|
|
|
2020-06-14 09:45:53 +00:00
|
|
|
if headAge <= man.maxHeadAge:
|
2020-09-11 12:46:01 +00:00
|
|
|
man.notInSyncEvent.clear()
|
|
|
|
# We are marking SyncManager as not working only when we are in sync and
|
|
|
|
# all sync workers are in `Sleeping` state.
|
|
|
|
if pending > 0:
|
|
|
|
debug "Synchronization loop waits for workers completion",
|
|
|
|
wall_head_slot = wallSlot, local_head_slot = headSlot,
|
|
|
|
difference = (wallSlot - headSlot), max_head_age = man.maxHeadAge,
|
|
|
|
sleeping_workers_count = sleeping,
|
|
|
|
waiting_workers_count = waiting, pending_workers_count = pending,
|
2021-12-16 14:57:16 +00:00
|
|
|
direction = man.direction, topics = "syncman"
|
2020-09-11 12:46:01 +00:00
|
|
|
man.inProgress = true
|
|
|
|
else:
|
|
|
|
debug "Synchronization loop sleeping", wall_head_slot = wallSlot,
|
|
|
|
local_head_slot = headSlot, difference = (wallSlot - headSlot),
|
2021-12-16 14:57:16 +00:00
|
|
|
max_head_age = man.maxHeadAge, direction = man.direction,
|
|
|
|
topics = "syncman"
|
2020-06-14 09:45:53 +00:00
|
|
|
man.inProgress = false
|
|
|
|
else:
|
2020-10-30 12:33:52 +00:00
|
|
|
if not(man.notInSyncEvent.isSet()):
|
|
|
|
# We get here only if we lost sync for more then `maxHeadAge` period.
|
|
|
|
if pending == 0:
|
2021-12-16 14:57:16 +00:00
|
|
|
man.initQueue()
|
2020-10-30 12:33:52 +00:00
|
|
|
man.notInSyncEvent.fire()
|
|
|
|
man.inProgress = true
|
|
|
|
else:
|
|
|
|
man.notInSyncEvent.fire()
|
|
|
|
man.inProgress = true
|
2020-06-14 09:45:53 +00:00
|
|
|
|
2020-09-11 12:46:01 +00:00
|
|
|
await sleepAsync(chronos.seconds(2))
|
|
|
|
|
2020-08-10 07:15:50 +00:00
|
|
|
proc start*[A, B](man: SyncManager[A, B]) =
|
|
|
|
## Starts SyncManager's main loop.
|
|
|
|
man.syncFut = man.syncLoop()
|
2020-11-26 19:23:45 +00:00
|
|
|
|
2021-08-03 15:17:11 +00:00
|
|
|
proc getInfo*[A, B](man: SyncManager[A, B]): RpcSyncInfo =
|
2020-11-26 19:23:45 +00:00
|
|
|
## Returns current synchronization information for RPC call.
|
|
|
|
let wallSlot = man.getLocalWallSlot()
|
|
|
|
let headSlot = man.getLocalHeadSlot()
|
2021-03-04 09:13:23 +00:00
|
|
|
let sync_distance = wallSlot - headSlot
|
2021-03-17 20:42:55 +00:00
|
|
|
(
|
|
|
|
head_slot: headSlot,
|
|
|
|
sync_distance: sync_distance,
|
|
|
|
is_syncing: man.inProgress
|
|
|
|
)
|