Skip to content
Smart contracts Write-up Advanced

The Graph

medium.com

Published on medium.com

Immunefi Editor

Immunefi Editor, 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. 7 min read.

Context

The Graph describes itself as a "decentralized indexing protocol". It lets developers access and query data across different blockchains through "subgraphs", which are APIs. Like other decentralized protocols, it depends on the coordination of several parties, namely indexers, curators and delegators, to deliver its services and generate value.

Blockchain data is public by default, but collecting it is not straightforward. Even with the technical knowledge and the right setup to download and interpret raw block data from a node, you would still have to find the needle in the haystack of transactions, and do it efficiently. The Graph lets users access blockchain data more easily through its GraphQL API, paying only for the specific information they need with GRT, the protocol's native token. Indexers, the node operators of the network, also use GRT to stake and index data based on specific curated subgraphs.

The part of The Graph discussed in this analysis is mainly the staking functionality. Two rounding errors, in two separate assets, produced two discrete impacts.

Setup

On 7 January and 24 January 2024, whitehat @GregadETH submitted High and Critical vulnerabilities in the Graph ecosystem. The report does not describe any accounts or tooling beyond the contracts involved and the Arbitrum deployment. The Graph patched the issues and paid a bounty total of $290,497 to the whitehat.

Finding it

The root cause of both vulnerabilities is rounding. Ensuring the precision and proper handling of floating-point arithmetic is crucial to avoiding financial discrepancies or exploitation of contract logic. Its versatility and frequency of finding made rounding error number 6 of the Top 10 common smart contract vulnerabilities identified by Immunefi in 2023.

The first issue: curation tax

When a new subgraph API is created, the curator, or creator of the subgraph, stakes a certain amount of GRT tokens and pays a curation tax of 1% of the staked amount to the platform. The amount is variable, because a higher amount increases the likelihood that the subgraph will be indexed and earn fees. From this point onwards the curator is referred to as "user".

The first rounding issue occurred in Curation.sol and L2Curation.sol, precisely in the mint function. The expected behaviour of this function is that a user passes an amount of tokens to mint and then pays the curationTax amount of tokens to the called contract.

From the original on medium.com

Here, the curationTax calculation implemented in the body of tokensToSignal works incorrectly when the amount of minted tokens is below 100. The rounding implementation in the calculation in the tokensToSignal function is shown below.

From the original on medium.com

At the moment of the submission of the bug report, the curation tax percentage was capped at 1% (variable equal to uint256(10000)), and the constant MAX_PPM was capped at 100% (variable equal to uint256(1000000)). That means that if an attacker passes uint256(99) as the tokensIn variable, he will need to pay 990000/1000000 of the curationTax, which is rounded down to 0.

Normally, high gas costs on mainnet would prevent this from becoming a lucrative attack. But because this target contract is also deployed on Arbitrum, an L2 with much cheaper gas, the attacker could avoid paying the curationTax completely by minting the needed amount of tokens in batches of 99 tokens per call, as presented in the PoC created by @GregadETH.

The second issue: lock duration

The second rounding issue @GregadETH uncovered was in another asset, L2Staking.sol.

When an indexer (a node operator or hardware provider to the network) wants to provide services to the network in order to earn rewards and fees, they need to stake GRT tokens, which stay locked for a period of time. The Graph documentation states: "GRT that is staked in the protocol is subject to a thawing period and can be slashed if Indexers are malicious and serve incorrect data to applications or if they index incorrectly."

This second rounding error results in a calculation error that allows a malicious user to bypass the proper lock duration and unstake tokens earlier than they should.

In the unstake function, a call to the vulnerable lockTokens function was made. This function was responsible for adding unstaked tokens to a thawing (locked) pool and calculating the duration of the lock.

From the original on medium.com

The lockTokens function adds the unstaked tokens to an existing pool containing previously unstaked and locked tokens. It then calculates the new duration of lock to a value between the current lock duration and the maximum locked duration, which was capped at 28 days at the time of submission.

From the original on medium.com

If there are already some tokens unstaked and sitting in the locked pool, the calculation of a new lock time is done like this:

Text
newLockedUntil = ((currentLockedUntil * currentlyUnstakedTokens) + (201600 * newUnstakedTokens)) / (currentUnstakedTokens + newUnstakedTokens)

If currentUnstakedTokens is roughly 201600 times larger than newUnstakedTokens, newLockedUntil will evaluate to currentLockedUntil. Thus, the attacker can pass a small enough value to the unstake function to withdraw small portions of the staked tokens without any additional lock applied. After that, he could proceed with the same attack plan as in the first bug: unstake small batches of tokens to avoid adding any value to the lock period.

Exploitation

Step 1: mint in batches of 99 tokens

With the curation tax percentage at 1% (uint256(10000)) and MAX_PPM at 100% (uint256(1000000)), passing uint256(99) as tokensIn makes the tax 990000/1000000, which rounds down to 0. Repeating the call in batches of 99 tokens lets the attacker mint the needed amount while paying no curationTax at all. The cheap gas on Arbitrum, where the contract is also deployed, makes the batching practical; on mainnet the gas cost would normally prevent the attack from being lucrative.

Step 2: unstake in small batches

Once tokens are already unstaked and sitting in the locked pool, the attacker passes a small enough value to unstake such that currentUnstakedTokens is roughly 201600 times larger than newUnstakedTokens. The weighted average then evaluates to currentLockedUntil, so no additional lock is applied. Repeating this withdraws small portions of the staked tokens without extending the lock period, and the attacker can immediately withdraw them without any penalty.

Root cause

Both bugs are rounding errors. In the first, the tax is computed from the input amount in a way that truncates to zero for inputs below 100, so the protocol receives nothing. In the second, the weighted average used to compute the new lock time can return the current lock time when the new unstaked amount is small relative to the existing pool, so the lock is not extended. The cheap gas of the L2 deployment is what removed the economic barrier to the first.

Impact

The first issue could rob the protocol of owed revenue and cause loss of user funds or yield owed to protocol participants.

The impact of the second varies, from an individual indexer making unfair gains and being able to unstake tokens faster than other indexers, to the possibility of multiple indexers removing their stake entirely without penalty, adversely affecting the security of the network overnight. The process of unstaking, calling unstake() and then waiting until the tokens are unlocked, is broken: a malicious user can avoid the lock period for unstaked tokens and withdraw them immediately without any penalty.

Fix

For the first issue, The Graph dev team presented a new way of calculating the tax, where the code calculates the tokens after tax first and subtracts that from tokensIn to get the curation tax, avoiding rounding down to zero. The change is in commit [redacted].

For the second issue, the separate library contract MathUtils.sol was changed: the vulnerable weightedAverage was changed to weightedAverageRoundingUp to ensure that the result is always greater than the lesser of the two input values. This commit solves the problem of allowing users to unstake before they should.

From the original on medium.com

Variants to test

  1. Percentage and fee calculations with small inputs: pass amounts just below the threshold where a fee truncates to zero (here, 99 against a 1% tax) and check whether the fee charged is zero. A positive result is a fee of 0 for a non-zero mint.
  2. Weighted averages over a pool: when a new amount is added to an existing pool, try values where the existing pool is orders of magnitude larger than the new amount, and check whether the computed deadline equals the current deadline. A positive result is a lock time that does not move.
  3. L2 deployments of mainnet contracts: repeat fee and lock calculations on the L2 where gas is cheap, since batching that is uneconomical on mainnet may be profitable there. A positive result is a profitable batch of zero-fee or zero-lock operations.
  4. Rounding direction in library helpers: look for weightedAverage-style helpers and check whether they round down where the protocol needs the result to be at least the lesser input. A positive result is a helper whose output can fall below the smaller input.

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. 15 min read.

What happened, in plain words

A security researcher found two mistakes in the code of a cryptocurrency project called The Graph. Both mistakes came from the same basic problem: the code did maths in a way that threw away small fractions, and those thrown-away fractions could be abused. The project fixed both problems and paid the researcher a total of $290,497 for reporting them.

This article explains what The Graph is, what the two mistakes were, how someone could have taken advantage of them, and how they were fixed. You do not need to know how to program to follow it. Every technical word is explained the first time it appears, and there is a glossary at the end.

What The Graph is

The Graph describes itself as a "decentralized indexing protocol". That phrase needs unpacking.

A blockchain is a shared record of transactions that many computers keep copies of. Bitcoin and Ethereum are well-known examples. All the data on a blockchain is public, but it is stored as a huge pile of raw records. Finding one specific piece of information in that pile is like looking for one sentence in a library where all the books have been emptied onto the floor.

An API (Application Programming Interface) is a way for one piece of software to ask another piece of software for information in a tidy, agreed format. Think of it as a waiter: you tell the waiter what you want, and the waiter brings it from the kitchen. You do not walk into the kitchen yourself.

A subgraph is The Graph's name for one of these APIs. Each subgraph answers questions about one particular slice of blockchain data.

A protocol here means a set of rules and software that several independent people run together, without a single company in charge. The Graph relies on three kinds of participants:

  • Indexers: the people (or companies) who run computers that store and serve the data. Think of them as librarians.
  • Curators: people who decide which subgraphs are worth indexing and put money behind that decision. Think of them as people recommending which books the library should buy.
  • Delegators: people who lend their tokens to an indexer to increase that indexer's standing, in exchange for a share of the rewards.

A token in this world is a unit of value recorded on the blockchain. The Graph's own token is called GRT. It works a bit like a casino chip: you use it inside the system, and it has real market value outside it.

Staking means locking up tokens as a deposit. If you behave honestly, you get the tokens back plus rewards. If you misbehave, the system can take some of your deposit away. That punishment is called slashing. Staking is what gives participants a reason to play fair.

The part of The Graph discussed here is mainly the staking functionality: the rules for locking tokens up and for taking them back out.

The two mistakes, briefly

Both bugs are rounding errors. A rounding error happens when a calculation produces a fraction and the software keeps only the whole-number part, discarding the rest. If you split a bill of £10 three ways, each person owes £3.33 and a third of a penny is lost. Usually that is harmless. In financial software, it can be exploited: do it thousands of times and the lost fractions add up to real money, or they let someone skip a rule entirely.

Rounding errors are common enough that Immunefi, a company that runs bug bounty programmes for blockchain projects, ranked them number 6 in its Top 10 common smart contract vulnerabilities of 2023. A smart contract is a program that lives on a blockchain and runs automatically when someone sends it a transaction.

A bug bounty is a scheme where a company offers money to anyone who finds a flaw in its software and reports it privately instead of abusing it. The person who reports it is often called a whitehat, meaning a hacker who works on the defence side.

How the bugs were reported

On 7 January and 24 January 2024, a whitehat using the handle @GregadETH submitted two reports to The Graph: one rated High severity and one rated Critical. Severity is a rough label for how much damage a flaw could cause. The Graph patched the issues and paid a total bounty of $290,497.

The code involved lived in four files: Curation.sol, L2Curation.sol, L2Staking.sol and a shared helper library called MathUtils.sol. The .sol ending means these are Solidity files, Solidity being the programming language used to write smart contracts on Ethereum and similar networks.

The first bug: the curation tax that rounded to zero

Background: what a curator does

When someone creates a new subgraph, they are the curator. To create it, they lock up a certain amount of GRT. On top of that, they pay a curation tax of 1% of the amount they lock. That tax goes to the platform.

