Skip to content
Business logic Write-up Advanced

Q Blockchain

A flaw in the voting weight calculation allowed a user's locked tokens to be counted twice: once when delegated to another voter and again when the original owner voted after announcing an unlock. An attacker could exploit this to double their voting power and potentially influence proposal outcomes.

medium.com

Published on medium.com

Blockchain

Blockian, on medium.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 8 min read.

Context

Q Blockchain is a blockchain built on Ethereum technology. Its native assets, Q Tokens, are used by validators and root nodes securing the network. These actors stake Q Tokens in dedicated smart contracts, signalling their investment and allegiance to the network.

Changes to the Q system, particularly the Q constitution, go through Q proposals, which can be voted on. A voter's voting power is proportional to the amount of Q Tokens they have locked in a designated smart contract. Voting covers things such as changes to the constitution, root node appointments and slashing of validator funds. Each of these voting mechanisms is governed by a smart contract that inherits from the IVoting interface. The write-up uses the RootsVoting.sol contract, which handles proposing root nodes and voting to pick a root node, as its example.

The audit focused on the project at commit [redacted].

Setup

The work was done by the author and a friend, hunting bugs in projects listed on Immunefi. The starting point was the Q Blockchain bounty on Immunefi. No special accounts, roles or tooling are described beyond reading the contracts at the commit above; the analysis is a source review of the voting and locking contracts.

Finding it

The Q voting system has four primary steps:

  1. A proposal is created.
  2. Voters lock Q Tokens.
  3. Voters cast their votes on the proposal.
  4. The proposal is either accepted or rejected.

The shared interface looks like this:

Text
interface IVoting {    enum ProposalStatus {        NONE,        PENDING,        REJECTED,        ACCEPTED,        PASSED,        EXECUTED,        OBSOLETE,        EXPIRED    }    enum VotingOption {        NONE,        FOR,        AGAINST    }    struct VotingParams {        uint256 votingStartTime;        uint256 votingEndTime;        uint256 vetoEndTime;        uint256 proposalExecutionP;        uint256 requiredQuorum;        uint256 requiredMajority;        uint256 requiredSMajority;        uint256 requiredSQuorum;    }    struct VotingCounters {        uint256 weightFor;        uint256 weightAgainst;        uint256 vetosCount;    }    struct VotingStats {        uint256 requiredQuorum;        uint256 currentQuorum;        uint256 requiredMajority;        uint256 currentMajority;        uint256 currentVetoPercentage;    }    struct BaseProposal {        string remark;        VotingParams params;        VotingCounters counters;        bool executed;    }    event ProposalCreated(uint256 _id, BaseProposal _proposal);        function execute(uint256 _proposalId) external;        function voteFor(uint256 _proposalId) external;        function voteAgainst(uint256 _proposalId) external;        function getProposal(uint256 _proposalId) external view returns (BaseProposal calldata);    function getProposalStats(uint256 _proposalId) external view returns (VotingStats calldata);}

Users call createProposal to create a proposal and then use voteFor and voteAgainst to vote on it. The vote path is:

Text
function voteFor(uint256 _proposalId) external override {    _vote(_proposalId, VotingOption.FOR);}function _vote(uint256 _proposalId, VotingOption option) private shouldExist(_proposalId) returns (bool) {    require(        getStatus(_proposalId) == ProposalStatus.PENDING,        "[QEC-003003]-Voting is only possible on PENDING proposals."    );    require(!hasUserVoted[_proposalId][msg.sender], "[QEC-003005]-The caller has already voted for the proposal.");    VotingWeightProxy proxy = VotingWeightProxy(_getVotingWeightProxyAddress());    uint256 _totalLockedQ = proxy.extendLocking(msg.sender, proposals[_proposalId].base.params.votingEndTime);    require(_totalLockedQ > 0, "[QEC-003013]-The total voting weight must be greater than zero.");    if (option == VotingOption.FOR) {        proposals[_proposalId].base.counters.weightFor += _totalLockedQ;     } else {        proposals[_proposalId].base.counters.weightAgainst += _totalLockedQ;     }    hasUserVoted[_proposalId][msg.sender] = true;     emit UserVoted(_proposalId, option, _totalLockedQ);    return true;}

In _vote the contract adds the vote with its weight to the for or against counter, and marks that the user has voted. After enough users have voted or a time span has passed, the proposal is accepted or rejected. To count a voter's weight, the contract asks the VotingWeightProxy contract how many locked Q Tokens that voter has.

Locking Q Tokens

Locking involves several smart contracts, each of which uses a specific function in VotingWeightProxy called _lock. Users can also delegate their voting power to another person or entity, a voting agent, so they can participate indirectly.

