Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[I-04] Unit Test Gaps #283

Open
softstackio opened this issue Jan 13, 2025 · 0 comments
Open

[I-04] Unit Test Gaps #283

softstackio opened this issue Jan 13, 2025 · 0 comments
Assignees

Comments

@softstackio
Copy link

softstackio commented Jan 13, 2025

Testing Gaps

  1. nonReentrant Modifier branch not covered in reward function of BlockRewardHbbft contract
  2. a validator's score can increase from the minimum score (MIN_SCORE) after receiving frequent penalties
it("should allow score increase from MIN_SCORE after frequent
penalties", async function() {
        const { bonusScoreSystem, stakingHbbft } = await
helpers.loadFixture(deployContracts);
        const validator = initialValidators[0];
        const validatorSet = await impersonateAcc(await
bonusScoreSystem.validatorSetHbbft());
        const connectivityTracker = await impersonateAcc(await
bonusScoreSystem.connectivityTracker());
        // Apply penalties to reach MIN_SCORE
        for (let i = 0; i < 10; i++) {
          await
bonusScoreSystem.connect(validatorSet).penaliseNoKeyWrite(validator);
          await
bonusScoreSystem.connect(connectivityTracker).penaliseBadPerformance(valid
ator, 0);
}
        // Verify score is at MIN_SCORE
        expect(await
bonusScoreSystem.getValidatorScore(validator)).to.equal(MIN_SCORE);
        // Attempt to increase score
        const availableSince = await helpers.time.latest();
        const standByTime = await
bonusScoreSystem.getTimePerScorePoint(ScoringFactor.StandByBonus) * 5n;
        await helpers.time.increase(standByTime);
await
bonusScoreSystem.connect(validatorSet).rewardStandBy(validator,
availableSince);
        // Verify score has increased
        const newScore = await
bonusScoreSystem.getValidatorScore(validator);
        expect(newScore).to.be.gt(MIN_SCORE);
        await helpers.stopImpersonatingAccount(validatorSet.address);
await
helpers.stopImpersonatingAccount(connectivityTracker.address);
      });

  1. test the withinAllowedRange modifier in the setReportDisallowPeriod function in ConnectivityTrackerHbbft contract
it("should revert when setting value outside allowed range", async
function () {
           const { connectivityTracker } = await
helpers.loadFixture(deployContracts);
           const tooLowValue = 1 * 60; // 1 minute (assuming this
is below the minimum allowed)
           const tooHighValue = 31 * 60; // 31 minutes (assuming
this is above the maximum allowed)
           await expect(
connectivityTracker.connect(owner).setReportDisallowPeriod(tooLowVal
ue)
"NewValueOutOfRange")
).to.be.revertedWithCustomError(connectivityTracker,
   .withArgs(tooLowValue);
await expect(
connectivityTracker.connect(owner).setReportDisallowPeriod(tooHighVa
lue)
           ).to.be.revertedWithCustomError(connectivityTracker,
"NewValueOutOfRange")
});

  1. onlyBlockRewardContractmodifieroffunctionhandleFailedKeyGenerationin contract validatorSetHbbft
it('should revert if not called by BlockReward contract', async ()
=> {
await
expect(validatorSetHbbft.connect(accounts[1]).handleFailedKeyGenerat
ion())
"Unauthorized");
       });
       
  1. EpochNotYetzFinishedrevertnottriggering,inhandleFailedKeyGeneration function
it('should revert if epoch has not yet finished', async () => {
           const epochEndTime = await
stakingHbbft.stakingFixedEpochEndTime();
           await helpers.time.setNextBlockTimestamp(epochEndTime -
100n);
           await helpers.mine();
           console.log("Epoch end time:", epochEndTime.toString());
           console.log("Current block timestamp:", (await
helpers.time.latest()).toString());
           await expect(validatorSetHbbft.connect(
               await impersonateAcc(await
blockRewardHbbft.getAddress())
).handleFailedKeyGeneration()).to.be.revertedWithCustomError(
validatorSetHbbft,
       "EpochNotYetFinished"
); });

  1. Revert StakingPoolNotExist in setValidatorInternetAddress
it('should revert with StakingPoolNotExist for non-validator
address', async () => {
          const nonValidatorAddress = accounts[10];
          const ipAddress = new Uint8Array(16).fill(1);
          const port = 30303;
          await expect(
validatorSetHbbft.connect(nonValidatorAddress).setValidatorInternetA
ddress(
          ethers.hexlify(ipAddress),
          ethers.hexlify(convertToBigEndian(port))
      )
  ).to.be.revertedWithCustomError(
      validatorSetHbbft,
      "StakingPoolNotExist"
  ).withArgs(nonValidatorAddress.address);
});

  1. getPreviousValidators function
