Platform: Code4rena
Start Date: 01/03/2024
Pot Size: $60,500 USDC
Total HM: 4
Participants: 18
Period: 21 days
Judge: Lambda
Total Solo HM: 3
Id: 344
League: POLKADOT
Rank: 15/18
Findings: 1
Award: $59.23
🌟 Selected for report: 0
🚀 Solo Findings: 0
🌟 Selected for report: hunter_w3b
Also found by: 0xepley, Bauchibred, Cryptor, DarkTower, aariiif, albahaca, fouzantanveer, kaveyjoe, popeye, roguereggiant
59.2291 USDC - $59.23
graph TD A[Contract Developer] --> B[Write Smart Contracts] B --> C[Compile Contracts] C --> D[Generate Wasm Bytecode] D --> E[Deploy Contracts] E --> F[Pink Runtime] F --> G[Contract Instantiation] G --> H[Contract Execution] H --> I[Storage Operations] H --> J[Event Emission] H --> K[Off-chain Interactions] I --> L[ExternalStorage Backend] L --> M[Host Environment] M --> L F --> N[Gas Metering] F --> O[Resource Management] P[Contract User] --> Q[Invoke Contract Functions] Q --> H R[Node Operator] --> S[Run Phala Network Nodes] S --> T[TEE Workers] T --> F U[Runtime Administrator] --> V[Manage Runtime Parameters] V --> F U --> W[Coordinate Runtime Upgrades] W --> F X[Treasury Manager] --> Y[Manage Funds] Y --> Z[Gas Payments] Y --> AA[Storage Fees] Z --> F AA --> F
The Phat Contract Runtime, also known as Pink Runtime, is a smart contract execution engine for the Phala Network. It is built on top of Substrate's pallet-contracts
module and includes custom chain extensions. The runtime is compiled into a shared library (libpink.so
) and runs inside Trusted Execution Environment (TEE) workers of the Phala Network.
The Phat Contract Runtime, also known as Pink Runtime, is a smart contract execution environment designed specifically for the Phala Network. It serves as the foundation for running ink! smart contracts within the network's Trusted Execution Environment (TEE) workers. The Pink Runtime is built on top of Substrate's pallet-contracts
module and incorporates custom chain extensions to provide additional functionality and security features.
The primary goal of the Pink Runtime is to enable secure, efficient, and flexible execution of smart contracts while leveraging the benefits of TEE technology. It aims to provide developers with a familiar and intuitive programming model based on ink!, a Rust-based embedded domain-specific language (eDSL) for writing smart contracts.
Dependency on Substrate's pallet-contracts
:
pallet-contracts
module. Any vulnerabilities or issues in the underlying module could potentially impact the security of the Pink Runtime.pallet-contracts
module to ensure its security and stability.TEE Worker Security:
External Dependencies:
pink
and pink-capi
crates. Vulnerabilities in these dependencies could introduce risks to the runtime.The Pink Runtime follows a layered architecture that integrates with the Phala Network's infrastructure.
Smart Contract Development:
Contract Deployment:
contract_instantiate
ecall.Contract Execution:
contract_call
ecall.Storage Operations:
Event Emission:
Off-chain Interactions:
Gas Metering and Resource Management:
Runtime Upgrades and Maintenance:
The Pink Runtime codebase follows a modular and well-organized structure. The code is written in Rust, which provides strong type safety and memory safety guarantees. The use of traits and abstractions, such as ExternalStorage
and ChainExtension
, promotes code reusability and maintainability.
However, there are a few areas that could be improved:
Error Handling:
Result
types and panics for error handling. Panics should be avoided in production code as they can lead to abrupt termination of the runtime.Result
types for error handling and propagate errors to the caller for proper error management.Documentation:
Testing:
The Pink Runtime provides a range of functions and features to support the execution of smart contracts. Some of the key functions include:
The runtime allows the deployment of new smart contracts by uploading their code and initializing their state. This process is facilitated by the contract_instantiate
ecall.
Once deployed, smart contracts can be executed by invoking their functions through the contract_call
ecall. The runtime handles the execution of the contract code and manages the associated state changes.
The Pink Runtime incorporates a gas metering system to measure and limit the computational resources consumed by smart contracts during execution. This helps prevent excessive resource usage and ensures fair allocation among different contracts.
The runtime provides functions for reading from and writing to the contract storage. It utilizes the ExternalStorage backend to delegate storage operations to the host environment via ocalls.
The Pink Runtime offers cryptographic functions, such as signing, verification, and key derivation, through the custom chain extensions. These functions enable secure interactions between smart contracts and external entities.
Smart contracts can emit events during their execution using the event system provided by the Pink Runtime. These events can be captured and processed by external systems for various purposes.
The runtime includes functions for retrieving off-chain data, such as making HTTP requests, through the custom chain extensions. This allows smart contracts to access external data sources and integrate with other systems.
The contract developer is responsible for writing and deploying smart contracts using the ink! language. They interact with the Pink Runtime through the provided APIs and follow the guidelines and best practices for secure and efficient contract development.
Contract users are entities that interact with deployed smart contracts by invoking their functions and participating in transactions. They can be external users, other smart contracts, or off-chain systems.
Node operators are responsible for running the Phala Network nodes that host the TEE workers. They ensure the availability and security of the network infrastructure and may also participate in consensus and governance activities.
The runtime administrator has privileged access to certain runtime functions and configurations. They are responsible for managing the runtime's parameters, such as gas prices, storage fees, and system contracts.
The treasury manager oversees the funds collected from gas payments and storage fees. They ensure the proper allocation and utilization of these funds in accordance with the network's governance policies.
Owner Privileges:
SystemContract Privileges:
Treasury Account:
Gas Metering and Weights:
Contract Execution Modes:
Event System:
Scalability:
Interoperability:
Upgrade Mechanism:
set_ocall_fn
(crates/pink/runtime/src/capi/ocall_impl.rs:18-34)pub(super) fn set_ocall_fn(ocalls: ocalls_t) -> Result<(), &'static str> { let Some(ocall) = ocalls.ocall else { return Err("No ocall function provided"); }; unsafe { OCALL = ocall; #[cfg(feature = "allocator")] if let Some(alloc) = ocalls.alloc { allocator::ALLOC_FUNC = alloc; } #[cfg(feature = "allocator")] if let Some(dealloc) = ocalls.dealloc { allocator::DEALLOC_FUNC = dealloc; } } Ok(()) }
Explanation: The set_ocall_fn
function uses unsafe
blocks to set the OCALL
, ALLOC_FUNC
, and DEALLOC_FUNC
function pointers. If these pointers are not properly validated or if they are set to invalid or malicious functions, it could lead to undefined behavior or security vulnerabilities.
Recommendation: Ensure that the ocalls
parameter is properly validated before setting the function pointers. Consider implementing additional safety checks and error handling to prevent the setting of invalid or malicious function pointers.
unwrap
in storage_root
(crates/pink/runtime/src/storage/external_backend.rs:42-45)pub fn instantiate() -> Self { let root = OCallImpl .storage_root() .unwrap_or_else(sp_trie::empty_trie_root::<sp_state_machine::LayoutV1<Hashing>>); let backend = TrieBackendBuilder::new(ExternalDB, root).build(); crate::storage::Storage::new(backend) }
Explanation: The instantiate
function uses unwrap_or_else
to retrieve the storage root from OCallImpl.storage_root()
. If the storage_root
function returns None
, it falls back to an empty trie root. However, if the storage_root
function itself panics or returns an invalid value, it could lead to unexpected behavior or runtime errors.
Recommendation: Handle the case when OCallImpl.storage_root()
returns None
more gracefully. Consider logging an error or returning an error type instead of using unwrap_or_else
. Additionally, ensure that the storage_root
function is properly implemented and tested to avoid panics or invalid return values.
Err
variant in mask_low_bits128
(crates/pink/runtime/src/contract.rs:75-84)define_mask_fn!(mask_low_bits128, 128, u128); fn mask_deposit(deposit: u128, deposit_per_byte: u128) -> u128 { const MIN_MASKED_BYTES: u128 = 256; let min_masked_value = deposit_per_byte .saturating_mul(MIN_MASKED_BYTES) .saturating_sub(1); let min_mask_bits = 128 - min_masked_value.leading_zeros(); mask_low_bits128(deposit, min_mask_bits) }
Explanation: The mask_low_bits128
macro is used to mask the low bits of a u128
value. However, the macro does not handle the case when the min_mask_bits
is greater than 128, which could lead to unexpected behavior or runtime errors.
Recommendation: Modify the mask_low_bits128
macro to properly handle the case when min_mask_bits
is greater than 128. Consider adding a check to ensure that min_mask_bits
is within the valid range (0 to 128) and return an error or use a default value if it exceeds the range.
The Pink Runtime consists of several key components that work together to facilitate the execution of smart contracts:
Trusted Execution Environment (TEE) Workers: The Pink Runtime operates within the TEE workers of the Phala Network. These workers provide a secure and isolated environment for executing smart contracts, protecting them from unauthorized access and tampering.
pallet-contracts
Module: The Pink Runtime is built on top of Substrate's pallet-contracts
module, which provides the core functionality for managing and executing smart contracts. It handles tasks such as contract deployment, storage, and gas metering.
Custom Chain Extensions: The Pink Runtime introduces custom chain extensions that extend the capabilities of the pallet-contracts
module. These extensions include additional APIs and features specific to the Phala Network, such as cryptographic operations, cache management, and off-chain data retrieval.
ExternalStorage Backend: The Pink Runtime utilizes an ExternalStorage backend that implements the TrieBackendStorage trait. This backend allows the runtime to delegate key-value storage operations to the host environment via ocalls (outside calls), rather than managing the storage directly.
Ecall and Ocall Interfaces: The Pink Runtime defines a set of ecall and ocall interfaces that facilitate communication between the runtime and the host environment. Ecalls are incoming calls from the host to the runtime, while ocalls are outgoing calls from the runtime to the host.
Event System: The Pink Runtime includes an event system that allows smart contracts to emit events during execution. These events can be captured and processed by external systems for various purposes, such as monitoring, indexing, or triggering further actions.
The Pink Runtime is a critical component of the Phala Network, enabling the execution of smart contracts within a Trusted Execution Environment. While the codebase follows a modular and well-organized structure, there are areas that require further attention to ensure its security, scalability, and robustness.
In the analysis I highlighted potential risks related to centralization, admin control abuse, and systemic issues. It is crucial to implement appropriate mitigation measures, such as multi-signature schemes, access controls, and regular audits, to address these risks.
Furthermore, the codebase quality can be improved by enhancing error handling, documentation, and testing. Regular updates and security audits of external dependencies are also recommended to maintain the runtime's security and compatibility.
To ensure the long-term success and resilience of the Pink Runtime, it is essential to continuously monitor and optimize its performance, scalability, and interoperability. Implementing a robust upgrade mechanism and following best practices for secure coding and deployment will help mitigate risks and maintain the trust of the Phala Network community.
40 hours
#0 - c4-pre-sort
2024-03-25T07:13:53Z
141345 marked the issue as sufficient quality report
#1 - c4-judge
2024-03-27T15:42:05Z
OpenCoreCH marked the issue as grade-b