Text
function lock(address _who, uint256 _amount) external onlyEligibleContracts {    require(_amount > 0, "[QEC-028002]-Invalid amount value, amount cannot be zero.");    VotingLockInfo memory _votingLockInfo = lockInfos[msg.sender][_who];    _votingLockInfo.lockedAmount += _amount;    lockInfos[msg.sender][_who] = _votingLockInfo;    emit LockedAmountChanged(msg.sender, _who, _votingLockInfo.lockedAmount);    VotingDelegationInfo storage delegationInfo = delegationInfos[_who];    if (delegationInfo.votingAgent == address(0)) {        delegationInfo.votingAgent = _who;    }    if (!delegationInfo.isPending) {        delegationInfos[delegationInfo.votingAgent].receivedWeight += _amount;     }}

The critical line sits inside the final if: it updates the receivedWeight of the voting agent. By default the voting agent is the user locking the tokens, unless they have delegated to another party.

Voting power calculation

A user's voting power is based on the Q Tokens they have locked until the end of a proposal's voting period. The VotingWeightProxy contract exposes extendLocking, which takes the voting end time as a parameter:

Text
function extendLocking(address _who, uint256 _lockNeededUntil) external onlyVotingContracts returns (uint256) {    lockedUntil[_who] = _max(lockedUntil[_who], _lockNeededUntil);    return getVotingWeight(_who, _lockNeededUntil);}

extendLocking sets the user's lockedUntil to the maximum of the current deadline and the proposal's voting end time, then returns the number of tokens locked until that date:

Text
function getVotingWeight(address _who, uint256 _lockNeededUntil) public view returns (uint256) {    VotingLockInfo memory _votingLockInfo;    VotingDelegationInfo memory _delegationInfo = delegationInfos[_who];    uint256 _totalVotingWeight = 0;    for (uint256 i = 0; i < tokenLockSourcesKeys.length; ++i) {        _votingLockInfo = lockInfos[registry.mustGetAddress(tokenLockSourcesKeys[i])][_who];        if (_votingLockInfo.pendingUnlockTime > _lockNeededUntil) {            _totalVotingWeight += _votingLockInfo.pendingUnlockAmount;        }    }    _totalVotingWeight += _delegationInfo.receivedWeight;     return _totalVotingWeight;}

The calculation is not straightforward: receivedWeight is the amount of Q Tokens locked and delegated to a voting agent, and there is also a mechanism for users who want to unlock funds ahead of the voting end time. The for loop is covered after the unlocking process.

Unlocking funds

Unlocking happens in two parts: announcing that a certain amount will be unlocked at a certain time, and the actual unlocking. The announcement function is:

Text
function announceUnlock(      address _who,      uint256 _amount,      uint256 _newUnlockTime  ) external onlyEligibleContracts {      VotingLockInfo storage votingLockInfo = lockInfos[msg.sender][_who];      if (_amount < votingLockInfo.pendingUnlockAmount) {          uint256 amountDifference = votingLockInfo.pendingUnlockAmount - _amount;          _increaseLockedAmount(_who, amountDifference);      } else {          uint256 amountDifference = _amount - votingLockInfo.pendingUnlockAmount;          _reduceLockedAmount(_who, amountDifference);       }      votingLockInfo.pendingUnlockAmount = _amount;       uint256 _maxLockedUntil = _getMaxLockedUntil(_who);      if (_newUnlockTime < _maxLockedUntil) {          _newUnlockTime = _maxLockedUntil;       }      votingLockInfo.pendingUnlockTime = _newUnlockTime;       emit PendingUnlockChanged(          msg.sender,          _who,          votingLockInfo.pendingUnlockAmount,          votingLockInfo.pendingUnlockTime      );  }

The important parts are:

  1. A call to _reduceLockedAmount.
  2. Setting the member holding the amount to be unlocked.
  3. Making sure the unlocking time is greater than the expiration time of the user's votes, or correcting it.
  4. Setting the unlock time to the requested (or corrected) time.
Text
function _reduceLockedAmount(address _who, uint256 _amount) private onlyEligibleContracts {      VotingLockInfo storage votingLockInfo = lockInfos[msg.sender][_who];      require(votingLockInfo.lockedAmount >= _amount, "[QEC-028003]-Cannot unlock more than is currently locked.");      votingLockInfo.lockedAmount -= _amount;      emit LockedAmountChanged(msg.sender, _who, votingLockInfo.lockedAmount);      VotingDelegationInfo memory _delegationInfo = delegationInfos[_who];      if (!_delegationInfo.isPending) {          delegationInfos[_delegationInfo.votingAgent].receivedWeight -= _amount;       }  }