describe('getPreviousValidators', () => {
      let validatorSetHbbft: ValidatorSetHbbftMock;
      let blockRewardHbbft: BlockRewardHbbftMock;
      let initialValidators: string[];
      beforeEach(async () => {
          const fixture = await
helpers.loadFixture(deployContractsFixture);
          validatorSetHbbft = fixture.validatorSetHbbft;
          blockRewardHbbft = fixture.blockRewardHbbft;
          initialValidators = fixture.initialValidators;
      });
it('should initially return an empty array', async () => {
          const previousValidators = await
validatorSetHbbft.getPreviousValidators();
expect(previousValidators).to.be.an('array').that.is.empty;
}); });

  1. Revert InvalidPossibleValidatorCount
describe('getValidatorCountSweetSpot', async () => {
      let validatorSetHbbft: ValidatorSetHbbftMock;
      beforeEach(async () => {
          const { validatorSetHbbft: vsh } = await
helpers.loadFixture(deployContractsFixture);
          validatorSetHbbft = vsh;
});
      it('should revert with InvalidPossibleValidatorCount when
input is zero', async () => {
await
expect(validatorSetHbbft.getValidatorCountSweetSpot(0))
              .to.be.revertedWithCustomError(validatorSetHbbft,
"InvalidPossibleValidatorCount");
      });
      it('hbbft sweet spots are calculated correct.
getValidatorCountSweetSpot', async () => {
          const { validatorSetHbbft } = await
helpers.loadFixture(deployContractsFixture);
          const expectedResults =
              [
                  1n, 2n, 3n,
                  4n, 4n, 4n,
                  7n, 7n, 7n,
                  10n, 10n, 10n,
                  13n, 13n, 13n,
                  16n, 16n, 16n,
19n, 19n, 19n,
                  22n, 22n, 22n,
                  25n
];
          for (let i = 0; i < expectedResults.length; i++) {
              const expected = expectedResults[i];
              const result = await
validatorSetHbbft.getValidatorCountSweetSpot(i + 1);
              expect(result).to.equal(expected);
} });
});

  1. Test for the public keys count check initialize in StakingHbbft
it('should fail if public keys count is invalid', async () => {
         let stakingParams = {
             _validatorSetContract: validatorSetContract,
             _bonusScoreContract: bonusScoreContract,
             _initialStakingAddresses: initialStakingAddresses,
             _delegatorMinStake: minStake,
             _candidateMinStake: minStake,
             _maxStake: maxStake,
             _stakingFixedEpochDuration:
stakingFixedEpochDuration,
             _stakingTransitionTimeframeLength:
stakingTransitionTimeframeLength,
             _stakingWithdrawDisallowPeriod:
stakingWithdrawDisallowPeriod
};
         // Create an invalid public keys array by removing one
element
         const invalidPublicKeys =
initialValidatorsPubKeysSplit.slice(0, -1);
         const StakingHbbftFactory = await
ethers.getContractFactory("StakingHbbftMock");
         await expect(upgrades.deployProxy(
             StakingHbbftFactory,
[
                 owner.address,
                 stakingParams,
                 invalidPublicKeys, // Invalid _publicKeys
                 initialValidatorsIpAddresses
],
             { initializer: 'initialize' }
         )).to.be.revertedWithCustomError(StakingHbbftFactory,
"InvalidPublicKeysCount");
     });
     
  1. Test for the IP addresses count check: initialize in StakingHbbft
