Pragma
Oracle

Pragma provides price feeds on Starknet, aggregating data that whitelisted publishers submit on-chain. We reviewed the oracle, including its volatility and yield curve feeds.
report id
0147
category
Infra & Wallets
language
Cairo
final report
November 16, 2023
lines of code
4531
Content

Download audit report

1

Executive Summary

This document presents the security review performed by Nethermind on the Pragma Oracle protocol. Pragma is an oracle protocol designed to provide asset price feeds to other various protocols on the Starknet network. It is designed to reduce off-chain infrastructure dependencies by using trusted "publishers" to submit their pricing data directly to Oracle, where multiple submissions from different publishers can be aggregated, and the final results can be calculated on-chain. The data aggregation can be done as a mean or median; however, the Pragma team highly recommends protocols use the calculated median to prevent outlier price data from affecting the result. Publishers must complete an application process before being verified and whitelisted by the Pragma team. Each publisher is then manually given permission to submit to each price feed individually. The protocol also features more advanced computational feeds using historical price data. At the time of this report, the supported computational feeds are volatility and yield curves, with more to be added in the future.

The audit was performed using (a) manual analysis of the codebase, (b) automated analysis tools, (c) simulation of the smart contract, and (d) creation of test cases. Along with this document, we report 38 points of attention, where 2 are classified as Critical, 3 are classified as High, 1 is classified as Medium, 13 are classified as Info and 19 are classified as Best Practices.