_reduceLockedAmount is the exact opposite of locking with regard to voting power: it decreases receivedWeight, which is part of the user's voting power.

Voting power calculation revisited

With the unlocking flow understood, the inner loop of getVotingWeight makes sense: if a user decided to withdraw their funds and then noticed a proposal they wanted to vote on, they could still vote if the unlock time is far enough in the future.

Exploitation

The vulnerability allows a user's locked Q Tokens to vote twice. The sequence is:

Step 1: delegate

User A delegates their Q Tokens to User B. The lock function records the delegation and adds the amount to the voting agent's receivedWeight.

Step 2: the agent votes

User B votes on a proposal. Their voting power, returned by getVotingWeight, includes User A's locked tokens through receivedWeight.

Step 3: the delegator announces an unlock

User A calls announceUnlock. This runs _reduceLockedAmount, which subtracts the amount from the voting agent's receivedWeight, and records the amount and time in pendingUnlockAmount and pendingUnlockTime.

Step 4: the delegator votes

User A votes on the same proposal. In getVotingWeight, the loop over tokenLockSourcesKeys adds pendingUnlockAmount when pendingUnlockTime is greater than the proposal's voting end time, so the same locked tokens now count towards User A's own voting power.

The same locked tokens influence the voting power twice: once through the agent's receivedWeight and once through the delegator's pending unlock amount.

Root cause

The locking and unlocking paths keep two separate accounting entries for the same tokens. lock adds the amount to the voting agent's receivedWeight, and _reduceLockedAmount subtracts it again when an unlock is announced. But the announced amount is not removed from voting power; it is moved into pendingUnlockAmount, which getVotingWeight counts whenever pendingUnlockTime is later than the voting end time. Nothing in _vote or getVotingWeight checks whether the same tokens have already been counted for the same proposal through a different account, and the per-proposal guard hasUserVoted only applies per caller, so the delegator and the agent are each allowed to vote once.

Impact

A user can make the same locked Q Tokens count twice in a vote: once through the voting agent they delegated to, and once through their own vote after announcing an unlock. Because voting power decides whether proposals are accepted or rejected, this lets a voter inflate their weight on a proposal beyond the tokens they actually locked. The write-up's title calls it a critical vulnerability.

Fix

The write-up does not describe the fix that was applied.

Reporting and reward

The vulnerability was reported to Q Blockchain via Immunefi on 30 September, and the reward of $50,000 was paid by 24 October.

Variants to test

  1. Delegation plus unlock on other voting contracts. Check every contract inheriting IVoting for the same receivedWeight and pendingUnlockAmount accounting. A positive result is a vote whose weight exceeds the tokens the voter actually locked.
  2. Re-announcing an unlock. Call announceUnlock more than once with different amounts and times, and compare the resulting voting weight with the locked balance. A positive result is weight that grows without new tokens being locked.
  3. Unlock timing around the voting end. Announce an unlock with a time just after the proposal's voting end and vote. A positive result is the pending amount being counted for a proposal it should no longer cover.
  4. Delegation chains. Delegate to an agent who has themselves delegated, and check whether receivedWeight is credited at each level. A positive result is the same tokens appearing in more than one agent's weight.
  5. Self-delegation edge cases. Lock with the default agent (the user themselves) and then announce an unlock before voting. A positive result is the pending amount being counted on top of a weight that was never reduced.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 19 min read.

What happened, in plain words

Two friends were on a five-hour flight in September 2022. They had been talking for months about hunting for bugs in projects listed on Immunefi, a website where companies offer money to people who find mistakes in their software, but they had never really got started. On the plane they decided to begin, and the first project they looked at was Q Blockchain.

Q Blockchain is a system where people who hold its digital money, called Q Tokens, can vote on decisions that affect the network. To vote, you lock your tokens in a piece of software called a smart contract. The more tokens you lock, the more voting power you have. You can also hand your voting power to someone else, called a voting agent, so that person votes on your behalf.

The two researchers read the code that handles locking tokens, delegating votes and unlocking tokens. They found a flaw: the same locked tokens could be counted twice in the same vote. First the voting agent used them, then the original owner announced they were unlocking their tokens and voted themselves, and the tokens counted again. Because votes decide whether proposals are accepted or rejected, the same tokens could influence the outcome twice. They reported it on 30 September and were paid $50,000 by 24 October.

This article walks through the same code they read, explaining each idea from scratch. You do not need to know anything about blockchains to follow it.

Background: what Q Blockchain is

A blockchain is a shared record book that many computers keep copies of. Nobody can quietly change an old entry, because everyone else's copy would disagree. Ethereum is the best-known blockchain, and Q Blockchain is built using Ethereum technology.