it('should fail if IP addresses count is invalid', async () => {
            let stakingParams = {
                _validatorSetContract: validatorSetContract,
                _bonusScoreContract: bonusScoreContract,
                _initialStakingAddresses: initialStakingAddresses,
                _delegatorMinStake: minStake,
                _candidateMinStake: minStake,
                _maxStake: maxStake,
                _stakingFixedEpochDuration:
stakingFixedEpochDuration,
                _stakingTransitionTimeframeLength:
stakingTransitionTimeframeLength,
                _stakingWithdrawDisallowPeriod:
stakingWithdrawDisallowPeriod
};
            // Create an invalid IP addresses array by adding an
extra element
            const invalidIpAddresses =
[...initialValidatorsIpAddresses, ZeroIpAddress];
const StakingHbbftFactory = await
ethers.getContractFactory("StakingHbbftMock");
            await expect(upgrades.deployProxy(
                StakingHbbftFactory,
                [
                    owner.address,
                    stakingParams,
                    initialValidatorsPubKeysSplit,
                    invalidIpAddresses // Invalid _internetAddresses
],
                { initializer: 'initialize' }
            )).to.be.revertedWithCustomError(StakingHbbftFactory,
"InvalidIpAddressesCount");
        });
  1. test the withinAllowedRange modifier for the setDelegatorMinStake function
     it('should set delegator min stake within allowed range',
async () => {
           const minStakeValue = ethers.parseEther('150');
await
expect(stakingHbbft.connect(owner).setDelegatorMinStake(minStakeValu
e))
               .to.emit(stakingHbbft, "SetDelegatorMinStake")
               .withArgs(minStakeValue);
           expect(await
stakingHbbft.delegatorMinStake()).to.be.equal(minStakeValue);
       });
       it('should allow setting min stake to the lowest allowed
value', async () => {
           const lowestAllowedStake = ethers.parseEther('50');
await
expect(stakingHbbft.connect(owner).setDelegatorMinStake(lowestAllowe
dStake))
               .to.emit(stakingHbbft, "SetDelegatorMinStake")
               .withArgs(lowestAllowedStake);
           expect(await
stakingHbbft.delegatorMinStake()).to.be.equal(lowestAllowedStake);
       });
  1. test the stakingFixedEpochEndTime function
 describe('stakingFixedEpochEndTime', () => {
        let stakingHbbft: StakingHbbftMock;
        beforeEach(async () => {
            const fixture = await
helpers.loadFixture(deployContractsFixture);
            stakingHbbft = fixture.stakingHbbft;
});
        it('should calculate correct end time based on current
stakingFixedEpochDuration', async () => {
            const startTime = await
stakingHbbft.stakingEpochStartTime();
            const extraTimeWindow = await
stakingHbbft.currentKeyGenExtraTimeWindow();
            const epochDuration = await
stakingHbbft.stakingFixedEpochDuration();
            const expectedEndTime = startTime + epochDuration +
extraTimeWindow - (epochDuration === 0n ? 0n : 1n);
            const actualEndTime = await
stakingHbbft.stakingFixedEpochEndTime();
            expect(actualEndTime).to.equal(expectedEndTime);
        });
});

Test Results (Reference)
BlockRewardHbbft
✔ should get governance address
✔ staking epoch #0 finished (166ms)
✔ staking epoch #1 started
✔ validators and their delegators place stakes during the epoch #1 (259ms) ✔ staking epoch #1 finished (189ms)
✔ DMD Pots: filling delta pot
✔ DMD Pots: governance pot got correct share. (262ms)
✔ DMD Pots: reinsert pot works as expected. (252ms)
✔ transfers to reward contract works with 100k gas and fills reinsert pot
✔ reduces the reward if the epoch was shorter than expected (220ms)
✔ gives full reward if the epoch was longer than expected (219ms)
✔ upscaling: add multiple validator pools and upscale if needed. (12281ms) ✔ upscaling: removing validators up to 16 (511ms)
✔ upscaling: mining twice shouldn't change pending validator set (529ms) ✔ upscaling: set is scaled to 25 (1520ms)
initialize
✔ should fail if owner = address(0) (72ms)
✔ should fail if ValidatorSet = address(0) (71ms)
✔ should fail if ConnectivityTracker = address(0) (54ms) ✔ should fail on double initialization (69ms)
setGovernancePotShareNominator
✔ should restrict calling to contract owner
✔ should not allow values outside allowed range (51ms)
✔ should allow value increase within allowed range (136ms) ✔ should allow value decrease within allowed range (142ms)
reward
✔ should restrict calling reward only to system address
✔ should revert for zero validators (42ms)
✔ should save epochs in which validator was awarded (1887ms)
✔ should not reward validators who announced availability in the current epoch
(342ms)
✔ should not distribute rewards if there is no rewarded validators (295ms) ✔ should not distribute rewards if pool reward = 0 (291ms)
✔ should not reward validators with stake amount = 0 and save undistributed amount (169ms)
early epoch end
✔ should restrict calling notifyEarlyEpochEnd to connectivity tracker contract only ✔ should emit event on early epoch end notification receive
✔ should end epoch earlier if notified (66ms)
✔ should not end epoch earlier if not notified
✔ should ignore and reset early epoch end flag received during key generation
phase (75ms)
BonusScoreSystem Initializer
✔ should revert initialization with zero address argument, test #1 (80ms) ✔ should revert initialization with zero address argument, test #2 (57ms) ✔ should revert initialization with zero address argument, test #3 (70ms) ✔ should revert initialization with zero address argument, test #4 (61ms) ✔ should not allow re-initialization (110ms)
✔ should set initial scoring factor StandByBonus (118ms)
✔ should set initial scoring factor NoStandByPenalty (97ms)
✔ should set initial scoring factor NoKeyWritePenalty (86ms)
✔ should set initial scoring factor BadPerformancePenalty (91ms)
updateScoringFactor

  • should restrict calling to contract owner
  • should not allow zero factor value
  • should set scoring factor StandByBonus and emit event
  • should set scoring factor NoStandByPenalty and emit event
  • should set scoring factor NoKeyWritePenalty and emit event
  • should set scoring factor BadPerformancePenalty and emit event
    getScoringFactorValue
    ✔ should revert for unknown scoring factor (303ms) ✔ should get scoring factor value
    getTimePerScorePoint
    ✔ should get time per StandByBonus factor point
    ✔ should get time per NoStandByPenalty factor point
    ✔ should get time per NoKeyWritePenalty factor point
    ✔ should get time per BadPerformancePenalty factor point
    getValidatorScore
    ✔ should return MIN_SCORE if not previously recorded
    rewardStandBy