Audit assessment
Audit TypeSecurity Review
Initial ReportNov 9, 2023
Response from ClientNov. 14, 2023
Final ReportNov. 16, 2023
MethodsManual Review, Automated Analysis, Tests
Repositoryastraly-labs/pragma-oracle
Commit Hash (Network-Contract43ae793167
DocumentationWebsite documentation
Documentation AssessmentHigh
Test Suite AssessmentMedium
Total findings
38
Fixed
37
Acknowledged
1
Mitigated
0
Unresolved
0

Findings by severity

  • Critical2
  • High3
  • Medium1
  • Low0
  • Informational13
  • Best Practices19

3

Summary of Issues

#FindingSeverityUpdate
1A publisher can reliably manipulate price feeds to any valueCriticalFixed
2Data aggregation includes stale entriesCriticalFixed
3Incorrect calculation of pair prices with USD hopHighFixed
4Incorrect price comparison results in inaccurate yield pointsHighAcknowledged
5StorePacking implementation for EntryStorage struct is not correctly packedHighFixed
6Lack of timestamp validation allows potential DOS in publish_data(...)MediumFixed
7A currency and pair with id of zero can be addedInfoFixed
8A new pair can be added with non-existing base and quote currenciesInfoFixed
9Cannot remove publisher with zero addressInfoFixed
10Empty arrays lead to revert in _sum_volatility(...)InfoFixed
11Empty arrays lead to revert in merge(...) functionInfoFixed
12Incorrect sign determination in pairwise_1D(...) multiplication operationInfoFixed
13Missing check in calculate_volatility(...)InfoFixed
14Missing request cancellation logic in cancel_random_request (...)InfoFixed
15Multiple publishers can share the same addressInfoFixed
16Necessary checks are inadequateInfoFixed
17Request status handling issues in randomness.cairo contractInfoFixed
18Undefined divisions may occur in several functionsInfoFixed
19get_implementation_hash(...) returns empty classhash until first upgradeInfoFixed
20Control Coupling in function pairwise_1D(...)Best PracticesFixed
21Dead codeBest PracticesFixed
22Duplicate code in mul_decimals(...) functionBest PracticesFixed
23Hash implementation TupleSize4LegacyHash has an incorrect nameBest PracticesFixed
24Inconsistent type casting approach for u8 and AggregationModeBest PracticesFixed
25Inconsistent use of getter functionBest PracticesFixed
26Incorrect commentsBest PracticesFixed
27Shadowed arrays are unusedBest PracticesFixed
28Unnecessary iteration counterBest PracticesFixed
29Unnecessary local variable assignmentBest PracticesFixed
30Unnecessary storage readBest PracticesFixed
31Unnecessary use of into in some functionsBest PracticesFixed
32Unnecessary variable redefinition inside a loopBest PracticesFixed
33Unnecessary variable shadowingBest PracticesFixed
34Unrequired overhead for computing the varianceBest PracticesFixed
35Unused function parametersBest PracticesFixed
36Unused importsBest PracticesFixed
37Unused parameters in function get_future_spot_pragma_source_- key(...)Best PracticesFixed
38Use the same value while converting typesBest PracticesFixed

4

System Overview

The Pragma protocol consists of the following components:

Oracle: Contains the primary logic for the protocol, including storing published data, aggregating data on-chain using median or mean, setting and querying checkpoints, getters for information related to pair and sources, and admin management.

PublisherRegistry: Tracks all publishers and the sources they have permission to publish data to. Once approved as a publisher, an admin specifies each source that the publisher can provide data for. Publishers are able to change their address which they use to submit data. Admins are also able to disable sources or remove publishers entirely.

Compute Engine: The compute engine represents a group of contracts that can return more complex data based on historical checkpoints from the oracle contract. At the time of this report, the supported compute engine contracts are the yield curve and summarty stats. In the future, more compute engine contracts will be supported.

Publishers: Publishers are selected by the Pragma team and are permitted to submit price data to the oracle contract. There are multiple publishers per source, to ensure that price data updates regularly.

Admin: Controlled by the Pragma team, with the ability to manage publishers, change the registry contract, manage new pairs, currencies and sources and upgrade the oracle contract implementation.

Dependent Protocol: A protocol that depends on the oracle price feed data, such as lending/borrowing protocols or perpetual trading protocols. These contracts will use the price aggregation functions to get the median price for a given pair most frequently.

4.1 Analysis of the source-publisher oracle structure

Pragma sources its pricing data through “publishers” and “sources”. A publisher is a trusted entity with permission to publish price data to a source. There can be multiple publishers per source. A source represents pricing data from one entity, and there can be many sources for a given pair. When protocols request pricing data on-chain, the mean or median of all source pricing is calculated and returned to the caller.

Each publisher must be manually approved for each source by the admin of the publisher registry contract, meaning that the publisher role is effectively whitelisted, but this does not guarantee that publishers will always behave correctly. Publishers will likely publish data through an automated program or script. It is possible that the private key for a given publisher could be compromised, or the script could be tampered with. It also may be possible that the script may have a bug or behave incorrectly for some unintentional reason.

The current data aggregation structure relies on the trusted publishers as a group to behave correctly, so we only wish to explore the impacts of a single compromised publisher.

The purpose of having multiple sources and multiple publishers is that if one publisher acts incorrectly, the remaining publishers will still be correct. Pragma highly recommends its clients use the median for their aggregation approach, so we will assume that all pricing calculations use the median for the rest of this analysis. With only one publisher providing incorrect data, it won’t be considered, and the median will still return an accurate price. This structure prevents one publisher from manipulating the price, but there are some constraints and nuances that should be considered, which we explore below:

The safety in numbers comes from how many sources you have, not how many publishers. Each source only tracks its most recent entry, so if you have a source with many honest publishers and one malicious publisher, we can consider the entire source compromised since the malicious publisher can repeatedly publish new incorrect data to overwrite the honest data. While the number of publishers doesn’t contribute to safer pricing calculations, the number of sources do. The more sources you have, the more prices you calculate a median from, making it harder for an incorrect price to impact the result. This distinction between publishers and sources is important:

  • More publishers increase the rate at which a source is updated.
  • More sources increase the safety and reliability of price data.

A minimum number of sources per pair is required. Having just one source is naturally a risk since pricing is effectively centralized to the most recent publisher. A risk still exists with two sources because the median calculation will attempt to average out the two source prices. If one of these sources is compromised (has a malicious publisher), the outcome of this average can be manipulated. With three sources, if one source is compromised, the median result will be chosen from a correct source. Therefore, at least three sources are needed to protect against a malicious publisher. This minimum threshold check already exists in the code. However, when setting this minimum using set_sources_theshold, there is no check to ensure the new threshold is three or more. Without this check, it’s possible to put the protocol in a state where price manipulation is possible. The threshold check also only applies to checkpoints, not live data, so price manipulation can still be done and may impact other protocols that depend on Pragma for pricing.

A publisher should not be able to publish to more than one source for a given pair. Returning to a point discussed earlier, if one publisher is compromised, we can consider its source compromised as well. If a publisher has permission to more than one source for the same pair, each of these sources are compromised, which breaks the idea that a minimum of three sources is needed to be safe from a malicious publisher. For example, with three sources, a malicious publisher could publish a zero price for both sources, and the median would choose the sorted middle price, which would be zero, meaning a publisher could have complete control of price data. For this reason, a publisher should only have permission to one source for each pair.

5

Risk Rating Methodology

The risk rating methodology used by Nethermind Security follows the principles established by the OWASP Foundation. The severity of each finding is determined by two factors: Likelihood and Impact.

Likelihood measures how likely the finding is to be uncovered and exploited by an attacker. This factor will be one of the following values:

  1. High: the issue is trivial to exploit and has no specific conditions that need to be met;
  2. Medium: the issue is moderately complex and may have some conditions that need to be met;
  3. Low: the issue is very complex and requires very specific conditions to be met.

When defining the likelihood of a finding, other factors are also considered. These can include but are not limited to motive, opportunity, exploit accessibility, ease of discovery, and ease of exploit.

Impact is a measure of the damage that may be caused if an attacker exploits the finding. This factor will be one of the following values:

  1. High: the issue can cause significant damage, such as loss of funds or the protocol entering an unrecoverable state;
  2. Medium: the issue can cause moderate damage, such as impacts that only affect a small group of users or only a particular part of the protocol;
  3. Low: the issue can cause little to no damage, such as bugs that are easily recoverable or cause unexpected interactions that cause minor inconveniences.

When defining the impact of a finding, other factors are also considered. These can include but are not limited to data and state integrity, loss of availability, financial loss, and reputation damage. After defining the likelihood and impact of an issue, the severity is determined according to the table below.

Impact / LikelihoodLowMediumHigh
HighMediumHighCritical
MediumLowMediumHigh
LowInfo / Best PracticesLowMedium
UndeterminedUndeterminedUndeterminedUndetermined

To address issues that do not fit a High, Medium or Low severity, Nethermind Security also uses three more finding severities: Informational, Best Practices, and Undetermined.

  1. Informational findings do not pose any risk to the application, but they carry some information that the audit team intends to pass to the client formally;
  2. Best Practice findings are used when some piece of code does not conform with smart contract development best practices;
  3. Undetermined findings are used when we cannot predict the impact or likelihood of the issue.

6

Issues

6.1 A publisher can reliably manipulate price feeds to any value

FileFix commitTypeStatus
src/oracle/oracle.cairoe468387CriticalFixed

Publishers use the publish_data(...) function to submit new price data to the Oracle contract. This function has two logic flows, depending on whether the given source has previously provided data.

If the source has not previously provided data, it is considered "new" for the given pair, and the source ID is added to the pair’s list of valid sources. After this, the entry data is written to storage. If the source has already provided data, then the new data is validated and written to storage. A snippet demonstrating these logic flows is shown below:

let res = get_entry_storage(@self, spot_entry.pair_id, SPOT, spot_entry.base.source, 0);

// When a source has an existing entry
if (res.timestamp != 0) {
let entry: PossibleEntries = IOracleABI::get_data_entry(
@self, DataType::SpotEntry(spot_entry.pair_id), spot_entry.base.source
);
match entry {
PossibleEntries::Spot(spot) => {
validate_data_timestamp(ref self, new_entry, spot);
},
PossibleEntries::Future(_) => {},
PossibleEntries::Generic(_) => {},
}
// When a source doesn't have an entry
} else {
let sources_len = self
.oracle_sources_len_storage
.read((spot_entry.pair_id, SPOT, 0));
self
.oracle_sources_storage
.write(
(spot_entry.pair_id, SPOT, sources_len, 0),
spot_entry.get_base_entry().source
);
self
.oracle_sources_len_storage
.write((spot_entry.pair_id, SPOT, 0), sources_len + 1);
}

The Oracle contract determines if a source is "new" by checking if the stored entry’s timestamp is zero. However, the only validation for a newly submitted timestamp is that it must be greater than or equal to the existing stored timestamp. A malicious publisher could provide a timestamp of zero to a new source for a given pair and repeatedly call publish_data(...), each time creating an additional entry into the list of sources for the given pair, all duplicates of the same source.

fn build_sources_array(
self: @ContractState, data_type: DataType, ref sources: Array<felt252>, sources_len: u64
) {
let mut idx: u64 = 0;
loop {
if (idx == sources_len) {
break ();
}
match data_type {
DataType::SpotEntry(pair_id) => {
let new_source = self
.oracle_sources_storage
.read((pair_id, SPOT, idx.into(), 0));
/////////////////////////////////////////////////////////////////
// @audit The sources array can contain duplicate source entries
/////////////////////////////////////////////////////////////////
sources.append(new_source);
},
// ...
}
// ...
}
// ...
}

All data aggregation methods use the list of sources. A mutated source list containing many entries for the same source ID can lead to the same price data being considered multiple times, heavily affecting the mean and median calculations.

This exploit can be combined with the finding related to entry storage packing to manipulate the sources list even if an existing entry exists. An attacker could provide a timestamp greater than 32 bits, which will pass input validations, but when written to storage, all bits over 32 are cut off. If the remaining 32 bits are zero, resetting the stored entry timestamp to zero is possible, allowing the exploit scenario discussed above.

This exploit allows any publisher to have their source data duplicated an arbitrary number of times, affecting the mean and median calculations such that their single price source can outweigh all other pricing, effectively taking complete control of Oracle pricing.

A malicious publisher can also leave the timestamp as zero and never set it to a non-zero value, causing the function get_data_entry(...) to revert due to the following line, which will cause any on-chain price query to revert:

assert(!_entry.timestamp.is_zero(), 'No data entry found');

Recommendation

Address the packing issue highlighted in the other finding and add a zero check to validate_data_timestamp(...) for the new entry timestamp.

Resolution

The issue was resolved with the changes made in commit e46838774da325db1541d6dcc6d6b954fa1e9777. In this update, we introduced a check for zero timestamps and also reevaluated the overall structure of our data storage. The initial design is thoroughly explained in the Analysis section of our audit documentation. However, we ultimately chose not to adopt the approach where one source equates to one publisher. Instead, we opted for a strategy that categorizes data by source, providing us with more flexibility.

Rather than simply updating the latest price from a source, we have restructured our storage system to also consider the publisher’s information. This means that when our aggregation functions are called, they will first aggregate data from different publishers within each source (noting that a single publisher may provide data for multiple sources), followed by an aggregation across various sources. This new method makes her less prone to manipulation.

6.2 Data aggregation includes stale entries

FileFix commitTypeStatus
src/oracle/oracle.cairo1a7b0ceCriticalFixed

When getting price data, the internal function build_entries_array(...) is used to collect an array of PossibleEntries, which can then be aggregated to return a price. For an entry to be appended to the array, it should be initialized and within 2h10m from the most recent entry timestamp or the current block timestamp, whichever is lower. These requirements are designed to prevent stale data from being a part of the aggregate calculations. A snippet from the function is shown below:

PossibleEntries::Spot(spot_entry) => {
let is_entry_not_initialized: bool = spot_entry.get_base_timestamp() == 0;
let condition: bool = is_entry_not_initialized
&& (spot_entry
.get_base_timestamp() < (latest_timestamp - BACKWARD_TIMESTAMP_BUFFER));
if !condition {
entries.append(PossibleEntries::Spot(spot_entry));
}
},

The condition variable is determined by the AND operation, considering (both) whether the entry is initialized and the timestamp is stale. This logic uses many negatives both language-wise and with the NOT operator, which makes it hard to follow when reading the code, so the logic paths have been simplified below:

Condition:  entry is uninitialized AND entry is stale

Case 1: entry is uninitialized AND entry is stale
True AND True == True
!True == False
False so we skip

Case 2: entry is initialized AND entry is recent
False AND False == False
!False == True
True so we append

Case 3: entry is initialized AND entry is stale
False AND True == False
!False == True
True so we append

As shown in the logic paths above, an entry will be appended even if the entry timestamp for the given source is stale. A source may stop providing data for publishers to use for a number of reasons, such as de-listing assets, changing to a paid API that publishers don’t want to use, or even the source shutting down.

The impact of stale source entries being part of the aggregate calculations differs depending on whether a Median or Mean aggregation method is used:

  • Mean: The impact can be measured immediately, where the stale price is part of the calculated mean;
  • Median: The impact cannot be measured until a minimum of 50% of the entries for a given source are stale. Another condition is that every stale price is lower than the current price or every stale price is higher than the current price. When these two conditions are met, the median price will begin to return arbitrary stale prices from retired sources;

Recommendation

Consider changing the condition from LOGICAL AND to LOGICAL OR, which will ensure that an entry can only be appended when it is both initialized and it’s timestamp is recent. We also recommend changing how this logic is written to make it more readable, removing "negatives" where possible, and giving a more meaningful name to the condition variable.

Resolution

The issue is resolved in commit 1a7b0ce207f90065797a45f79422d5f7cff78e73. We made the logic much clearer and, thus, more understandable.

6.3 Incorrect calculation of pair prices with USD hop

FileFix commitTypeStatus
src/operations/time_series/convert.cairo2db748eHighFixed

Function convert_via_usd(...) is used to calculate the base tokens price quoted by quote tokens price with USD prices of each token. However, the calculation inside convert_via_usd(...) function is incorrect. In cases like base tokens, decimals are higher than quote token decimals. The calculation will be like this:

BASE_TOKEN_PRICE_IN_USD * (OUTPUT_DECIMALS) / QUOTE_TOKENS_PRICE_IN_USD

The above calculation results in higher values than expected.

Recommendation

Consider converting each token price into the same decimals, then continue the calculation.

Resolution

The issue is resolved in commit 2db748ed922f6a0b6d80dc83da54df456fb52646, following the recommendations.

Update from Nethermind Security

The fix resolves the issue of using prices in different decimal representations. However, we noticed that the variable decimals was changed from min( base_decimals, quote_decimals) to be the base_decimals. This makes the first call to normalize_to_decimals(..) unnecessary as it converts from base_decimals to base_decimals.

Additionally, if base_decimals is less than quote_decimals, we will have a precision loss while normalizing the quote price. We suggest a better approach to avoid this issue:

  • Convert one of the two prices to the max decimals between base and quote;
  • Compute rebased_value using the desired output decimals. Below we exemplify our suggestion;
if ( base_decimals < quote_decimals) {
// convert base price to quote decimals
} else {
// convert quote price to base decimals
}
// compute rebased value, `decimals` here is the expected output decimals
let rebased_value = convert_via_usd( normalised_basePPR_price, normalised_quotePPR_price, decimals);

Second update from the client: We implemented the following logic in our code:

let (rebased_value, decimals) = if (base_decimals < quote_decimals) {
let normalised_basePPR_price = normalize_to_decimals(
basePPR.price, IOracleABI::get_decimals(self, base_data_type), quote_decimals
);
(
convert_via_usd(normalised_basePPR_price, quotePPR.price, quote_decimals),
quote_decimals)
} else {
let normalised_quotePPR_price = normalize_to_decimals(
quotePPR.price, IOracleABI::get_decimals(self, quote_data_type), base_decimals);
(convert_via_usd(basePPR.price, normalised_quotePPR_price, base_decimals),base_decimals)
};

In the original implementation, we operated under the assumption that we would always deal with the same number of decimals, since the conversion was being realized through the USD currency. This assumption was based on the fact that the get_decimals function would always return the decimal count of USD. However, we recognized the need for greater flexibility to handle different decimal counts between base and quote currencies. Therefore, we introduced changes to normalize the price of the base and quote currencies to the higher decimal precision of the two. This approach ensures accurate conversions regardless of the decimal discrepancies between different currencies. You can check the commit here: 008c977b25b502ba5ec427158a98109d8935ed6a

6.4 Incorrect price comparison results in inaccurate yield points

FileFix commitTypeStatus
yield_curve.cairo—HighAcknowledged

The function calculate_future_spot_yield_point(...) calculates the yield point for a given future and spot entry. It takes as an input the future and spot entries: future_entry, spot_entry, along with their respective price decimals: future_decimals and output_decimals.

However, an issue arises as the function directly compares future_entry.price and spot_entry.price without converting them to a unified decimal representation. This can result in inaccurate outputs, possibly leading to erroneously returning a rate of 0 in many cases, particularly when future_decimals are less than spot_decimals.

Additionally, there’s a potential risk of underflow in the interest_ratio computation due to the incorrect comparison of prices. The calculation assumes shifted_ratio >= decimals_multiplier. This is ensured when the future price is higher than the spot price when both are in the same decimal representation. However, the current comparison doesn’t guarantee this, resulting in unexpected reverts in multiple cases.

This issue directly impacts the construction of yield curve points within the get_yield_points(...) function, leading to unexpected reverts or incorrect data returns.

fn calculate_future_spot_yield_point(...) -> YieldPoint {
let mut time_scaled_value = 0;
// @audit `future_entry.price` and `spot_entry.price` are in different decimals
if (future_entry.price > spot_entry.price) {
// ...
let decimals_multiplier = pow(10, output_decimals.into());
// ...
if (future_decimals <= output_decimals
+ spot_decimals) {
let exponent = output_decimals + spot_decimals - future_decimals;
// ...
let ratio_multiplier = pow(10, exponent.into());
shifted_ratio = (future_entry.price * ratio_multiplier) / spot_entry.price;
} else {
let exponent = future_decimals - output_decimals - spot_decimals;
// ...
let ratio_multiplier = pow(10, exponent.into());
shifted_ratio = (future_entry.price) / (spot_entry.price * ratio_multiplier);
}
// @audit the current check could lead to an underflow in `interest_ratio` computation
let interest_ratio = shifted_ratio - decimals_multiplier;
// ...
}
// ...
}

Recommendation

Ensure proper conversion of future_entry.price and spot_entry.price to a unified decimal representation before comparison. Implementing this fix will mitigate the risk of underflow in the interest_ratio as shifted_ratio >= decimals_multiplier will always be true.

Resolution

Our system architecture is designed in such a way that it does not support different decimal places for a given currency pair. To elaborate, let’s examine the get_decimals function in our code:

fn get_decimals(self: @ContractState, data_type: DataType) -> u32 {
let base_currency = match data_type {
DataType::SpotEntry(pair_id) => {
let pair = self.oracle_pairs_storage.read(pair_id);
assert(!pair.id.is_zero(), 'No pair found');
let base_cur = self.oracle_currencies_storage.read(pair.base_currency_id);
base_cur
},
DataType::FutureEntry((
pair_id, expiration_timestamp
)) => {
let pair = self.oracle_pairs_storage.read(pair_id);
assert(!pair.id.is_zero(), 'No pair found');
let base_cur = self.oracle_currencies_storage.read(pair.base_currency_id);
base_cur
},
DataType::GenericEntry(key) => {
let pair = self.oracle_pairs_storage.read(key);
assert(!pair.id.is_zero(), 'No pair found');
let base_cur = self.oracle_currencies_storage.read(pair.base_currency_id);
base_cur
}
// DataType::OptionEntry((pair_id, expiration_timestamp)) => {}
};
base_currency.decimals
}

In this implementation, the function retrieves the decimal count solely from the base currency of the pair. This approach is consistent across different types of data entries, whether they are SPOT, FUTURE, or OPTION. As a result, the final decimal value remains the same for any given currency pair, regardless of the type of financial instrument involved. This uniformity in handling decimals ensures consistency but also means that our system does not accommodate variations in decimal places between different pairs or types of entries.

6.5 StorePacking implementation for EntryStorage struct is not correctly packed

FileFix commitTypeStatus
src/oracle/oracle.cairo9e721f4
3480572
HighFixed

Entries have a custom StorePacking implementation to use storage efficiently by fitting all values of an entry within a single storage slot of size felt252. The custom pack function is shown below:

// EntryStorage.timestamp: u64
// EntryStorage.volume: u128
// EntryStorage.price: u128
// 320 bits total

fn pack(value: EntryStorage) -> felt252 {
value.timestamp.into()
+ value.volume.into() * TIMESTAMP_SHIFT_U32
+ value.price.into() * VOLUME_SHIFT_U132
}

Since, as integers, it is not possible to fit 320 bits into a 252 bits storage slot, the Pragma team treats the timestamp as 32 bits in storage, volume as 100 bits, and price as 120, totaling 252 bits. The pack function converts the integer to felt252, then multiplies by the amount to complete the equivalent of a bit shift action. These shifted values are then summed together to result in the final packed representation of the entry data.

There is no check to ensure that the integer data size will exceed the expected packed storage size. For example, timestamp is represented as 32 bits in storage, but when packing the u64 value, there is no check to ensure that the size of timestamp is greater than 32 bits. In the case of timestamp, this can lead to the 32 most significant bits "bleeding" into the bits above that are meant to represent volume.

The following demonstrates each part of the packed data and which bits may bleed into other sections or overflow:

'B' = Expected storage bits
'.' = Bleed or overflow bits
'_' = Unaffected bits

timestamp: 0x_______________________________________________........BBBBBBBB 32 bits, actual 64bits
volume: 0x_______________________.......BBBBBBBBBBBBBBBBBBBBBBBBB________ 100 bits, actual 128bits
price: 0xBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB................................. 120 bits, actual 128bits

// Price has the potential to overflow, changing all bits in the packed storage felt

As shown in the diagram above, a specially crafted timestamp can be used to manipulate bits representing volume, and a specially crafted volume can be used to manipulate bits representing price, and a specially crafted price can be used to overflow the felt, manipulating the lower timestamp bits or even causing the entire felt to be zero.

Recommendation

Consider adding a check when packing an EntryStorage to ensure each field fits within its expected storage size.

Resolution

The issue was addressed in two commits, identified by their hash codes. In these updates, we implemented a masking technique for the data elements we intended to store. For instance, by applying a bitwise AND operation between the timestamp and a predefined mask, we can determine if the timestamp exceeds the mask’s limit. If the result of this operation differs from the original timestamp, it indicates an overflow beyond the mask’s capacity. This method allows us to effectively manage and limit the size of the elements we are working with.

Update from Nethermind Security

The fixes implemented are not enough. There are 2 issues with it:

Issue 1) Possible overflow in function pack(...) when price value is greater than or equal to 0x800000000000011000000000000000: The function pack(...) packs three variables with 120 bits, 100 bits, and 32 bits respectively - a total of 252 bits, into a single felt252 variable.