Q has its own digital money, Q Tokens. Two kinds of participants keep the network running: validators and root nodes. To show they are committed to the network, these participants lock up Q Tokens in smart contracts. Locking means the tokens are held by the contract and cannot be spent freely while they are locked. Think of it like a deposit you leave with a landlord: the money is still yours, but you cannot use it until the arrangement ends.

A smart contract is a small program that lives on the blockchain. It runs automatically and follows exactly the rules written in its code. Nobody can change those rules after the fact, and anyone can read them.

Changes to Q, especially changes to its constitution (the set of rules the network follows), go through Q proposals. A proposal is a suggested change that people vote on. Your voting power is proportional to how many Q Tokens you have locked in a particular smart contract: lock twice as many tokens, get twice the say. Voting covers things such as constitution changes, appointing root nodes and punishing (slashing) validators' funds.

Each type of vote is handled by its own smart contract. All of these contracts share a common blueprint, called an interface, named IVoting. An interface is like a standard plug shape: it says which functions a contract must offer, without saying how they work inside. The write-up uses one of these contracts, RootsVoting.sol, as its example. It handles proposing root nodes and voting to choose a root node.

The researchers looked at the project at a specific saved version of the code, identified by the commit [redacted]. A commit is a snapshot of a code repository at one moment, so anyone can go back and read exactly the same code.

How the work was set up

The work was done by the author and a friend, looking for bugs in projects listed on Immunefi. Their starting point was the Q Blockchain bounty page on Immunefi. A bounty is a public offer: find a bug in our software and we will pay you.

No special accounts, roles or tools are described beyond reading the contracts at that commit. In other words, this was a source review: reading the code carefully, the way you might read a long contract or a rulebook, looking for a rule that contradicts another rule.

Finding it: the voting system

The Q voting system has four main steps:

  1. A proposal is created.
  2. Voters lock Q Tokens.
  3. Voters cast their votes on the proposal.
  4. The proposal is either accepted or rejected.

All the voting contracts share the same interface. Here it is:

Text
interface IVoting {    enum ProposalStatus {        NONE,        PENDING,        REJECTED,        ACCEPTED,        PASSED,        EXECUTED,        OBSOLETE,        EXPIRED    }    enum VotingOption {        NONE,        FOR,        AGAINST    }    struct VotingParams {        uint256 votingStartTime;        uint256 votingEndTime;        uint256 vetoEndTime;        uint256 proposalExecutionP;        uint256 requiredQuorum;        uint256 requiredMajority;        uint256 requiredSMajority;        uint256 requiredSQuorum;    }    struct VotingCounters {        uint256 weightFor;        uint256 weightAgainst;        uint256 vetosCount;    }    struct VotingStats {        uint256 requiredQuorum;        uint256 currentQuorum;        uint256 requiredMajority;        uint256 currentMajority;        uint256 currentVetoPercentage;    }    struct BaseProposal {        string remark;        VotingParams params;        VotingCounters counters;        bool executed;    }    event ProposalCreated(uint256 _id, BaseProposal _proposal);        function execute(uint256 _proposalId) external;        function voteFor(uint256 _proposalId) external;        function voteAgainst(uint256 _proposalId) external;        function getProposal(uint256 _proposalId) external view returns (BaseProposal calldata);    function getProposalStats(uint256 _proposalId) external view returns (VotingStats calldata);}

Line by line, in plain words:

  • interface IVoting starts the definition of the shared blueprint. Everything inside the curly braces is part of it.
  • enum ProposalStatus lists the possible states a proposal can be in: NONE, PENDING (waiting for votes), REJECTED, ACCEPTED, PASSED, EXECUTED, OBSOLETE and EXPIRED. An enum is simply a fixed list of allowed labels, like the status field on a parcel tracking page.
  • enum VotingOption lists the choices a voter has: NONE, FOR and AGAINST.
  • struct VotingParams groups the settings of a vote: when voting starts (votingStartTime), when it ends (votingEndTime), when the veto period ends (vetoEndTime), a value called proposalExecutionP, and four thresholds: requiredQuorum, requiredMajority, requiredSMajority and requiredSQuorum. A struct is a bundle of related values kept together, like a form with several fields. A quorum is the minimum amount of voting power that must take part for a vote to count; a majority is the share needed to win.
  • struct VotingCounters keeps the running totals: weightFor, weightAgainst and vetosCount. This is the scoreboard.
  • struct VotingStats holds the numbers used to judge a vote: the required and current quorum, the required and current majority, and the current veto percentage.
  • struct BaseProposal is the full record of a proposal: a remark (a text note), its params, its counters, and a flag executed saying whether it has been carried out.
  • event ProposalCreated(uint256 _id, BaseProposal _proposal); announces to the outside world that a proposal was created. An event is a public notice written into the blockchain's log, like a receipt being printed.
  • The function lines list the actions the contract must offer: execute (carry out a proposal), voteFor, voteAgainst, getProposal (read a proposal) and getProposalStats (read its statistics). The word external means the function can be called from outside the contract, and view means it only reads data and changes nothing.

