Avalaunch XAVA Protocol Audit

Introduction

CoinFabrik was asked to audit the contracts for Avalaunch’s XAVA Protocol project.
First we will provide a summary of our discoveries and then we will show the
details of our findings.

Scope

The contracts audited are from the https://github.com/avalaunch-app/xava-protocol/
git repository. The audit is based on the commit
fd9b97ccd963819a282fa5c21bf0545d180f8797. Revisions were made based on
commit 8c9f3c021f0a3366e9f8cfc3fd74163f31b57b40.

The audited contracts are:

● contracts/airdrop/Airdrop.sol
● contracts/airdrop/AirdropAVAX.sol
● contracts/airdrop/AirdropSale.sol
● contracts/farming/DevToken.sol
● contracts/farming/FarmingXava.sol
● contracts/interfaces/IAdmin.sol
● contracts/interfaces/IAllocationStaking.sol
● contracts/interfaces/IAvalaunchSale.sol
● contracts/interfaces/ICollateral.sol
● contracts/interfaces/IDexalotPortfolio.sol
● contracts/interfaces/IERC20Metadata.sol
● contracts/interfaces/ISalesFactory.sol
● contracts/sales/AvalaunchSale.sol
● contracts/sales/SalesFactory.sol
● contracts/utils/Context.sol
● contracts/Admin.sol
● contracts/AllocationStaking.sol
● contracts/AvalaunchColateral.sol
● contracts/IERC20.sol
● contracts/XavaToken.sol

The scope of the audit is limited to those files. No other files in this repository were
audited. Its dependencies are assumed to work according to their documentation.
Also, no tests were reviewed for this audit.

Analyses

Without being limited to them, the audit process included the following analyses:

● Arithmetic errors
● Outdated version of Solidity compiler
● Race conditions
● Reentrancy attacks
● Misuse of block timestamps
● Denial of service attacks
● Excessive gas usage
● Missing or misused function qualifiers
● Needlessly complex code and contract interactions
● Poor or nonexistent error handling
● Insufficient validation of the input parameters
● Incorrect handling of cryptographic signatures
● Centralization and upgradeability

Summary of Findings

We found one critical issue and four minor issues. Also, some enhancements were
proposed.

Security Issues

Privileged Roles

The audit encompasses 20 contracts including interfaces and libraries. Contracts
like AllocationStaking and FarmingXava are Ownable. The owner is responsible for
setting sale parameters in the first case, and adding pools, setting allocation points
in the second case.
Other contracts, like AllocationStaking, AvalaunchBadgeFactory,
AvalaunchCollateral, the airdrop contracts (Airdrop, AirdropAVAX, AirdropSale),
AvalaunchSale and SaleFactory make use of the Admin interface, setting an
administrator at construction.
The new AvalaunchCollateral contact further introduces the role of the moderator
who is responsible for approving sales to have collateral as per this contract.

Security Issues Found

Severity Classification

Security risks are classified as follows:

Critical: These are issues that we manage to exploit. They compromise the
system seriously. They must be fixed immediately.
Medium: These are potentially exploitable issues. Even though we did not
manage to exploit them or their impact is not clear, they might represent a
security risk in the near future. We suggest fixing them as soon as possible.
Minor: These issues represent problems that are relatively small or difficult
to take advantage of but can be exploited in combination with other issues.
These kinds of issues do not block deployments in production environments.
They should be taken into account and be fixed when possible.

Issues Status

An issue detected by this audit can have four distinct statuses:

● Unresolved: The issue has not been resolved.
● Acknowledged: The issue remains in the code but is a result of an intentional
decision.
● Resolved: Adjusted program implementation to eliminate the risk.
● Partially resolved: Adjusted program implementation to eliminate part of the
risk. The other part remains in the code but is a result of an intentional
decision.
● Mitigated: Implemented actions to minimize the impact or likelihood of the
risk.

Critical Severity Issues

CR-01 Unlimited Permits Issued for Admin

Location:

● contracts/AvalaunchCollateral.sol:135-176,
● contracts/AvalaunchCollateral.sol:192-226

The admin can call autoParticipate() or boostParticipation() in the contract
AvalaunchCollateral and act on behalf of a user, paying with this user’s
collateral. The user only allows the sale (address), but cannot limit amounts,

Recommendation

Include an amount (or maximum amount) that the user allows the admin to use.

Status

Resolved. Developers informed us that this is the expected use. Users must
therefore trust that the admin will select the amount safely in their interests.

Medium Severity Issues

No issues found.

Minor Severity Issues

MI-01 No Booster Round Is Possible

In AvalaunchSale.setSalesParams() we set the boosterRoundId as

boosterRoundId = _stakingRoundId.add(1);

after the following check

require(_stakingRoundId > 0, "Invalid staking round id.");

However, since stakingRoundId may be equal to roundIds.length-1 and
boosterRoundId could point to a nonexistent round, thus rendering the booster
round unavailable to all practical purposes.

Recommendation

Validate that _stakingRoundId is not the last index. Alternatively, revisit the order in
which parameters are set to prevent inconsistencies between number of rounds,
and specific rounds.

Status

Acknowledged. Developers explained that this is an expected behavior and the
booster round is optional.

MI-02 Floating Pragma

Location:

● contracts/AvalaunchCollateral.sol:2
● contracts//DevToken.sol:2

● contracts/interfaces/IAvalaunchSale.sol:2
● contracts/interfaces/IDexalotPortfolio.sol:2
● contracts/interfaces/ICollateral.sol:2
● contracts/interfaces/IERC20Metadata.sol:3
● contracts/utils/Context.sol:3

Contracts should be deployed with the same compiler version that they have been
tested with. Locking the pragma helps to ensure that contracts do not accidentally
get deployed using, for example, an outdated compiler version that might introduce
bugs that affect the contract system negatively.

Recommendation

Lock the pragma version, replacing pragma solidity ^0.8.0; with a specific patch,
preferring the most updated version. For example, pragma solidity 0.8.14;.

Status

Acknowledged.

MI-03 Inconsistent Parameters in AvalaunchSale and SalesFactory

There is a problem if the collateral parameter set in SalesFactory is different to that
set in AvalaunchSales.

Recommendation

Set the parameter in only one contract.

Status

Acknowledged.

MI-04 Prefer Importing Libraries from NPM

Library IERC20Metadata.sol is stored locally and imported, instead of using NPM
to import it from openzeppelin’s repository. This may lead to errors in copying, or
lose an update.

Recommendation

Import all externally-generated code through NPM.

Status

Acknowledged.

Enhancements

These items do not represent a security risk. They are best practices that we
suggest implementing.

Table

Details

EN-01 Outdated Solidity Compiler Version

The audited contracts use the outdated version of solidity v0.6.12 (SWC-102).

Recommendation

Consider updating the code to compile with the latest version.

Status

Not implemented.

EN-02 Unused Flattened Library

Flattened old version of OpenZeppelin’s TransparentUpgradeableProxy. If not using
the latest version, devs should specify what version they are using so we can check
for reported issues.

Recommendation

Document the usage of this variable and allow modifications.

Status

Not implemented.

EN-03 tokenPriceInUSD Is Unused and Misleading

The variable tokenPriceInUSD in AvalauncSale.sol is misleading, since it is not used
by any of the sale functions nor needs to have any relationship with
tokenPriceInAVAX. Also tokenIpriceInAVAX may be changed but this cannot.

Recommendation

Document the usage of this variable and allow modifications.

Status

Not implemented.

EN-04 dexalotPortfolio May Be Set Before Sale Is Created

Ensure the sale is created in setAndSupportDexalotPortfolio()

EN-05 admin Array Not Checked For Repetitions During Construction

Location:

● Admin.sol:18-24.

In the constructor of Admin.sol it could happen that an address is repeated in the
input array _addresses. If this happens, the same address would be pushed more
than once to the array admins and may create inconsistencies, e.g., when calling
removeAdmin(). We recommend you check isAdmin[_admins[i]] = false
before turning it to true.

EN-06 Replace Integers by Constants

In FarmingXava.sol replace occurrences of 1e18 and 1e36 by a call or a constant
(e.g., IERC20Metadata(address(token)).decimals() as it is done in the
AvalaunchSale.sol contract).

EN-07 Two safeMath Libraries

Some contracts import OpenZeppelin’s safeMath library and others use a custom
safeMath library (math/safeMath.sol) which is a copy of OpenZeppelin’s safeMath
with some modifications. Also, note that some contracts, like AirdropSale.sol, are
importing safeMath but not using it. In that case, consider removing and saving gas.

EN-08 Documentation

Use Solidity’s NatSpec format for documentation (link), removing “todo”s and other
development comments.

Changelog

● 2022-03-22 – Initial report based on commit
fd9b97ccd963819a282fa5c21bf0545d180f8797.
● 2022-04-05 – Revision based on commit
8c9f3c021f0a3366e9f8cfc3fd74163f31b57b40.

Disclaimer: This audit report is not a security warranty, investment advice, or an
approval of the Avalaunch XAVA Protocol project since CoinFabrik has not
reviewed its platform. Moreover, it does not provide a smart contract code
faultlessness guarantee.

CityCoins Audit

Introduction

CoinFabrik was asked to audit the contracts for the CityCoins project. First we will provide a summary of our discoveries and then we will show the details of our findings.

Scope

The contracts audited are from the https://github.com/citycoins/citycoin repository.
The audit is based on the commit 653056fe4f58b4eed5674009c55cedf0dc2dced3.
Fixes were checked on 9dbc51e80e2653bd3d77175cd44c3e411ce2d7c9.

The audited contracts are:

contracts/citycoin-vrf.clar: Contains the required functions to generate an integer from the specified block’s VRF seed.
contracts/citycoin-core-trait.clar: Trait definition for a core contract.
contracts/citycoin-token-trait.clar: Trait definition for a token contract.
contracts/MiamiCoin/auth.clar: Administrative functions for the approvers and city wallet roles.
contracts/MiamiCoin/token.clar: Token implementation.
contracts/MiamiCoin/core-v1.clar: Contains mining, staking and reward claiming functions.

Analyses

The following analyses were performed:
● Misuse of the different call methods
● Integer overflow errors
● Division by zero errors
● Front running attacks
● Reentrancy attacks
● Misuse of block timestamps
● Softlock denial of service attacks
● Functions with excessive gas cost
● Missing or misused function qualifiers
● Needlessly complex code and contract interactions
● Poor or nonexistent error handling
● Failure to use a withdrawal pattern
● Insufficient validation of the input parameters
● Incorrect handling of cryptographic signatures

Findings and Fixes

Severity Classification

Security risks are classified as follows:
Critical: These are issues that we manage to exploit. They compromise the system seriously. They must be fixed immediately.
Medium: These are potentially exploitable issues. Even though we did not manage to exploit them or their impact is not clear, they might represent a security risk in the near future. We suggest fixing them as soon as possible.
Minor: These issues represent problems that are relatively small or difficult to take advantage of but can be exploited in combination with other issues. These kinds of issues do not block deployments in production environments. They should be taken into account and be fixed when possible.
Enhancement: These kinds of findings do not represent a security risk. They are best practices that we suggest to implement.
This classification is summarized in the following table:

Issues Found by Severity

Critical Severity Issues

CR-01 Lost Miners Funds after Shut Down