fn pack(value: EntryStorage) -> felt252 {
value.timestamp.into()
+ value.volume.into() * TIMESTAMP_SHIFT_U32
+ value.price.into() * VOLUME_SHIFT_U132
}
MAX_FELT = 3618502788666131213697322783095070105623107215331596699973092056135872020480;
// If we convert it to Hex, it would be
MAX_FELT = 0x800000000000011000000000000000000000000000000000000000000000000;

As seen, value.price will occupy the first 120 bits during packing. So, if value.price is greater than or equal to 0x800000000000011000000000000000, the resulting pack_value will overflow.

Issue 2) Unnecessary check for pack_value in the function pack(...): The function pack(...) packs three variables with 120 bits, 100 bits, and 32 bits respectively - a total of 252 bits, into a single felt252 variable.

fn pack(value: EntryStorage) -> felt252 {
...
let pack_value: felt252 = value.timestamp.into()
+ value.volume.into() * TIMESTAMP_SHIFT_U32
+ value.price.into() * VOLUME_SHIFT_U132;
assert(pack_value.into() < MAX_FELT, 'EntryStorePacking:tot too big');
pack_value
}

After the calculation, pack_value is verified to be smaller than MAX_FELT. However, since pack_value is already a felt252, this check is always true, making it unnecessary.