Why would anyone lock more than the minimum? Because a subgraph with more GRT behind it looks more trustworthy and is more likely to be picked up by indexers, which means it earns fees. So the amount is a judgement call. From here on, the article calls the curator simply the "user".

Where the mistake was

The first rounding issue was in Curation.sol and L2Curation.sol, specifically in a function called mint. A function is a named block of code that does one job; you can think of it as a recipe with a name. The mint function is supposed to take an amount of tokens to mint from the user and charge them the curationTax.

From the original on medium.com

Inside mint, the tax is worked out by another function called tokensToSignal. That calculation goes wrong whenever the amount being minted is below 100 tokens.

From the original on medium.com

Why it went wrong

At the time of the report, two numbers governed the calculation:

  • The curation tax percentage was capped at 1%, stored as the value uint256(10000).
  • A constant called MAX_PPM was capped at 100%, stored as the value uint256(1000000).

PPM stands for parts per million. It is a way of writing percentages as whole numbers so that a computer does not have to deal with decimal points. 1,000,000 parts per million is 100%. 10,000 parts per million is 1%.

uint256 is a data type: it means an unsigned (non-negative) whole number that takes up 256 bits of storage. The practical point is that it can only hold whole numbers, never fractions. That is exactly where the trouble starts.

Now follow the arithmetic. If a user asks to mint 99 tokens, the tax is 1% of 99, which is 0.99 tokens. But the code computes it as 990,000 divided by 1,000,000, and because the result must be a whole number, it is rounded down to 0. The user pays no tax at all.

On its own, saving 0.99 tokens is not worth anyone's effort. Every transaction on a blockchain costs a fee, called gas, paid to the computers that process it. On Ethereum's main network, mainnet, gas is expensive, so repeating this trick many times would cost more than it saves.

But the same contract is also deployed on Arbitrum, which is an L2. An L2, or layer 2, is a separate network built on top of a main blockchain that processes transactions more cheaply. On Arbitrum, gas is much cheaper, so the trick becomes worthwhile. The attacker can mint the tokens they need in batches of 99 per transaction and never pay the tax. @GregadETH demonstrated this with a PoC, a proof of concept: a small working demonstration that the attack really works.

What the first bug could cost

The effect is that the protocol is robbed of revenue it is owed, which can in turn mean a loss of funds or of yield owed to the people taking part in the protocol. Yield here means the rewards participants earn for staking.

The first fix

The Graph's development team changed how the tax is calculated. Instead of computing the tax directly and rounding it down to zero, the new code first works out how many tokens remain after tax, then subtracts that from the amount the user put in. The difference is the tax. This way the tax cannot silently become zero.

The change is in this commit, which is a recorded set of code changes in the project's public code repository:

Text
https://github.com/graphprotocol/contracts/commit/[redacted]

That line is simply the web address of the fix, so anyone can open it and read exactly what changed.

The second bug: the lock that never extended

Background: staking and thawing

When an indexer wants to earn rewards, they stake GRT. Staked tokens do not come back instantly. They stay locked for a period, and The Graph's documentation explains why: "GRT that is staked in the protocol is subject to a thawing period and can be slashed if Indexers are malicious and serve incorrect data to applications or if they index incorrectly."

In plain words: after you ask for your tokens back, there is a waiting period, called thawing, during which the tokens are still at risk. If you cheated, the system can still take them. This waiting period is the whole point. Without it, a dishonest indexer could grab rewards and vanish before anyone noticed.

Where the mistake was

The second rounding issue was in L2Staking.sol. It lets a malicious user skip the proper lock duration and take tokens out earlier than they should.

When someone calls the unstake function, meaning "I want my tokens back", that function calls another function called lockTokens. lockTokens is responsible for two things: adding the newly unstaked tokens to a pool of tokens that are already waiting to be released, and working out how long the new lock should last.

From the original on medium.com

Why it went wrong

The lockTokens function adds the new tokens to the existing pool of previously unstaked, still-locked tokens. It then calculates a new lock duration somewhere between the current lock duration and the maximum, which at the time of submission was capped at 28 days.

From the original on medium.com

If some tokens are already sitting in the locked pool, the new lock time is calculated like this:

Text
newLockedUntil = ((currentLockedUntil * currentlyUnstakedTokens) + (201600 * newUnstakedTokens)) / (currentUnstakedTokens + newUnstakedTokens)

Line by line, in plain words:

  • newLockedUntil is the answer being calculated: the moment in the future when the tokens will be free.
  • currentLockedUntil is the moment the tokens already in the pool will become free.
  • currentlyUnstakedTokens is how many tokens are already in the pool.
  • 201600 is the constant used in the formula as printed; the report does not explain what it represents.
  • newUnstakedTokens is how many tokens are being added right now.
  • The formula is a weighted average: it blends the old deadline and the new maximum deadline in proportion to how many tokens sit behind each. If most of the tokens are old, the answer stays close to the old deadline; if most are new, it moves towards the maximum.
  • The final division by (currentUnstakedTokens + newUnstakedTokens) is where the rounding happens. The result must be a whole number, so any fraction is dropped.

Now the trick. If currentUnstakedTokens is roughly 201,600 times larger than newUnstakedTokens, the weighted average comes out as currentLockedUntil. In other words, the deadline does not move at all. The attacker can pass a small enough amount to unstake that no extra lock is applied.

They then repeat the same plan as in the first bug: unstake in small batches, so that each batch adds nothing to the lock period. The normal process of unstaking, calling unstake() and then waiting until the tokens unlock, is broken. A malicious user can avoid the lock period entirely and withdraw immediately, with no penalty.

What the second bug could cost

The impact ranges from one indexer gaining an unfair advantage by unstaking faster than everyone else, all the way up to several indexers pulling out their entire stake without penalty. That last case would damage the security of the network overnight, because staked tokens are what keep participants honest.

The second fix

The fix was made in a separate helper library, MathUtils.sol. A library is a collection of reusable functions that other contracts can call, a bit like a toolbox shared between recipes. The vulnerable function weightedAverage was replaced with weightedAverageRoundingUp, which always rounds the result upwards. That guarantees the answer is never smaller than the smaller of the two input values, so the lock can no longer fail to extend.

This commit solves the problem of allowing users to unstake before they should:

Text
https://github.com/graphprotocol/contracts/commit/[redacted]

Again, that is just the web address where the change can be read.

From the original on medium.com

How the attacks would have been carried out, step by step

Step 1: mint in batches of 99 tokens

With the tax at 1% (uint256(10000)) and MAX_PPM at 100% (uint256(1000000)), passing uint256(99) as the tokensIn variable makes the tax 990000/1000000, which rounds down to 0. tokensIn is simply the name of the input variable holding the amount the user wants to mint. Repeating the call in batches of 99 tokens lets the attacker mint everything they need while paying no curationTax at all. The cheap gas on Arbitrum, where the contract is also deployed, makes the batching practical; on mainnet the gas cost would normally stop the attack from being worth it.

Step 2: unstake in small batches

Once tokens are already unstaked and sitting in the locked pool, the attacker passes a small enough value to unstake that currentUnstakedTokens is roughly 201,600 times larger than newUnstakedTokens. The weighted average then comes out as currentLockedUntil, so no additional lock is applied. Repeating this withdraws small portions of the staked tokens without extending the lock period, and the attacker can withdraw them immediately without any penalty.

The common root cause

Both bugs are rounding errors, and both come from the same habit: doing division with whole numbers and dropping the remainder.

  • In the first, the tax is computed from the input amount in a way that truncates to zero for inputs below 100, so the protocol receives nothing.
  • In the second, the weighted average used to compute the new lock time can return the current lock time when the new unstaked amount is small relative to the existing pool, so the lock is not extended.

What removed the economic barrier to the first one was the cheap gas of the L2 deployment.

What to look for elsewhere

These patterns are worth testing in other projects:

  1. Percentage and fee calculations with small inputs. Pass amounts just below the threshold where a fee truncates to zero, here 99 against a 1% tax, and check whether the fee charged is zero. A positive result is a fee of 0 for a non-zero mint.
  2. Weighted averages over a pool. When a new amount is added to an existing pool, try values where the existing pool is orders of magnitude larger than the new amount, and check whether the computed deadline equals the current deadline. A positive result is a lock time that does not move.
  3. L2 deployments of mainnet contracts. Repeat fee and lock calculations on the L2 where gas is cheap, since batching that is uneconomical on mainnet may be profitable there. A positive result is a profitable batch of zero-fee or zero-lock operations.
  4. Rounding direction in library helpers. Look for weightedAverage-style helpers and check whether they round down where the protocol needs the result to be at least the lesser input. A positive result is a helper whose output can fall below the smaller input.

Closing acknowledgements

The report thanks @GregadETH for responsibly disclosing such an important bug, and the team at The Graph for responding quickly and patching the issue.

Glossary

  • API: an agreed way for one piece of software to ask another for information, like a waiter carrying your order to the kitchen.
  • Arbitrum: an L2 network built on top of Ethereum, where transaction fees are much cheaper.
  • Blockchain: a shared, public record of transactions kept in copies by many computers.
  • Bug bounty: a scheme paying people to report flaws privately instead of exploiting them.
  • Commit: a recorded set of code changes in a project's public code repository.
  • Constant: a named value in code that is not meant to change while the program runs.
  • Curation tax: the 1% fee a curator pays to the platform when creating a subgraph.
  • Curator: the person who creates a subgraph and stakes GRT behind it.
  • Data type: the kind of value a variable can hold, such as a whole number or a piece of text.
  • Delegator: someone who lends tokens to an indexer in exchange for a share of rewards.
  • Function: a named block of code that performs one job.
  • Gas: the fee paid to the computers that process a blockchain transaction.
  • GRT: The Graph's own token, used for staking and paying for data.
  • High / Critical: severity labels for how much damage a flaw could cause.
  • Indexer: a participant who runs computers that store and serve data on The Graph.
  • L2 (layer 2): a network built on top of a main blockchain that processes transactions more cheaply.
  • Library: a collection of reusable functions that other contracts can call.
  • Mainnet: the main, live version of a blockchain network, where fees are typically higher.
  • PPM (parts per million): a way of writing percentages as whole numbers, where 1,000,000 ppm is 100%.
  • PoC (proof of concept): a small working demonstration that an attack really works.
  • Protocol: a set of rules and software run by several independent participants without a single company in charge.
  • Rounding error: a mistake caused by dropping the fractional part of a calculation.
  • Severity: a label for how serious a flaw is.
  • Slashing: taking away part of a participant's staked tokens as punishment.
  • Smart contract: a program that lives on a blockchain and runs automatically when someone sends it a transaction.
  • Solidity: the programming language used to write smart contracts on Ethereum and similar networks.
  • Staking: locking up tokens as a deposit to earn rewards and to guarantee honest behaviour.
  • Subgraph: The Graph's name for one API covering a particular slice of blockchain data.
  • Thawing: the waiting period after unstaking during which tokens are still at risk.
  • Token: a unit of value recorded on a blockchain.
  • uint256: a data type holding a non-negative whole number of 256 bits, so it cannot store fractions.
  • Unstake: to ask for staked tokens back.
  • Variable: a named slot in code that holds a value.
  • Weighted average: an average where each value counts in proportion to its weight, here the number of tokens behind it.
  • Whitehat: a hacker who finds flaws and reports them to be fixed rather than abused.
  • Yield: the rewards participants earn for staking.

Similar reports

View all

Same bug class and techniques, clearest first.

Smart contract vulnerabilities

The lesson behind this report.

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.