Download audit report
This document presents the security review performed by Nethermind on the Prop-House protocol by Nouns DAO. Prop-House is a novel approach to community-based funding, where each community can have a "house" from which many funding "rounds" can be created. During a funding round, users can submit proposals which are then voted by the community. There are two types of rounds currently supported; timed rounds (where winners are calculated after some period of time) and infinite rounds (where winners are calculated at an arbitrary point in time decided by the round creator). Voting power can be calculated in different ways through voting strategies, which at the time of this audit included token amounts held and pre-determined weighting via a merkle tree. There can be multiple winners for a given round, and it is possible for assets to be distributed to winners. Prop-House leverages the cheaper execution cost of Starknet for all voting logic and winner calculations, where the final winner results are sent to Ethereum.
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.
| Audit assessment | |
| Audit Type | Security Review |
| Initial Report | Jul. 26, 2023 |
| Response from Client | - |
| Final Report | - |
| Methods | Manual Review, Automated Analysis |
| Repository | https://github.com/Prop-House/prop-house-monorepo/ |
| Commit Hash (Audit) | c3f5ebfe91 |
| Commit Hash (Fix Review) | 6c67d0c032 |
| Documentation | README.md |
| Documentation Assessment | High |
| Test Suite Assessment | Solidity: High, Cairo: Low |
Findings by severity
The Prop-House protocol can be split into the Ethereum and Starknet layers. A user will create a round on the Ethereum layer, where this round data is then sent to Starknet. Prop-House utilizes the cheaper execution cost of Starknet to make the voting process and winner calculations more affordable. Users will then create and vote on proposals on Starknet before winners are chosen, and a Merkle root containing winner information is returned back to Ethereum. Winners can then prove their existence in the Merkle tree on Ethereum and claim rewards. Below, we show the contract interaction graphs for each layer and describe each contract and its purpose.
PropHouse: Main entrypoint which users interact with. Allows anyone to deploy a new house, create and/or deposit to a round.
Round: Can be a timed round or infinite round. Once the round is created, users can submit proposals on Starknet. When a round is finalized, a Merkle tree of the winners is passed from Starknet back to this contract, where winners can claim assets.
Manager: Tracks valid house and round implementations, which can be cloned by the PropHouse contract.
CommunityHouse: A house is owned by one address, and any number of addresses can be assigned a creator pass. Users with creator passes can create rounds for that given house.
CreatorPassIssuer: Tracks the assigned creator passes for all houses. Can add or remove passes from an address, also can query if a particular address holds a pass.
Messenger: Wrapper contract for making calls to the Starknet contract for message sending and cancellation. Message consumption is handled directly without this contract.
Asset: An external asset used for round asset deposits. Can be ERC20, ERC721, ERC1155 or Ether.
Render logic contracts: These contracts are exclusively used for tokens with a uri() function, and exist to help render the token URI.
Starknet Contract: The Starknet contract on Ethereum which is used to communicate with the Starknet chain.
Timed Round: This round type can be broken down into three separate stages. First is the proposal submission stage, where users can submit proposals to the round, but no votes can be cast yet. Second, is the voting phase, where votes can be made on the proposals. After these two stages, there is the finalization stage, where the proposals with the most votes are compiled into a Merkle tree that is sent to the matching round contract on the Ethereum layer.
Infinite Round: This round type doesn’t have a specified end. Instead, only the deployer of the round is able to start the finalization process. While the round has not yet been finalized, users can vote in favor or against proposals. If a certain threshold of "for" or "against" votes is met, then a proposal can be considered accepted or rejected. In the case of an accepted proposal, it is added to the Merkle tree that will eventually be sent to the matching round contract on the Ethereum layer.
Transaction Auth Strategy: Given a commit hash containing relevant information for a voting/proposal call to a round which has been sent from the Ethereum layer, make a call to the Starknet round contract with the same arguments used to derive the hash. This can be executed by any account on Starknet and allows for Ethereum users to vote on Starknet without the need for their own Starknet wallet.
Signature Auth Strategy: Given a message signed by an EOA on Ethereum, if the signature can be verified to be correct, then execute a call to interact with the round on behalf of the user who signed the message.
Round Factory: Receives messages from Ethereum to create new rounds and finalize them. New rounds are created using the REGISTER_ROUND selector and rounds are finalized or canceled using the ROUTE_CALL selector.
Ethereum Execution Strategy: This smart contract should be paired with a round factory. It will use information from the round factory to relay information from any round to the equivalent round on the Ethereum layer. Starknet to Ethereum communication would happen when a round is finalized or when winners are being processed in an infinite round.
Strategy Registry: Acts as universal storage for all defined governance strategies.
Round Dependency Registry: This contract stores immutable dependencies such as authentication and execution strategies for rounds. It uses a combination of the origin chain ID and round type as the dependency key, which allows the Starknet rounds to service many origin chains. Rounds can only read dependencies from this contract if they have been permanently locked.
Vanilla: This is for testing only, all users have a power of 1.
Allowlist: A predefined list of accounts with specified voting weights.
Ethereum Based: Uses Herodotus V1 to determine governance power using ERC20 or ERC721 balance on the Ethereum layer.
Ethereum Block Registry: This contract maps timestamps to Ethereum block numbers by reading from the Herodotus V1 headers store.
Facts Registry: Used to query Ethereum storage from Starknet.
Starknet: This is not a real contract, but exists on the diagram to represent information that travels from Starknet to Ethereum.
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:
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:
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 / Likelihood | Low | Medium | High |
| High | Medium | High | Critical |
| Medium | Low | Medium | High |
| Low | Info / Best Practices | Low | Medium |
| Undetermined | Undetermined | Undetermined | Undetermined |
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.
StorageSlotIntoU256 causes all L1 storage queries revert| File | Fix commit | Type | Status |
single_slot_proof.cairo | e231305 | High | Fixed |
The struct type StorageSlot is used in the function get_slot_value(...) to represent an Ethereum storage slot. It contains four felt252 values representing 64 bits of data each. The struct implements the TryInto trait allowing the struct representation of the storage slot to be converted into a u256 type instead. The function is shown below:
impl StorageSlotIntoU256 of Into<StorageSlot, u256> {
fn into(self: StorageSlot) -> u256 {
let word_1_shifted = self.word_1 * UINT64_MAX_FELT;
let word_3_shifted = self.word_3 * UINT64_MAX_FELT;
let low = (word_3_shifted + self.word_4).try_into().unwrap();
let high = (word_1_shifted + self.word_2).try_into().unwrap();
u256 { low, high }
}
}When converting from StorageSlot to u256 the first and third entries in the struct are left-shifted 64 bits by multiplying with UINT64_MAX_FELT, which has the value 0xffffffffffffffff, or 2**64-1. This does not result in the correct shift output however. The first and third entries should be multiplied by 2**64 instead of 2**64-1. Consider the following example below:
// Incorrect left-shift by multiplying with 2^64-1
0xaa * 0x0ffffffffffffffff = 0xa9ffffffffffffff56
// Correct left-shift by multiplying with 2^64
0xaa * 0x10000000000000000 = 0xaa0000000000000000This causes all conversions from StorageSlot to u256 to result in an incorrect value, which will cause the following assert to fail on every call, preventing any transactions that involve L1 storage queries from executing.
// Ensure the slot proof is for the correct slot
let valid_slot = get_slot_key(slot_index, user);
assert(slot.into() == valid_slot, 'SSP: Invalid slot');Recommendation
Change the shift calculation to use 2**64 instead of 2**64-1.
Resolution
Fixed in e231305. The shift calculation now uses 2**64.
| File | Fix commit | Type | Status |
infinite/round.cairo | d1c66f6 | High | Fixed |
For infinite rounds in the function _cast_votes_on_proposal(...), voting power is spent according to the user parameters. While there are checks to ensure that the user has enough voting power to spend, the spent_voting_power storage variable is not updated after voting. The unchanged spent_voting_power is then written back to storage. This allows users to infinitely vote on a proposal in an infinite round without spending any votes. A snippet from the code is shown below:
fn _cast_votes_on_proposal(...) {
// ...
let mut spent_voting_power = _spent_voting_power::read((voter, proposal_id));
// `spent_voting_power` is not updated or changed
// ...
////////////////////////////////////////////////////////////////////////////////////////////
// @audit-issue The spent voting power is rewritten back to storage with no changes made
// Spent voting power never changes, users effectively have unlimited votes
////////////////////////////////////////////////////////////////////////////////////////////
_spent_voting_power::write((voter, proposal_id), spent_voting_power);
// ...
}Recommendation
Ensure that the spent_voting_power storage variable is updated to correctly track the amount of spent voting power per voter.
Resolution
Fixed in d1c66f6. The spent_voting_power storage variable is now correctly updated.
| File | Fix commit | Type | Status |
ethereum_block.cairo | bc63398 | High | Fixed |
The function get_eth_block_number(...) can retrieve an Ethereum block number for a given timestamp, using Herodotus to as the oracle for Ethereum block numbers. If this function is called with a timestamp that has already been stored, it returns that data. Otherwise, it will query Herodotus for the latest block number and associate that value with the provided timestamp. The function is shown below:
fn get_eth_block_number(timestamp: felt252) -> felt252 {
let number = _timestamp_to_eth_block_number::read(timestamp);
if number.is_non_zero() {
number
} else {
//////////////////////////////////////////////////////////////////////////////////
// @audit-issue If timestamp not associated with a block, current block is used
// A timestamp in the past or future can be linked to current block
//////////////////////////////////////////////////////////////////////////////////
let number = IL1HeadersStoreDispatcher {
contract_address: _l1_headers_store::read()
}.get_latest_l1_block();
_timestamp_to_eth_block_number::write(timestamp, number);
number
}
}Since on a call with a new timestamp argument the latest block number is used, if a timestamp argument from the past or future is used, it will still associate that timestamp with the current block number. This function is externally reachable through the function shown below, so any user can access this:
#[external]
fn get_eth_block_number(timestamp: felt252) -> felt252 {
EthereumBlockRegistry::get_eth_block_number(timestamp)
}This function is used to determine Ethereum ERC20 token balances for governance style proposal voting, which an attacker may take advantage of to affect voting and round outcomes. Since the voting strategies and snapshot timestamps are known when a round is deployed, an attacker could accumulate tokens to affect their voting power for a few blocks, and then call get_eth_block_number(...) with the timestamp matching the snapshot timestamp on L2. The attacker could then sell tokens to diminish their exposure, but maintain their high voting power since the future timestamp to be used will point to their current amount held. This could also be used to reduce the votes of other users, as any tokens that other users acquire to gain more voting power after the attacker has maliciously called get_eth_block_number(...) will not be used for vote weighting.
Recommendation
Consider preventing the function get_eth_block_number(...) from being called by any user, so the function can only be called internally with safe timestamp values retrieved from L1.
Resolution
Addressed in bc63398. This commit removes the ability to populate the block for a future timestamp. An attacker can still populate a timestamp with a block in the registry between the timestamp in question and the first time get_eth_block_number is called by a round, but the risk is greatly reduced.
Nethermind comment: After further investigation there is no risk of the protocol reading a past timestamp that has not already been written to. Therefore reading past timestamps are not a concern and since future timestamps have been addressed, this issue can be considered fixed as all risks have been addressed.
| File | Fix commit | Type | Status |
timed/round.cairo | 14cdba6 | Medium | Fixed |
In the propose(...) method on timed rounds, if the config.proposal_threshold is zero then any user can submit any number of proposals. The propose function is shown below:
fn propose(
proposer: EthAddress,
metadata_uri: Array<felt252>,
used_proposing_strategies: Array<UserStrategy>,
) {
// ...
//////////////////////////////////////////////////////
// @audit-issue No limit to the number of proposals
//////////////////////////////////////////////////////
assert(
cumulative_proposition_power >= config.proposal_threshold.into(),
'TR: Proposition power too low'
);
let proposal_id = _proposal_count::read() + 1;
// ...
_proposal_count::write(proposal_id);
// ...
}During round finalization, all proposals are passed through multiple loops. A malicious actor could propose a large amount of proposals to cause the Cairo step limit to be reached before execution can finish.
Recommendation
Consider limiting the number of proposals that can be created by each user.
Resolution
Fixed in 14cdba6. Rather than retrieve and sort all active proposals during finalization, the top winner_count proposals are stored in a min heap, which is updated following each vote. This socializes the cost of maintaining an up-to-date list of the leading proposals. During finalization, we loop through the min heap, popping the root proposal in each iteration to efficiently determine winners. The min heap is packed into storage, ensuring that vote costs remain reasonable. Even with 25 winners, only four storage slots are used.
| File | Fix commit | Type | Status |
starknet/src/rounds/* | 21cede3 | Medium | Fixed |
When a proposal is cancelled, its votes are not returned and they remain spent. It is possible for a malicious user who has a highly voted proposal and holds unspent voting power to cancel their proposal, removing all associated votes from the round winner calculations. This effectively increases the weighting of all unspent voting power, including the malicious user’s.
This attack approach can be applied to a round with multiple winners. If enough votes can be removed upon cancellation of the proposal and the attacker’s unspent voting power is high enough, it is possible for the attacker to create multiple new proposals and use the increased voting weight to ensure wins for these multiple proposals. When these conditions are met, the proposer can extract more value out of the round than the expected single award.
An example scenario is presented below:
A round exists where there is 1000 total voting power across all possible voters. Alice has a proposal which has been very well received with 500 votes. Of the remaining 500 voting power, Alice holds 250 unspent, and the other 250 votes are spent across 10 proposals at 25 votes each. There can be five award winners, winning 5 ETH each. Alice has the highest voted proposal and is guaranteed to win 5 ETH. However if she cancels her proposal the 500 votes on her proposal are gone, meaning that the winner calculations will only be based on the 500 remaining voting power, 250 of which still belongs to Alice as unspent, and the remaining spent. Alice creates five proposals and distributes 50 votes each, so now all of her proposals have a higher vote than the others at 25 each. When the round is finalized Alice will receive 25 ETH in awards, instead of the expected 5 ETH.
Recommendation
Consider preventing proposals from being cancelled during the voting period.
Resolution
Fixed in 21cede3. Proposals can no longer be cancelled during the voting period.
| File | Fix commit | Type | Status |
infinite/round.cairo | c604fc6 | Medium | Fixed |
In the function _approve_proposal(...) when when adding a new proposal to the incremental Merkle tree, the current sub-tree is read from storage and a new leaf containing the approved proposal is appended to the tree. However, the resulting sub-tree with the appended leaf is not written back to storage. After inserting the first leaf, this causes all subsequent entries to produce incorrect Merkle roots. The function is shown below:
fn _approve_proposal(proposal_id: u32, ref proposal: Proposal) {
// ...
//////////////////////////////////////////////////////////////////////////
// @audit-note: The incremental tree gets created here using the previous
// subtree information
//////////////////////////////////////////////////////////////////////////
let mut incremental_merkle_tree = IncrementalMerkleTreeTrait::<u256>::new(
MAX_WINNER_TREE_DEPTH, winner_count, _read_sub_trees_from_storage(),
);
//////////////////////////////////////////////////////////////////////////
// @audit-note: The hash of the leaf is calculated
//////////////////////////////////////////////////////////////////////////
let leaf = _compute_leaf(proposal_id, proposal);
//////////////////////////////////////////////////////////////////////////
// @audit-issue: The new root is then calculated, but the new sub tree is
// not stored back in permanent storage.
//////////////////////////////////////////////////////////////////////////
_winner_merkle_root::write(incremental_merkle_tree.append_leaf(leaf));
// ...
}If there is more than one approved proposal in the tree, this will cause the incremental Merkle tree root to be corrupted, and no proposers will be able to claim awards.
Recommendation
Consider adding a call to write_sub_trees_to_storage(...) using incremental_merkle_tree.sub_trees as an argument after appending the new leaf.
Resolution
Fixed in c604fc6. Sub-trees are now correctly written to storage and have been optimized. Now, only used merkle tree depths are written to storage.
| File | Fix commit | Type | Status |
timed/round.cairo | a41a825 | Medium | Fixed |
Voting on more than one proposal in the same transaction leads to users not being able to spent all their voting power. The calculations for remaining_voting_power are incorrect, as the cumulative amount spent is subtracted from the remaining voting power on each loop. The function is shown below:
fn _cast_votes_on_one_or_more_proposals(
voter: EthAddress,
cumulative_voting_power: u256,
mut proposal_votes: Span<ProposalVote>
) {
let mut spent_voting_power = _spent_voting_power::read(voter);
let mut remaining_voting_power = cumulative_voting_power - spent_voting_power;
loop {
match proposal_votes.pop_front() {
Option::Some(proposal_vote) => {
///////////////////////////////////////////////////////////////////////////////
// @audit-issue : Assuming voting to 4 proposals with power of (20,30,30,20).
// total 100
// spent = 0, remaining = 100 as initial values.
// 1st iter spent_voting_power = 20, remaining_voting_power = 100 - 20 = 80
// 2nd iter spent_voting_power = 50, remaining_voting_power 80 - 50 = 30 which is wrong !
///////////////////////////////////////////////////////////////////////////////
spent_voting_power += _cast_votes_on_proposal(
voter, *proposal_vote, remaining_voting_power,
);
remaining_voting_power -= spent_voting_power;
},
Option::None(_) => {
// Update the spent voting power for the user
_spent_voting_power::write(voter, spent_voting_power);
break;
},
};
};
}Recommendation
Consider calculating the remaining voting power as follows:
remaining_voting_power = cumulative_voting_power - spent_voting_power;Resolution
Fixed in a41a825. The recommended remaining voting power calculation has been implemented.
startTimestamp in the L2 message payload is not modified when creating an infinite round| File | Fix commit | Type | Status |
InfiniteRound.sol | 37a26ef | Medium | Fixed |
When creating an infinite round, the round creator passes a RoundConfig struct containing important parameters. The startTimestamp parameter is a part of this config data, and it is used to determine at what timestamp a voter’s L1 ERC20 token balance was when a governance voting strategy is used.
The InfiniteRound contract has logic in the function _register(...) to ensure that the provided startTimestamp is not in the past. If the config’s startTimestamp is in the past, then the current time should be used. This check is presented below:
function _register(RoundConfig memory config) internal {
//...
startTimestamp = _max(config.startTimestamp, uint40(block.timestamp));
//...
}This validation only changes the startTimestamp storage variable on the L1 round contract, and the config.startTimestamp value is left unchanged, then passed to L2 where the incorrect startTimestamp is used for voting power calculations. This could be exploited by a malicious user with permissions to create a round. They could use a timestamp from the past where they had more voting tokens than they currently have, or use a timestamp where other potential voters have less tokens to reduce their impact on the outcome of the round.
Recommendation
Ensure that the L1 and L2 track the same startTimestamp by updating config.startTimestamp to be the correct value before being passed to L2.
Resolution
Fixed in 37a26ef. Both config.startTimestamp and startTimestamp are now set to the same value.
FinalizationPending| File | Fix commit | Type | Status |
InfiniteRound.sol | d285cb8 | Low | Fixed |
For an infinite round, when the finalization process begins with startFinalization(...) the contract state is changed to FinalizationPending. During this time, while waiting for a finalize message from Starknet, it is not possible to cancel the round or recover funds. If the message cannot reach Starknet, either because the msg.value during message send was not high enough, or the Starknet sequencers are behaving incorrectly, it is not possible to cancel the round or reclaim funds.
To cancel a round or reclaim funds the contract state must be Active, Finalized or Cancelled. When the state is FinalizationPending these functions will revert. This issue only applies to infinite rounds, as timed rounds do not have a FinazilationPending state.
function _canReclaim() internal view returns (bool) {
/////////////////////////////////////////////////////////////
// @audit-issue Cannot claim if state is FinalizationPending
/////////////////////////////////////////////////////////////
if (state == RoundState.Cancelled) {
return true;
}
if (state == RoundState.Finalized) {
return block.timestamp - finalizedAt >= RECLAIM_UNCLAIMED_ASSETS_AFTER
|| claimedWinnerCount == currentWinnerCount;
}
return false;
}
function startFinalization() external payable onlyRoundManager {
/////////////////////////////////////////////////////////////
// @audit-issue Once finalization starts cannot recover any
// funds until finalize message from Starknet
/////////////////////////////////////////////////////////////
if (state != RoundState.Active || currentWinnerCount == 0) {
revert FINALIZATION_NOT_AVAILABLE();
}
// ...
}Recommendation
Consider adding a safety measure to allow funds to be retrieved from a FinalizationPending state if a reasonable amount of time has passed without the state changing to Finalized. Message cancellation for the FINALIZE_ROUND message from L1 -> L2 is an additional approach that can be considered.
Resolution
Fixed in d285cb8. Funds can now be retrieved after one week has passed and the round is still in the FinalizationPending state.
| File | Fix commit | Type | Status |
infinite/round.cairo | 364155a | Low | Fixed |
When a proposal is updated, the voting_power_for storage variable is reset to zero, however the spent voting power for previous voters is not reset. This means that users who had previously voted on the proposal before the update will not be able to re-vote on the same or any other proposal, effectively disregarding their votes. Relevant code snippets are shown below:
fn edit_proposal(...) {
// ...
// @audit-issue: Proposal's "for" votes are cleared, but users spent voting power is not
proposal.voting_power_for = 0;
// ...
}
fn _cast_votes_on_proposal(...) {
// ...
// @audit-issue: The spent voting power doesn't depend on the version of the proposal
// "For" votes are reset on version updates, but the voting power is not
let mut spent_voting_power = _spent_voting_power::read((voter, proposal_id));
let mut remaining_voting_power = cumulative_voting_power - spent_voting_power;
// ...
}Recommendation
Consider returning the spent votes back to users who have voted for a proposal which has been updated.
Resolution
Fixed in 364155a. Previously, to prevent infinite round proposers from bypassing proposal rejections, ‘against’ votes accumulated across proposal versions. Now, both ‘for’ and ‘against’ votes are reset when a proposal is edited. If proposers try to sidestep the ‘against’ vote threshold by modifying the proposal, voters can let the proposal go stale.
| File | Fix commit | Type | Status |
storage.cairo | d07108b | Info | Fixed |
The write_span function used in StorageAccess::< Span<T> > doesn’t check the size of the value Span. At most 256 field elements can be stored in a single storage variable. This function will fail if value.len() + offset > 256
fn write_span<T, impl TCopy: Copy<T>, impl TDrop: Drop<T>, impl TSA: StorageAccess<T>>(
address_domain: u32, base: StorageBaseAddress, mut offset: u8, mut value: Span<T>
) -> SyscallResult<()> {
///////////////////////////////////////////////////////////////////////////////////
// @audit-issue: This call will fail if 'offset + value.len()' > 256
///////////////////////////////////////////////////////////////////////////////////
StorageAccess::<u32>::write_at_offset_internal(address_domain, base, offset, value.len())?;
loop {
match value.pop_front() {
// ...
};
}
}Recommendation
The size of the Span should be checked explicitly prior to writing it to storage in the StorageAccess impl. The result of value.len() + offset must be lower or equal than 255.
Resolution
Added in d07108b.
FINALIZED, FINALIZED_PENDING and CANCELLED state| File | Fix commit | Type | Status |
PropHouse.sol | — | Info | Acknowledged |
It is possible to fund rounds through the function PropHouse.depositTo(...) after a round has been created. This allows for communities to collaboratively fund a round rather than needing a single address to provide all assets up-front during round creation. However, it is possible to use the depositTo function outside to deposit assets to a round outside of the ACTIVE state. If the round state is FINALIZED, FINALIZED_PENDING or CANCELLED the added funds will serve no purpose as all funds should already have been added to the round at that point.
It should be noted that this does not lead to lost funds, since the the depositor will be able to use the round functions reclaim(...) or reclaimTo(...) after enough time has passed.
Recommendation
Consider preventing asset deposits when the round state is not ACTIVE.
Resolution
Acknowledged, but do not plan to fix as funds can always be reclaimed at a later time.
| File | Fix commit | Type | Status |
Constants.sol | f726550 | Info | Fixed |
In constants.sol the function selector for the Starknet l1_handler function route_call_to_round(...) is declared. The comment describing how selector was derived states "round_call_from_round" where it should actually be "route_call_from_round". The actual value being used is correct however, so L1 -> L2 messages will operate correctly. The relevant code is shown below:
// print(get_selector_from_name("round_call_to_round"))
uint256 constant ROUTE_CALL_TO_ROUND = 0x24931ca109ce0ffa87913d91f12d6ac327550c015a573c7b17a187c29ed8c1a;Recommendation
Consider changing the comment to accurately reflect what the value in ROUTE_CALL_TO_ROUND represents.
Resolution
Fixed in f726550.
| File | Fix commit | Type | Status |
ethereum/* | — | Info | Acknowledged |
The Ethereum implementation of the protocol does not support message cancellation. When sending a message from L1 to L2 through starknet.sendMessageToL2(...) the caller must provide some msg.value which the StarkNet sequencers will accept as payment to execute the message on StarkNet. In the case that the msg.value is not enough for a sequencer to accept, these messages will remain unconsumed. Since it is not possible to cancel a message and receive the msg.value back, this could lead to permanently lost Ether. It should be noted that for a sequencer to ignore a message, the amount of Ether would have to be reasonably small.
Recommendation
Consider allowing message cancellation to ensure Ether cannot be lost if a sequencer does not accept a message.
Resolution
Acknowledged, but do not plan to fix as the risk is low, the funds at risk are small, and the fix requires careful consideration as to not break other parts of the round.
SpanStorageAccess::size_internal can infinitely recurse| File | Fix commit | Type | Status |
storage.cairo | bf8a615 | Info | Fixed |
The implementation of the StorageAccess<Span<T>> trait named SpanStorageAccess has a size_internal function which calls itself infinitely. This method is not used in the protocol, but any dependency on it will result in failed transactions due to infinite loops.
fn size_internal(value: Span<T>) -> u8 {
///////////////////////////////////////////////////////////////////////////////////
// @audit-issue: calling SpanStorageAccess::<T>::size_internal
// instead of StorageAccess::<T>::size_internal
///////////////////////////////////////////////////////////////////////////////////
1 + (SpanStorageAccess::<T>::size_internal(value) * downcast(value.len()).unwrap())
}Recommendation
If the Span is empty, return 1. If it’s not, get the size of T by using StorageAccess::<T> instead of SpanStorageAccess.
Resolution
Fixed in bf8a615.
downcast directly| File | Fix commit | Type | Status |
storage.cairo | 8f3806f | Best Practices | Fixed |
The downcast extern function is used to convert length from u32 to u8. A good practice is to use higher-level traits for type conversions, such as TryInto and Into, instead of using upcast and downcast.
fn read_span<T, impl TCopy: Copy<T>, impl TDrop: Drop<T>, impl TSA: StorageAccess<T>>(
address_domain: u32, base: StorageBaseAddress, mut offset: u8
) -> SyscallResult<Span<T>> {
let length = StorageAccess::<u32>::read_at_offset_internal(address_domain, base, offset)?;
offset += 1; // Increment offset by 1 for the length.
///////////////////////////////////////////////////////////////////////////////////
// @audit-issue: Avoid using 'downcast' directly and prefer
// high-level 'TryInto' and 'Into' traits.
///////////////////////////////////////////////////////////////////////////////////
let exit_at = downcast(length).unwrap() + offset;
let mut arr = Default::<Array<T>>::default();
}Recommendation
Use the try_into method from the TryInto trait to perform downcasts. To avoid downcasting, length can also be directly stored into a u8 using StorageAccess::<u8> instead, given that at most 255 elements can be stored in a storage variable.
Resolution
Updated in 8f3806f.
EthAddress| File | Fix commit | Type | Status |
ethereum_tx.cairoethereum_tx.cairocommit_receiver.cario | 52ff5f0 | Best Practices | Fixed |
Commits are received from Ethereum to Starknet through the _commit_address storage variable, which is declared in commit_receiver.cairo. The type for this storage variable is ContractAddress, which is used to store the address of a Starknet contract. The issue is shown in the code snippet below:
/// Initializes the contract by setting the commit address.
fn initializer(commit_address: ContractAddress) {
_commit_address::write(commit_address);
}Recommendation
Since _commit_address will be storing an Ethereum address, consider using the type EthAddress instead of ContractAddress.
Resolution
Updated in 52ff5f0. While the commit_address parameter type has been changed to EthAddress, the _commit_address storage variable type has been changed to felt252 to avoid the need to create a StorageAccess implementation for EthAddress.
get_power can have a view visibility| File | Fix commit | Type | Status |
allowlist.cairo | 70fa82d | Best Practices | Fixed |
The function get_power(...) is marked as external, but it doesn’t mutate the state of any contract. It can be marked as view instead.
/////////////////////////////////////////////////////////
// @audit-issue: This function can be marked as 'view'
/////////////////////////////////////////////////////////
#[external]
fn get_power(
timestamp: u64, user: felt252, params: Span<felt252>, user_params: Span<felt252>,
) -> u256 {
AllowlistGovernancePowerStrategy::get_power(timestamp, user, params, user_params)
}Recommendation
Consider marking the function as #[view]
Resolution
Updated in 70fa82d.
get_slot_key(...) cannot query a mapping with a key higher than felt252 size| File | Fix commit | Type | Status |
single_slot_proof.cairo | 76aa0f7 | Best Practices | Fixed |
The function get_slot_key(...) is used to calculate the storage slot for a mapping given a mapping slot and key in an Ethereum smart contract. However, this function is not able to access all potential storage slots for a mapping. The function takes two arguments slot_index and mapping_key, which represent the mapping slot and index respectively. The argument mapping_key is of type felt252, which means it is not possible to query for storage slots where the index would exceed what a felt252 type can store. The function is shown below:
/////////////////////////////////////////////////////////////////////////////////
// @audit-issue The key is felt252 but mapping key can be uint256 on Ethereum
/////////////////////////////////////////////////////////////////////////////////
fn get_slot_key(slot_index: felt252, mapping_key: felt252) -> u256 {
let mut encoded_array = Default::default();
encoded_array.append(mapping_key.into());
encoded_array.append(slot_index.into());
keccak_u256s_be(encoded_array.span())
}This means that it is not possible to query mapping entries where the key is greater that what a felt252 type can represent. Some examples of mappings keys that may be affected are hashed data or signatures. Currently this does not cause a problem as the protocol only uses this function to query ERC20 balances, where the key is a 160 bit Ethereum address. However if this function is used elsewhere it may not behave correctly.
Recommendation
Consider changing get_slot_key(...) such that it can calculate the storage slot for all possible keys in a mapping.
Resolution
Updated in 76aa0f7.
get_slot_value(...) reverts if Ethereum storage slot has value 0| File | Fix commit | Type | Status |
single_slot_proof.cairo | f8d88fc | Best Practices | Fixed |
The function get_slot_value(...) is used to read the value in a given storage slot on Ethereum using Herodotus. Part of the logic in get_slot_value state that the transaction should revert if the loaded storage value is 0, as shown in the code snippet below:
fn get_slot_value(
timestamp: u64, user: felt252, params: Span<felt252>, user_params: Span<felt252>,
) -> u256 {
// ...
assert(slot_value.is_non_zero(), 'SSP: Slot value is zero');
slot_value
}Reverting when the storage value is zero should not be part of this function, as there may be cases when it is valid for storage to be zero. Instead, if a revert is necessary this should belong in the logic of the function caller, as there are valid use cases for get_slot_value returning zero. One such example could be querying a boolean mapping where different logic will execute depending on if the value is true or false..
Recommendation
Consider allowing get_slot_value(...) to return a value of zero, and if a revert is necessary then consider placing it in the calling logic instead.
Resolution
Updated in f8d88fc.
| File | Fix commit | Type | Status |
contracts/* | c41e7b4 | Best Practices | Fixed |
It is considered a best practice to use the best-fitting visibility for each function. The following is a list of functions that have a visibility of public but can be changed to external:
CommunityHouse.isRound()
CreatorPassIssuer.uri()
AssetRound.uri()
ERC1155.uri()Recommendation
Consider changing the visibility of the functions listed below to external.
Resolution
Updated in c41e7b4.
| File | Fix commit | Type | Status |
contracts/starknet/* | cf72793 | Best Practices | Fixed |
The following variables and arguments have the mut keyword but are not modified.
_computer_root(...)
sub_tree
parse_strategies(...)
starting_index
_mergesort_proposals_by_voting_power_desc_and_slice(...)
left_arr
right_arr
sorted_left
sorted_right
_cast_votes_on_proposal(...)
spent_voting_power
remaining_voting_powerNote that for the function _cast_votes_on_proposal(...) some of the listed variables should keep the mut keyword after other issues in the report have been addressed, where they should be updated but currently are not.
Recommendation
Consider removing the mut keyword for the variables and arguments listed above.
Resolution
Removed in cf72793.
state in round contracts| File | Fix commit | Type | Status |
ethereum/rounds/* | ff91a94 | Best Practices | Fixed |
The TimedRound and InfiniteRound contracts have a storage variable state which tracks what the current state of the round is. When initializing these rounds, the function _register(...) sets state to RoundState.Active as shown below:
function _register(RoundConfig memory config) internal {
//...
state = RoundState.Active;
// ...
}The definition of the RoundState enum in both ITimedRound and IInfiniteRound set Active as the first item. The first item in an enum has a value of zero, and since the contract has just been deployed state would be zero as it hasn’t been set yet. This means that setting state to RoundState.Active again is an unnecessary SSTORE operation.
Recommendation
Removing the unnecessary setting of state in _register for round contracts. Alternatively this can be kept for code readability purposes, at the cost of a slight gas increase.
Resolution
Removed in ff91a94 and added a comment noting that the round state defaults to active.
| File | Fix commit | Type | Status |
strategy.cairo | 8db19c8 | Best Practices | Fixed |
The _compute_strategy_id function takes a snapshot of a Strategy as a parameter and desnaps it right away. The strategy can simply be passed by value instead, as Strategy derives the Copy trait.
fn register_strategy_if_not_exists(mut strategy: Strategy) -> felt252 {
// ...
let strategy_id = _compute_strategy_id(@strategy);
// ...
}
fn _compute_strategy_id(strategy: @Strategy) -> felt252 {
///////////////////////////////////////////////////////////////////////////////////
// @audit-issue: 'strategy' is passed by snapshot and directly de-snapped.
// It can be passed by value instead.
///////////////////////////////////////////////////////////////////////////////////
let mut strategy = *strategy;
// ...
}Recommendation
Consider passing the strategy parameter as mut strategy: Strategy instead.
Resolution
Removed in 8db19c8.
i in get_cumulative_governance_power(...)| File | Fix commit | Type | Status |
libraries/round.cairo | 27ca7ae | Best Practices | Fixed |
The function get_cumulative_governance_power(...) has a variable i which is set and incremented, but is never used. A snippet from the function is shown below:
fn get_cumulative_governance_power(...) -> u256 {
let mut i = 0;
// ...
loop {
match used_strategies.pop_front() {
Option::Some(s) => {
// ...
i += 1;
// ...
},
Option::None(_) => {
break;
},
};
};
// ...
}Recommendation
Consider removing the unused variable.
Resolution
Removed in 27ca7ae.
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:
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.
Nouns DAO has provided the documentation for Prop-House in the form of a README.md. The quality of this documentation is very high, and provides detailed information on the following:
The quality of the inline comments for both Solidity and Cairo contracts are of very high quality. In Solidity files, each function has an associated NatSpec comment explaining the function’s purpose, inputs and outputs. For Cairo files, an equivalent explanation of purpose, inputs and outputs has been provided as well. Aside from general function comments, specific lines of code that may be hard for a reader to understand are accompanied with an explanation.
The test suite for the Solidity contracts are well implemented and covers edge cases, exploring function calls with different inputs, both valid and invalid. The test suite for the Cairo contracts at the time of this audit is incomplete, only parameter decoding for rounds and the incremental Merkle tree implementation are tested. It is recommended to add more tests to cover the Cairo contracts to ensure that all code behaves as expected not only for the code in its current state, but in the future when changes are made. Integration tests are also implemented to ensure that communication between each chain behaves correctly. Functionality surrounding creating proposals, casting votes, signature validation, determining round winners, and claiming awards on the Ethereum layer
| 7Tests passed | 0Failed |
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.
The Leading Engineers of Blockchain Infrastructure