mirror of
https://github.com/pezkuwichain/revive.git
synced 2026-06-14 12:11:02 +00:00
Emerge Yul recompiler (#1)
Provide a modified (and incomplete) version of ZKSync zksolc that can compile the most basic contracts
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
//!
|
||||
//! The `solc --standard-json` output contract EVM bytecode.
|
||||
//!
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
///
|
||||
/// The `solc --standard-json` output contract EVM bytecode.
|
||||
///
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Bytecode {
|
||||
/// The bytecode object.
|
||||
pub object: String,
|
||||
}
|
||||
|
||||
impl Bytecode {
|
||||
///
|
||||
/// A shortcut constructor.
|
||||
///
|
||||
pub fn new(object: String) -> Self {
|
||||
Self { object }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//!
|
||||
//! The `solc --standard-json` output contract EVM extra metadata.
|
||||
//!
|
||||
|
||||
pub mod recursive_function;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
use self::recursive_function::RecursiveFunction;
|
||||
|
||||
///
|
||||
/// The `solc --standard-json` output contract EVM extra metadata.
|
||||
///
|
||||
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExtraMetadata {
|
||||
/// The list of recursive functions.
|
||||
#[serde(default = "Vec::new")]
|
||||
pub recursive_functions: Vec<RecursiveFunction>,
|
||||
}
|
||||
|
||||
impl ExtraMetadata {
|
||||
///
|
||||
/// Returns the recursive function reference for the specified tag.
|
||||
///
|
||||
pub fn get(
|
||||
&self,
|
||||
block_key: &era_compiler_llvm_context::EraVMFunctionBlockKey,
|
||||
) -> Option<&RecursiveFunction> {
|
||||
for function in self.recursive_functions.iter() {
|
||||
match block_key.code_type {
|
||||
era_compiler_llvm_context::EraVMCodeType::Deploy => {
|
||||
if let Some(creation_tag) = function.creation_tag {
|
||||
if num::BigUint::from(creation_tag) == block_key.tag {
|
||||
return Some(function);
|
||||
}
|
||||
}
|
||||
}
|
||||
era_compiler_llvm_context::EraVMCodeType::Runtime => {
|
||||
if let Some(runtime_tag) = function.runtime_tag {
|
||||
if num::BigUint::from(runtime_tag) == block_key.tag {
|
||||
return Some(function);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
//!
|
||||
//! The `solc --standard-json` output contract EVM recursive function.
|
||||
//!
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
///
|
||||
/// The `solc --standard-json` output contract EVM recursive function.
|
||||
///
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RecursiveFunction {
|
||||
/// The function name.
|
||||
pub name: String,
|
||||
/// The creation code function block tag.
|
||||
pub creation_tag: Option<usize>,
|
||||
/// The runtime code function block tag.
|
||||
pub runtime_tag: Option<usize>,
|
||||
/// The number of input arguments.
|
||||
#[serde(rename = "totalParamSize")]
|
||||
pub input_size: usize,
|
||||
/// The number of output arguments.
|
||||
#[serde(rename = "totalRetParamSize")]
|
||||
pub output_size: usize,
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//!
|
||||
//! The `solc --standard-json` output contract EVM data.
|
||||
//!
|
||||
|
||||
pub mod bytecode;
|
||||
pub mod extra_metadata;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::evmla::assembly::Assembly;
|
||||
|
||||
use self::bytecode::Bytecode;
|
||||
use self::extra_metadata::ExtraMetadata;
|
||||
|
||||
///
|
||||
/// The `solc --standard-json` output contract EVM data.
|
||||
///
|
||||
/// It is replaced by EraVM data after compiling.
|
||||
///
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EVM {
|
||||
/// The contract EVM legacy assembly code.
|
||||
#[serde(rename = "legacyAssembly")]
|
||||
pub assembly: Option<Assembly>,
|
||||
/// The contract EraVM assembly code.
|
||||
#[serde(rename = "assembly")]
|
||||
pub assembly_text: Option<String>,
|
||||
/// The contract bytecode.
|
||||
/// Is reset by that of EraVM before yielding the compiled project artifacts.
|
||||
pub bytecode: Option<Bytecode>,
|
||||
/// The contract function signatures.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub method_identifiers: Option<BTreeMap<String, String>>,
|
||||
/// The extra EVMLA metadata.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub extra_metadata: Option<ExtraMetadata>,
|
||||
}
|
||||
|
||||
impl EVM {
|
||||
///
|
||||
/// Sets the EraVM assembly and bytecode.
|
||||
///
|
||||
pub fn modify(&mut self, assembly_text: String, bytecode: String) {
|
||||
self.assembly_text = Some(assembly_text);
|
||||
self.bytecode = Some(Bytecode::new(bytecode));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//!
|
||||
//! The `solc --standard-json` output contract.
|
||||
//!
|
||||
|
||||
pub mod evm;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
use self::evm::EVM;
|
||||
|
||||
///
|
||||
/// The `solc --standard-json` output contract.
|
||||
///
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Contract {
|
||||
/// The contract ABI.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub abi: Option<serde_json::Value>,
|
||||
/// The contract metadata.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub metadata: Option<serde_json::Value>,
|
||||
/// The contract developer documentation.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub devdoc: Option<serde_json::Value>,
|
||||
/// The contract user documentation.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub userdoc: Option<serde_json::Value>,
|
||||
/// The contract storage layout.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub storage_layout: Option<serde_json::Value>,
|
||||
/// Contract's bytecode and related objects
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub evm: Option<EVM>,
|
||||
/// The contract optimized IR code.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub ir_optimized: Option<String>,
|
||||
/// The contract EraVM bytecode hash.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub hash: Option<String>,
|
||||
/// The contract factory dependencies.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub factory_dependencies: Option<BTreeMap<String, String>>,
|
||||
/// The contract missing libraries.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub missing_libraries: Option<HashSet<String>>,
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
//!
|
||||
//! The `solc --standard-json` output error.
|
||||
//!
|
||||
|
||||
pub mod source_location;
|
||||
|
||||
use std::str::FromStr;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
use self::source_location::SourceLocation;
|
||||
|
||||
///
|
||||
/// The `solc --standard-json` output error.
|
||||
///
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Error {
|
||||
/// The component type.
|
||||
pub component: String,
|
||||
/// The error code.
|
||||
pub error_code: Option<String>,
|
||||
/// The formatted error message.
|
||||
pub formatted_message: String,
|
||||
/// The non-formatted error message.
|
||||
pub message: String,
|
||||
/// The error severity.
|
||||
pub severity: String,
|
||||
/// The error location data.
|
||||
pub source_location: Option<SourceLocation>,
|
||||
/// The error type.
|
||||
pub r#type: String,
|
||||
}
|
||||
|
||||
impl Error {
|
||||
///
|
||||
/// Returns the `ecrecover` function usage warning.
|
||||
///
|
||||
pub fn message_ecrecover(src: Option<&str>) -> Self {
|
||||
let message = r#"
|
||||
┌──────────────────────────────────────────────────────────────────────────────────────────────────┐
|
||||
│ Warning: It looks like you are using 'ecrecover' to validate a signature of a user account. │
|
||||
│ zkSync Era comes with native account abstraction support, therefore it is highly recommended NOT │
|
||||
│ to rely on the fact that the account has an ECDSA private key attached to it since accounts might│
|
||||
│ implement other signature schemes. │
|
||||
│ Read more about Account Abstraction at https://v2-docs.zksync.io/dev/developer-guides/aa.html │
|
||||
└──────────────────────────────────────────────────────────────────────────────────────────────────┘"#
|
||||
.to_owned();
|
||||
|
||||
Self {
|
||||
component: "general".to_owned(),
|
||||
error_code: None,
|
||||
formatted_message: message.clone(),
|
||||
message,
|
||||
severity: "warning".to_owned(),
|
||||
source_location: src.map(SourceLocation::from_str).and_then(Result::ok),
|
||||
r#type: "Warning".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// Returns the `<address payable>`'s `send` and `transfer` methods usage error.
|
||||
///
|
||||
pub fn message_send_and_transfer(src: Option<&str>) -> Self {
|
||||
let message = r#"
|
||||
┌──────────────────────────────────────────────────────────────────────────────────────────────────┐
|
||||
│ Warning: It looks like you are using '<address payable>.send/transfer(<X>)' without providing │
|
||||
│ the gas amount. Such calls will fail depending on the pubdata costs. │
|
||||
│ This might be a false positive if you are using an interface (like IERC20) instead of the │
|
||||
│ native Solidity `send/transfer`. │
|
||||
│ Please use 'payable(<address>).call{value: <X>}("")' instead, but be careful with the reentrancy │
|
||||
│ attack. `send` and `transfer` send limited amount of gas that prevents reentrancy, whereas │
|
||||
│ `<address>.call{value: <X>}` sends all gas to the callee. Learn more on │
|
||||
│ https://docs.soliditylang.org/en/latest/security-considerations.html#reentrancy │
|
||||
└──────────────────────────────────────────────────────────────────────────────────────────────────┘"#
|
||||
.to_owned();
|
||||
|
||||
Self {
|
||||
component: "general".to_owned(),
|
||||
error_code: None,
|
||||
formatted_message: message.clone(),
|
||||
message,
|
||||
severity: "warning".to_owned(),
|
||||
source_location: src.map(SourceLocation::from_str).and_then(Result::ok),
|
||||
r#type: "Warning".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// Returns the `extcodesize` instruction usage warning.
|
||||
///
|
||||
pub fn message_extcodesize(src: Option<&str>) -> Self {
|
||||
let message = r#"
|
||||
┌──────────────────────────────────────────────────────────────────────────────────────────────────┐
|
||||
│ Warning: Your code or one of its dependencies uses the 'extcodesize' instruction, which is │
|
||||
│ usually needed in the following cases: │
|
||||
│ 1. To detect whether an address belongs to a smart contract. │
|
||||
│ 2. To detect whether the deploy code execution has finished. │
|
||||
│ zkSync Era comes with native account abstraction support (so accounts are smart contracts, │
|
||||
│ including private-key controlled EOAs), and you should avoid differentiating between contracts │
|
||||
│ and non-contract addresses. │
|
||||
└──────────────────────────────────────────────────────────────────────────────────────────────────┘"#
|
||||
.to_owned();
|
||||
|
||||
Self {
|
||||
component: "general".to_owned(),
|
||||
error_code: None,
|
||||
formatted_message: message.clone(),
|
||||
message,
|
||||
severity: "warning".to_owned(),
|
||||
source_location: src.map(SourceLocation::from_str).and_then(Result::ok),
|
||||
r#type: "Warning".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// Returns the `origin` instruction usage warning.
|
||||
///
|
||||
pub fn message_tx_origin(src: Option<&str>) -> Self {
|
||||
let message = r#"
|
||||
┌──────────────────────────────────────────────────────────────────────────────────────────────────┐
|
||||
│ Warning: You are checking for 'tx.origin' in your code, which might lead to unexpected behavior. │
|
||||
│ zkSync Era comes with native account abstraction support, and therefore the initiator of a │
|
||||
│ transaction might be different from the contract calling your code. It is highly recommended NOT │
|
||||
│ to rely on tx.origin, but use msg.sender instead. │
|
||||
│ Read more about Account Abstraction at https://v2-docs.zksync.io/dev/developer-guides/aa.html │
|
||||
└──────────────────────────────────────────────────────────────────────────────────────────────────┘"#
|
||||
.to_owned();
|
||||
|
||||
Self {
|
||||
component: "general".to_owned(),
|
||||
error_code: None,
|
||||
formatted_message: message.clone(),
|
||||
message,
|
||||
severity: "warning".to_owned(),
|
||||
source_location: src.map(SourceLocation::from_str).and_then(Result::ok),
|
||||
r#type: "Warning".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// Returns the internal function pointer usage error.
|
||||
///
|
||||
pub fn message_internal_function_pointer(src: Option<&str>) -> Self {
|
||||
let message = r#"
|
||||
┌──────────────────────────────────────────────────────────────────────────────────────────────────┐
|
||||
│ Error: Internal function pointers are not supported in EVM legacy assembly pipeline. │
|
||||
│ Please use the Yul IR codegen instead. │
|
||||
└──────────────────────────────────────────────────────────────────────────────────────────────────┘"#
|
||||
.to_owned();
|
||||
|
||||
Self {
|
||||
component: "general".to_owned(),
|
||||
error_code: None,
|
||||
formatted_message: message.clone(),
|
||||
message,
|
||||
severity: "error".to_owned(),
|
||||
source_location: src.map(SourceLocation::from_str).and_then(Result::ok),
|
||||
r#type: "Error".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// Appends the contract path to the message..
|
||||
///
|
||||
pub fn push_contract_path(&mut self, path: &str) {
|
||||
self.formatted_message
|
||||
.push_str(format!("\n--> {path}\n").as_str());
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.formatted_message)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
//!
|
||||
//! The `solc --standard-json` output error source location.
|
||||
//!
|
||||
|
||||
use std::str::FromStr;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
///
|
||||
/// The `solc --standard-json` output error source location.
|
||||
///
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SourceLocation {
|
||||
/// The source file path.
|
||||
pub file: String,
|
||||
/// The start location.
|
||||
pub start: isize,
|
||||
/// The end location.
|
||||
pub end: isize,
|
||||
}
|
||||
|
||||
impl FromStr for SourceLocation {
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(string: &str) -> Result<Self, Self::Err> {
|
||||
let mut parts = string.split(':');
|
||||
let start = parts
|
||||
.next()
|
||||
.map(|string| string.parse::<isize>())
|
||||
.and_then(Result::ok)
|
||||
.unwrap_or_default();
|
||||
let length = parts
|
||||
.next()
|
||||
.map(|string| string.parse::<isize>())
|
||||
.and_then(Result::ok)
|
||||
.unwrap_or_default();
|
||||
let file = parts.next().unwrap_or_default().to_owned();
|
||||
|
||||
Ok(Self {
|
||||
file,
|
||||
start,
|
||||
end: start + length,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
//!
|
||||
//! The `solc --standard-json` output.
|
||||
//!
|
||||
|
||||
pub mod contract;
|
||||
pub mod error;
|
||||
pub mod source;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sha3::Digest;
|
||||
|
||||
use crate::evmla::assembly::instruction::Instruction;
|
||||
use crate::evmla::assembly::Assembly;
|
||||
use crate::project::contract::ir::IR as ProjectContractIR;
|
||||
use crate::project::contract::Contract as ProjectContract;
|
||||
use crate::project::Project;
|
||||
use crate::solc::pipeline::Pipeline as SolcPipeline;
|
||||
use crate::solc::version::Version as SolcVersion;
|
||||
use crate::warning::Warning;
|
||||
use crate::yul::lexer::Lexer;
|
||||
use crate::yul::parser::statement::object::Object;
|
||||
|
||||
use self::contract::Contract;
|
||||
use self::error::Error as SolcStandardJsonOutputError;
|
||||
use self::source::Source;
|
||||
|
||||
///
|
||||
/// The `solc --standard-json` output.
|
||||
///
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct Output {
|
||||
/// The file-contract hashmap.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub contracts: Option<BTreeMap<String, BTreeMap<String, Contract>>>,
|
||||
/// The source code mapping data.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub sources: Option<BTreeMap<String, Source>>,
|
||||
/// The compilation errors and warnings.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub errors: Option<Vec<SolcStandardJsonOutputError>>,
|
||||
/// The `solc` compiler version.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub version: Option<String>,
|
||||
/// The `solc` compiler long version.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub long_version: Option<String>,
|
||||
/// The `zksolc` compiler version.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub zk_version: Option<String>,
|
||||
}
|
||||
|
||||
impl Output {
|
||||
///
|
||||
/// Converts the `solc` JSON output into a convenient project.
|
||||
///
|
||||
pub fn try_to_project(
|
||||
&mut self,
|
||||
source_code_files: BTreeMap<String, String>,
|
||||
libraries: BTreeMap<String, BTreeMap<String, String>>,
|
||||
pipeline: SolcPipeline,
|
||||
solc_version: &SolcVersion,
|
||||
debug_config: Option<&era_compiler_llvm_context::DebugConfig>,
|
||||
) -> anyhow::Result<Project> {
|
||||
if let SolcPipeline::EVMLA = pipeline {
|
||||
self.preprocess_dependencies()?;
|
||||
}
|
||||
|
||||
let files = match self.contracts.as_ref() {
|
||||
Some(files) => files,
|
||||
None => {
|
||||
anyhow::bail!(
|
||||
"{}",
|
||||
self.errors
|
||||
.as_ref()
|
||||
.map(|errors| serde_json::to_string_pretty(errors).expect("Always valid"))
|
||||
.unwrap_or_else(|| "Unknown project assembling error".to_owned())
|
||||
);
|
||||
}
|
||||
};
|
||||
let mut project_contracts = BTreeMap::new();
|
||||
|
||||
for (path, contracts) in files.iter() {
|
||||
for (name, contract) in contracts.iter() {
|
||||
let full_path = format!("{path}:{name}");
|
||||
|
||||
let source = match pipeline {
|
||||
SolcPipeline::Yul => {
|
||||
let ir_optimized = match contract.ir_optimized.to_owned() {
|
||||
Some(ir_optimized) => ir_optimized,
|
||||
None => continue,
|
||||
};
|
||||
if ir_optimized.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(debug_config) = debug_config {
|
||||
debug_config.dump_yul(full_path.as_str(), ir_optimized.as_str())?;
|
||||
}
|
||||
|
||||
let mut lexer = Lexer::new(ir_optimized.to_owned());
|
||||
let object = Object::parse(&mut lexer, None).map_err(|error| {
|
||||
anyhow::anyhow!("Contract `{}` parsing error: {:?}", full_path, error)
|
||||
})?;
|
||||
|
||||
ProjectContractIR::new_yul(ir_optimized.to_owned(), object)
|
||||
}
|
||||
SolcPipeline::EVMLA => {
|
||||
let evm = contract.evm.as_ref();
|
||||
let assembly = match evm.and_then(|evm| evm.assembly.to_owned()) {
|
||||
Some(assembly) => assembly.to_owned(),
|
||||
None => continue,
|
||||
};
|
||||
let extra_metadata = evm
|
||||
.and_then(|evm| evm.extra_metadata.to_owned())
|
||||
.unwrap_or_default();
|
||||
|
||||
ProjectContractIR::new_evmla(assembly, extra_metadata)
|
||||
}
|
||||
};
|
||||
|
||||
let source_code = source_code_files
|
||||
.get(path.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("Source code for path `{}` not found", path))?;
|
||||
let source_hash = sha3::Keccak256::digest(source_code.as_bytes()).into();
|
||||
|
||||
let project_contract = ProjectContract::new(
|
||||
full_path.clone(),
|
||||
source_hash,
|
||||
solc_version.to_owned(),
|
||||
source,
|
||||
contract.metadata.to_owned(),
|
||||
);
|
||||
project_contracts.insert(full_path, project_contract);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Project::new(
|
||||
solc_version.to_owned(),
|
||||
project_contracts,
|
||||
libraries,
|
||||
))
|
||||
}
|
||||
|
||||
///
|
||||
/// Removes EVM artifacts to prevent their accidental usage.
|
||||
///
|
||||
pub fn remove_evm(&mut self) {
|
||||
if let Some(files) = self.contracts.as_mut() {
|
||||
for (_, file) in files.iter_mut() {
|
||||
for (_, contract) in file.iter_mut() {
|
||||
if let Some(evm) = contract.evm.as_mut() {
|
||||
evm.bytecode = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// Traverses the AST and returns the list of additional errors and warnings.
|
||||
///
|
||||
pub fn preprocess_ast(
|
||||
&mut self,
|
||||
version: &SolcVersion,
|
||||
pipeline: SolcPipeline,
|
||||
suppressed_warnings: &[Warning],
|
||||
) -> anyhow::Result<()> {
|
||||
let sources = match self.sources.as_ref() {
|
||||
Some(sources) => sources,
|
||||
None => return Ok(()),
|
||||
};
|
||||
|
||||
let mut messages = Vec::new();
|
||||
for (path, source) in sources.iter() {
|
||||
if let Some(ast) = source.ast.as_ref() {
|
||||
let mut eravm_messages =
|
||||
Source::get_messages(ast, version, pipeline, suppressed_warnings);
|
||||
for message in eravm_messages.iter_mut() {
|
||||
message.push_contract_path(path.as_str());
|
||||
}
|
||||
messages.extend(eravm_messages);
|
||||
}
|
||||
}
|
||||
|
||||
self.errors = match self.errors.take() {
|
||||
Some(mut errors) => {
|
||||
errors.extend(messages);
|
||||
Some(errors)
|
||||
}
|
||||
None => Some(messages),
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
///
|
||||
/// The pass, which replaces with dependency indexes with actual data.
|
||||
///
|
||||
fn preprocess_dependencies(&mut self) -> anyhow::Result<()> {
|
||||
let files = match self.contracts.as_mut() {
|
||||
Some(files) => files,
|
||||
None => return Ok(()),
|
||||
};
|
||||
let mut hash_path_mapping = BTreeMap::new();
|
||||
|
||||
for (path, contracts) in files.iter() {
|
||||
for (name, contract) in contracts.iter() {
|
||||
let full_path = format!("{path}:{name}");
|
||||
let hash = match contract
|
||||
.evm
|
||||
.as_ref()
|
||||
.and_then(|evm| evm.assembly.as_ref())
|
||||
.map(|assembly| assembly.keccak256())
|
||||
{
|
||||
Some(hash) => hash,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
hash_path_mapping.insert(hash, full_path);
|
||||
}
|
||||
}
|
||||
|
||||
for (path, contracts) in files.iter_mut() {
|
||||
for (name, contract) in contracts.iter_mut() {
|
||||
let assembly = match contract.evm.as_mut().and_then(|evm| evm.assembly.as_mut()) {
|
||||
Some(assembly) => assembly,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let full_path = format!("{path}:{name}");
|
||||
Self::preprocess_dependency_level(
|
||||
full_path.as_str(),
|
||||
assembly,
|
||||
&hash_path_mapping,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
///
|
||||
/// Preprocesses an assembly JSON structure dependency data map.
|
||||
///
|
||||
fn preprocess_dependency_level(
|
||||
full_path: &str,
|
||||
assembly: &mut Assembly,
|
||||
hash_path_mapping: &BTreeMap<String, String>,
|
||||
) -> anyhow::Result<()> {
|
||||
assembly.set_full_path(full_path.to_owned());
|
||||
|
||||
let deploy_code_index_path_mapping =
|
||||
assembly.deploy_dependencies_pass(full_path, hash_path_mapping)?;
|
||||
if let Some(deploy_code_instructions) = assembly.code.as_deref_mut() {
|
||||
Instruction::replace_data_aliases(
|
||||
deploy_code_instructions,
|
||||
&deploy_code_index_path_mapping,
|
||||
)?;
|
||||
};
|
||||
|
||||
let runtime_code_index_path_mapping =
|
||||
assembly.runtime_dependencies_pass(full_path, hash_path_mapping)?;
|
||||
if let Some(runtime_code_instructions) = assembly
|
||||
.data
|
||||
.as_mut()
|
||||
.and_then(|data_map| data_map.get_mut("0"))
|
||||
.and_then(|data| data.get_assembly_mut())
|
||||
.and_then(|assembly| assembly.code.as_deref_mut())
|
||||
{
|
||||
Instruction::replace_data_aliases(
|
||||
runtime_code_instructions,
|
||||
&runtime_code_index_path_mapping,
|
||||
)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
//!
|
||||
//! The `solc --standard-json` output source.
|
||||
//!
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::solc::pipeline::Pipeline as SolcPipeline;
|
||||
use crate::solc::standard_json::output::error::Error as SolcStandardJsonOutputError;
|
||||
use crate::solc::version::Version as SolcVersion;
|
||||
use crate::warning::Warning;
|
||||
|
||||
///
|
||||
/// The `solc --standard-json` output source.
|
||||
///
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Source {
|
||||
/// The source code ID.
|
||||
pub id: usize,
|
||||
/// The source code AST.
|
||||
pub ast: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
impl Source {
|
||||
///
|
||||
/// Checks the AST node for the `ecrecover` function usage.
|
||||
///
|
||||
pub fn check_ecrecover(ast: &serde_json::Value) -> Option<SolcStandardJsonOutputError> {
|
||||
let ast = ast.as_object()?;
|
||||
|
||||
if ast.get("nodeType")?.as_str()? != "FunctionCall" {
|
||||
return None;
|
||||
}
|
||||
|
||||
let expression = ast.get("expression")?.as_object()?;
|
||||
if expression.get("nodeType")?.as_str()? != "Identifier" {
|
||||
return None;
|
||||
}
|
||||
if expression.get("name")?.as_str()? != "ecrecover" {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(SolcStandardJsonOutputError::message_ecrecover(
|
||||
ast.get("src")?.as_str(),
|
||||
))
|
||||
}
|
||||
|
||||
///
|
||||
/// Checks the AST node for the `<address payable>`'s `send` and `transfer` methods usage.
|
||||
///
|
||||
pub fn check_send_and_transfer(ast: &serde_json::Value) -> Option<SolcStandardJsonOutputError> {
|
||||
let ast = ast.as_object()?;
|
||||
|
||||
if ast.get("nodeType")?.as_str()? != "FunctionCall" {
|
||||
return None;
|
||||
}
|
||||
|
||||
let expression = ast.get("expression")?.as_object()?;
|
||||
if expression.get("nodeType")?.as_str()? != "MemberAccess" {
|
||||
return None;
|
||||
}
|
||||
let member_name = expression.get("memberName")?.as_str()?;
|
||||
if member_name != "send" && member_name != "transfer" {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(SolcStandardJsonOutputError::message_send_and_transfer(
|
||||
ast.get("src")?.as_str(),
|
||||
))
|
||||
}
|
||||
|
||||
///
|
||||
/// Checks the AST node for the `extcodesize` assembly instruction usage.
|
||||
///
|
||||
pub fn check_assembly_extcodesize(
|
||||
ast: &serde_json::Value,
|
||||
) -> Option<SolcStandardJsonOutputError> {
|
||||
let ast = ast.as_object()?;
|
||||
|
||||
if ast.get("nodeType")?.as_str()? != "YulFunctionCall" {
|
||||
return None;
|
||||
}
|
||||
if ast
|
||||
.get("functionName")?
|
||||
.as_object()?
|
||||
.get("name")?
|
||||
.as_str()?
|
||||
!= "extcodesize"
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(SolcStandardJsonOutputError::message_extcodesize(
|
||||
ast.get("src")?.as_str(),
|
||||
))
|
||||
}
|
||||
|
||||
///
|
||||
/// Checks the AST node for the `origin` assembly instruction usage.
|
||||
///
|
||||
pub fn check_assembly_origin(ast: &serde_json::Value) -> Option<SolcStandardJsonOutputError> {
|
||||
let ast = ast.as_object()?;
|
||||
|
||||
if ast.get("nodeType")?.as_str()? != "YulFunctionCall" {
|
||||
return None;
|
||||
}
|
||||
if ast
|
||||
.get("functionName")?
|
||||
.as_object()?
|
||||
.get("name")?
|
||||
.as_str()?
|
||||
!= "origin"
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(SolcStandardJsonOutputError::message_tx_origin(
|
||||
ast.get("src")?.as_str(),
|
||||
))
|
||||
}
|
||||
|
||||
///
|
||||
/// Checks the AST node for the `tx.origin` value usage.
|
||||
///
|
||||
pub fn check_tx_origin(ast: &serde_json::Value) -> Option<SolcStandardJsonOutputError> {
|
||||
let ast = ast.as_object()?;
|
||||
|
||||
if ast.get("nodeType")?.as_str()? != "MemberAccess" {
|
||||
return None;
|
||||
}
|
||||
if ast.get("memberName")?.as_str()? != "origin" {
|
||||
return None;
|
||||
}
|
||||
|
||||
let expression = ast.get("expression")?.as_object()?;
|
||||
if expression.get("nodeType")?.as_str()? != "Identifier" {
|
||||
return None;
|
||||
}
|
||||
if expression.get("name")?.as_str()? != "tx" {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(SolcStandardJsonOutputError::message_tx_origin(
|
||||
ast.get("src")?.as_str(),
|
||||
))
|
||||
}
|
||||
|
||||
///
|
||||
/// Checks the AST node for the internal function pointers value usage.
|
||||
///
|
||||
pub fn check_internal_function_pointer(
|
||||
ast: &serde_json::Value,
|
||||
) -> Option<SolcStandardJsonOutputError> {
|
||||
let ast = ast.as_object()?;
|
||||
|
||||
if ast.get("nodeType")?.as_str()? != "VariableDeclaration" {
|
||||
return None;
|
||||
}
|
||||
|
||||
let type_descriptions = ast.get("typeDescriptions")?.as_object()?;
|
||||
if !type_descriptions
|
||||
.get("typeIdentifier")?
|
||||
.as_str()?
|
||||
.contains("function_internal")
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(
|
||||
SolcStandardJsonOutputError::message_internal_function_pointer(
|
||||
ast.get("src")?.as_str(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
///
|
||||
/// Returns the list of messages for some specific parts of the AST.
|
||||
///
|
||||
pub fn get_messages(
|
||||
ast: &serde_json::Value,
|
||||
version: &SolcVersion,
|
||||
pipeline: SolcPipeline,
|
||||
suppressed_warnings: &[Warning],
|
||||
) -> Vec<SolcStandardJsonOutputError> {
|
||||
let mut messages = Vec::new();
|
||||
if !suppressed_warnings.contains(&Warning::EcRecover) {
|
||||
if let Some(message) = Self::check_ecrecover(ast) {
|
||||
messages.push(message);
|
||||
}
|
||||
}
|
||||
if !suppressed_warnings.contains(&Warning::SendTransfer) {
|
||||
if let Some(message) = Self::check_send_and_transfer(ast) {
|
||||
messages.push(message);
|
||||
}
|
||||
}
|
||||
if !suppressed_warnings.contains(&Warning::ExtCodeSize) {
|
||||
if let Some(message) = Self::check_assembly_extcodesize(ast) {
|
||||
messages.push(message);
|
||||
}
|
||||
}
|
||||
if !suppressed_warnings.contains(&Warning::TxOrigin) {
|
||||
if let Some(message) = Self::check_assembly_origin(ast) {
|
||||
messages.push(message);
|
||||
}
|
||||
if let Some(message) = Self::check_tx_origin(ast) {
|
||||
messages.push(message);
|
||||
}
|
||||
}
|
||||
if SolcPipeline::EVMLA == pipeline && version.l2_revision.is_none() {
|
||||
if let Some(message) = Self::check_internal_function_pointer(ast) {
|
||||
messages.push(message);
|
||||
}
|
||||
}
|
||||
|
||||
match ast {
|
||||
serde_json::Value::Array(array) => {
|
||||
for element in array.iter() {
|
||||
messages.extend(Self::get_messages(
|
||||
element,
|
||||
version,
|
||||
pipeline,
|
||||
suppressed_warnings,
|
||||
));
|
||||
}
|
||||
}
|
||||
serde_json::Value::Object(object) => {
|
||||
for (_key, value) in object.iter() {
|
||||
messages.extend(Self::get_messages(
|
||||
value,
|
||||
version,
|
||||
pipeline,
|
||||
suppressed_warnings,
|
||||
));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
messages
|
||||
}
|
||||
|
||||
///
|
||||
/// Returns the name of the last contract.
|
||||
///
|
||||
pub fn last_contract_name(&self) -> anyhow::Result<String> {
|
||||
self.ast
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("The AST is empty"))?
|
||||
.get("nodes")
|
||||
.and_then(|value| value.as_array())
|
||||
.ok_or_else(|| {
|
||||
anyhow::anyhow!("The last contract cannot be found in an empty list of nodes")
|
||||
})?
|
||||
.iter()
|
||||
.filter_map(
|
||||
|node| match node.get("nodeType").and_then(|node| node.as_str()) {
|
||||
Some("ContractDefinition") => Some(node.get("name")?.as_str()?.to_owned()),
|
||||
_ => None,
|
||||
},
|
||||
)
|
||||
.last()
|
||||
.ok_or_else(|| anyhow::anyhow!("The last contract not found in the AST"))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user