✔ should restrict calling to ValidatorSet contract
✔ should revert for availability timestamp in the future
✔ should increase validator score depending on stand by interval
✔ should emit event
✔ should not exceed MAX_SCORE (1193ms)
✔ should use last score change timestamp if its higher than availability timestamp
(65ms)
✔ should increase pool likelihood (67ms) ✔ should be non-reentrant (107ms)
penaliseNoStandBy
✔ should restrict calling to ValidatorSet contract
✔ should revert for availability timestamp in the future
✔ should decrease validator score depending on no stand by interval (150ms)
✔ should emit event (149ms)
✔ should not decrease below MIN_SCORE (45ms)
✔ should use last score change timestamp if its higher than availability timestamp
(379ms)
✔ should decrease pool likelihood (415ms) ✔ should be non-reentrant (91ms)
penaliseNoKeyWrite
✔ should restrict calling to ValidatorSet contract
✔ should decrease validator score (170ms)
✔ should not decrease below MIN_SCORE (158ms) ✔ should emit event (161ms)
✔ should decrease pool likelihood (279ms)
✔ should be non-reentrant (92ms)
penaliseBadPerformance
✔ should restrict calling to ConnectivityTracker contract
✔ should decrease validator score depending on disconnect interval (228ms) ✔ should fully penalise for bad performance (243ms)
✔ should emit event (289ms)
✔ should decrease pool likelihood (749ms)
✔ should be non-reentrant (85ms)
CertifierHbbft contract Initializer
✔ should revert initialization with validator contract = address(0) (56ms) ✔ should revert initialization with owner = address(0) (70ms)
✔ should not allow initialization if initialized contract (80ms)

certification
✔ should restrict calling certify to contract owner (205ms) ✔ should restrict calling revoke to contract owner
✔ should sertify address
✔ should revoke cerification
✔ validator account should be certified by default
ConnectivityTrackerHbbft Initializer
✔ should revert if owner = address(0) (86ms)
✔ should revert if validator set contract = address(0) (71ms)
✔ should revert if staking contract = address(0) (60ms)
✔ should revert if block reward contract = address(0) (49ms)
✔ should revert if block bonus score contract = address(0) (52ms) ✔ should revert double initialization (85ms)
setReportDisallowPeriod
✔ should revert calling function by unauthorized account (1419ms) ✔ should set report disallow period and emit event
✔ should revert when setting value outside allowed range (44ms)
reportMissingConnectivity
✔ should restrict calling function only to validators
✔ should revert calling for future block
✔ should revert calling with invalid block hash
✔ should revert too early report
✔ should revert duplicate report by same validator (82ms)
✔ should revert report by flagged validator (55ms)
✔ should report missing connectivity and emit event (41ms)
✔ should report missing connectivity and flag validator (55ms)
✔ should increase validator connectivity score with each report (637ms) ✔ should set faulty validator as unavailable (446ms)
✔ should not mark validator faulty if it's already marked (480ms)
reportReconnect
✔ should restrict calling function only to validators
✔ should revert calling for future block
✔ should revert calling with invalid block hash
✔ should revert too early report
✔ should revert report reconnect without disconnect report ✔ should revert report reconnect by flagged validator (50ms) ✔ should report validator reconnected and emit event (55ms)

✔ should report validator reconnected and unflag it (62ms)
✔ should decrease validator connectivity score if reported reconnect (76ms)
✔ should send bad performance penalty after faulty validator full reconnect (844ms)
penaliseFaultyValidators
✔ should restrict calling to BlockReward contract
✔ should not send penalties twice for same epoch
✔ should penalise faulty validators (2344ms)
✔ should not penalise flagged but non faulty validators (2666ms)
countFaultyValidators
✔ should count faulty validators (2456ms)
✔ should return 0 if validators reported but not faulty (2276ms)
isReported
✔ should check if validator reported (620ms)
earlyEpochEndThreshold
✔ should get epoch end threshold for hbbft fault tolerance: 0, network size: 1 ✔ should get epoch end threshold for hbbft fault tolerance: 0, network size: 2 ✔ should get epoch end threshold for hbbft fault tolerance: 0, network size: 3 ✔ should get epoch end threshold for hbbft fault tolerance: 1, network size: 4 ✔ should get epoch end threshold for hbbft fault tolerance: 2, network size: 7 ✔ should get epoch end threshold for hbbft fault tolerance: 3, network size: 10 ✔ should get epoch end threshold for hbbft fault tolerance: 4, network size: 13 ✔ should get epoch end threshold for hbbft fault tolerance: 5, network size: 16 ✔ should get epoch end threshold for hbbft fault tolerance: 6, network size: 19 ✔ should get epoch end threshold for hbbft fault tolerance: 7, network size: 22 ✔ should get epoch end threshold for hbbft fault tolerance: 8, network size: 25
early epoch end
✔ should set early epoch end = true with sufficient reports (2354ms)
✔ should skip check for current epoch if early end already set (2192ms)
KeyGenHistory initialize
✔ should revert initialization with owner = address(0) (131ms)
✔ should revert initialization with validator contract address = address(0) (125ms) ✔ should revert initialization with empty validators array (151ms)
✔ should revert initialization with wrong number of parts (134ms)
✔ should revert initialization with wrong number of acks (71ms)
✔ should not allow reinitialization (178ms)
contract functions
✔ should restrict calling clearPrevKeyGenState to ValidatorSet contract

✔ should restrict calling notifyNewEpoch to ValidatorSet contract ✔ should restrict calling notifyKeyGenFailed to ValidatorSet contract ✔ should revert writePart for wrong epoch
✔ should revert writePart for wrong round
✔ should revert writePart by non-pending validator
✔ should revert writeAcks for wrong epoch
✔ should revert writeAcks for wrong round
✔ should revert writeAcks by non-pending validator
✔ failed KeyGeneration, availability. (825ms)
✔ 1/2 KeyGeneration - PART Failure (674ms)
✔ 1/2 KeyGeneration - ACKS Failure (503ms)
Certifier
✔ Owner must be able to certify any user
✔ Mining addresses with pools should be certified by default ✔ Should be able to revoke from non-validators
✔ Shouldn't be able to revoke from working validators
✔ Shouldn't be able to certify zero address
RandomHbbft Initializer
✔ should revert initialization with validator contract = address(0) (49ms) ✔ should revert initialization with owner = address(0) (53ms)
✔ should not allow initialization if initialized contract (71ms)
currentSeed()
✔ setCurrentSeed must revert if called by non-owner (858ms)
✔ should set current seed by system
✔ last 10 seeds must be equal to last 10 elements in the array (373ms)
FullHealth()
✔ should display health correctly
✔ should mark unhealty blocks (47ms)
✔ should get full health historic array (590ms)
StakingHbbft addPool()
✔ should set the corresponding public keys (517ms)
✔ should set the corresponding IP addresses
✔ should create a new pool
✔ should create pool and set node operator configuration (51ms) ✔ should fail if created with overstaked pool (80ms)

✔ should fail if mining address is 0
✔ should fail if mining address is equal to staking
✔ should fail if the pool with the same mining/staking address is already existing
(171ms)
✔ should fail if gasPrice is 0
✔ should fail if staking amount is 0

  • should fail if stacking time is inside disallowed range
    ✔ should fail if staking amount is less than CANDIDATE_MIN_STAKE
    ✔ stake amount should be increased (38ms)
    ✔ should be able to add more than one pool (74ms)
    ✔ shouldn't allow adding more than MAX_CANDIDATES pools (1656ms) ✔ should remove added pool from the list of inactive pools
    setNodeOperator
    ✔ should revert for non-existing pool
    ✔ should not allow to change node operator twice within same epoch (96ms) ✔ should not allow zero address and non-zero percent (61ms)
    ✔ should not exceed max share percent (62ms)
    ✔ should change pool node operator configuration (65ms)
    contract balance
    ✔ cannot be increased by sending native coins
    ✔ can be increased by sending coins to payable functions (53ms)
    incrementStakingEpoch()
    ✔ should increment if called by the ValidatorSet ✔ can only be called by ValidatorSet contract
    initialize()
    ✔ should fail if public keys count is invalid (92ms)
    ✔ should fail if IP addresses count is invalid (72ms)
    ✔ should initialize successfully (186ms)
    ✔ should fail if owner = address(0) (88ms)
    ✔ should fail if ValidatorSet contract address is zero (77ms)
    ✔ should fail if delegatorMinStake is zero (104ms)
    ✔ should fail if candidateMinStake is zero (85ms)
    ✔ should fail if already initialized (144ms)
    ✔ should fail if stakingEpochDuration is 0 (102ms)
    ✔ should fail if stakingWithdrawDisallowPeriod is 0 (88ms)
    ✔ should fail if stakingWithdrawDisallowPeriod >= stakingEpochDuration (79ms) ✔ should fail if some staking address is 0 (123ms)
    ✔ should fail if timewindow is 0 (88ms)