Users call createProposal to create a proposal, then use voteFor and voteAgainst to vote on it. Here is the path a vote takes:

Text
function voteFor(uint256 _proposalId) external override {    _vote(_proposalId, VotingOption.FOR);}function _vote(uint256 _proposalId, VotingOption option) private shouldExist(_proposalId) returns (bool) {    require(        getStatus(_proposalId) == ProposalStatus.PENDING,        "[QEC-003003]-Voting is only possible on PENDING proposals."
    );    require(!hasUserVoted[_proposalId][msg.sender], "[QEC-003005]-The caller has already voted for the proposal.");    VotingWeightProxy proxy = VotingWeightProxy(_getVotingWeightProxyAddress());    uint256 _totalLockedQ = proxy.extendLocking(msg.sender, proposals[_proposalId].base.params.votingEndTime);    require(_totalLockedQ > 0, "[QEC-003013]-The total voting weight must be greater than zero.");    if (option == VotingOption.FOR) {        proposals[_proposalId].base.counters.weightFor += _totalLockedQ;     } else {        proposals[_proposalId].base.counters.weightAgainst += _totalLockedQ;     }    hasUserVoted[_proposalId][msg.sender] = true;     emit UserVoted(_proposalId, option, _totalLockedQ);    return true;}

What each part does:

  • voteFor is the public function a user calls to vote in favour. It takes the proposal's number, _proposalId, and immediately passes the work to an internal function _vote, telling it the choice is VotingOption.FOR.
  • _vote is private, meaning only code inside this contract can call it. The tag shouldExist(_proposalId) is a guard that checks the proposal exists before anything else happens.
  • The first require checks that the proposal is still PENDING. If it is not, the whole call is cancelled with the message [QEC-003003]-Voting is only possible on PENDING proposals. A require is a checkpoint: if the condition is false, the action is refused.
  • The second require checks hasUserVoted[_proposalId][msg.sender] is false. msg.sender is the address of whoever called the function, so this is a per-person, per-proposal record of whether they have already voted. If they have, the call fails with [QEC-003005]-The caller has already voted for the proposal.
  • VotingWeightProxy proxy = ... fetches the helper contract that knows how much voting power each address has. A proxy here is just a separate contract that the voting contract asks for information.
  • proxy.extendLocking(msg.sender, ...votingEndTime) asks that helper: how much voting power does this caller have, given that their tokens must stay locked until the proposal's voting end time? The answer is stored in _totalLockedQ.
  • The next require refuses the vote if that number is zero, with the message [QEC-003013]-The total voting weight must be greater than zero.
  • The if/else adds _totalLockedQ to either weightFor or weightAgainst on the proposal's scoreboard, depending on the choice.
  • hasUserVoted[_proposalId][msg.sender] = true; records that this caller has now voted, so the second require will block a second attempt.
  • emit UserVoted(...) writes a public log entry recording the vote, the choice and the weight.
  • return true; reports success.

After enough users have voted, or a time span has passed, the proposal is accepted or rejected. To count a voter's weight, the contract asks the VotingWeightProxy contract how many locked Q Tokens that voter has.

Locking Q Tokens

Locking involves several smart contracts, each of which uses a specific function in VotingWeightProxy called _lock. Users can also delegate their voting power to another person or entity, a voting agent, so they can participate indirectly. Delegation is like giving a friend your proxy vote at a meeting: you still own your share, but they cast it.

Text
function lock(address _who, uint256 _amount) external onlyEligibleContracts {    require(_amount > 0, "[QEC-028002]-Invalid amount value, amount cannot be zero.");    VotingLockInfo memory _votingLockInfo = lockInfos[msg.sender][_who];    _votingLockInfo.lockedAmount += _amount;    lockInfos[msg.sender][_who] = _votingLockInfo;    emit LockedAmountChanged(msg.sender, _who, _votingLockInfo.lockedAmount);    VotingDelegationInfo storage delegationInfo = delegationInfos[_who];    if (delegationInfo.votingAgent == address(0)) {        delegationInfo.votingAgent = _who;
    }    if (!delegationInfo.isPending) {        delegationInfos[delegationInfo.votingAgent].receivedWeight += _amount;     }}