Second update from the client The issue stemmed from our initial intention to define pack_value as a u256 rather than a felt252. By opting to return a u256, the subsequent assertion becomes logical, as it ensures there is no overflow before we convert pack_value into its final felt252 form. Here is the final commit: 4355f00d3c3728c254eb12150ca19e686261a529

fn pack(value: EntryStorage) -> felt252 {
...
let pack_value: u256 = value.timestamp.into()
+ value.volume.into() * TIMESTAMP_SHIFT_U32
+ value.price.into() * VOLUME_SHIFT_U132;
assert(pack_value.into() < MAX_FELT, 'EntryStorePacking:tot too big');
pack_value
}

6.6 Lack of timestamp validation allows potential DOS in publish_data(...)

FileFix commitTypeStatus
src/oracle/oracle.cairo22d2969
780b2bd
MediumFixed

When submitting a new timestamp, the function validate_data_timestamp(...) is used to ensure that the new entry timestamp cannot be less than the existing entry timestamp. However, there are no restrictions on how far into the future the new entry timestamp may be.

With no restriction on the future timestamp, if a publisher publishes an entry with a timestamp far in the future (either maliciously or unintentionally, e.g., a bug on the publisher’s automated script), assuming all other publishers continue to behave correctly and attempt to submit valid timestamps on their entries, they will revert, as the current entry with a timestamp far in the future prevents and new entries with a timestamp at the current time. This check is shown below:

assert(
spot_entry.get_base_timestamp() >= last_entry.get_base_timestamp(),
'Existing entry is more recent'
);

Recommendation

Consider adding a check in validate_data_timestamp(...) to ensure that the provided timestamp for the new entry is reasonable.

Resolution

The issue is resolved in commits:

We defined a FORWARD_TIMESTAMP_BUFFER of 2 minutes to guarantee future validation within block emission range.

6.7 A currency and pair with id of zero can be added

FileFix commitTypeStatus
src/oracle/oracle.cairof2b3d81
49e7aca
InfoFixed

When adding a currency or pair to the oracle, there is no check to ensure that its ID is not zero. Various parts of the protocol assume that an ID of zero means the given pair or currency does not exist. When an ID of zero is used, it can lead to unexpected behavior, such as early reverts and overwrites, which should normally not be possible. The following functions have unexpected behaviors for zero ID currencies:

Oracle::add_currency
The same currency ID can be overwritten multiple times

Oracle::update_currency
The currency cannot be updated

The following functions have unexpected behaviors for zero ID pairs:

Oracle::get_decimals
Reverts on what is expected to be a valid pair

Oracle::add_pair
The same currency ID can be overwritten multiple times

Recommendation

Consider adding a check to add_currency(...), add_pair(...), _set_keys_currencies(...), and _set_keys_pairs(...) to ensure that the ID of the new item cannot be zero.

Resolution

This issue is resolved in the commits below, following the recommendations. We added zero-check for the required functions.

6.8 A new pair can be added with non-existing base and quote currencies

FileFix commitTypeStatus
src/oracle/oracle.cairo3bee9c9
2f877e8
InfoFixed

When adding a pair through add_pair(...) and _set_keys_pairs(...), there is no input validation for the new pair’s quote_currency_id and base_currency_id.

fn add_pair(ref self: ContractState, new_pair: Pair) {
self.assert_only_admin();
let check_pair = self.oracle_pairs_storage.read(new_pair.id);

//////////////////////////////////////////////////////////////////////
// @audit Missing validations on new pair quote and base currency id
// Quote or base or both currencies may not exist
// Quote and base currencies may be the same
//////////////////////////////////////////////////////////////////////
assert(check_pair.id == 0, 'Pair with this key registered');
self.emit(Event::SubmittedPair(SubmittedPair { pair: new_pair }));
self.oracle_pairs_storage.write(new_pair.id, new_pair);
self
.oracle_pair_id_storage
.write((new_pair.quote_currency_id, new_pair.base_currency_id), new_pair.id);
return ();
}

This can allow a pair to be created with invalid one or both currencies. Other functions in the code that use these currency IDs may assume that the currency exists, which may not be the case. This affects get_decimals(...), for example, which does not verify that the base currency of a given pair exists, making it possible to read from an unwritten storage slot and return a decimals of 0, as shown in the snippet below:

DataType::SpotEntry(pair_id) => {
let pair = self.oracle_pairs_storage.read(pair_id);
assert(!pair.id.is_zero(), 'No pair found');
////////////////////////////////////////////////////////////////
// @audit Existence check is only for pair
// Base currency existence is not checked before reading
////////////////////////////////////////////////////////////////
let base_cur = self.oracle_currencies_storage.read(pair.base_currency_id);
base_cur
},

Recommendation

Consider adding checks to both add_pair(...) and _set_keys_pairs(...) to ensure that the base and quote currencies exist before writing the new pair to storage.

Resolution

The issue has been resolved through two separate commits.

The commit 3bee9c addresses the add_pair function, while the commit 2f877 pertains to the _set_keys_pairs() function. In both instances, the solution involved accessing the storage slot associated with the base/quote currency and managing scenarios where the returned ID is null.

6.9 Cannot remove publisher with zero address

The publisher registry contract checks if a given publisher exists by checking if the publisher address is non-zero. However, setting a publisher address to zero through the functions add_publisher and update_publisher_address is possible. A publisher can update their address to zero, which can prevent them from being removed by removed_publisher since the zero check will cause the call to revert, as shown below:

fn remove_publisher(...) {
// ...
// @audit Zero check will revert for a manually set zero address
let not_exists: bool = self.publisher_address_storage.read(publisher).is_zero();
assert(!not_exists, 'Publisher not found');
// ...
}

Recommendation

Consider implementing a zero address check in the functions update_publisher_address(...) and add_publisher(...).

Resolution

This issue is resolved in commits

Following the recommendation, we added zero-address checks in both functions.

6.10 Empty arrays lead to revert in _sum_volatility(...)

FileFix commitTypeStatus
metrics.cairo01d9a1bInfoFixed

In the function _sum_volatility(...), when an empty array is passed, the stop condition for the loop will not be triggered. This happens because the cur_idx is set to 1, while the array length would be zero. As a result, the function will revert as it attempts to access an index that does not exist.