✔ should fail if transition timewindow is smaller than the staking time window (77ms)
moveStake()
✔ should move entire stake (60ms)
✔ should move part of the stake (57ms)
✔ should move part of the stake (73ms)
✔ should fail for zero gas price
✔ should fail if the source and destination addresses are the same
✔ should fail if the staker tries to move more than they have (48ms) ✔ should fail if the staker tries to overstake by moving stake. (159ms)
stake()
✔ should be zero initially
✔ should place a stake (62ms)
✔ should fail for zero gas price
✔ should fail for a zero staking pool address
✔ should fail for a non-existing pool
✔ should fail for a zero amount

  • should only success in the allowed staking window
    ✔ should fail if a candidate stakes less than CANDIDATE_MIN_STAKE
    ✔ should fail if a delegator stakes less than DELEGATOR_MIN_STAKE (44ms)
    ✔ should fail if a delegator stakes more than maxStake (48ms)
    ✔ should fail if a delegator stakes into an empty pool
    ✔ should increase a stake amount (54ms)
    ✔ should increase the stakeAmountByCurrentEpoch (59ms)
    ✔ should increase a total stake amount (65ms)
    ✔ should add a delegator to the pool (88ms)
    ✔ should update pool's likelihood (80ms)
    ✔ should decrease the balance of the staker and increase the balance of the Staking
    contract
    ✔ should not create stake snapshot on epoch 0 (79ms)
    ✔ should create stake snapshot if staking on an active validator (149ms)
    removePool()
    ✔ should remove a pool
    ✔ can only be called by the ValidatorSetHbbft contract
    ✔ shouldn't fail when removing a nonexistent pool
    ✔ should add/remove a pool to/from the utility lists (70ms)
    removePools()
    ✔ should restrict calling removePools to validator set contract
    removeMyPool()