In the core contract, users can commit to mine as many as the next 200 blocks. The city wallet or the approvers can upgrade the core contract through the auth contract (auth.clar), stopping the mining in the previous core. Therefore, those miners who committed for the blocks after the upgrade will have lost their committed tokens.

Recommendation

Implement a function to refund miners which is called by the shutdown function (shutdown-contract()). This function should store the committed values in a mapping. Finally, miners would be able to claim their tokens by calling a withdrawal function.

Status

Acknowledged. Additional research will be done on this issue. In the meantime, the development team expressed that upgrades would only be performed when absolutely necessary, scheduled in advance and well-communicated.

Medium Severity Issues

ME-01 Insecure Authentication through tx-sender

Global variable tx-sender returns the original sender of the current transaction, or if as-contract was called to modify the sending context, it returns that contract principal. Using this variable for authentication is not secure. Actors in the system could be targets of phishing. This is analogous to what happens to tx.origin and msg.sender in Solidity. There, the convention is to use msg.sender, which works like contract-caller.
For instance, an approver can be tricked to call a malicious contract which calls auth.approve-job() against his will. Also, the malicious contract could call the token transfer function (token.transfer()) to send the user’s tokens to itself.

Recommendation

Prefer contract-caller to tx-sender for authentication. contract-caller returns the caller of the current contract context.

Status

Mitigated. Job approval flow requires either two-of-three multi-signature transactions or three-of-five approvers’ votes.

Minor Severity Issues

MI-01 Rounding Issue when Calculating Stacking Rewards

MI-01 Rounding Issue when Calculating Stacking Rewards

In the core contract, stacking rewards are calculated through get-entitled-stacking-reward(). The amount of city coins locked by the user is multiplied by the total amount of micro-stacks staked for a cycle, and then divided by the total amount of city coins stacked for that cycle. Because of the data type imprecision, remainders will be accumulated in the contract and will not be used.

Recommendation
If there were a considerable amount of micro-stacks over time, the contract could calculate this value and use it. When all the stackers have claimed their rewards, the difference between the claimed amount and totalUstxThisCycle is the sum of these remainders.

Status
Acknowledged. The accumulated value is not considered worth enough to assume the runtime and implementation additional costs.

MI-02 Inactive Core Contract Can Activate Itself

All core contracts are stored in the auth contract with different states: STATE_DEPLOYED, STATE_ACTIVE and STATE_INACTIVE. The deployed state is the initial state. When it receives the required signals, it transits to the active state.

Finally, if it is upgraded, the previous contract will be inactive. auth.activate-core-contract() only checks if the caller is in the core contract mapping. If it were a malicious contract which was replaced through an upgrade, it would call activate-core-contract() and activate itself.

Recommendation

Verify the contract caller is a core registered with state STATE_DEPLOYED.

Status

Fixed. The recommendation was implemented.

MI-03 Malicious Inactive Core Contract Can Mint and Burn Tokens

The token contract (token.clar) only validates if the contract caller is registered in the auth contract. However, contracts cannot be removed from the auth contract. Therefore, if a malicious core were added and then replaced by the approvers, it could still mint new tokens and burn someone else’s tokens.

Recommendation

Instead of validating if the core contract is registered, the token contract should check if the core is active through get-active-core-contract().

Status

Acknowledged. This was a design choice. Core contracts need to be able to mint in order to reward the miners who have not claimed their tokens before the upgrade. Also, the unintended inclusion of a malicious core contract is mitigated by the job approval flow requirements (either two-of-three multi signature transactions or three-of-five approvers’ votes).

MI-04 Denial of Service in the Upgrade of a Malicious Core

upgrade-core-contract() and execute-upgrade-core-contract-job() are the functions that set a new active core contract. These functions call shutdown-contract() from the current active core to disable it. However, if the current core is a malicious contract, it might revert to stop the upgrade, making it impossible to change the core.

Recommendation

Instead of calling the core contract to modify the variables, those variables could be placed in the auth contract and be checked by the core through external calls. Therefore, the upgrade does not depend on unknown external logic.

Status

Mitigated. The unintended inclusion of a malicious core contract is mitigated by the job approval flow requirements (either two-of-three multi-signature transactions or three-of-five approvers’ votes).

Enhancements

EN-01 Approvers Need to Approve his Own Jobs

In the auth contract (auth.clar), approvers can create a job. For a job to be executed, it requires a minimum amount of approvals. Now, if an approver creates a job through create-job(), he can call approve-job() to approve his own job.

Recommendation

The job creation function should also add the creator approval. Then, the job creator does not need to make another transaction to approve his own job.

Status

Not fixed.

EN-02 Inactive Core Contract Can be Target of an Upgrade

In the auth contract (auth.clar), upgrade-core-contract() and execute-upgrade-core-contract-job() does not check if the new core contract was already registered before. Therefore, an inactive core can be passed as an argument and then be activated. This would result in a poor experience because that core was shut down when it was replaced and most of the functions are disabled.

Recommendation

Validate the new contract is not already registered in the auth contract.

Status

Fixed.

Other Considerations

● The burn function (token.burn()) allows a core contract to burn users’ tokens without their consent. The audited core contract does not implement any function which calls token.burn(), but a new core contract can be included and call that function. The new commit modified the burn() function, allowing only the owners to burn their own tokens.

Conclusion

We found the contracts to be simple and straightforward and have an adequate amount of documentation. We found a critical issue, a medium issue and several minor issues and enhancements. An issue was fixed, two were mitigated and three were acknowledged.

Disclaimer: This audit report is not a security warranty, investment advice, or an
approval of the CityCoins project since CoinFabrik has not reviewed its platform.
Moreover, it does not provide a smart contract code faultlessness guarantee.


YieldYak Audit :: Platypus

Introduction

CoinFabrik was asked to audit the contracts for the YieldYak project. First we will provide a summary of our discoveries and then we will show the details of our findings.

Scope

The contracts audited are from the https://github.com/yieldyak/smart-contracts git repository. The audit is based on the commit
2add9db9263a7bc8e1df8ef184b242d2ed502b1d.

The audited files are:

● contracts/strategies/PlatypusVoterProxy.sol: Contract used by the strategies to interact with the platypus system as a single entity. It only
allows registered strategies to interact with the Platypus system.
contracts/strategies/PlatypusVoter.sol: Helper contract used to
interact with the Platypus system. The PlatypusVoterProxy uses it for some interactions.
● contracts/strategies/PlatypusStrategy.sol: Investment strategy that uses the platypus system.
contracts/strategies/PlatypusMasterChefStrategy.sol: Abstract base contract used to make investment strategies that use the Platypus system. At the time of the audit, PlatypusStrategy is its only subcontract.
● contracts/lib/DSMath.sol: Library that provides utilities for some
arithmetic operations.
● contracts/lib/ERC20.sol: ERC20 token with permit implementation.
● contracts/interfaces/IPlatypusVoterProxy.sol: Interface definition for the PlatypusVoterProxy contract.
● contracts/interfaces/IPlatypusVoter.sol: Interface definition for the PlatypusVoter contract.
contracts/interfaces/IVePTP.sol: Interface definitions for the contract defined at address 0x5857019c749147EEE22b1Fe63500F237F3c1B692 in the
avalanche c-chain. It represents the vePTP token.
● contracts/interfaces/IPlatypusPool.sol: Platypus pool interface.
Contract documented in https://platypus-finance.gitbook.io/platypus-finance-docs/developers/contracts/pool

● contracts/interfaces/IMasterPlatypus.sol: Interface definitions for the contract defined at address
0xB0523f9F473812FB195Ee49BC7d2ab9873a98044 in the avalanche c-chain.
● contracts/interfaces/IPlatypusAsset.sol: Platypus asset interface. Contract documented in
https://platypus-finance.gitbook.io/platypus-finance-docs/developers/contracts/asset.
● contracts/interfaces/IWAVAX.sol: Interface defined to interact with the WAVAX contract.
● contracts/interfaces/IPair.sol: Interface defined to interact with
decentralized exchange contracts.

The scope of the audit is limited to those files. No other files in this repository were audited. Its dependencies are assumed to work according to their documentation.
These files were taken from the OpenZeppelin contracts library (version 3.4.2) and then only changed pragmas, import paths and other minor and not relevant changes were made:

● contracts/lib/Ownable.sol
● contracts/lib/Context.sol
● contracts/lib/EnumerableSet.sol
● contracts/lib/SafeERC20.sol
● contracts/lib/Address.sol
● contracts/lib/IERC20.sol

The following files were audited in other audits:

● contracts/lib/DexLibrary.sol
● contracts/lib/YakStrategy.sol
● contracts/lib/SafeMath.sol

Also, no tests were reviewed for this audit.

Fixes and improvements were checked in commit
cf8fd8a3088ea877ca6b23f54473a101703011ad. In this commit also
PlatypusMasterChefStrategy.sol was merged into PlatypusStrategy.sol and the PlatypusStrategy contract was made to inherit from YakStrategyV2 instead of YakStrategy, which was reviewed in a different audit.

Analyses

Without being limited to them, the audit process included the following analyses:

● Arithmetic errors
● Outdated version of Solidity compiler
● Race conditions
● Reentrancy attacks
● Misuse of block timestamps
● Denial of service attacks
● Excessive gas usage
● Missing or misused function qualifiers
● Needlessly complex code and contract interactions
● Poor or nonexistent error handling
● Insufficient validation of the input parameters
● Incorrect handling of cryptographic signatures
● Centralization and upgradeability

Summary of Findings

We found 1 critical issue, 2 medium issues and several minor issues. Also, several enhancements were proposed. We checked fixes in commit cf8fd8a3088ea877ca6b23f54473a101703011ad. All critical and medium issues were resolved. The minor issues were either resolved or
acknowledged. One of the proposed enhancements was implemented.

Security Issues

Privileged Roles

These are the privileged roles that we identified on each of the audited contracts.

ERC20

Approved Address

An address may allow a different address to transfer funds away from its
belongings by either using the approve() function or signing off-line an approval to be passed to the permit() function. This is specified in ERC-20.

PlatypusVoter

Besides all the roles documented below, it also has the privileged roles
documented for the ERC20 contract.

Owner

The owner can change the address of the voter proxy.
By default, the owner is the address that deployed the contract.

Dev

The dev can:

● Enable or disable deposits.
● Claim vePTPs.
The dev is passed in the constructor and cannot be changed.

Voter Proxy

The voter proxy can:

● Claim vePTPs.
● Use the contract balance to do deposits
● Transform AVAX in WAVAX.
● Invoke any function on any contract with any parameters on behalf of the
PlatypusVoter.

1 The dev cannot claim vePTPs anymore in commit cf8fd8a3088ea877ca6b23f54473a101703011ad.

PlatypusVoterProxy

Dev

The dev can:

● Add approved strategies (but cannot remove them)
● Set booster and staker fees.
● Set fee receivers for booster and staker fees.

The dev is passed in the constructor and cannot be changed.

Strategy

A strategy can:
● Do deposits
● Withdraw funds
● Do emergency withdraws
● Claim rewards
There are no registered strategies by default.

PlatypusMasterChefStrategy

It has all the roles defined for the YakStrategy contract. No new roles were added. Given that PlatypusMasterChefStrategy is an abstract contract, strategies inherited from it may have other roles.

Owner