fn _sum_volatility(arr: Span<TickElem>) -> ... {
let mut cur_idx = 1;
let mut sum = FixedTrait::new(0, false);
loop {
if (cur_idx == arr.len()) {
break ();
}
// @audit This array read will fail on a zero-length array
let cur_val = *arr.at(cur_idx);
let prev_val = *arr.at(cur_idx - 1);
// ...
};
}

This function is called by the volatility(...) function, which has logic to handle an array size of zero, but this check is done after the call to _sum_volatility(...), so execution will have reverted before this check can be reached.

fn volatility(arr: Span<TickElem>) -> ... {
// @audit Array of size zero will revert before the length check
let _volatility_sum = _sum_volatility(arr);
if (arr.len() == 0) {
return 0;
}
// ...
}

Recommendation

Consider adjusting the loop condition to the following to handle empty arrays:

if (cur_idx >= arr.len()) {
break ();
}

Resolution

This issue is resolved in commit 01d9a1bf1a9d80bc4215b0d6673e86910dae7dbd, following the recommendation.

6.11 Empty arrays lead to revert in merge(...) function

FileFix commitTypeStatus
merge_sort.cairoa08dc20InfoFixed

The merge(...) function performs a merge sort on an input array. However, the current implementation does not account for the case where the provided array arr is empty. In that case, the execution will revert inside the else block when attempting to access a non-existent element at index 0.

fn merge(...) -> Span<T> {
if arr.len() > 1_u32 {
// ...
} else {
let mut result_arr = ArrayTrait::<T>::new();
result_arr.append(*arr.at(0)); // @audit reverts if `arr` is an empty array
result_arr.span()
}
}

Recommendation

Consider implementing a check for empty arrays and return the appropriate result.

Resolution

The issue is resolved in commit a08dc20d26618f87af8bde8776c90db6e62b8764. We handle the edge case by returning an empty span if the length is null.

6.12 Incorrect sign determination in pairwise_1D(...) multiplication operation

FileFix commitTypeStatus
metrics.cairo0476e45InfoFixed

The function pairwise_1D(...) is used to perform subtraction and multiplication on elements in two given arrays. When conducting a multiplication operation, the current implementation erroneously determines the output sign by comparing the magnitudes of the input values.

This approach will lead to the wrong sign being applied to the output value, where it will only be possible to have a false sign when both magnitudes are equal. Instead, the signs of x1 and y1 should be compared, resulting in the correct outputs.

fn pairwise_1D(...) -> ... {
// ...
Operations::MULTIPLICATION(()) => {
// ...
// @audit Resulting sign should be determined by the equality of sign, not magnitude
if x1.mag == y1.mag {
output.append(FixedTrait::new(mag: x1.mag * y1.mag, sign: false));
} else {
output.append(FixedTrait::new(mag: x1.mag * y1.mag, sign: true));
}
},
// ...
}

Recommendation

Consider determining the resulting output sign by checking the signs of x1 and y1 rather than their magnitudes.

Resolution

The isssue is resolved in commit 0476e45d41d1e89fbaf2810655308ea01da2cc49, considering the sign instead of the magnitude.

6.13 Missing check in calculate_volatility(...)

FileFix commitTypeStatus
summary_stats.cairod5273b6
287959d
InfoFixed

The function calculate_volatility(...) has the following check to ensure that there is enough data available to compute the volatility, as shown below.

assert(start_index != latest_checkpoint_index, 'Not enough data');

However, another condition can lead to insufficient data to compute the volatility, which is when the start_index and end_index are the same.

Recommendation

Consider updating the check to cover the case when start_index == end_index. Alternatively, the existing check can be changed to start_index < end_index to cover both cases.

Resolution

Resolved in commits d5273b673ecc894c80e3f73a369af54c839ec1dc and 287959d51e8107aaec01c09ee0d4b76cb8d128e0, the operation will be reverted if the start_index is higher than the end_index.

6.14 Missing request cancellation logic in cancel_random_request (...)

FileFix commitTypeStatus
randomness.cairoa690ee3
0ac4296
InfoFixed

The cancel_random_request(...) function is currently missing the logic for canceling a request. Specifically, it does not update the request status to CANCELLED as it is indicated in the RandomnessStatusChange event.

fn cancel_random_request(...) {
...
assert(_hashed_value == stored_hash_, "invalid request owner");
assert(requestor_address == caller_address, "invalid request owner");

self
.emit(
Event::RandomnessStatusChange(
RandomnessStatusChange {
requestor_address: requestor_address,
request_id: request_id,
status: RequestStatus::CANCELLED(()) // @audit the function is not updating the request status
}
)
);
...
}

Recommendation

Consider updating the request status to CANCELLED, and implementing any other missing cancellation logic.

Resolution

This issue is resolved on commits

We implemented the missing logic for the cancellation and added tests.

6.15 Multiple publishers can share the same address

When adding or updating a publisher address on the publisher registry, it is possible to use the same address for multiple publisher IDs. Given two publishers, Alice and Bob, it is possible for Alice to set their address to the same as Bob, which will allow Bob to publish data on behalf of Alice as well as his own data. Although this is unlikely to occur, it can potentially lead to hidden centralization risks where one publisher can submit data on behalf of others.

Recommendation

Consider adding input validation to add_publisher(...) and update_publisher_address(...) to ensure the given address is not already used.

Resolution

The issue is resolved in the following commits. We added a function realizing the verification among the publishers’ addresses. If the boolean returned by the function is true, the address is already registered, and the operation is reverted.

6.16 Necessary checks are inadequate

The following functions do not check that their parameters pair_id and on_key already exist in storage. This can lead to non-existing pairs or keys being activated where it should otherwise not be possible.

fn set_pair_id_is_active(ref self: ContractState, pair_id: felt252, is_active: bool) {
assert_only_admin(@self);
self.pair_id_is_active_storage.write(pair_id, is_active); // @audit-issue: Can set active non-existent pair id
return ();
}

fn set_on_key_is_active(ref self: ContractState, on_key: felt252, is_active: bool) {
assert_only_admin(@self);
self.on_key_is_active_storage.write(on_key, is_active); // @audit-issue: Can set active non-existent key
return ();
}

Recommendation

We recommend checking if the relevant data exists in storage before setting it as active.

Resolution

The issue has been addressed in commit afff37b5fdbf41450e03d51c306c274468583601. We have implemented existence checks for the functions set_pair_id_is_active, add_pair, set_on_key_is_active, and add_on_keys. Now, before adding a new pair or on_key, we first verify that it does not already exist. Similarly, when the administrator intends to activate a pair_id or an on_key, we ensure it already exists in the storage.

6.17 Request status handling issues in randomness.cairo contract

FileFix commitTypeStatus
randomness.cairo4d05687InfoFixed

The randomness.cairo contract defines the RequestStatus enum structure to represent the status of a user request.

enum RequestStatus {
UNINITIALIZED: (),
RECEIVED: (),
FULFILLED: (),
CANCELLED: (),
EXCESSIVE_GAS_NEEDED: (),
ERRORED: (),
}

However, there are several issues related to the proper handling of request statuses:

  • A user is able to cancel a request that is in a state different from RECEIVED. This means the request could be already fulfilled or marked as EXCESSIVE_GAS_NEEDED or ERRORED by the admin, and the user will still be able to override this state. This is possible because cancel_random_request(...) function does not check the current request status;
  • Admin can mistakenly fulfill a request that is canceled. That is because submit_random(...) function doesn’t check for the current request status;
  • Contract admin is allowed to update the request status to any value, regardless of the current status. This can lead to unexpected consequences;
  • The admin can update the request status to EXCESSIVE_GAS_NEEDED or ERRORED. However, the code has no logic to handle these cases;

Recommendation

Consider revisiting the statuses implementation and flows within the randomness.cairo contract to ensure that only the expected flows are allowed. Remove any unused status for better code readability.

Resolution

This issue is resolved in commits 4d056879c81d6d4e50df00ee473bd7f3a854cc0a. We added more logics regarding the status management. We removed the unused requests status. An admin is not able anymore to fulfill a canceled request, and is able to upgrade the request status only if it is not canceled or fulfilled (status we considered as definitive). The user cannot cancel a request already fulfilled.

6.18 Undefined divisions may occur in several functions

FileFix commitTypeStatus
scaler.cairo
convert.cairo
metrics.cairo
5e6bd30InfoFixed

The functions below may face undefined divisions, i.e., divisions by zero:

  • scaler.calculate_slope(...);
  • scaler.scale_data(...);
  • convert.div_decimals(...);
  • metrics._sum_volatility(...);