✔ should
✔ should withdraw() ✔ should ✔ should ✔ should ✔ should
fail for zero gas price
fail for initial validator during the initial staking epoch (51ms)
withdraw a stake (107ms)
fail for zero gas price
fail for a zero pool address (61ms) fail for a zero amount (53ms)

  • shouldn't allow withdrawing during the stakingWithdrawDisallowPeriod
    ✔ should fail if non-zero residue is less than CANDIDATE_MIN_STAKE (106ms) ✔ should fail if non-zero residue is less than DELEGATOR_MIN_STAKE (113ms) ✔ should fail if withdraw more than staked (64ms)
    ✔ should revert orderWithdraw with gasPrice = 0
    ✔ should revert orderWithdraw with pool = address(0)
    ✔ should revert orderWithdraw with amount = 0
    ✔ should fail if withdraw already ordered amount (553ms)
    ✔ should decrease likelihood (50ms)
    recoverAbandonedStakes()
    ✔ should revert with invalid gas price
    ✔ should revert if there is no inactive pools
    ✔ should revert if validator inactive, but not abandonded (207ms)
    ✔ should recover abandoned stakes (237ms)
    ✔ should recover abandoned stakes, mark pool as abandoned and remove from
    inactive pools (242ms)
    ✔ should return maxWithdrawAllowed = 0 if pool was abandoned and removed
    (247ms)
    ✔ should disallow staking to abandoned pool (260ms)
    ✔ should not allow stake withdrawal if pool was abandoned (240ms)
    restake()
    ✔ should allow calling only to BlockReward contract ✔ should do nothing if zero value provided
    without node operator
    ✔ should restake all rewards to validator without delegators (473ms)
    ✔ should restake delegators rewards according to stakes (1177ms) with node operator
    ✔ should not distribute to node operator with 0% share (491ms)
    ✔ should include node operators in reward distribution (795ms)
    ✔ should send operator share to new address if it was changed (330ms)
    setStakingTransitionTimeframeLength()

  • should allow calling only to contract owner

  • should set staking transition time frame length

  • should not set staking transition time frame length to low value - should not set staking transition time frame length to high value
    setStakingFixedEpochDuration()

  • should allow calling only to contract owner

  • should set staking fixed epoch transition

  • should not set staking transition time frame length to low value
    setDelegatorMinStake()
    ✔ should set delegator min stake within allowed range
    ✔ should allow setting min stake to the lowest allowed value ✔ should allow calling only to contract owner
    ✔ should set delegator min stake
    snapshotPoolStakeAmounts()
    ✔ should allow calling only by BlockReward contract
    ✔ should create validator stake snapshot after epoch close (238ms)
    other functions
    ✔ should restrict calling notifyKeyGenFailed to validator set contract
    ✔ should restrict calling notifyNetworkOfftimeDetected to validator set contract ✔ should restrict calling notifyAvailability to validator set contract
    ✔ should restrict calling setStakingEpochStartTime to validator set contract
    ✔ should restrict calling setValidatorInternetAddress to validator set contract ✔ should update validator ip:port using setValidatorInternetAddress
    ✔ should update own pool info using setPoolInfo
    stakingFixedEpochEndTime
    ✔ should calculate correct end time based on current stakingFixedEpochDuration
    Transfer utils library
    ✔ should revert transferNative with insufficient contract balance (50ms) ✔ should revert transferNative if low level call failed
    ✔ should transfer ether using transferNative
    TxPermissionHbbft deployment
    ✔ should deploy and initialize contract (131ms)
    ✔ should revert initialization with CertifierHbbft = address(0) (75ms)
    ✔ should revert initialization with ValidatorSet = address(0) (57ms)
    ✔ should revert initialization with KeyGenHistory = address(0) (70ms)
    ✔ should revert initialization with ConnectivityTracker = address(0) (60ms) ✔ should revert initialization with owner = address(0) (59ms)

✔ should not allow initialization if initialized contract (86ms) contract functions
✔ should get contract name (733ms) ✔ should get contract name hash
✔ should get contract version addAllowedSender()
✔ should restrict calling addAllowedSender to contract owner ✔ should revert if sender address is 0
✔ should add allowed sender
✔ should revert adding same address twice
removeAllowedSender()
✔ should restrict calling removeAllowedSender to contract owner ✔ should revert for non-existing sender
✔ should remove sender
setMinimumGasPrice()
✔ should restrict calling setMinimumGasPrice to contract owner ✔ should not allow to set minimum gas price 0
✔ should set minimum gas price
setBlockGasLimit()
✔ should restrict calling setBlockGasLimit to contract owner ✔ should not allow to set block gas limit less than 100_000 ✔ should set block gas limit
allowedTxTypes()
✔ should allow all transaction types for allowed sender
✔ should not allow zero gas price transactions for uncertified senders
✔ should allow zero gas price transactions for certified senders
✔ should not allow usual transaction with gas price less than minimumGasPrice ✔ should allow usual transaction with sufficient gas price
✔ should not allow transactions to mining addresses
✔ should allow basic transactions from mining addresses with sufficient gas price ✔ should not allow transactions from mining addresses with zero balance
✔ should not allow transactions from mining addresses with zero balance
calls to ValidatorSet contract
✔ should allow announce availability by known unvailable validator
✔ should not allow announce availability by unknown validator
✔ should allow to set validator ip address for active staking pool
✔ should not allow to set validator ip address for inactive staking pool
✔ should not allow to set validator ip address for non existing validator
✔ should not allow other methods calls by validators with non-zero gas price