Besides all the abilities defined in the parent contracts, the owner can rescue deployed funds. The setAllowances() method has been deprecated and if invoked will revert with an error message even if invoked by the owner.

Dev

Besides all the abilities defined in the parent contracts, the dev can set the
extra-reward swap-pair.

EOA

Besides all the abilities defined in the parent contracts, an EOA can do a
reinvestment.

PlatypusStrategy

It has all the roles defined for the PlatypusMasterChefStrategy contract. No new roles were added.

Owner

Besides all the abilities defined in the parent contracts, the owner can set the Platypus voter proxy.

Dev

Besides all the abilities defined in the parent contracts, the dev can update the maximum withdraw slippage parameter.

Security Issues Found

Severity Classification

Security risks are classified as follows:
● Critical: These are issues that we manage to exploit. They compromise the system seriously. They must be fixed immediately.
● Medium: These are potentially exploitable issues. Even though we did not
manage to exploit them or their impact is not clear, they might represent a
security risk in the near future. We suggest fixing them as soon as possible.
● Minor: These issues represent problems that are relatively small or difficult to take advantage of but can be exploited in combination with other issues. These kinds of issues do not block deployments in production environments. They should be taken into account and be fixed when possible.

Issues Status

An issue detected by this audit can have four distinct statuses:
● Unresolved: The issue has not been resolved.
● Acknowledged: The issue remains in the code but is a result of an intentional decision.
● Resolved: Adjusted program implementation to eliminate the risk.
● Mitigated: Implemented actions to minimize the impact or likelihood of the risk.

Critical Severity Issues

CR-01 Race Condition for Rewards

Location:

● contracts/strategies/PlatypusVoterProxy.sol:230

Strategies that invoke PlatypusVoterProxy.claimReward() using the same Platypus PID will take all the rewards associated with that PID, including the ones that should be awarded to another strategy.

Recommendation

When the dev approves a strategy by calling PlatypusVoterProxy.aprove(), it should pass its PID and then the PID should be checked on each call the strategy makes to see that the correct one was used. It is also important not to have 2 different strategies with the same platypus PID, which should be controlled when PlatypusVoterProxy.aprove() is executed.

Status

Resolved. In commit cf8fd8a3088ea877ca6b23f54473a101703011ad, the
PlatypusVoterProxy.onlyStrategy() modifier receives the PID and checks if it matches the strategy.

Medium Severity Issues

ME-01 Rogue Strategy May Steal Funds of Different Strategy

Location:

● contracts/strategies/PlatypusVoterProxy.sol:166,203

Nothing in the PlatypusVoterProxy code stops a rogue strategy, which was previously approved by the dev, from invoking either
PlatypusVoterProxy.withdraw() or
PlatypusVoterProxy.emergencyWithdraw() with parameters corresponding to another strategy and stealing its funds.
The severity of this issue was lowered because the dev2 is required to approve the rogue strategy in order to be able to do this attack.

2 See PlatypusVoterProxy roles in the privileged roles section.

Recommendation

When the dev approves a strategy by calling PlatypusVoterProxy.aprove(), it should pass its PID and then the PID should be checked on each call the strategy makes to see that the correct one was used. It is also important not to have 2 different strategies with the same platypus PID, which should be controlled when PlatypusVoterProxy.aprove() is executed.

Status

Resolved. In commit cf8fd8a3088ea877ca6b23f54473a101703011ad, the PlatypusVoterProxy.onlyStrategy() modifier receives the PID and checks if it matches the strategy.

ME-02 Unguarded Overflows and Underflows

Location:

● contracts/strategies/PlatypusStrategy.sol:141,146,157,159
● contracts/lib/DSMath.sol:26,31,54-61,67
● contracts/strategies/PlatypusVoterProxy.sol:275

In several different places there are arithmetic operations that may overflow or underflow. The codebase is in solidity 0.7.3 so the standard operations wrap around when overflowing or underflowing, instead of raising an error.

Recommendation

Use the contracts/lib/SafeMath.sol library for all the arithmetic operations or, even better, upgrade the code to solidity ≥ 0.8 and use the default arithmetic operators, which check for overflows and underflows by default.

Status

Resolved. In commit cf8fd8a3088ea877ca6b23f54473a101703011ad, all the arithmetic operations mentioned are using the SafeMath library.

Minor Severity Issues

MI-01 Solidity Compiler Version

Most of the audited files use the pragma solidity 0.7.3; statement. This implies that an old solidity version is being used and also adds risks because bugs may be introduced by using a different solidity compiler. A few other files use a non-pinned version, such as pragma solidity >=0.6.0 <0.8.0; which also adds risks.

See https://swcregistry.io/docs/SWC-103 .

Recommendation