Recommendation

Consider applying the following checks:

fn _sum_volatility(arr: Span<TickElem>) -> Fixed {
...
////////////////////////////////////////////////////
// @audit check if prev_value is greater than zero
////////////////////////////////////////////////////
let numerator_value = FixedTrait::ln(cur_value / prev_value);
let numerator = numerator_value.pow(FixedTrait::new(2 * ONE_u128, false));
let denominator = FixedTrait::new((cur_timestamp - prev_timestamp).into(), false)
/ FixedTrait::new(ONE_YEAR_IN_SECONDS, false);
////////////////////////////////////////////////////
// @audit in case prev_timestamp == cur_timestamp,
// denominator is zero
////////////////////////////////////////////////////
let fraction_ = numerator / denominator;
...
}
fn scale_data(
start_tick: u64, end_tick: u64, tick_array: Span<TickElem>, num_intervals: u32
) -> Array<TickElem> {
///////////////////////////////////////////////////
// @audit check if num_intervals > 1 AND
// if start_tick <= end_tick
///////////////////////////////////////////////////
let interval = (end_tick - start_tick) / (num_intervals.into() - 1);
...
}
fn calculate_slope(x1: Fixed, x2: Fixed, y1: Fixed, y2: Fixed) -> Fixed {
///////////////////////////////////////////////////
// @audit check if x2 > x1
///////////////////////////////////////////////////
(y2 - y1) / (x2 - x1)
}
fn div_decimals(a_price: u128, b_price: u128, output_decimals: u128) -> u128 {
let power = pow(10_u128, output_decimals);
...
///////////////////////////////////////////////////
// @audit check if b_price > 0
///////////////////////////////////////////////////
a_price * power / b_price
}

Resolution

This issue is resolved in commit 5e6bd300af2b1b72287a98129da2d39389d48f30. We added assertions to avoid undefined operations.

6.19 get_implementation_hash(...) returns empty classhash until first upgrade

FileFix commitTypeStatus
src/upgradeable/upgradeable.cairo5242bbaInfoFixed

The Upgradeable contract contains the storage variable class_hash, which stores the class hash of the current contract. This storage variable is updated whenever the upgrade(...) function is called. However, class_hash will remain unset between deployment and the first upgrade, causing get_implementation_hash(...) to return a classhash of zero until the first upgrade.

////////////////////////////////////////////////////////////////////////////
// @audit Storage variable `class_hash` is only written to after an upgrade
////////////////////////////////////////////////////////////////////////////
fn upgrade(ref self: ContractState, new_class_hash: ClassHash) {
assert(!new_class_hash.is_zero(), 'Class hash cannot be zero');
starknet::replace_class_syscall(new_class_hash).unwrap();
self.class_hash.write(new_class_hash);
self.emit(Upgraded { class_hash: new_class_hash });
}

//////////////////////////////////////////////////////////////////
// @audit After deployment this will return zero until upgrade
//////////////////////////////////////////////////////////////////
fn get_implementation_hash(self: @ContractState) -> ClassHash {
self.class_hash.read()
}

Recommendation

Consider initializing the Upgradeable contract with its current class hash. Alternatively, since get_implementation_hash(...) is only used externally, it could be removed, and the class hash can be queried from a block explorer such as Voyager instead.

Resolution

The issue is resolved in the commit 5242bbaa2a4c2b3c791ac566977bfd9ffccc0122. We decided to simply remove the function.

6.20 Control Coupling in function pairwise_1D(...)

FileFix commitTypeStatus
src/operations/time_series/metrics.cairo79f96d5Best PracticesFixed

The function pairwise_1D(...) receives the operation as an argument (SUBTRACTION or MULTIPLICATION). Control coupling refers to a situation where one module (or component) controls the behavior of another module by passing information about what to do, typically in the form of control flags, parameters, or other control-related data. This form of coupling occurs when one module influences the execution flow or behavior of another module by providing information on how to perform a particular operation.

Control coupling can be contrasted with data coupling, where modules communicate primarily by passing data rather than control information. In well-designed software, minimizing control and data coupling is often considered a good practice. It enhances the modularity, reusability, and maintainability of the code.

Reducing control coupling helps to make modules more independent and less reliant on the internal details of each other. This independence makes modifying and maintaining individual modules easier without affecting the entire system. The code with audit comments is presented below.

fn pairwise_1D(operation: Operations, x_len: u32, x: Span<Fixed>, y: Span<Fixed>) -> Span<Fixed> {
//We assume, for simplicity, that the input arrays (x & y) are arrays of positive elements
let mut cur_idx: u32 = 0;
let mut output = ArrayTrait::<Fixed>::new();
match operation {
Operations::SUBTRACTION(()) => {
loop {
if (cur_idx >= x_len) {
break ();
}
let x1 = *x.get(cur_idx).unwrap().unbox();
let y1 = *y.get(cur_idx).unwrap().unbox();
if x1 < y1 {
output.append(FixedTrait::new(mag: y1.mag - x1.mag, sign: true));
} else {
output.append(FixedTrait::new(mag: x1.mag - y1.mag, sign: false));
}
cur_idx = cur_idx + 1;
};
},
Operations::MULTIPLICATION(()) => {
loop {
if (cur_idx >= x_len) {
break ();
}
let x1 = *x.get(cur_idx).unwrap().unbox();
let y1 = *y.get(cur_idx).unwrap().unbox();
if x1.mag == y1.mag {
output.append(FixedTrait::new(mag: x1.mag * y1.mag, sign: false));
} else {
output.append(FixedTrait::new(mag: x1.mag * y1.mag, sign: true));
}
cur_idx = cur_idx + 1;
};
},
}
output.span()
}

Recommendation

We recommend breaking the function into two separate functions, one for performing subtraction and the other for performing multiplication.

Resolution

This issue is resolved in commit 79f96d520c371bfd5223fc50b35db3f89216a4ba. Since the execution is different according to the operation parameter, we just implemented two separate functions instead.

6.21 Dead code