✔ should allow other methods calls by non-validators with non-zero gas price
✔ should use default validation for other methods calls with zero gas price calls to KeyGenHistory contract
✔ should not allow writePart transactions outside of write part time
✔ should not allow writePart transaction with data size < 36 (49ms)
✔ should not allow writePart transaction with wrong epoch number (87ms)
✔ should allow writePart transaction (105ms)
✔ should not allow writeAcks transactions outside of write acks time
✔ should not allow writeAck transaction with data size < 36 (53ms)
✔ should not allow writeAck transaction with incorrect epoch and round (142ms) ✔ should allow writeAck transaction with correct epoch (90ms)
✔ should allow writeAck transaction with correct round (116ms)
✔ should use default validation for other methods calls (45ms)
calls to ConnectivityTracker contract
✔ should allow reportMissingConnectivity if callable (59ms)
✔ should not allow reportMissingConnectivity if not callable (59ms) ✔ should allow reportReconnect if callable (85ms)
✔ should not allow reportReconnect if not callable (51ms)
✔ should use default validation for other methods calls (59ms)
✔ should skip unknown params in calldata (62ms)
ValidatorSetHbbft initialize
✔ should revert initialization with BlockRewardHbbft contract address (69ms) ✔ should revert initialization with RandomHbbft contract address (52ms)
✔ should revert initialization with StakingHbbft contract address (59ms)
✔ should revert initialization with KeyGenHistory contract address (66ms)
✔ should revert initialization with BonusScoreSystem contract address (56ms) ✔ should initialize successfully (218ms)
✔ should fail if owner address is zero (153ms)
✔ should fail if initial mining addresses are empty (147ms)
✔ should fail if already initialized (257ms)
✔ should fail if the number of mining addresses is not the same as the number of staking ones (143ms)
✔ should fail if the mining addresses are the same as the staking ones (156ms) ✔ should fail if some mining address is 0 (170ms)
✔ should fail if some staking address is 0 (140ms)
✔ should fail if a staking address was already used (121ms)
✔ should fail if a mining address is currently being used as a staking one (147ms)

✔ should fail if a staking address is currently being used as a mining one (157ms)
✔ should fail if a mining address was already used (134ms) handleFailedKeyGeneration
✔ should revert if not called by BlockReward contract setValidatorInternetAddress
✔ Validator Candidates can write and read their IP Address (467ms)
✔ should revert with StakingPoolNotExist for non-validator address getPreviousValidators
✔ should initially return an empty array setStakingAddress
✔ should restrict calling to staking contract
✔ should set stakingAddress newValidatorSet
✔ can only be called by BlockReward contract (54ms)
✔ should enqueue all initial validators (active pools) if there is no staking (60ms) ✔ should enqueue only one validator which has non-empty pool (60ms)
✔ should choose validators randomly (870ms)
announceAvailability
✔ should revert for non-validator caller
✔ should revert if validator is already announced availability ✔ should revert for future block
✔ should revert if provided block hash is wrong
✔ should revert if announce block too old
✔ should announce availability and emit event
notifyUnavailability
✔ should restrict calling to staking contract
✔ should notfiy unavailable by connectivity tracker contract ✔ should remove pool from active and to be elected (65ms)
validator availability tests
✔ should set validatorAvailableSince=timestamp and update last write timestamp ✔ should set validatorAvailableSince=0 and update last write timestamp
✔ should return false from isValidatorAbandoned for active validator
✔ should return true from isValidatorAbandoned for abandoned validator
finalizeChange
✔ should restrict calling to block reward contract ✔ should call by block reward address
getPublicKey
✔ should get public key by mining address ✔ should get public key by staking address

_getRandomIndex
✔ should return an adjusted index for defined inputs (637ms)
✔ should always return an index within the input array size (103118ms) ✔ should return indexes according to given likelihood (14311ms)
getValidatorCountSweetSpot
✔ should revert with InvalidPossibleValidatorCount when input is zero
✔ hbbft sweet spots are calculated correct. getValidatorCountSweetSpot (64ms)
ValueGuards contract Initializer
✔ should set allowed value ranges on initialization (108ms)
✔ should not allow value range initialization outside of initializer (93ms) setAllowedChangeableParameter
✔ should be callable only by contract owner
✔ should set allowed changeable parameter and emit event removeAllowedChangeableParameter
✔ should be callable only by contract owner
✔ should remove allowed changeable parameter and emit event getAllowedParamsRange
✔ should get by function sighash
✔ should get by function selector isWithinAllowedRange
✔ should return false for unknown selector ✔ should revert if getter function not exist ✔ should get is allowed, test #1 (44ms)
✔ should get is allowed, test #2 (53ms)
✔ should get is allowed, test #3
✔ should get is allowed, test #4
✔ should get is allowed, test #5
✔ should get is allowed, test #6 (75ms) ✔ should get is allowed, test #7 (68ms)
withinAllowedRange modifier
✔ should work for public storage variable getter func ✔ should work for external getter function
✔ should change value step by step (52ms)
✔ should not allow skipping steps
409 passing (3m)

16 pending

Screenshot 2025-01-13 at 11 30 27

@softstackio softstackio changed the title [I-01] Unit Test Gaps [I-04] Unit Test Gaps Jan 13, 2025
@axel-muller axel-muller self-assigned this Jan 21, 2025
@Kris-DMD Kris-DMD moved this to In Progress in Diamond Beta Feb 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: In Progress
Development

No branches or pull requests

2 participants