It is better to lock to a specific compiler version (for example, pragma solidity 0.8.11😉 and keep it up to date. Also, when updating to 0.8 take into account the new semantics for safe math operations.

Status

Acknowledged. The development team informed us that they will upgrade the solidity version in a separate scope.

MI-02 Extra-Reward Swap-Pair Not Properly Checked

Location:

● contracts/strategies/PlatypusMasterChefStrategy.sol:103-107
If the _extraTokenSwapPair.token0() is not the reward token, then it is assumed that _extraTokenSwapPair.token1() is the reward token. This may lead the strategy to use a wrong swap pair, and instead of getting reward tokens the strategy will get a different ERC20 token.
Hereunder are the lines 103-107 where the issue is located:

Recommendation

Check if _extraTokenSwapPair.token1() is the reward token in the else
statement on line 106 and revert if necessary.

Status

Resolved. The recommendation was implemented for commit
cf8fd8a3088ea877ca6b23f54473a101703011ad .

MI-03 No Symbol Set

Location:
● contracts/strategies/PlatypusStrategy.sol
● contracts/strategies/PlatypusMasterChefStrategy.sol

Neither PlatypusStrategy nor its parent, PlatypusMasterChefStrategy, set the symbol for the contract, so the symbol defined in the YakERC20 contract (“YRC”) is used, which may lead to confusion. Given that strategies are ERC20 tokens, a distinguishing symbol must be chosen in order to be properly labeled by several
tools, such as MetaMask.

Recommendation

Pass the symbol as a parameter in the constructors.

Status

Acknowledged. The development team informed us that because the YRT tokens are not meant to be added to Metamask, transferred or traded and they are purely a receipt and helper for the frontend, they don’t think resolving this issue is necessary.

Enhancements

These items do not represent a security risk. They are best practices that we
suggest implementing.

Table

Details

EN-01 Gas Usage Optimization

Location:
● contracts/strategies/PlatypusVoterProxy.sol:20

If the SafeProxy.safeExecute() function fails to run the
platypusVoter.execute() function all the available gas will be consumed. This is the offending line:

Recommendation

Use revert or require instead of assert to avoid consuming all the remaining
available gas.

Status

Implemented. In commit cf8fd8a3088ea877ca6b23f54473a101703011ad, assert() was replaced with revert().

EN-02 Strategy Repudiation

Location:
● contracts/strategies/PlatypusVoterProxy.sol

The PlatypusVoterProxy dev should have the ability to repudiate an approved strategy, disallowing the strategy to further interact with it. This functionality may be used to stop a rogue strategy.

Status

Not implemented. The development team informed us that strategy repudiation can be accomplished by migrating the VoterProxy if it is required.

Other Considerations

The considerations stated in this section are not right or wrong. We do not suggest any action to fix them. But we consider that they may be of interest for other stakeholders of the project, including users of the audited contracts, owners or project investors.

Centralization

PlatypusStrategy is an ownable contract where the owner has significant powers over the contract, so it must be trusted. PlatypusMasterChefStrategy is ownable as well, but given that it is an abstract contract it will never be instantiated as is.
The PlatypusVoter has an owner, but also a developer with significant
responsibility.
The PlatypusVoterProxy has an owner responsible to approve strategies to use the PlatypusVoter.
The development team informed us that they are using a community multisig to help mitigate centralization risks.

Upgradeability

A PlatypusVoter owner can change the PlatypusVoterProxy to a different contract in order to upgrade the logic, but keeping the PlatypusVoter state and assets. The owner of a PlatypusStrategy may change the voter proxy used by the strategy to point to the new PlatypusVoterProxy. The rest of the contracts do not have provisions to be upgraded.

Contract Instantiation

In order to do the security analysis, we assumed that when deploying a
PlatypusStrategy the _voterProxy constructor parameter receives an address of a PlatypusVoterProxy contract. We also assumed that when deploying a PlatypusVoterProxy the _platypusVoter constructor parameter receives an address of a PlatypusVoter contract.

Extra Fees

As a user of the PlatypusStrategy, fees taken by the PlatypusVoterProxy, staker fees and booster fees, need to be paid. This is in addition to all the fees that need to be paid as a normal operation for any YakStrategy, such as dev fees or reinvest fees.

Tests

The development team informed us that they have private tests covering the audited contracts outside the git repository.

Changelog

● 2022-02-18 – Initial report based on commit
2add9db9263a7bc8e1df8ef184b242d2ed502b1d.
● 2022-02-21 – Fixes checked on commit
cf8fd8a3088ea877ca6b23f54473a101703011ad.

Disclaimer: This audit report is not a security warranty, investment advice, or an approval of the YieldYak project since CoinFabrik has not reviewed its platform. Moreover, it does not provide a smart contract code faultlessness guarantee.

AlexGo Audit ::: Launchpad, Vault, and Reserve Pool

Introduction

CoinFabrik was asked to audit the contracts for the AlexGo project. First we will provide a summary of our discoveries and then we will show the details of our findings.

Scope

The contracts audited are from the alex-v1 git repository. The audit is based on the commit 44c44846bfbcce6096be04bd1380728c98f09ec8. The fixes were added to the commit 31a5d660c83d41c10cd1b34498f02bc3a407721e.

The audited contracts are:

clarity/contracts/alex-vault.clar: Contract that stores system tokens and allows flash loans.
clarity/contracts/pool/alex-launchpad.clar: IDO token launchpad.
clarity/contracts/pool/alex-reserve-pool.clar: Contract for token staking.

The scope of the audit is limited to those files. No other files in this repository were audited. Its dependencies are assumed to work according to their documentation. Also, no tests were reviewed for this audit.

Analyses

Without being limited to them, the audit process included the following analyses:

● Arithmetic errors
● Race conditions
● Reentrancy attacks
● Misuse of block timestamps
● Denial of service attacks
● Excessive gas usage
● Missing or misused function qualifiers
● Needlessly complex code and contract interactions
● Poor or nonexistent error handling
● Insufficient validation of the input parameters
● Incorrect handling of cryptographic signatures
● Centralization and upgradeability

Summary of Findings

We found a critical issue, two medium issues and a minor issue. Also, two
enhancements were proposed.
The critical severity issue and the two medium issues were acknowledged. Two minor severity issues were fixed. An enhancement was implemented.

Security Issues

Privileged Roles

These are the privileged roles that we identified on each of the audited contracts.

Alex-vault.clar

Owner

In the beginning, the owner is the address of the deployer. Then, the owner can set an address as a new owner. Also, this role can set a new flash loan fee rate and add new approved contracts, flash loan users and flash loan tokens. Finally, the owner can transfer fungible and semi-fungible tokens stored in the vault.

Approved Contracts

The approved contracts are addresses which can execute the transfer functions to move fungible and semi-fungible tokens from the vault contract. This address set is initialized including alex-reserve-pool, collateral-rebalancing-pool, fixed-weight-pool, liquidity-bootstrapping-pool, yield-token-pool, and yield-collateral-rebalancing-pool.

Approved Flash Loan Users

Flash loan users are addresses allowed to be used when flash-loan() is called. This contract should implement the specific trait in order for the vault contract to call the execute() function.

Alex-launchpad.clar

Owner

In the beginning, the owner is the address of the deployer. Then, the owner can set an address as a new owner. Also, this role can create new token-ticket pools.

Liquidity Provider

This is an address set by the owner for each pool created. This address is the only one allowed to provide tokens to the pool. Also, this address receives the amount of stacks paid to validate the winner ticket.

Alex-reserve-pool.clar

Owner

In the beginning, the owner is the address of the deployer. Then, the owner can set an address as a new owner. Also, this role can add new approved contracts and approved tokens, set a new activation delay, activation threshold, a new value for the halving cycle and coinbase amount of a token and a new reward cycle length. Finally, the owner can increase and decrease the balance of a token.

Approved Contracts

The approved contracts are addresses which can increase and decrease the balance of a token. Initially, the contracts included in this set are:
collateral-rebalancing-pool, fixed-weight-pool, yield-token-pool, yield-collateral-rebalancing-pool and the reserve pool itself.

Security Issues Found

Severity Classification

Security risks are classified as follows:

Critical: These are issues that we manage to exploit. They compromise the
system seriously. They must be fixed immediately.
●Medium: These are potentially exploitable issues. Even though we did not
manage to exploit them or their impact is not clear, they might represent a
security risk in the near future. We suggest fixing them as soon as possible.
Minor: These issues represent problems that are relatively small or difficult to take advantage of but can be exploited in combination with other issues. These kinds of issues do not block deployments in production environments. They should be taken into account and be fixed when possible

Issues Status

An issue detected by this audit can have four distinct statuses:

●Unresolved: The issue has not been resolved.
●Acknowledged: The issue remains in the code but is a result of an intentional decision.
●Resolved: Adjusted program implementation to eliminate the risk.
●Mitigated: Implemented actions to minimize the impact or likelihood of the risk.

Critical Severity Issues

CR-01 Unfair Lotteries through Weak Randomness

Location:

●clarity/contracts/pool/alex-launchpad.clar

Users can validate their tickets during the registration process, delimited by the variables registration-start and registration-end. A counter is increased for each ticket validated, and each user has a range of positions related to when they joined the lottery and the amount of tickets validated. When the registration ends and the minimum amount of participants is reached, users can call claim() one time for each ticket validated.

This function determines if the ticket is a winner based on a pseudo-random number modulo the counter of tickets. If the resulting value is in the range of positions of tickets validated by the user, then it is a winner ticket.

However, the first pseudo-random number is generated based on the vrf-seed of registration-start block in the first call to claim(). For the subsequent calls, the function calculates a new pseudo-random based on the latest random.
Therefore, since the contract is public and the process transparent, anyone can calculate the sequence of values to be generated. Users can speculate with which position is the most convenient to register themselves and when to claim based on the following number in the sequence.

Recommendation

The speculation in the registration can be solved using the VRF seed of the block next to the end of the registration (registration-end + 1) as randomness source.
Finally, the speculation in the claiming order can be solved computing the
pseudo-random number with the mentioned VRF seed and a value unique for each ticket (e.g., the ticket’s position). Then, using two constant values, the claiming order will not have an impact because the random number is already determined.

Status

Acknowledged. claim() now uses registration-end instead of
registration-start for the VRF seed. The speculation was reduced, but it still uses a seed that can be known if register() is called at registration-end. Using the block next to registration-end can solve the problem.
The new changes also made the entire random sequence unpredictable. However, the next random still can be predicted and the user might check if this random is beneficial and wait for the next random if not. In order to avoid the speculation in the claiming order, the number should be generated with either an input unknown for the user or constant values. The first solution makes the next random unpredictable for the user, while the second one makes it constant.

Medium Severity Issues

ME-01 Insecure Authentication through tx-sender

Location:

●clarity/contracts/alex-vault.clar,
●clarity/contracts/pool/alex-launchpad.clar,
●clarity/contracts/pool/alex-reserve-pool.clar

Global variable tx-sender returns the original sender of the current transaction, or if as-contract was called to modify the sending context, it returns that contract principal. Using this variable for authentication is not secure. Actors in the system could be targets of phishing. This is analogous to what happens to tx.origin and msg.sender in Solidity. There, the convention is to use msg.sender, which works like the contract-caller.
For instance, the vault’s owner can be tricked into calling a malicious contract which executes vault.set-contract-owner() against his will.

Recommendation

Prefer contract-caller to tx-sender for authentication. contract-caller
returns the caller of the current contract context.

Status

Acknowledged. A new development would address this issue.

ME-02 Independent Winning Probability in Lottery

Location:

●clarity/contracts/pool/alex-launchpad.clar

As it was described in CR-01, each claim() execution generates a new random number. Therefore, while there are tokens to transfer, the winning probability is independent and the amount of winners is unknown. In order to solve it, the function checks if all the tickets provided were won before executing the rest of the function. When all the winner tickets are determined, the listing is completed and new claims are not accepted. This mechanism may result in two issues.

Firstly, some tokens might not be claimed if there are not enough winner tickets. Furthermore, there is no use given to this remainder tokens.

Secondly, it generates a race condition between the users to claim before the listing is completed. Otherwise, a user will not be able to claim
even when he has tickets.

Recommendation

A solution would be to generate only n random numbers, where n is the number of winning tickets. Then, claim() would check if one of the random numbers were in the user’s range of tickets. However, due to Clarity limitations, this solution cannot be implemented.

Status

Acknowledged.

Minor Severity Issues

MI-01 Arithmetic Underflow Calculating Staking Reward

Location:

●clarity/contracts/pool/alex-reserve-pool.clar:[379]

In get-entitled-staking-reward(), the rewards are calculated with the quotient between the amount staked by the user and the total amount staked, multiplied by the token’s coinbase amount.

Quotient’s result may have a higher imprecision than the result obtained by
multiplying first and then dividing it by the total staked.

Recommendation:

For a more precise result, get the product between the coinbase amount and the amount staked by the user, and divide it by the total amount staked:

Status

Resolved.

MI-02 Ended Pool can be Created

Location:

●clarity/contracts/pool/alex-launchpad.clar

Pool creation function (create-pool()) does not validate the block numbers provided for the registration-start and registration-end variables. Therefore, a pool can be created without time for registration.

Recommendation

The input registration-start should be checked to be equal or greater than the current block number.

Status

Resolved.

Enhancements

These items do not represent a security risk. They are best practices that we
suggest implementing.

Table

Details

EN-01 Missing Source Code Comments

Location:

●clarity/contracts/pool/alex-launchpad.clar

The launchpad contract lacks of function documentation in the source code.
Comments documenting a function helps the contract reader to understand better the usage of that piece of code.

Status

Not implemented. The development team committed to add the documentation.

EN-02 Unnecessary Computation to Check if the Listing Is Activated

Location:

●clarity/contracts/pool/alex-launchpad.clar

The listing mapping contains a variable named activated that is initially set to false when the pool is created and then increased for each new register. The register() function updates the value to true if the amount of tickets validated (total-subscribed) reached the activation-threshold.

There is no other function that updates the total-subscribed value nor the activated value. However, the getter function is-listing-activated() computes again the comparison between the two variables instead of reading from the activated variable.

Recommendation:

Read from the activated variable instead of performing the comparison again.

Status

Implemented.

Changelog

●2022-01-07 – Initial report based on commit
44c44846bfbcce6096be04bd1380728c98f09ec8.
●2022-01-11 – Reaudit report based on the fixes in commit
31a5d660c83d41c10cd1b34498f02bc3a407721e.
●2022-01-13 – CR-01 state changed to “acknowledged”.

Disclaimer: This audit report is not a security warranty, investment advice, or an approval of the AlexGo project since CoinFabrik has not reviewed its platform. Moreover, it does not provide a smart contract code faultlessness guarantee.

Avalaunch Audit <> Allocation Staking and Cooldown feature

Introduction

CoinFabrik was asked to audit the contracts for the Avalaunch AllocationStaking project. First we will provide a summary of our discoveries and then we will show the details of our findings.

Summary

The contracts audited are from the GitHub repository at
https://github.com/avalaunch-app/xava-protocol.

The audit is based on the commit fc32d84a67233ebba6f980182a951076858d30c0.

Contracts

The audited contracts are:

● contracts/AllocationStaking.sol
● contracts/sales/AvalaunchSale.sol
● contracts/sales/SalesFactory.sol

Analyses

The following analyses were performed:

● Misuse of the different call methods
● Integer overflow errors
● Division by zero errors
● Outdated version of Solidity compiler
● Front running attacks
● Reentrancy attacks
● Misuse of block timestamps
● Softlock denial of service attacks
● Functions with excessive gas cost
● Missing or misused function qualifiers
● Needlessly complex code and contract interactions
● Poor or nonexistent error handling
● Failure to use a withdrawal pattern
● Insufficient validation of the input parameters
● Incorrect handling of cryptographic signatures

Findings and Fixes

Severity Classification

Security risks are classified as follows:

Critical: These are issues that we manage to exploit. They compromise the system seriously. They must be fixed immediately.
Medium: These are potentially exploitable issues. Even though we did not
manage to exploit them or their impact is not clear, they might represent a
security risk in the near future. We suggest fixing them as soon as possible.
Minor: These issues represent problems that are relatively small or difficult to take advantage of but can be exploited in combination with other issues. These kinds of issues do not block deployments in production environments. They should be taken into account and be fixed when possible.
Enhancement: These kinds of findings do not represent a security risk. They are best practices that we suggest to implement.

This classification is summarized in the following table:

Issues Found by Severity

Critical Severity Issues

No issues found.

Medium Severity Issues

No issues found.

Minor Severity Issues

MI-01 Failure to Use safeMath Library

The functions fund() (line 120), totalPending() (line 196) and erc20Transfer() (line 412) make use of standard arithmetic which are susceptible to overflows and underflows.

Recommendation

Replace + by add() and – by sub().

Enhancements

EN-01 Unvalidated Input in Function and Constructor

The following are functions and constructors that fail to validate the input. In most cases, they are used to set parameters which may be changed later and the impact of setting a bad parameter is small.

  • The parameter _token in setSaleParams() is not checked to be non-null.
  • The input addresses _erc20 and _salesFactory in the AllocationStaking constructor are not checked to be non-null.

Conclusion

We found the contracts to be simple and straightforward and have an adequate amount of documentation. A minor vulnerability pointing to unsafe use of math was found in some functions with little security impact.

Disclaimer: This audit report is not a security warranty, investment advice, or an approval of the Avalaunch project since CoinFabrik has not reviewed its platform. Moreover, it does not provide a smart contract code faultlessness guarantee.

Alex Logo

AlexGo Audit

Introduction

CoinFabrik was asked to audit the contracts for the AlexGo project. First we will provide a summary of our discoveries and then we will show the details of our findings.

Summary

The contracts audited are from the alex-v1 repository at
https://github.com/alexgo-io/alex-v1. The audit is based on the commit
0913c9eb0c8f79b3cd0b843641075ce27d437c96. Fixes were made and rechecked based on the commit feb43898de520ca1c55a6d8bc5bcf2d6f7df8ffa.

Contracts

The audited contracts are:

● clarity/contracts/equations/weighted-equation.clar: Library for
weighted math functions.
● clarity/contracts/equations/yield-token-equation.clar: Library for
yield token math functions.
● clarity/contracts/pool/alex-reserve-pool.clar: Staking contract.
● clarity/contracts/pool/collateral-rebalancing-pool.clar: Lending
and borrowing pool contract with pools of variable weights.
● clarity/contracts/pool/fixed-weight-pool.clar: Contract with
fixed-weight liquidity pools.
● clarity/contracts/pool/liquidity-bootstrapping-pool.clar:
Contract with liquidity pools that increase bootstrapped token weight over
the time.
● clarity/contracts/pool/yield-token-pool.clar: Liquidity pools for
token and correspondent yield token pairs.

Analyses

The following analyses were performed:

● Misuse of the different call methods
● Integer overflow errors
● Division by zero errors
● Front running attacks
● Reentrancy attacks
● Misuse of block timestamps
● Softlock denial of service attacks
● Functions with excessive gas cost
● Missing or misused function qualifiers
● Needlessly complex code and contract interactions
● Poor or nonexistent error handling
● Failure to use a withdrawal pattern
● Insufficient validation of the input parameters
● Incorrect handling of cryptographic signatures

Findings and Fixes

Severity Classification

Security risks are classified as follows:

Critical: These are issues that we manage to exploit. They compromise the system seriously. They must be fixed immediately.
Medium: These are potentially exploitable issues. Even though we did not
manage to exploit them or their impact is not clear, they might represent a
security risk in the near future. We suggest fixing them as soon as possible.
Minor: These issues represent problems that are relatively small or difficult to take advantage of but can be exploited in combination with other issues. These kinds of issues do not block deployments in production environments. They should be taken into account and be fixed when possible.
Enhancement: These kinds of findings do not represent a security risk. They are best practices that we suggest to implement.

This classification is summarized in the following table:

Issues Found by Severity

Critical Severity Issues

CR-01 Pools Transfer More Tokens than Expected

The function add-to-position() in the contracts
liquidity-bootstrapping-pool.clar and fixed-weight-pool.clar receives as a parameter how many tokens the user would like to provide to the pool. In order to conform the pool balance, the function calculates the amount of tokens y to be provided based on the amount of token x. As a consequence, the actual value provided to the pool could be greater than the one specified by the user. The result would be the contract moving more tokens than the ones consented by the user.

Recommendation

The actual amount of token y to be provided to the pool should never be greater than the value defined by the user (dy). This could be done by adding an asserts! that compares those values.

Solution

Fixed according to the recommendation

CR-02 Lost Funds when Burning Yield Tokens

In a collateral rebalancing pool (collateral-rebalancing-pool.clar), liquidity providers get an amount of yield and key tokens equal to the provided liquidity multiplied by ltv (Loan-to-Value). When yield tokens are burnt calling reduce-position-yield(), the pool is completely rebalanced, swapping all the collateral. Then, for instance, if a user owns 100% of the pool value and burns all his yield tokens, the balance stored in the blockchain will be reduced to zero.
However, the user gets transferred only the exact amount of yield token burnt (balance * ltv). Since this does not represent the actual value provided, users will realize they lost funds when they try to burn their key tokens and receive zero tokens because the pool is empty.

Recommendation

Subtract from the pool balance the same amount transferred to the user.

Solution

Fixed according to the recommendation.

CR-03 Denial of Service when Burning Yield Tokens

In a collateral rebalancing pool (collateral-rebalancing-pool.clar), when yield tokens are burnt calling reduce-position-yield(), the pool is completely rebalanced, swapping all the collateral (i.e., it becomes a 0-100 pool). As a consequence, it becomes unusable for token swaps since either the input or output value will be greater than the zero-balance, causing the transaction to revert because of the assertions made in weighted-equation.clar. These assertions verify the value deposited to a pool in an A token is lower than that token’s balance multiplied by a ratio, and also the amount of B tokens given in exchange is lower than that token’s balance multiplied by a ratio.
Moreover, this Denial of Service would be most of the time unintentionally executed by the users and would persist until someone provides liquidity to the pool again, incrementing the zero-balance.

Solution

Swap functions can only be called before the expiration block.

Medium Severity Issues

ME-01 Denial of Service when Burning Key Tokens

In a collateral rebalancing pool (collateral-rebalancing-pool.clar), if all the key tokens were burnt and the reserve pool (alex-reserve-pool.clar) does not have tokens in its balance, users might not burn any amount of their yield tokens.
Since reduce-position-yield() swaps all the collateral, a new balance of the token is calculated based on the previous balance and the amount of tokens received after the swap. Then, the function calculates a variable
shares-to-yield which is equal to the amount of yield tokens the user wants to burn (shares) divided by its total supply (yield-supply). Afterwards, it calculates dy, the product of new-bal-y and shares-to-yield, and compares dy to shares.
Since the pool only has a value equal to the yield supply, it is swapped and fees are taken out, dy will be lower than shares. Therefore, in line 496, it calls alex-reserve-pool.remove-from-balance() to transfer the shortfall, but if alex-reserve-pool does not have tokens, it will revert.

Solution

Changes made to fix CR-02 solved this issue.

Minor Severity Issues

MI-01 Low Decimal Precision

Clarity integer types are stored in 128-bit storage slots. In order to represent the fractional part, a fixed point precision is used with 8 decimal for the fractional part and 30 for the whole part. However, this precision is low and can result in significant decimal errors in the long term.

Recommendation

Since the whole part is more than long enough, the precision could be increased to, for instance, 18 decimal places.

Solution

The development team is studying the implementation of a higher decimal
precision.

MI-02 Funds Taken because of Liquidity Pool Token Repetition

Whenever users provide liquidity to a pool, they receive liquidity pool tokens (LP tokens). If two pools were created with the same LP token, users could provide liquidity in one of those pools and withdraw funds from the other. Currently, only the contract owners can create pools and it is at their discretion.

Recommendation

Restrict LP token repetition, not only in each contract, but also across pool
contracts: fixed-weight-pool.clar, liquidity-bootstrapping-pool.clar, yield-token-pool.clar. These are the pools that share the same trait for the LP tokens.

Solution

The development team is considering maintaining a registry contract that is
updated every time a pool is created and checks if the principal address of the pool token passed is already in use.

MI-03 Swap Limit Setter not Restricted

Amounts swapped are limited in order not to be larger than a certain percentage of total balance (MAX-IN-RATIO and MAX-OUT-RATIO). These values are set initially to 30% in weighted-equation.clar and yield-token-equation.clar, but they can be modified without restriction. It can result in a denial of service if the value is too small.

Recommendation

Setters should check the new value is, at least, greater than zero with an asserts!.

Solution

Fixed according to the recommendation.

MI-04 Front-running after Pool Creation

Liquidity bootstrapping pools (liquidity-bootstrapping-pool.clar) are created with a default value for maximum and minimum prices for bootstrapped token (maximum is set to 10^8 and minimum to zero). They can be changed, but only calling the setter in another transaction. Since the pool creator must provide liquidity in the same transaction they created the pool, under certain market conditions, an attacker might find it profitable to execute a swap immediately after the pool creation and before the maximum and minimum are modified.

Recommendation

Add two parameters to create-pool() to assign initial values for price-x-min and price-x-max.

Solution

Fixed according to the recommendation.

MI-05 New Max Expiry in the Past

In yield-token-pool.clar, max-expiry is a variable essential to calculate the time to maturity. If this variable is lower or equal to the current block, most of the transactions will revert, causing a denial of service in that contract. Currently, its setter, set-max-expiry(), does not check if the new value is valid.

Recommendation

Add an asserts! to check new-max-expiry is greater than block-height before assigning it to max-expiry.

Solution

Fixed according to the recommendation.

Enhancements

EN-01 Unused Math Constants and Functions

Useful math functions and constants are copied in the contracts. However, they are not always used by the rest of the contract functions and make the deployment more expensive. For instance, in collateral-rebalancing-pool.clar, pow-up(), ONE_10, log-fixed() and ln-fixed() are not used.

Recommendation

Remove the functions that are not necessary for the contracts.

Other Considerations

  1. collateral-rebalancing-pool.clar uses an approximation for the error function (Abramowitz and Stegun) which has a high maximum error. The recommendation is to extensively test it to assure it does not have unexpected implications.
  2. In yield-token-pool contract, max-expiry value is based on a 15-second block time. AlexGo team explained it is set for the mocknet environment. It should be changed to 10 minutes when it is deployed to Stacks mainnet.

Conclusion

We found the contracts to be simple and straightforward and have an adequate amount of documentation, but not always up-to-date. Three critical, one medium and five minor severity issues were found. Additionally, an enhancement was proposed. The development team fixed seven issues and acknowledged two minor issues.

Disclaimer: This audit report is not a security warranty, investment advice, or an approval of the AlexGo project since CoinFabrik has not reviewed its platform. Moreover, it does not provide a smart contract code faultlessness guarantee.

Censura de dados prejudiciais em blockchains

Autor: Hartwig Mayer, 10 de outubro de 2019

Introdução: Confirmação do Problema

Os blockchains públicos permitem a inserção de dados arbitrários. Até mesmo blockchains de propósito específico, como o Bitcoin, já contêm muitos dados não financeiros. Embora essa inserção de dados possa ser benéfica em alguns casos de uso (por exemplo, Proof of Existence – PoE), ela também pode causar danos. Se uma blockchain contivesse vídeos com instruções sobre como torturar alguém, haveria imediatamente um consenso geral de que esses dados deveriam ser excluídos. Mas, como os blockchains devem ser bancos de dados imutáveis, a questão é: o que pode ser feito se isso acontecer?

Em nosso artigo anterior (Imutabilidade: existe um limite?) Discutimos a inserção de dados não financeiros em blockchains de uma perspectiva diferente. O exemplo foi um relatório publicado contendo informações importantes para a sociedade, mas que incomodam um pequeno grupo de pessoas. A análise mostrou métodos realistas de censura de dados do blockchain, explorando vulnerabilidades e limitações conhecidas desta tecnologia. Em um cenário, a censura é desejável e em outro não.

Nas páginas a seguir revisamos dois artigos que propõem formas de apagar dados quando há amplo consenso, sem ter que reiniciar o sistema e sem colocar em risco toda o blockchain. Os artigos em revisão são Apagando Dados de Nodes Blockchain [BF19] e Blockchain redutível na configuração sem permissão [DM19].

Outra estratégia evita tais situações filtrando os dados antes que eles entrem no blockchain. O artigo [HH18b] pesquisa quais informações não financeiras já entraram no blockchain do Bitcoin. Também revisamos o artigo Impedindo a Inserção Indesejada de Conteúdo da Blockchain [HH18a], que discute métodos para impedir a inserção de dados não financeiros.

Projetos de Blockchain Editáveis

Blockchains criam uma sequência de blocos de dados em que o conteúdo de cada bloco é bloqueado por seu sucessor (consulte a Figura 1).

Figura 1: Cada bloco é “bloqueado, travado” por seu bloco sucessor.

Blockchains têm dois elementos principais para atingir esse tipo de bloqueio:

1. Uma rede que segue um protocolo para armazenar, manter e compartilhar as informações do blockchain com novos pares.

2. Uma função que é resistente à colisão: uma função H para a qual é (quase) impossível encontrar dois blocos diferentes B, B ‘que são mapeados para a mesma saída, ou seja, H (B) = H (B’).

As funções de hash são usadas para bloquear os blocos juntos, o que explica a terminologia comum: BlockHash para o hash H (B) do bloco B e PrevBlockHash para o hash do bloco anterior (consulte a Figura 2). O conteúdo do bloco Bi-1 é bloqueado para si mesmo incluindo H (Bi-1) para seu sucessor Bi. Se alguém edita / suprime o bloco Bi-1 resultando em um novo bloco B ‘, então todos os pares, novos e antigos, podem notar essa mudança, já que o cálculo de BlockHash H (B’) não coincidiria com o valor PrevBlockHash H (Bi-1) no bloco Bi.

Figura 2: Os blocos são “encadeados” usando funções hash resistentes a colisões. Os blocos contêm metadados no BlockHeader, entre eles o PrevBlockHash. Os blocos também contêm uma lista de transações.

Uma abordagem para a edição do blockchain é por meio de uma função que permite que um grupo específico de usuários produza colisões. O artigo [AM17] interrompe essa abordagem em que uma parte de um trapdoor (função armadilha) é fornecida a cada membro do grupo. Todo o grupo deve consentir em desbloquear as conexões e redigir o bloqueio. Isso só funciona bem para casos de uso especiais. Conforme mencionado no artigo [DM19], o método da chave trapdoor é insuficiente para redes como a rede Bitcoin: ele não pode ser dimensionado para grandes redes e apenas os detentores da chave trapdoor estão cientes dos dados alterados, reduzindo a transparência.

Nas páginas seguintes, revisamos e comparamos os artigos [BF19] e [DM19], que apresentam um mecanismo de edição para a rede Bitcoin. Sua contribuição está na modificação do primeiro elemento para o “bloqueio” entre os blocos, introduzindo outra camada de comunicação entre os nodes da rede. Ambos fazem uso do fato de que os servidores de node completo têm o blockchain inteiro e podem suprimir sua cópia armazenada localmente do livro-razão, uma prática já usada para apagar partes antigas do blockchain para redução de armazenamento.

Apagando Dados de Nodes Blockchain

Visão Geral da Proposta

Os autores de [BF19] sugerem alterar o protocolo de rede para tornar possível o apagamento de dados. Os nodes da rede marcam os dados que devem ser apagados em seu banco de dados de eliminação local (semelhante ao banco de dados chainstate no cliente Bitcoind) antes de excluir os dados de sua cópia do blockchain. Dessa forma, fica garantida a responsabilidade pelos dados apagados, necessária para evitar a solicitação desses dados novamente a outros nodes e para diferenciar entre dados inexistentes e apagados. A mudança de protocolo proposta sugere uma política de validação de transação para os nodes quando eles se deparam com uma transação referente aos dados que eles apagaram de sua cópia local do blockchain. A política é baseada na mesma ideia do método de verificação de pagamento simplificado. Para obter mais detalhes, consulte a seção Detalhes de Protocolo de Eliminação de Dados de Nodes de Blockchain.

Escopo da Pesquisa

A proposta funciona em geral para qualquer blockchain baseada no modelo UTXO que inclua o modelo Bitcoin. A mudança de protocolo proposta não atrapalha a funcionalidade de todo o sistema blockchain e pode ser implantada sem intervir na arquitetura central do blockchain. A pesquisa não inclui um mecanismo descentralizado para encontrar consenso sobre quais dados devem ser removidos. Os autores demonstram a viabilidade da proposta por meio de uma implementação de prova de conceito utilizando o software Bitcoind para participação na rede Bitcoin.

Resumo das Limitações

Os autores de [BF19] apresentam uma maneira interessante e muito pragmática de apagar dados em blockchains, mas a proposta atual vem com certas limitações:

Resumo das Limitações

A proposta não cobre a eliminação de todos os métodos de inserção de dados possíveis discutidos na pesquisa [SSV19]. O foco é definido apenas em um campo de dados, isto é, os dados de saída da transação scriptPubKey (para obter mais detalhes, consulte Detalhes do Protocolo para Apagar Dados).

A proposta não inclui um mecanismo de consenso descentralizado para chegar a um acordo e responsabilidade sobre a eliminação de dados específicos. Em vez disso, o consenso é alcançado fora da cadeia e a responsabilidade é gerenciada localmente. Por exemplo, através da publicação em uma página da web as identidades de transação a serem apagadas e os nodes atualizam seu banco de dados de eliminação localmente.

Limitações de compatibilidade

Os nodes que não estão atualizando seu software para essas alterações recentemente propostas, ocasionalmente divergirão dos nodes que executam o software atualizado. Portanto, o novo protocolo de validação deve ser introduzido como um soft fork.

Limitações de Segurança

A mudança de protocolo proposta aumenta a probabilidade de forks de blockchain que impactam a segurança de todo o sistema (ver [GK16]). Embora os forks só possam ser criados por um usuário desonesto, isso abre um novo vetor de ataque. Um estudo formal das implicações de segurança está faltando.

A validação de cadeia refere-se ao processo que os nodes de rede novos ou fora de sincronia executam para garantir que as informações de blockchain recebidas sejam realmente válidas. A eliminação de dados torna impossível para novos nodes validar a cadeia, uma vez que os dados apagados estão faltando para calcular e verificar o valor da BlockHash.

Limitações da implementação de Proof of Concept

Suas restrições atuais de implementação são devido ao uso da lógica de eliminação de lixo existente do software cliente Bitcoind:

  • Mais dados são apagados além de apenas o arquivo de dados indesejados, ou seja, todos os blocos até a altura do alvo/objetivo. Portanto, os nodes que apagam dados não serão mais nodes completos arquivando e indexando o blockchain completo.
  • O apagamento completo pode ser feito não antes de aproximadamente 50 horas após o conteúdo ter sido incluído na cadeia ativa devido à lógica de remoção do Bitcoind.
  • Sugere-se evitar o uso do protocolo no modo de mineração, pois pode causar forks de blockchain. Portanto, a rede ainda terá muitos nodes completos, ou seja, nodes de mineração, que ainda disponibilizarão os dados apagados por meio de suas cópias locais.

• A implementação da prova de conceito é ainda mais restrita a saídas de transações que não são transações SegWit.

Blockchain editável na configuração não permissionada

Visão geral da proposta

Os autores do segundo artigo [DM19] propõem um método seguro para o apagamento de dados. Os nodes da rede podem propor a edição de campos de dados armazenados no blockchain. Para que esta proposta seja aprovada, uma política de validação especificada deve ser seguida, que inclui que a maioria dos nodes da rede votem nas propostas dentro de um determinado período de tempo. A validação da cadeia e do bloco é modificada para capturar os blocos editados.

Escopo da Pesquisa

A proposta pode ser aplicada a blockchains baseada em Proof of Work (PoW) e pode ser facilmente adaptada a qualquer mecanismo de consenso. A proposta requer mudanças do protocolo blockchain principal. Ele introduz um mecanismo de votação descentralizado usando a infraestrutura blockchain disponível para decidir quais dados devem ser apagados. Como um subproduto, todas as informações sobre as edições do blockchain são escritas de forma transparente no livro-razão. A pesquisa inclui uma análise de segurança formal rigorosa e fornece uma implementação de prova de conceito para demonstrar a viabilidade da proposta.

Resumo das Limitações

Os autores de [DM19] apresentam um método interessante e comprovado como seguro para o apagamento de dados em blockchains.

Limitações Funcionais

A proposta permite alterar apenas os componentes das transações que não afetam a consistência de eventos passados ​​e futuros, por ex. OP_RETURN em Bitcoin. Este formulário, não abrange todos os métodos de inserção de dados (ver [SSV19]), por ex. a saída da transação PaytoPublicKeyHash (P2PKH), que é um componente que pode ser gasto, embora se usado para dados arbitrários, não pode ser gasto. Esta restrição não se deve a razões técnicas, mas para proteger os usuários de eventuais inconsistências futuras no blockchain. De qualquer forma, essas restrições podem ser ajustadas. É mais um mecanismo para remover a responsabilidade do usuário em decidir quais novas edições/redações podem causar inconsistências na cadeia no futuro.

Limitações de compatibilidade

A proposta requer que os nodes da rede modifiquem seu software para executar o protocolo aprimorado. Em particular, a estrutura do bloco Bitcoin deve acomodar outro campo (para obter mais informações, consulte a seção Detalhes de Protocolo para Blockchains Editáveis). Isso exigiria um hard fork da blockchain do Bitcoin e, portanto, o apoio de toda a comunidade.

Limitações de Segurança

Existe um risco aumentado de Ataque de Negação de Serviço (DoS), uma vez que mineradores mal-intencionados podem incluir muitas solicitações de edição para diminuir o desempenho geral do sistema.

Desempenho

O protocolo aprimorado produz uma nova sobrecarga devido à votação e validação adicionais para transações editadas, mas os testes de sua implementação de prova de conceito mostram que a sobrecarga adicional é muito pequena.

Limitações da implementação da Proof of Concept

A implementação da Proof of Concept está em um ambiente de teste que imita todas as funcionalidades básicas do Bitcoin. Inclui a linguagem de script Bitcoin que permite inserir dados arbitrários na cadeia, que podem ser editados posteriormente. Um teste na rede Bitcoin atual não é viável, pois isso exigiria que todos os nodes atualizassem seus softwares.

Comparação

Na Tabela 1, resumimos as limitações e pontos fortes de ambas as propostas para a blockchain do Bitcoin medindo-os em relação às seguintes métricas:

Limitações Funcionais

• Faixa de dados editáveis: o mecanismo de edição cobre todo o espectro de possíveis componentes de inserção de dados?

• Votação descentralizada: o protocolo fornece um sistema descentralizado para propor e votar em solicitações de edição?

Limitações de compatibilidade

Fácil Adoção de Protocolo: A mudança de protocolo requer suporte apenas da comunidade (Sim) ou também requer uma mudança na arquitetura central do blockchain (Não)?

Limitações de Segurança

• Responsabilidade: o protocolo fornece um método seguro e transparente para contabilizar todas as solicitações aprovadas de edição?

Análise de Segurança: Não há análise de segurança (Baixa), há uma discussão sobre segurança (Média) e há uma análise de segurança formal (Alta).

Desempenho

• Escalabilidade: A mudança de protocolo mantém a sobrecarga computacional estável quando comparada à versão original do blockchain (Sim – Moderado – Não)?

• Crescimento moderado do Blockchain: A alteração do protocolo mantém o crescimento do tamanho da blockchain semelhante à versão original da blockchain? (Sim – Moderado – Não)

Tabela 1: Tabela de Comparação de duas propostas [BF19] e [DM19] para edição de dados no blockchain

Prevenção de inserção de dados indesejados

Impedindo a inserção indesejada de conteúdo no blockchain

Visão geral da proposta e escopo da pesquisa

Os autores do artigo [HH18a] analisam métodos de filtragem de conteúdo tendo o Bitcoin como principal exemplo. Eles primeiro identificam o padrão de transações que transportam dados indesejados e, em seguida, propõem contramedidas contra a inserção de dados indesejados:

1. Detectores de conteúdo: transações com dados de grande porte que transportam muitas saídas de transação com texto geram sinais positivos, o que resulta na exclusão dessas transações em blocos durante a geração de blocos.

2. Incentivos econômicos: Uma política de taxas de transação, que aumenta a taxa de acordo com o tamanho dos dados da transação. Isso torna o sistema menos atraente para a inserção de dados não financeiros, visto que eles deveriam ser grandes, enquanto as transações financeiras padrão permanecem “baratas”.

Por fim, os autores propõem Compromissos de Identificador (Cis) – uma nova ferramenta de criptografia que permite que nodes completos verifiquem se os endereços do receptor na saída da transação são endereços válidos ou dados arbitrários. Isso permite identificar e descartar transações com dados prejudiciais durante a geração do bloco. No protocolo Bitcoin atual, apenas quando as transações são gastas, os nodes verificam a validade do endereço do receptor, mas a essa altura eles já fazem parte do blockchain.

Resumo das Limitações

Limitações Funcionais

Os detectores de conteúdo não podem capturar todos os dados indesejados, por exemplo, impedir a inserção de arquivos binários não é viável por meio desta abordagem.

Da mesma forma, a introdução de incentivos econômicos não impede todos os casos. Não está claro qual deve ser o preço de publicação em Bitcoin para evitar qualquer inserção de dados indesejados no blockchain. Qual é o preço de prejudicar a reputação de outra pessoa ou mostrar qualquer tipo de dado prejudicial?

Limitações de compatibilidade

Ambos os métodos de filtragem são fáceis de implantar. A introdução de ICs requer que os nodes da rede modifiquem o software do blockchain para participar com o novo protocolo. Isso requer que toda a comunidade apoie a mudança de protocolo.

Desempenho

A introdução de ICs implica que os nodes de validação têm mais trabalho computacional a realizar, mas o overhead computacional é mínimo.

Detalhes e análise do protocolo

Lembrete do formato de transação Bitcoin

Uma transação T possui dados de entrada e saída, bem como um identificador de transação iT (TxID) – o hash da transação T. Os dados de entrada (prevOut) fazem referência a transações anteriores usando o TxID (consulte a Figura 3). O remetente deve fornecer uma prova de autenticação para gastar esta entrada (ScriptSig) e ele deve especificar nos dados de saída o valor da transação (Valor) e o endereço do destinatário (scriptPubKey).

Figura 3: Formato de transação simplificado

Detalhes de Protocolo de Apagamento de Dados de Nodes de Blockchain

O protocolo proposto [BF19] permite apenas apagar dados indesejados armazenados no campo de dados de saída scriptPubKey. Os nodes executam as seguintes etapas:

1. Apague os dados X de uma transação T com TxID iTresultando em uma transação T ‘.

2. Armazene T ’em um banco de dados de apagamento junto com o identificador iT.

3. Apague fisicamente T da cópia local do blockchain.

Apagar dados do blockchain pode causar problemas ao validar transações referentes a dados apagados. A política proposta é a seguinte:

1. As transações não confirmadas, ou seja, as transações que ainda não fazem parte do blockchain, mas apenas “fofocadas” entre os nodes da rede para inclusão no próximo bloco, são sempre consideradas inválidas e não são comunicadas a outros pares se fizerem referência a dados apagados.

2. As transações confirmadas, ou seja, as transações já aprovadas pela rede e que fazem parte do blockchain, são sempre consideradas válidas, mesmo que façam referência a dados apagados.

Análise de Apagamento de Dados de Nodes de Blockchain

Para facilitar a exposição, usamos os termos nodes honestos para nodes que seguem o antigo protocolo de validação e nodes de apagamento para nodes que apagam dados e seguem a nova política de validação aprimorada. Tanto os nodes honestos quanto os nodes apagadores são “honestos” em oposição aos nodes desonestos, que não seguem um protocolo específico o tempo todo.

Observação 1

A nova política de validação não afeta a segurança do blockchain quando aplicada a transações não confirmadas. Os problemas surgem quando o blockchain contém transações confirmadas com uma referência a dados de saída mais antigos que eram dados arbitrários e não um endereço de receptor válido. Observe que isso só pode acontecer quando a transação foi explorada por um node desonesto ou um node não validador (um node que não válida para recursos seguros e corre o risco de perder a recompensa do bloco). Tais transações são transações inválidas devido aos dados de entrada incorretos e não são incluídas nas propostas de bloco nem por nodes honestos nem apagadores. Por este motivo, a ocorrência de transações confirmadas com dados apagados não é frequente, mas a possibilidade não pode ser excluída uma vez que pode ser produzida por mineiros desonestos dependendo do seu poder de mineração.

Como mencionado no artigo, nesses casos, haverá um desacordo sobre a validade de tais transações entre nodes honestos e apagadores da rede. Dependendo de qual grupo supera o outro, as transações são finalmente consideradas como inválidas ou válidas. Isso leva aos seguintes novos riscos adicionais em comparação com o protocolo original (Bitcoin):

Maior número de forks:

Discordâncias sobre a validade de transações específicas entre nodes honestos e de apagamento são refletidas como “forks” no blockchain. Normalmente, estas bifurcações aparecem devido a atrasos na comunicação da rede, resultando em uma falta de sincronização entre os nodes. Em muitos protocolos de blockchain, a regra da cadeia mais longa ajuda os mineiros a se reconciliarem após uma bifurcação indesejada: a cadeia mais longa é a válida. Isso também acarreta problemas de segurança, como ataques de gasto duplo que são bifurcações intencionais. Este tópico é bem estudado em [GK16]. A política de validação aprimorada proposta em [BF19] aumenta as chances de desacordos temporais que podem ser explorados por nodes desonestos, embora mais estudos sobre as implicações de segurança sejam necessários.

Explorando forks:

A análise de risco em [BF19] considera dois casos: 1) Os nodes de apagamento formam a minoria. 2) Os nodes de apagamento constituem a maioria. A análise não reflete a estabilidade do sistema quanto a sua dependência da porcentagem de nodes desonestos. Por exemplo, se assumirmos que 15% da rede é desonesta e os nodes de apagamento formam uma minoria de 36%, uma transação confirmada com referência a dados apagados pode fazer parte da cadeia mais longa (ou seja, considerada válida), dependendo da decisão da parte desonesta.

Soft Forks:

Além disso, neste caso, a situação é diferente de ataques de gasto duplo em que duas cadeias válidas são apresentadas e a regra da cadeia mais longa decide qual é a correta. Aqui, os mineiros honestos, que não apagam os dados indesejados, considerarão a cadeia mais longa como uma cadeia inválida quando um node de apagamento minar um bloco com uma referência aos dados apagados. Isso leva a uma “divisão” permanente da rede se houver uma maioria de nodes de apagamento, não apenas uma bifurcação temporal, uma vez que nodes honestos não seguem o protocolo dos nodes de apagamento. Isso implica que a proposta deve ser apresentada como um soft fork. Vemos isso como um problema, desde que o banco de dados apagado seja mantido localmente e não haja uma visão comum sobre esse banco de dados.

Observação: Se supormos que 100% da comunidade concorda com quais dados devem ser removidos e apagados de suas cópias locais, então não há risco de forks adicionais. No entanto, isso exigiria um bom sistema de responsabilidade, onde todos os usuários vissem e agissem com base nas informações. O cenário de consenso total é difícil de imaginar, dada a diversidade cultural e geográfica dentro de qualquer comunidade de blockchain.

Observação 2:

Bootstrapping:

Outro grande risco é a validação da cadeia insegura durante o bootstrapping. O blockchain do Bitcoin tem um método muito seguro para isso que é resistente a Sybil (usando a cadeia mais longa). Como a validação da cadeia requer todos os dados que constituem o blockchain, o apagamento torna a validação da cadeia impossível. Isso pode ser resolvido deixando todos os nodes da rede ou armazenando os dados relevantes em um banco de dados central que novos nodes podem consultar para validar a cadeia. No primeiro caso, os dados indesejados ainda estarão acessíveis a todos, enquanto a segunda solução leva a uma centralização muito forte com todos os riscos implícitos, por exemplo, ponto único de falha, mau uso de energia, etc. Portanto, os autores começaram a definir um método sem confiança para bootstrapping que ainda não foi completamente descrito.

Detalhes de protocolo para blockchain editável

O protocolo do [DM19] tem três componentes: Proposta de edição, validação da proposta e validação de bloco e cadeia. Para contabilizar as edições, o cabeçalho do bloco (consulte a Figura 1) deve acomodar um campo adicional chamado old_MerkleRoot: Todos os blocos contêm uma lista de transações e um compromisso com esse conjunto de transações usando seu MerkleRoot. Quando um bloco é inicialmente criado, ou seja, antes de qualquer edição, este novo campo assume o mesmo valor da raiz Merkle. Se uma edição for aprovada, este campo será atualizado, enquanto old_MerkleRoot armazenará a raiz Merkle antiga para fornecer uma conta transparente no histórico de edição.

Proposta de Edição

Os usuários que desejam propor uma edição constroem uma transação especial editTx que contém a transação original T com seu identificador de transação iT e a transação editada T ’. Em seguida, os nodes transmitem a transação especial editTx que requer uma taxa de transação como de costume. A transação proposta T ‘é validada verificando seu conteúdo em relação a T, e se for válida, pode ser considerada para votação.

Validação da Proposta

O novo protocolo de validação dita os requisitos e restrições para operações de edição no blockchain. Os autores fornecem uma descrição formal e uma descrição informal de uma política (básica) para Bitcoin que poderia ser implementada, que citamos aqui:

• A edição proposta T ‘é idêntica à transação T, exceto que pode remover dados.

• Apenas dados que nunca serão gastos, por exemplo, scripts de saída OP RETURN, podem ser removidos.

• Nenhuma edição de votos pode ser proposta para outras edições na cadeia.

• A edição proposta recebe mais de 50% dos votos nos 1024 blocos consecutivos (período de votação) após o editTx correspondente estar estável na cadeia.

Após uma votação bem-sucedida, os nodes substituem em seu livro razão local a transação T por (iT, T ‘).

Validação de bloco e corrente (block and chain)

Quando os nodes têm que validar um bloco contendo uma transação editada, o node pode verificar se a transação original T estava lá antes e agora é substituída por T ‘. A verificação da primeira parte faz uso do identificador de transação iT e old_MerkleRoot (árvores de Merkle), enquanto a segunda parte é processada localizando o editTx correspondente na cadeia e verificando se a solicitação de edição satisfaz a política de validação.

Quando os nodes precisam validar uma cadeia completa e encontrar um bloco editado, o minerador verifica se a edição foi aprovada. O minerador rejeita uma cadeia como inválida se qualquer um dos seguintes ocorrer: (1) a edição de um bloco não foi aprovada de acordo com a política, (2) o valor MerkleRoot do bloco redigido está incorreto em relação ao conjunto de transações ou (3) uma edição aprovada anteriormente não foi realizada na cadeia.

Análise de Blockchain Editável

Observação 1

Ataque de Negação de Serviço – DoS (Denial of Service Attacks):