FileFix commitTypeStatus
src/*6ce4288
82cca31
5242bba
Best PracticesFixed

The codebase contains unused code, affecting overall readability and quality. A list of files and their unused declarations are shown below:

src/entry/structs.cairo
const MEDIAN
const BOTH_TRUE
enum PossibleEntryStorage
struct GenericEntryStorage
struct FetchCheckpoint

src/oracle/oracle.cairo
struct SubmittedOptionEntry
fn aggregation_into_u8
fn add_pair (private function only)

src/compute_engines/summary_stats/summary_stats.cairo
const SCALED_ARR_SIZE
fn _make_scaled_array:
test
first
first_t

src/operations/time_series/metrics.cairo
fn extract_value:
cur_idx
fn sum_tick_array:
cur_idx
fn sum_array:
cur_idx

Recommendation

Consider removing the unused code shown above.

Resolution

This issue is resolved in commits (Part of the dead code was already handled while solving other audit findings):

6.22 Duplicate code in mul_decimals(...) function

FileFix commitTypeStatus
convert.cairo779c574Best PracticesFixed

The function mul_decimals(...) contains duplicate assert statements, which are shown below:

fn mul_decimals(...) -> ... {
...
assert(power <= MAX_POWER, 'Conversion overflow');
assert(a_price <= MAX_POWER, 'Conversion overflow');

assert(power <= MAX_POWER, 'Conversion overflow');
assert(a_price <= MAX_POWER, 'Conversion overflow');
...
}

Recommendation

Consider removing the unnecessary code to improve readability.

Resolution

This issue is resolved in commit 779c574d531fd404a6ca763bac54b8a2c0d0a029, by removing the duplicate code.

6.23 Hash implementation TupleSize4LegacyHash has an incorrect name

FileFix commitTypeStatus
src/oracle/oracle.cairoc514164Best PracticesFixed

To support a mapping that takes a tuple of five elements as a key, a custom implementation for LegacyHash has been written, which can hash such a tuple into one felt252. This implementation has been incorrectly named TupleSize4LegacyHash. It should be named TupleSize5LegacyHash instead.

Recommendation

Consider correcting the name of the custom LegacyHash implementation to TupleSize5LegacyHash.

Resolution

Resolved in commit c5141649d45264bdd7f8206ccab76634cad3d6fd. We changed the previous implementation for TupleSize5LegacyHash, since we implemented it for 5 elements.

6.24 Inconsistent type casting approach for u8 and AggregationMode

FileFix commitTypeStatus
src/oracle/oracle.cairo72bd410Best PracticesFixed

Type casting between AggregationMode and u8 is supported to allow packed checkpoint storage reads and writes. The type casting approach differs depending on whether the conversion is to or from an AggregationMode type. When converting AggregationMode to u8, the into trait is used:

impl AggregationModeIntoU8 of Into<AggregationMode, u8> {
fn into(self: AggregationMode) -> u8 {
match self {
AggregationMode::Median(()) => 0_u8,
AggregationMode::Mean(()) => 1_u8,
AggregationMode::Error(()) => 150_u8,
}
}
}

However, when converting u8 to AggregationMode, a regular function is used instead:

fn u8_into_AggregationMode(value: u8) -> AggregationMode {
if value == 0_u8 {
AggregationMode::Median(())
} else if value == 1_u8 {
AggregationMode::Mean(())
} else {
AggregationMode::Error(())
}
}

Recommendation

Consider implementing the conversion from u8 to AggregationMode as an into method to improve consistency and composability, should this type be used in other contracts.

Resolution

Resolved in commit 72bd41086c2af243abc11c76bc67648d01ac4806. We implemented try_into for the aggregation mode into u8 conversion and the into for the u8 into aggregation mode.

6.25 Inconsistent use of getter function

FileFix commitTypeStatus
src/oracle/oracle.cairo5242bbaBest PracticesFixed

The oracle contract contains the function get_publisher_registry_address(...), which is used internally and externally. However, some functions use the getter, and others read directly from the storage variable.

// @audit Direct storage read
fn update_publisher_registry_address(...) {
...
let old_publisher_registry_address = self
.oracle_publisher_registry_address_storage
.read();
...
}

// @audit Getter function used
fn validate_sender_for_source<...>(...) {
let publisher_registry_address = IOracleABI::get_publisher_registry_address(self);
// ...
}

Recommendation

Consider retrieving the publisher registry address in a consistent manner across all functions.

Resolution

This issue is resolved in commit 5242bbaa2a4c2b3c791ac566977bfd9ffccc0122.

6.26 Incorrect comments

FileFix commitTypeStatus
src/*6a0b2e3Best PracticesFixed

There are several comments which contain incorrect information or contain typos, which are listed below:

  • Oracle.get_all_sources has a comment stating it returns a span of sources when an array is returned instead;
  • Oracle.get_all_entries is missing an @returns NatSpec comment;
  • PublisherRegistry.get_publisher_address has a typo for the word "publisher";
  • Randomness.cancel_random_request has a revert message "invalid request owner", while it should be "request hash != stored hash";

Recommendation

Consider adding the missing comments and fixing the incorrect ones.

Resolution

This issue is resolved in commit 6a0b2e3a4db9de42a75db71e521fb664e513fe6f. We updated and corrected the wrong comments.

6.27 Shadowed arrays are unused

FileFix commitTypeStatus
src/oracle/oracle.cairo8e1ff20Best PracticesFixed

The functions get_data_for_sources(...) and get_data_entries(...) define an array immediately shadowed by a span with the same name returned from an internal function call. In both of these cases, the original array is never used. A snippet from get_data_for_sources is shown below:

fn get_data_for_sources(...) -> PragmaPricesResponse {
/////////////////////////////////////////////////////////
// @audit `entries` is shadowed immediately and not used
/////////////////////////////////////////////////////////
let mut entries = ArrayTrait::<PossibleEntries>::new();

let (entries, last_updated_timestamp) = IOracleABI::get_data_entries_for_sources(
self, data_type, sources
);
// ...
}

Recommendation

Consider removing the shadowed arrays in get_data_for_sources and get_data_entries to reduce unused code and improve readability.

Resolution

This issue is resolved in commit 8e1ff20847cdb1bb52758a43007a34b066b14ab2. We just removed the unused code.

6.28 Unnecessary iteration counter

FileFix commitTypeStatus
src/operations/time_series/metrics.cairo5242bbaBest PracticesFixed

The functions extract_value, sum_tick_array and sum_array all define an unused variable cur_idx, as shown below:

/////////////////////////////////////////////////////////////////
// @audit Unused variable `cur_idx`
// Same issue applies to `sum_tick_array` and `sum_array`
/////////////////////////////////////////////////////////////////
fn extract_value(mut tick_arr: Span<TickElem>) -> Array<Fixed> {
let mut output = ArrayTrait::<Fixed>::new();
let mut cur_idx = 0; // @audit-issue: Unnecessary variable.
// ...
}

Recommendation

Consider removing the unused variables to improve code clarity.

Resolution

This issue is resolved in commit 5242bbaa2a4c2b3c791ac566977bfd9ffccc0122. We deleted the unnecessary variable.

6.29 Unnecessary local variable assignment

FileFix commitTypeStatus
src/oracle/oracle.cairo5242bbaBest PracticesFixed

The function get_data_with_USD_hop(...) declares local variables base_dt and quote_dt inside the FutureEntry branch of the match statement. These variable declarations are unnecessary as the assigned value can be returned directly, similar to what is done in the SpotEntry branch.

Recommendation

We recommend to directly return the values using idiomatic syntax to make the code more concise and readable.

Option::Some(expiration) => {
- let base_dt = DataType::FutureEntry((base_pair_id, expiration));
- let quote_dt = DataType::FutureEntry((quote_pair_id, expiration));
(
- base_dt,
- quote_dt,
+ DataType::FutureEntry((base_pair_id, expiration)),
+ DataType::FutureEntry((quote_pair_id, expiration)),
self.oracle_currencies_storage.read(quote_currency_id)
)
},

Resolution

This issue is resolved in commit 5242bbaa2a4c2b3c791ac566977bfd9ffccc0122, following the recommendation.

6.30 Unnecessary storage read

FileFix commitTypeStatus
src/publisher_registry/publisher_registry.cairo6e45950Best PracticesFixed

The function add_source_for_publisher(...) performs an unnecessary storage read by defining the cur_idx and then re-reading later in the function. This is shown in the code snippet below:

fn add_source_for_publisher(...) {
...
let cur_idx = self.publishers_sources_idx.read(publisher); // @audit Defined here 1st
if (cur_idx == 0) {
// ...
} else {
// ...
let cur_idx = self.publishers_sources_idx.read(publisher); // @audit Shadowed here 2nd
...
}
}

Recommendation

Consider removing the unnecessary storage read for cur_idx.

Resolution

This issue is resolved in commmit 6e45950699fd652ba7472da553e8dc8b83b81056, by deleting the unnecessary index definition.

6.31 Unnecessary use of into in some functions

FileFix commitTypeStatus
src/oracle/oracle.cairo5242bbaBest PracticesFixed

The functions publish_data(...) and build_sources_array(...) unnecessarily use the into trait, where both the variable and the target type are the same. Snippets of both functions are shown below:

//////////////////////////////////////////////////
// @audit Function `publish_data`
// All fields are already the correct type
//////////////////////////////////////////////////

let element = EntryStorage {
timestamp: spot_entry.base.timestamp.into(),
volume: spot_entry.volume.into(),
price: spot_entry.price.into()
};
//////////////////////////////////////////////////
// @audit Function `build_sources_array`
// `idx` is aready the correct type
//////////////////////////////////////////////////

let new_source = self
.oracle_sources_storage
.read((pair_id, SPOT, idx.into(), 0));

Recommendation

As shown above, consider removing the unnecessary into casts. Note that for each of these functions, there are three occurrences of the shown snippets. We have only shown SPOT, but there is FUTURE and GENERIC too.

Resolution

This issue is resolved in commit 5242bbaa2a4c2b3c791ac566977bfd9ffccc0122, removing the unnecessary conversion.

6.32 Unnecessary variable redefinition inside a loop

FileFix commitTypeStatus
summary_stats.cairof634c4cBest PracticesFixed

The oracle_dispatcher and offset variables are unnecessarily redefined in each iteration of the loop, even though their values are constant during the execution.

fn _make_scaled_array(...) -> Array<TickElem> {
let mut tick_arr = ArrayTrait::<TickElem>::new();
let mut idx = 0;
loop {
// @audit `oracle_dispatcher` and `offset` are redefined in each iteration
let oracle_dispatcher = IOracleABIDispatcher { contract_address: oracle_address };
let offset = latest_checkpoint_index - num_datapoints;
// ...
};
// ...
}

Recommendation

Consider moving the declaration of oracle_dispatcher and offset outside the loop.

Resolution

This issue is resolved in commit f634c4c1e3aecdcad0a758351e1b992860abd027, following the recommendation.

6.33 Unnecessary variable shadowing

FileFix commitTypeStatus
src/compute_engines/yield_curve/yield_curve.cairo5242bbaBest PracticesFixed

The function set_future_expiry_timestamp_is_active(...) defines the variable old_expiry, which is immediately shadowed by a duplicated line that declares the same data to the same variable name.

fn set_future_expiry_timestamp_is_active(...) {
// ...
let old_expiry = IYieldCurveABI::get_future_expiry_timestamp_expiry(
@self, pair_id, future_expiry_timestamp
);
let old_expiry = IYieldCurveABI::get_future_expiry_timestamp_expiry(
@self, pair_id, future_expiry_timestamp
);
// ...
}

Recommendation

Consider removing the duplicated line.

Resolution

This issue is resolved in commit 5242bbaa2a4c2b3c791ac566977bfd9ffccc0122. We removed the duplicate.

6.34 Unrequired overhead for computing the variance

FileFix commitTypeStatus
src/operations/time_series/metrics.cairo59a7856Best PracticesFixed

The function variance(...) computes the variance of the dataset. To compute the variance of a dataset, first, we must find the mean by summing up all values and dividing by the number of data points. This is performed by the function mean(...).

Next, we must calculate the squared differences between each data point and the mean. To achieve this, the code creates an array having the same length as the original dataset using the function fill_1d(...), as shown below.

/// Fills an array with one `value`
fn fill_1d(arr_len: u32, value: u128) -> Array<Fixed> {
let mut cur_idx = 0;
let mut output = ArrayTrait::new();
loop {
if (cur_idx >= arr_len) {
break ();
}
output.append(FixedTrait::new(mag: value, sign: false));
cur_idx = cur_idx + 1;
};
output
}

The instantiation of a new array with identical values at each position is deemed an unnecessary overhead.

Recommendation

Compute the difference between each element of the dataset and the mean without instantiating this new array with identical values at each position.

Resolution

The issue has been resolved in the commit 59a78563561e58bcecaab6053300a2b5c35a542b. We modified the second parameter of the pairwise_1D_sub function. Rather than accepting a Span of elements, it now takes a single element. This element is then subtracted from an array of elements x. By doing so, we were able to remove fill_1D.

6.35 Unused function parameters

FileFix commitTypeStatus
src/*7214f51
d4e1fb9
Best PracticesFixed

The codebase contains some functions with unused parameters, which are listed below:

src/compute_engines/summary_stats/summary_stats.cairo
_make_scaled_array -> start_tick

src/compute_engines/yield_curve/yield_curve.cairo
assert_only_admin -> self
change_decimals -> self

src/randomness/randomness.cairo
assert_only_admin -> self
submit_random -> block_hash

Recommendation

Consider removing these parameters from the above functions to improve code clarity and readability.

Resolution

This issue is resolved in commits 7214f51f7b1801fedeadacbfafe874e3b30019c3 and d4e1fb90d7dcb5242c934770cc288cba5252e2be. We removed all the unnecessary function parameters left after previous code changes.

6.36 Unused imports

FileFix commitTypeStatus
src/*9c0b4aaBest PracticesFixed

The codebase contains unused imports affecting overall readability and code quality. A list of files with unused imports is shown below:

src/compute_engines/summary_stats/summary_stats.cairo
cubit::f128::types::fixed::Fixed
result::ResultTrait
debug::PrintTrait
starknet::get_caller_address
zeroable::Zeroable
option::OptionTrait
result::ResultTrait
traits::Into
traits::TryInto
pragma::operations::time_series::scaler::scale_data

src/operations/time_series/structs.cairo
integer::u32

Recommendation

Consider removing the unused imports shown above.

Resolution

This issue is resolved in commit 9c0b4aaefa2edd0ceee4f76214060528cd9fd963. We removed the unnecessary imports(the debug::PrintTrait was removed for all contracts in another commit).

6.37 Unused parameters in function get_future_spot_pragma_source_- key(...)

FileFix commitTypeStatus
yield_curve.cairoa6f92c2Best PracticesFixed

The function get_future_spot_pragma_source_key(...) does not use the parameters pair_id and future_expiry_timestamp in the contract YieldCurve.

fn get_future_spot_pragma_source_key(
self: @ContractState, pair_id: felt252, future_expiry_timestamp: u64
) -> felt252 {
let future_spot_pragma_source_key = self.future_spot_pragma_source_key_storage.read();
return future_spot_pragma_source_key;
}

Recommendation

Consider removing them from the function.

Resolution

The issue has been resolved with commit a6f92c2c87a7f84aaee26cbd4c1a503fd0c39634. In this update, we removed remnants of a previous implementation that were no longer needed.

6.38 Use the same value while converting types

FileFix commitTypeStatus
src/oracle/oracle.cairo72bd410Best PracticesFixed

The enum AggregationMode has three variants: Median, Mean, and Error. The Error variant represents failed conversions between u8 where the provided integer is not associated with an aggregation variant, and if the aggregation mode is Error, then the protocol panics, as shown below:

fn aggregate_entries<...>(...) -> u128 {
// ...
match aggregation_mode {
// ...
AggregationMode::Error(()) => {
panic_with_felt252('Wrong aggregation mode');
0
}
}
}

Instead of having a native Error variant for AggregationMode, a better approach would be to use the try_into trait when converting from a u8 to AggregationMode, where the try_into returns an Option::None() for an invalid u8. This more idiomatic approach suits the Cairo language and will ensure that conversion errors are handled at conversion rather than at some later point in the code.

Recommendation

Consider removing the Error variant from AggregationMode and using try_into to handle conversions from u8 to AggregationMode instead.

Resolution

This issue is resolved in commit 72bd41086c2af243abc11c76bc67648d01ac4806. We implemented try_into for the aggregation mode into u8 conversion and for the u8 into aggregation mode.

7

Documentation Evaluation

Software documentation refers to the written or visual information that describes the functionality, architecture, design, and implementation of software. It provides a comprehensive overview of the software system and helps users, developers, and stakeholders understand how the software works, how to use it, and how to maintain it. Software documentation can take different forms, such as user manuals, system manuals, technical specifications, requirements documents, design documents, and code comments. Software documentation is critical in software development, enabling effective communication between developers, testers, users, and other stakeholders. It helps to ensure that everyone involved in the development process has a shared understanding of the software system and its functionality. Moreover, software documentation can improve software maintenance by providing a clear and complete understanding of the software system, making it easier for developers to maintain, modify, and update the software over time. Smart contracts can use various types of software documentation. Some of the most common types include:

  • Technical whitepaper: A technical whitepaper is a comprehensive document describing the smart contract’s design and technical details. It includes information about the purpose of the contract, its architecture, its components, and how they interact with each other;
  • User manual: A user manual is a document that provides information about how to use the smart contract. It includes step-by-step instructions on how to perform various tasks and explains the different features and functionalities of the contract;
  • Code documentation: Code documentation is a document that provides details about the code of the smart contract. It includes information about the functions, variables, and classes used in the code, as well as explanations of how they work;
  • API documentation: API documentation is a document that provides information about the API (Application Programming Interface) of the smart contract. It includes details about the methods, parameters, and responses that can be used to interact with the contract;
  • Testing documentation: Testing documentation is a document that provides information about how the smart contract was tested. It includes details about the test cases that were used, the results of the tests, and any issues that were identified during testing;
  • Audit documentation: Audit documentation includes reports, notes, and other materials related to the security audit of the smart contract. This type of documentation is critical in ensuring that the smart contract is secure and free from vulnerabilities.

These types of documentation are essential for smart contract development and maintenance. They help ensure that the contract is properly designed, implemented, and tested, and they provide a reference for developers who need to modify or maintain the contract in the future.

8

Remarks & Test Suite

Pragma has sufficient documentation on the website https://docs.pragmaoracle.com/ and inline comments. Moreover, the client provided additional detailed documentation for the audit team. During the audit process, the audit team remained in constant communication with the client.

Test suite
63Tests passed0Failed

The complete test output is in the full report.

As auditors, we recommend that any changes or updates made to the audited codebase undergo a re-audit or security review to address potential vulnerabilities or risks introduced by the modifications. By conducting a re-audit or security review of the modified codebase, you can significantly enhance the overall security of your system and reduce the likelihood of exploitation. However, we do not possess the authority or right to impose obligations or restrictions on our clients regarding codebase updates, modifications, or subsequent audits. Accordingly, the decision to seek a re-audit or security review lies solely with you.

This report is based on the scope of materials and documentation provided by you to Nethermind in order that Nethermind could conduct the security review outlined in 1. Executive Summary and 2. Audited Files. The results set out in this report may not be complete nor inclusive of all vulnerabilities. Nethermind has provided the review and this report on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. This report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on this report in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, Nethermind disclaims any liability in connection with this report, its content, and any related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. Nethermind does not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and Nethermind will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE.