Keeper assignment and release in RanDAO realisation
Keeper assignment
Choice algorithm
The algorithm for a RanDAO-based choice of a next keeper is encoded in the _assignNextKeeper function. We outline it here
function_assignNextKeeper(bytes32 jobKey_) internal {//get the randao realisation for the current block, stored in the block.difficultyuint256 pseudoRandom =_getPseudoRandom();//get the cardinality of the keeper set so that the index may be taken modulo ituint256 totalActiveKeepers = activeKeepers.length();//get the minimal CVP stake demanded of the keeper by the jobuint256 _jobMinKeeperCvp = jobMinKeeperCvp[jobKey_]; //obtain the index by taking the pseudorandom input, adding the job key so that variance in chosen keeper indices is observed within any single block, and mapping the result into the keeper index set by taking the modulo operation
//the resultant variable index is the index of the keeper selected for executionuint256 index;unchecked { index = ((pseudoRandom +uint256(jobKey_)) % totalActiveKeepers); } //iterate over all the keepers, starting with the randomly selected one, until a keeper admissible for the job at hand is found or all gas has been expended
while (true) {//effectively modulo operationif (index >= totalActiveKeepers) { index =0; }//obtain the ID of the next keeper by the index selecteduint256 _nextExecutionKeeperId = activeKeepers.at(index);//required stake is set to be the global minimal demanded CVP unless the job has a specification of its ownuint256 requiredStake = _jobMinKeeperCvp >0? _jobMinKeeperCvp : minKeeperCvp;//load the keeper object at the selected ID Keeper memory keeper = keepers[_nextExecutionKeeperId]; //if the keeper is admissible, i.e. active and has sufficient stake, then assign him as the next keeper of the job and terminate the passage
if (keeper.isActive && keeper.cvpStake >= requiredStake) { jobNextKeeperId[jobKey_] = _nextExecutionKeeperId; keeperLocksByJob[_nextExecutionKeeperId].add(jobKey_);emitKeeperJobLock(_nextExecutionKeeperId, jobKey_);return; } index +=1; } }}
Calling the internal function of keeper assignment
Exogeneously
Exogeneous manual keeper assignment is available to the job(s) owner if needed:
Of more interest is the wrapped conditional keeper assignment, since we do not wish keepers to be assigned to jobs with below-minimum resources with which to pay them. This is handled by the internal function
function_assignNextKeeperIfRequired(//key of the job for which to assign a keeperbytes32 jobKey_) internalreturns (//assignment success indicatorbool assigned)//get the job credits balance (11 bytes, or 256-168 = 88 bits, starting from 128-th bit (12th byte) in binary representation)
uint256credits = (binJob << 128) >> 168;//check job owner credits instead if the owner paysif (ConfigFlags.check(binJob, CFG_USE_JOB_OWNER_CREDITS)) { credits = jobOwnerCredits[jobOwners[jobKey_]];}//if a keeper is not assigned yetif (jobNextKeeperId[jobKey_] ==0&&//and the job/owner has enough credits with respect to the threshold given by the Agent parameter jobMinCreditsFinneycredits >= (uint256(rdConfig.jobMinCreditsFinney) *0.001ether)) {//then assign a keeper and return True_assignNextKeeper(jobKey_);returntrue;}//else Falsereturnfalse;
Cases in which conditional assignment is invoked
The conditional keeper assignment happens when:
The job config is updated, with the credits source having changed or a previously inactive job activating
Credits are deposited to a Job (via the overridden hook _afterDepositJobCredits(bytes32 jobKey) invoked in function depositJobCredits(bytes32 jobKey_) in the core contract)
Cases in which unconditional assignment is invoked
Unconditional keeper assignment happens when:
Job execution is successful, and the old keeper needs to be swapped for a new one (inside the function _afterExecutionSucceeded(bytes32 jobKey, uint256 actualKeeperId_, uint256 binJob_) internal hook).
After a job is registered (inside the function _afterRegisterJob(bytes32 jobKey) internal hook)
Keeper release
Technical implementation of releasing a keeper
Keeper release is performed by the internal function _releaseKeeper(bytes32 jobKey_, uint256 keeperId_) and consists of clearing the Job parameters pertaining to the next keeper and possible slashing and removing the job from the keeper's pending pool:
function_releaseKeeper(//key of job for which to releasebytes32 jobKey_,//ID of keeper which to release; in actuality could be inferred from the job's NextKeeperId mappinguint256 keeperId_) internal {//remove job from the keeper's pending jobs pool keeperLocksByJob[keeperId_].remove(jobKey_);//remove the assigned keeper from the Job's corresponding mapping jobNextKeeperId[jobKey_] =0;//slashing is no longer possible, since there is no keeper assigned jobSlashingPossibleAfter[jobKey_] =0;//so clear the reserved slasher as well jobReservedSlasherId[jobKey_] =0;//event for WS listenersemitKeeperJobUnlock(keeperId_, jobKey_); }
Calling the keeper release function
We need to exercise utmost care in calling such function so that it does not provide malicious keepers with a way to escape punishment.
Firstly, there is a defined conditional release on insufficiency of Job credits, wrapped into a function releaseKeeperIfRequired, itself wrapping releaseKeeperIfRequiredBinJob. Since releaseKeeperIfRequired is a simple wrapping of a call to releaseKeeperIfRequiredBinJob with a freshly read binary job representation passed as an argument, we only describe the latter function.
function_releaseKeeperIfRequiredBinJob(//job for which to releasebytes32 jobKey_,//keeper whom to releaseuint256 keeperId_,//binary job representation corresponding to the job with jobKey_uint256 binJob_,//whether to check if a keeper has already been releasedbool checkAlreadyReleased) internalreturns (bool released) { //get the job credits balance (11 bytes, or 256-168 = 88 bits, starting from 128-th bit (12th byte) in binary representation)
uint256 credits = (binJob_ <<128) >>168;//if job owner pays, get his credits insteadif (ConfigFlags.check(binJob_, CFG_USE_JOB_OWNER_CREDITS)) { credits = jobOwnerCredits[jobOwners[jobKey_]]; } //if the keeper is not yet released (or the check flag is False), and credits of the job are insufficient with respect to an Agent-wide acceptable minimum
if ((!checkAlreadyReleased || jobNextKeeperId[jobKey_] != 0) && credits < (uint256(rdConfig.jobMinCreditsFinney) * 0.001 ether)) {
//then release and return True_releaseKeeper(jobKey_, keeperId_);returntrue; }//else Falsereturnfalse;}
This function is called when:
Assigning a keeper (in keeper assignment, a check of _releaseKeeperIfRequiredBinJob (with the checkAlreadyReleased flag passed as False) being False ensures no keeper is assigned for an job with too few tokens)
Job credits are withdrawn (via the hook _afterWithdrawJobCredits(bytes32 jobKey_) internal)
releaseJob is called by a keeper admin (the check happens before any slashing checks and is the only way for a job to be released without satisfying these checks, e.g. when the admissibility period is not over yet, and the keeper is technically locked by the possibility of being slashed, he still can be released from his duty if the job does not meet the minimum credit demand)
The job config is updated, with the credits source having changed, and _assignNextKeeperIfRequired returning False.
Unwrapped _releaseKeeperIfRequiredBinJob is called when:
Assigning a new keeper; checkAlreadyReleased is passed as False, so this has the meaning of exiting the keeper assignment process when the job/owner does not have sufficient tokens.
Unconditional release is called when:
The job owner calls releaseJob
The keeper admin calls releaseJob, the Job has sufficient (from the Agent's standpoint) credits, and the admissibility period of slashing has elapsed
The keeper is disabled
After execution of the job being automated reverts
The job is deactivated
After execution of the job being automated succeeds