Enviar spam para a rede com muitas solicitações de edição pode levar à negação do serviço. No entanto, conforme mencionado no artigo, os mineiros são dissuadidos de fazer isso porque isso incorre no custo de uma taxa de transação para as solicitações de edição. Além disso, uma taxa de transação mais alta para solicitações de edição pode ajudar ainda mais a proteger o sistema contra esse tipo de ataque. De qualquer forma, existem técnicas mais refinadas, conforme listadas aqui, para proteger a rede.

Observação 2

Aumento da sobrecarga computacional:

A votação, a validação de proposta adicional e o protocolo aprimorado para validação de bloco e cadeia aumentam a sobrecarga computacional que os nodes precisam realizar. No entanto, conforme estimado pelos autores usando sua implementação de Proof of Concept, o cálculo extra não deve ser considerado crítico.

Observação 3

Escopo da análise de segurança:

O modelo de segurança de [GKL15] é usado para provar formalmente que as alterações de protocolo propostas não estão afetando a segurança do blockchain. Este modelo de segurança se aplica aos blockchain públicos, incluindo o blockchain do Bitcoin. Embora, por exemplo, o protocolo de Proof of Stake – (PoS) de Ouroboros se baseie nesse artigo, as considerações teóricas do jogo são feitas separadamente. Uma investigação mais aprofundada deve ser feita para saber se a introdução de um mecanismo de edição (com uma política que permita redigir mais componentes da transação) permite ou não outras estratégias racionais com recompensa maior do que a honesta.

Detalhes do protocolo para impedir a inserção de conteúdo indesejado

Detectores e filtragem de conteúdo

Os autores descobriram que quase a totalidade das aproximadas 255 milhões de transações em Bitcoin (em agosto de 2017) tinham no máximo 50 saídas de transações (99,73%). Além disso, de todas as transações, 97,22% têm no máximo 5 saídas e 91,77% têm no máximo 2 saídas. Em contraste, a inserção de dados arbitrários usa mais de 50 saídas de transação devido ao tamanho limitado dos dados nos campos de saída e, portanto, podem ser detectados por meio de seu tamanho maior.

O primeiro método de filtragem detecta se as transações contêm texto, arquivos baseados em ASCII ou quaisquer arquivos binários de imagens ou arquivos. Além disso, os autores apresentam um detector que fornece sinais positivos quando uma transação contém muitos caracteres ASCII imprimíveis distribuídos em muitas (por exemplo, mais de 50) saídas de transação.

O segundo método de filtragem propõe uma taxa mínima obrigatória para penalizar grandes transações. A fórmula para calcular a taxa obrigatória considera o tamanho da transação e o número de saídas, e tem o objetivo de desestimular a inserção de conteúdo não financeiro.

Mudança de protocolo: compromissos do identificador (Indentifier Commitments – IC)

Identifier Commitments (IC) ajudam a evitar a inserção arbitrária de dados colocados nos campos de dados de saída de uma transação. A ideia básica deste conceito consiste em não enviar o endereço público do destinatário no blockchain – que pode conter dados nocivos em vez de um endereço -, mas sim um dado diferente que impede a inserção de dados não financeiros e funciona como endereço do destinatário. Referimo-nos a [HH18a] para mais detalhes sobre a solução técnica.

Análise de como impedir a inserção de conteúdo indesejado

Observação 1

Detector de conteúdo:

O método de filtragem, proposto com base em arquivos de dados de grande porte também pode causar falsos positivos. A alta qualidade de filtragem pode penalizar algumas transações honestas de grande porte, por exemplo, emitido por trocas de criptografia ou um pagamento de receita para muitas partes interessadas. O risco de falsos positivos existe, embora os experimentos mostrem alta probabilidade de sinais corretos. A limitação de tais detectores é que eles são incapazes de detectar campos de dados binários que podem transportar dados perigosos codificados. Esta é a motivação dos autores para apresentar ICs.

Observação 2

Incentivos econômicos:

As taxas obrigatórias mínimas podem afetar os pagamentos com muitos resultados, por exemplo, repartições de recompensas para investidores ou pagamentos de serviços de câmbio. O problema aqui é que quanto melhor a proteção contra a inserção de dados prejudiciais, maior será a penalização de algumas transações financeiras.

Observação 3

Compromissos do identificador:

A introdução de ICs requer uma mudança de software a fim de integrar o conceito e permitir um processo de validação aprimorado. Essa mudança pode ser alcançada facilmente, mas precisa do suporte da comunidade do blockchain.

Os ICs ajudam a rejeitar a inserção de dados prejudiciais nos campos de saída das transações, mas deixam outros métodos de inserção de dados possíveis, conforme discutido em [SSV19], ainda em aberto.

A sobrecarga computacional adicional causada pela validação do IC é insignificante. Nodes completos precisam de apenas 4 segundos a mais de acordo com seus experimentos. Esse atraso não é crítico, pois a geração média de blocos leva cerca de 10 minutos. Os ICs aumentam o tamanho geral da transação, mas a economia no armazenamento do blockchain por meio da anulação de dados não financeiros pode superar o tamanho do blockchain aumentado pelos ICs.

Conclusões

Na Tabela 1, resumimos os aspectos gerais dos protocolos [BF19] e [DM19]. De acordo com nossa análise, o primeiro artigo deve fornecer provas de segurança mais fortes, uma vez que a alteração proposta aumenta o número de forks, o que pode reduzir a segurança de todo o sistema de blockchain. Esses forks também podem resultar em divisões permanentes da comunidade. Se todos os nodes seguirem a política de validação proposta em [BF19], esses dois riscos são eliminados. No entanto, é essencial encontrar um método seguro de concordar sobre quais dados devem ser apagados. Além disso, deve haver um registro verificável de dados removidos legitimamente para que a inicialização seja possível. Se esse registro for mantido por uma autoridade central, como os autores de [BF19] sugerem, contradizemos a filosofia blockchain de descentralização. Também é questionável até que ponto e com que rapidez os acordos podem ser alcançados, dada a natureza heterogênea das comunidades de blockchain.

O artigo [DM19] sugere um método para apagar dados do blockchain que requer que a comunidade atualize seu software para executar o novo protocolo. Os autores apresentam uma forte análise de segurança e os únicos pequenos defeitos da proposta são um pequeno risco de um ataque de negação de serviço e uma sobrecarga computacional ligeiramente maior. Gostaríamos de ver uma análise da teoria dos jogos de sua proposta para avaliar o uso indevido potencial das novas regras. Se todos os nodes seguirem o protocolo aprimorado, não haverá risco de segurança e nenhum obstáculo à inicialização. Embora a proposta inclua um mecanismo de votação seguro, é novamente questionável se um acordo sobre dados prejudiciais pode ser alcançado facilmente entre uma comunidade multicultural.

A abordagem do [HH2a] consiste em prevenir a inserção de dados prejudiciais, fazendo uso de detectores de texto e incentivos econômicos. Ambos os métodos melhoram a prevenção, mas falham em excluir totalmente dados prejudiciais. A ferramenta criptográfica proposta ajuda a detectar dados prejudiciais que passam pelos dois primeiros filtros, mas não podem controlar todos os métodos de inserção possíveis.

Referencias

[AM17] G. Ateniese, B. Magri et al.: Redactable Blockchain or Rewriting History in Bitcoin and Friends, IEEE European Symposium on Security and Privacy, 2017.

[BF19] S. Beaucamp, M. Florian, et al.: Erasing Data from Blockchain Nodes, arxiv:1904.08901, 2019. 

[DM19] D. Deuber, B. Magri et al.: Redactable Blockchain in the Permissionless Setting, IEEE Symposium on Security and Privacy, 2019. 

[GK16] A. Gervais, G. K. Karame, et al.: On the Security and Performance of Proof of Work Blockchains, Proceedings of the 2016 ACM SIGSAC Conference on Computer and Communications Security, 2016.

[GKL15] J.A. Garay, A. Kiayias, N. Leobardos: The Bitcoin Backbone Protocol: Analysis and Applications, Proc. Eurocrypt, 2015.

[HH18a] M. Henze, J. Hiller, et al.: Thwarting Unwanted Blockchain Content Insertion, IEEE International Conference on Cloud Engineering, 2018. 

[HH18b] M. Henze, J. Hiller, et al.: A Quantitative Analysis of the Impact of Arbitrary Blockchain Content on Bitcoin, in Proc. 22nd International Conference on Financial Cryptography and Data Security, 2018

[M13] G. Maxwell: To Prevent Arbitrary Data Storage in Txouts – The Ultimate Solution, 2013.

[SSV19] F. Stonedahl, A. Sward, I. Vecna: Data Insertion in Bitcoin’s Blockchain, Ledger Journal Vol 3, 2019.

Portrait Image by Brian J. Matis. License creative commons.

MintingFactoryV2, BaseUpgradableMarketplace & KODAV3UpgradableGatedMarketplace

Reading Time: 8 minutes

Introduction CoinFabrik was asked to audit the contracts for the KnownOrigin project. First wewill provide a summary of our discoveries and then we will show the details of ourfindings. Scope The contracts audited are from thehttps://github.com/knownorigin/known-origin-contracts-v3.git git repository. Theaudit is based on the commit d592c5f4fa4e0b6fc65a1fce43e302706aedf607. The audited files are: ● /contracts/marketplace/KODAV3UpgradableGatedMarketplace.sol:Contains the contract used to […]

AlexGo Audit
Launchpad, Yield Vault and Collateral Rebalancing Pool

Reading Time: 4 minutes

Introduction CoinFabrik was asked to audit the contracts for the AlexGo project. First we willprovide a summary of our discoveries and then we will show the details of ourfindings. Scope The contracts audited are from the https://github.com/alexgo-io/alex-v1 gitrepository. The audit is based on the commite268fd53370be3a271625bd45523ae07cb1239ac. The audited contracts are: ● clarity/contracts/pool/alex-launchpad-v1-1.clar: Launchpadcontract for IDO creation.● […]

Mokens League Audit

Reading Time: 3 minutes

Introduction CoinFabrik was asked to audit the contracts for the Mokens League project. First, we will provide a summary of our discoveries and then we will show the details of our findings. Scope The contracts audited are from the https://github.com/Mokens-League/mokens-league-tokens/ git repository. The audit is based on the commit b2e3a17f7f8c8d220fc135fc9a8364fdf07d51c. The audited contracts are: /contracts/Token.sol:MainERC777Token […]

AlexGo DAO Audit

Reading Time: 5 minutes

Introduction CoinFabrik was asked to audit the contracts for AlexGo’s DAO project. First we will provide a summary of our discoveries and then we will show the details of our findings. Scope The contracts audited are from the https://github.com/MarvinJanssen/executor-daoand https://github.com/alexgo-io/alex-dao git repositories. The audit is based on the commits aa748ceecbad201c226ecbba4d7111995851e7f5 and9f99127e3aa7487c620982b6f7017c0541a6790d, respectively. alex-dao was forked […]

EMDX – Protocol Audit

Reading Time: 4 minutes

Introduction CoinFabrik was asked to audit the contracts for the EMDX project. First, we will provide a summary of our discoveries and then we will show the details of our findings. Summary The contracts audited are from the EMDX repository at https://github.com/emdx-dex/perpetual-protocol/. The audit is based on the commit ca34a5e9e254caca5056ab5002a3fdb0b4f3b004.Fixes were made and rechecked based […]