Step by step:

  • lock can only be called by contracts on an approved list, enforced by onlyEligibleContracts. This stops random outsiders from creating fake locks.
  • The first require rejects an amount of zero with [QEC-028002]-Invalid amount value, amount cannot be zero. Locking nothing makes no sense.
  • lockInfos[msg.sender][_who] looks up the record of how much _who has locked through this particular calling contract. The record is copied into memory (a temporary working copy).
  • _votingLockInfo.lockedAmount += _amount; adds the new amount to the locked total.
  • The updated record is written back into storage, the contract's permanent memory.
  • emit LockedAmountChanged(...) writes a public log entry with the new total.
  • delegationInfos[_who] fetches the delegation settings for _who.
  • If votingAgent is the zero address (meaning no agent has been set), it is set to _who themselves. So by default you are your own voting agent.
  • The final if runs when isPending is false. It adds _amount to receivedWeight of the voting agent. receivedWeight is the running total of tokens whose voting power this agent is holding for others.

The critical line sits inside that final if: it updates the receivedWeight of the voting agent. By default the voting agent is the user locking the tokens, unless they have delegated to another party.

Voting power calculation

A user's voting power is based on the Q Tokens they have locked until the end of a proposal's voting period. The VotingWeightProxy contract exposes extendLocking, which takes the voting end time as a parameter:

Text
function extendLocking(address _who, uint256 _lockNeededUntil) external onlyVotingContracts returns (uint256) {    lockedUntil[_who] = _max(lockedUntil[_who], _lockNeededUntil);    return getVotingWeight(_who, _lockNeededUntil);}
  • Only voting contracts may call this, enforced by onlyVotingContracts.
  • lockedUntil[_who] = _max(lockedUntil[_who], _lockNeededUntil); sets the user's locking deadline to whichever is later: the deadline already recorded, or the voting end time passed in. _max returns the larger of two numbers. This is how voting automatically extends a lock: your tokens must stay locked at least until the vote you are taking part in finishes.
  • return getVotingWeight(_who, _lockNeededUntil); then asks for the actual weight and hands it back.

That weight comes from this function:

Text
function getVotingWeight(address _who, uint256 _lockNeededUntil) public view returns (uint256) {    VotingLockInfo memory _votingLockInfo;    VotingDelegationInfo memory _delegationInfo = delegationInfos[_who];    uint256 _totalVotingWeight = 0;    for (uint256 i = 0; i < tokenLockSourcesKeys.length; ++i) {        _votingLockInfo = lockInfos[registry.mustGetAddress(tokenLockSourcesKeys[i])][_who];        if (_votingLockInfo.pendingUnlockTime > _lockNeededUntil) {            _totalVotingWeight += _votingLockInfo.pendingUnlockAmount;
        }
    }    _totalVotingWeight += _delegationInfo.receivedWeight;     return _totalVotingWeight;}
  • _delegationInfo is the delegation record for _who.
  • _totalVotingWeight starts at zero. This will be the running total.
  • The for loop walks through tokenLockSourcesKeys, a list of the different contracts through which tokens can be locked. For each one, it fetches _who's lock record from that source.
  • Inside the loop, if pendingUnlockTime is later than _lockNeededUntil, the amount in pendingUnlockAmount is added to the total. In plain words: if you have announced that you will unlock some tokens, but the unlock date is still after the vote ends, those tokens still count for this vote.
  • After the loop, _delegationInfo.receivedWeight is added: the tokens other people have delegated to this address.
  • The total is returned.

The calculation is not straightforward: receivedWeight is the amount of Q Tokens locked and delegated to a voting agent, and there is also a mechanism for users who want to unlock funds ahead of the voting end time. The for loop is covered after the unlocking process.

Unlocking funds

Unlocking happens in two parts: announcing that a certain amount will be unlocked at a certain time, and the actual unlocking. The announcement function is:

Text
function announceUnlock(      address _who,      uint256 _amount,      uint256 _newUnlockTime  ) external onlyEligibleContracts {      VotingLockInfo storage votingLockInfo = lockInfos[msg.sender][_who];      if (_amount < votingLockInfo.pendingUnlockAmount) {          uint256 amountDifference = votingLockInfo.pendingUnlockAmount - _amount;          _increaseLockedAmount(_who, amountDifference);
      } else {          uint256 amountDifference = _amount - votingLockInfo.pendingUnlockAmount;          _reduceLockedAmount(_who, amountDifference);       }      votingLockInfo.pendingUnlockAmount = _amount;       uint256 _maxLockedUntil = _getMaxLockedUntil(_who);      if (_newUnlockTime < _maxLockedUntil) {          _newUnlockTime = _maxLockedUntil;       }      votingLockInfo.pendingUnlockTime = _newUnlockTime;       emit PendingUnlockChanged(          msg.sender,          _who,          votingLockInfo.pendingUnlockAmount,          votingLockInfo.pendingUnlockTime      );  }
  • Again, only approved contracts may call it.
  • votingLockInfo is a direct reference to the stored lock record for _who (the word storage means changes to it are permanent).
  • The if/else compares the newly requested unlock amount with the amount already announced. If the new amount is smaller, the difference is locked again via _increaseLockedAmount. Otherwise the difference is released via _reduceLockedAmount. This keeps the locked balance in step with the announced amount.
  • votingLockInfo.pendingUnlockAmount = _amount; records the announced amount.
  • _getMaxLockedUntil(_who) finds the latest date until which the user's votes commit their tokens.
  • If the requested unlock time is earlier than that date, it is pushed forward to that date. You cannot unlock before the votes you took part in have finished.
  • votingLockInfo.pendingUnlockTime = _newUnlockTime; records the final unlock time.
  • emit PendingUnlockChanged(...) writes a public log entry with the amount and time.

The important parts are:

  1. A call to _reduceLockedAmount.
  2. Setting the member holding the amount to be unlocked.
  3. Making sure the unlocking time is greater than the expiration time of the user's votes, or correcting it.
  4. Setting the unlock time to the requested (or corrected) time.

Here is _reduceLockedAmount:

Text
function _reduceLockedAmount(address _who, uint256 _amount) private onlyEligibleContracts {      VotingLockInfo storage votingLockInfo = lockInfos[msg.sender][_who];      require(votingLockInfo.lockedAmount >= _amount, "[QEC-028003]-Cannot unlock more than is currently locked.");      votingLockInfo.lockedAmount -= _amount;      emit LockedAmountChanged(msg.sender, _who, votingLockInfo.lockedAmount);      VotingDelegationInfo memory _delegationInfo = delegationInfos[_who];      if (!_delegationInfo.isPending) {          delegationInfos[_delegationInfo.votingAgent].receivedWeight -= _amount;       }  }
  • It fetches the lock record for _who.
  • The require refuses to unlock more than is locked, with [QEC-028003]-Cannot unlock more than is currently locked.
  • votingLockInfo.lockedAmount -= _amount; subtracts the amount from the locked balance.
  • emit LockedAmountChanged(...) logs the new balance.
  • It fetches the delegation record.
  • If isPending is false, it subtracts _amount from the voting agent's receivedWeight.

_reduceLockedAmount is the exact opposite of locking with regard to voting power: it decreases receivedWeight, which is part of the user's voting power.

Voting power calculation revisited

With the unlocking flow understood, the inner loop of getVotingWeight makes sense: if a user decided to withdraw their funds and then noticed a proposal they wanted to vote on, they could still vote if the unlock time is far enough in the future. The tokens are on their way out, but they still count until the unlock date arrives.

Exploitation

The vulnerability allows a user's locked Q Tokens to vote twice. The sequence is:

Step 1: delegate

User A delegates their Q Tokens to User B. The lock function records the delegation and adds the amount to the voting agent's receivedWeight.

Why this matters: from this moment, User B's voting power includes User A's tokens. If User B votes, those tokens are counted.

Step 2: the agent votes

User B votes on a proposal. Their voting power, returned by getVotingWeight, includes User A's locked tokens through receivedWeight.

Why this matters: the tokens have now been used once, through the agent.

Step 3: the delegator announces an unlock

User A calls announceUnlock. This runs _reduceLockedAmount, which subtracts the amount from the voting agent's receivedWeight, and records the amount and time in pendingUnlockAmount and pendingUnlockTime.

Why this matters: the agent's weight goes down, so it looks as though the tokens have stopped counting. But they have not disappeared from the system; they have been moved into the pending unlock record.

Step 4: the delegator votes

User A votes on the same proposal. In getVotingWeight, the loop over tokenLockSourcesKeys adds pendingUnlockAmount when pendingUnlockTime is greater than the proposal's voting end time, so the same locked tokens now count towards User A's own voting power.

Why this matters: the tokens have now been used a second time, through their owner. The same locked tokens influence the voting power twice: once through the agent's receivedWeight and once through the delegator's pending unlock amount.

Root cause

The locking and unlocking paths keep two separate accounting entries for the same tokens. lock adds the amount to the voting agent's receivedWeight, and _reduceLockedAmount subtracts it again when an unlock is announced. But the announced amount is not removed from voting power; it is moved into pendingUnlockAmount, which getVotingWeight counts whenever pendingUnlockTime is later than the voting end time. Nothing in _vote or getVotingWeight checks whether the same tokens have already been counted for the same proposal through a different account, and the per-proposal guard hasUserVoted only applies per caller, so the delegator and the agent are each allowed to vote once.

A useful comparison: imagine a club where each member's share of the vote is written on a card. You can hand your card to a friend, who then votes with it. Later you ask for the card back, and the club writes you a new card for the same shares without taking anything away from your friend's vote. Both votes stand, but there is only one set of shares.

Impact

A user can make the same locked Q Tokens count twice in a vote: once through the voting agent they delegated to, and once through their own vote after announcing an unlock. Because voting power decides whether proposals are accepted or rejected, this lets a voter inflate their weight on a proposal beyond the tokens they actually locked. The write-up's title calls it a critical vulnerability.

Fix

The write-up does not describe the fix that was applied.

Reporting and reward

The vulnerability was reported to Q Blockchain via Immunefi on 30 September, and the reward of $50,000 was paid by 24 October.

Variants to test

  1. Delegation plus unlock on other voting contracts. Check every contract inheriting IVoting for the same receivedWeight and pendingUnlockAmount accounting. A positive result is a vote whose weight exceeds the tokens the voter actually locked.
  2. Re-announcing an unlock. Call announceUnlock more than once with different amounts and times, and compare the resulting voting weight with the locked balance. A positive result is weight that grows without new tokens being locked.
  3. Unlock timing around the voting end. Announce an unlock with a time just after the proposal's voting end and vote. A positive result is the pending amount being counted for a proposal it should no longer cover.
  4. Delegation chains. Delegate to an agent who has themselves delegated, and check whether receivedWeight is credited at each level. A positive result is the same tokens appearing in more than one agent's weight.
  5. Self-delegation edge cases. Lock with the default agent (the user themselves) and then announce an unlock before voting. A positive result is the pending amount being counted on top of a weight that was never reduced.

Glossary

  • Blockchain: a shared record book kept by many computers, where old entries cannot be quietly changed.
  • Ethereum: a well-known blockchain platform; Q Blockchain is built on its technology.
  • Q Token: the native digital money of Q Blockchain, used by validators and root nodes.
  • Validator: a participant that helps keep a blockchain network running and secure.
  • Root node: a participant in Q Blockchain that is appointed through voting.
  • Staking: locking tokens in a contract to show commitment to the network.
  • Smart contract: a small program stored on a blockchain that runs automatically and follows fixed rules.
  • Proposal: a suggested change that token holders vote on.
  • Constitution: the set of rules the Q network follows.
  • Slashing: taking away part of a validator's locked funds as a punishment.
  • Interface: a shared blueprint listing the functions a contract must offer, without their internal details.
  • IVoting: the interface shared by Q's voting contracts.
  • Commit: a saved snapshot of a code repository at a particular moment.
  • Immunefi: a website where projects offer money to people who find bugs in their software.
  • Bounty: a public reward offered for finding and reporting a bug.
  • Source review: reading code carefully to find mistakes, without running it.
  • Enum: a fixed list of allowed labels, such as the possible states of a proposal.
  • Struct: a bundle of related values kept together under one name.
  • Event: a public notice written into the blockchain's log when something happens.
  • Function: a named action a contract can perform.
  • external: a function that can be called from outside the contract.
  • private: a function that only code inside the same contract can call.
  • view: a function that only reads data and changes nothing.
  • require: a checkpoint that cancels the action if its condition is false.
  • msg.sender: the address of whoever called the function.
  • Address: a unique identifier for an account or contract on the blockchain.
  • Zero address: the special empty address, used here to mean no agent has been set.
  • Storage: a contract's permanent memory, where changes persist.
  • Memory: a temporary working copy of data used during a function call.
  • Quorum: the minimum voting power that must take part for a vote to count.
  • Majority: the share of voting power needed to win a vote.
  • Veto: a block placed on a decision, tracked here by vetosCount and the veto period.
  • Voting power: the weight a voter's vote carries, based on locked tokens.
  • Voting agent: a person or entity to whom a token holder delegates their voting power.
  • Delegation: handing your voting power to someone else so they vote on your behalf.
  • receivedWeight: the running total of tokens whose voting power a voting agent holds for others.
  • pendingUnlockAmount: the amount a user has announced they intend to unlock.
  • pendingUnlockTime: the date at which that announced unlock will happen.
  • lockedUntil: the date until which a user's tokens must stay locked because of votes they have taken part in.
  • hasUserVoted: a per-person, per-proposal record of whether someone has already voted.
  • tokenLockSourcesKeys: the list of contracts through which tokens can be locked.
  • Commit [redacted]: the exact saved version of the code that was reviewed.
  • Critical: the severity label the write-up gives the issue, meaning it can seriously undermine how the system works.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.