Skip to content
Merged
Show file tree
Hide file tree
Changes from 29 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
51117cc
Add skeleton of `Verify` command
HCastano Aug 10, 2022
13d29dc
Read `BuildInfo` from contract metadata
HCastano Aug 10, 2022
85ccd7d
Manually build contract using `BuildInfo`
HCastano Aug 10, 2022
7de595c
Check built Wasm file against that in the reference metadata
HCastano Aug 11, 2022
e67d108
Comopare `SourceWasm`'s instead of byte strings
HCastano Aug 11, 2022
b90f126
Check that current `nightly` matches that from contract
HCastano Aug 15, 2022
a350f4c
Switch from `env_logger` to `tracing`
HCastano Aug 18, 2022
e87c51a
Use helper function to get current Rust toolchain
HCastano Aug 18, 2022
4317f55
Clean up docs a little
HCastano Aug 18, 2022
fed9c3f
Bail out if `wasm-opt` versions don't match
HCastano Aug 19, 2022
b743987
Use stable `rustc` toolchain
HCastano Aug 29, 2022
f6770de
Use `keep_debug_symbols` from metadata
HCastano Sep 29, 2022
2f3ca03
Make output more colourful
HCastano Sep 29, 2022
e2c5675
Add missing doc comment
HCastano Sep 29, 2022
963387c
Do a better job of error handling
HCastano Sep 29, 2022
e7b9577
Add more error handling improvements
HCastano Sep 29, 2022
a64b631
Add `CHANGELOG` entry
HCastano Sep 29, 2022
d6db73f
Appease Clippy
HCastano Sep 29, 2022
80233c4
Use updated Rust toolchain build info
HCastano Oct 20, 2022
98cc7fb
Apply fixes for `clap` `v4.0`
HCastano Oct 20, 2022
b2d10c2
Compare `cargo-contract` versions instead of `wasm-opt` versions
HCastano Oct 20, 2022
1a71959
Merge branch 'master' into gn/verify-command
SkymanOne Aug 29, 2023
2fd80f1
update code
SkymanOne Aug 29, 2023
02a9e65
add docker support
SkymanOne Aug 29, 2023
5759843
remove docker flag
SkymanOne Aug 29, 2023
3889a62
fix error message
SkymanOne Aug 29, 2023
83373d8
display paths of the contracts
SkymanOne Aug 29, 2023
2154bf3
fix changelog
SkymanOne Aug 29, 2023
c81857f
fix file header
SkymanOne Aug 29, 2023
33dd9eb
Merge branch 'master' into gn/verify-command
SkymanOne Aug 30, 2023
56b27de
apply review suggestions
SkymanOne Aug 30, 2023
6e4fee5
prettify code hash output
SkymanOne Aug 30, 2023
dee765c
add integration tests
SkymanOne Aug 30, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added
- Adds workflow for publishing docker images for the verifiable builds - [#1267](https://github.com/paritytech/cargo-contract/pull/1267)
- Add `verify` command - [#1306](https://github.com/paritytech/cargo-contract/pull/1306)

## [4.0.0-alpha]

Expand Down
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 18 additions & 4 deletions crates/build/src/docker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,16 @@ pub enum ImageVariant {
Custom(String),
}

impl From<Option<String>> for ImageVariant {
fn from(value: Option<String>) -> Self {
if let Some(image) = value {
ImageVariant::Custom(image)
} else {
ImageVariant::Default
}
}
}

/// Launches the docker container to execute verifiable build.
pub fn docker_build(args: ExecuteArgs) -> Result<BuildResult> {
let ExecuteArgs {
Expand Down Expand Up @@ -408,8 +418,12 @@ async fn run_build(
match output {
LogOutput::StdOut { message } => {
build_result = Some(
serde_json::from_reader(BufReader::new(message.as_ref()))
.context("Error decoding BuildResult"),
serde_json::from_reader(BufReader::new(message.as_ref())).context(
format!(
"Error decoding BuildResult:\n {}",
std::str::from_utf8(&message).unwrap()
),
),
);
}
LogOutput::StdErr { message } => {
Expand All @@ -436,8 +450,8 @@ async fn run_build(
fn compose_build_args() -> Result<Vec<String>> {
use regex::Regex;
let mut args: Vec<String> = Vec::new();
// match --image with arg with 1 or more white spaces surrounded
let rex = Regex::new(r#"--image[ ]*[^ ]*[ ]*"#)?;
// match `--image` or `verify` with arg with 1 or more white spaces surrounded
let rex = Regex::new(r#"(--image|verify)[ ]*[^ ]*[ ]*"#)?;
// we join the args together, so we can remove `--image <arg>`
let args_string: String = std::env::args().collect::<Vec<String>>().join(" ");
let args_string = rex.replace_all(&args_string, "").to_string();
Expand Down
2 changes: 1 addition & 1 deletion crates/build/src/util/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use std::{
use term_size as _;

// Returns the current Rust toolchain formatted by `<channel>-<target-triple>`.
pub(crate) fn rust_toolchain() -> Result<String> {
pub fn rust_toolchain() -> Result<String> {
let meta = rustc_version::version_meta()?;
let toolchain = format!("{:?}-{}", meta.channel, meta.host,).to_lowercase();

Expand Down
4 changes: 4 additions & 0 deletions crates/cargo-contract/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,19 @@ include = [
contract-build = { version = "4.0.0-alpha", path = "../build" }
contract-extrinsics = { version = "4.0.0-alpha", path = "../extrinsics" }
contract-transcode = { version = "4.0.0-alpha", path = "../transcode" }
contract-metadata = { version = "4.0.0-alpha", path = "../metadata" }

anyhow = "1.0.75"
clap = { version = "4.4.0", features = ["derive", "env"] }
tracing = "0.1.37"
tracing-subscriber = { version = "0.3.17", features = ["env-filter"] }
which = "4.4.0"
colored = "2.0.4"
serde = { version = "1", default-features = false, features = ["derive"] }
serde_json = "1.0.105"
url = { version = "2.4.1", features = ["serde"] }
semver = "1.0"



# dependencies for extrinsics (deploying and calling a contract)
Expand Down
2 changes: 2 additions & 0 deletions crates/cargo-contract/src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub mod build;
pub mod decode;
pub mod encode;
pub mod info;
pub mod verify;

pub(crate) use self::{
build::{
Expand All @@ -26,6 +27,7 @@ pub(crate) use self::{
},
decode::DecodeCommand,
info::InfoCommand,
verify::VerifyCommand,
};

pub(crate) use contract_extrinsics::{
Expand Down
236 changes: 236 additions & 0 deletions crates/cargo-contract/src/cmd/verify.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of cargo-contract.
//
// cargo-contract is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// cargo-contract is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with cargo-contract. If not, see <http://www.gnu.org/licenses/>.

use anyhow::{
Context,
Result,
};
use colored::Colorize;
use contract_build::{
execute,
BuildArtifacts,
BuildInfo,
BuildMode,
ExecuteArgs,
ImageVariant,
ManifestPath,
Verbosity,
VerbosityFlags,
};
use contract_metadata::ContractMetadata;

use std::{
fs::File,
path::PathBuf,
};

const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Checks if a contract in the given workspace matches that of a reference contract.
#[derive(Debug, clap::Args)]
#[clap(name = "verify")]
pub struct VerifyCommand {
/// Path to the `Cargo.toml` of the contract to verify.
#[clap(long, value_parser)]
manifest_path: Option<PathBuf>,
/// The reference Wasm contract (`*.contract`) that the workspace will be checked
/// against.
contract: PathBuf,
/// Denotes if output should be printed to stdout.
#[clap(flatten)]
verbosity: VerbosityFlags,
/// Output the result in JSON format
#[clap(long, conflicts_with = "verbose")]
output_json: bool,
}

impl VerifyCommand {
pub fn run(&self) -> Result<VerificationResult> {
let manifest_path = ManifestPath::try_from(self.manifest_path.as_ref())?;
let verbosity: Verbosity = TryFrom::<&VerbosityFlags>::try_from(&self.verbosity)?;

// 1. Read the given metadata, and pull out the `BuildInfo`
let path = &self.contract;
let file = File::open(path)
.context(format!("Failed to open contract bundle {}", path.display()))?;

let metadata: ContractMetadata = serde_json::from_reader(&file).context(
format!("Failed to deserialize contract bundle {}", path.display()),
)?;
let build_info = if let Some(info) = metadata.source.build_info {
info
} else {
anyhow::bail!(
"\nThe metadata does not contain any build information which can be used to \
verify a contract."
.to_string()
.bright_yellow()
)
};

let build_info: BuildInfo =
serde_json::from_value(build_info.into()).context(format!(
"Failed to deserialize the build info from {}",
path.display()
))?;

tracing::debug!(
"Parsed the following build info from the metadata: {:?}",
&build_info,
);

let build_mode = if metadata.image.is_some() {
BuildMode::Verifiable
} else {
build_info.build_mode
};

// 2. Check that the build info from the metadata matches our current setup.
// if the build mode is `Verifiable` we skip
if build_mode != BuildMode::Verifiable {
let expected_rust_toolchain = build_info.rust_toolchain;
let rust_toolchain = contract_build::util::rust_toolchain()
.expect("`rustc` always has a version associated with it.");

let rustc_matches = rust_toolchain == expected_rust_toolchain;
let mismatched_rustc = format!(
"\nYou are trying to `verify` a contract using the `{rust_toolchain}` toolchain.\n\
However, the original contract was built using `{expected_rust_toolchain}`. Please\n\
install the correct toolchain (`rustup install {expected_rust_toolchain}`) and\n\
re-run the `verify` command.",);
anyhow::ensure!(rustc_matches, mismatched_rustc.bright_yellow());

let expected_cargo_contract_version = build_info.cargo_contract_version;
let cargo_contract_version = semver::Version::parse(VERSION)?;

// Note, assuming both versions of `cargo-contract` were installed with the
// same lockfile (e.g `--locked`) then the versions of `wasm-opt`
// should also match.
let cargo_contract_matches =
cargo_contract_version == expected_cargo_contract_version;
let mismatched_cargo_contract = format!(
"\nYou are trying to `verify` a contract using `cargo-contract` version \
`{cargo_contract_version}`.\n\
However, the original contract was built using `cargo-contract` version \
`{expected_cargo_contract_version}`.\n\
Please install the matching version and re-run the `verify` command.",
);
anyhow::ensure!(
cargo_contract_matches,
mismatched_cargo_contract.bright_yellow()
);
}

// 3a. Call `cargo contract build` with the `BuildInfo` from the metadata.
let args = ExecuteArgs {
manifest_path: manifest_path.clone(),
verbosity,
build_mode,
build_artifact: BuildArtifacts::All,
optimization_passes: Some(build_info.wasm_opt_settings.optimization_passes),
keep_debug_symbols: build_info.wasm_opt_settings.keep_debug_symbols,
image: ImageVariant::from(metadata.image.clone()),
dylint: false,
..Default::default()
};

let build_result = execute(args)?;

// 4. Grab the code hash from the built contract and compare it with the reference
// one.
let reference_code_hash = metadata.source.hash;
let built_contract_path = if let Some(m) = build_result.metadata_result {
m
} else {
// Since we're building the contract ourselves this should always be
// populated, but we'll bail out here just in case.
anyhow::bail!(
"\nThe metadata for the workspace contract does not contain a Wasm binary,\n\
therefore we are unable to verify the contract."
.to_string()
.bright_yellow()
)
};

let target_bundle = built_contract_path.dest_bundle;

let file = File::open(target_bundle.clone()).context(format!(
"Failed to open contract bundle {}",
target_bundle.display()
))?;
let built_contract: ContractMetadata =
serde_json::from_reader(file).context(format!(
"Failed to deserialize contract bundle {}",
target_bundle.display()
))?;

let target_code_hash = built_contract.source.hash;

if reference_code_hash != target_code_hash {
tracing::debug!(
"Expected Code Hash: '{:?}'\n\nGot Code Hash: `{:?}`",
&reference_code_hash,
&target_code_hash
);

anyhow::bail!(format!(
"\nFailed to verify the authenticity of {} contract against the workspace \n\
found at {}.",
format!("`{}`", metadata.contract.name).bright_white(),
format!("{:?}", manifest_path.as_ref()).bright_white()).bright_red()
);
}

Ok(VerificationResult {
is_verified: true,
image: metadata.image,
contract: target_bundle.display().to_string(),
reference_contract: path.display().to_string(),
output_json: self.output_json,
verbosity,
})
}
}

/// The result of verification process
#[derive(serde::Serialize, serde::Deserialize)]
pub struct VerificationResult {
pub is_verified: bool,
pub image: Option<String>,
pub contract: String,
pub reference_contract: String,
#[serde(skip_serializing, skip_deserializing)]
pub output_json: bool,
#[serde(skip_serializing, skip_deserializing)]
pub verbosity: Verbosity,
}

impl VerificationResult {
/// Display the result in a fancy format
pub fn display(&self) -> String {
format!(
"\n{} {} against reference contract {}",
"Successfully verified contract".bright_green().bold(),
format!("`{}`", &self.contract).bold(),
format!("`{}`!", &self.reference_contract).bold()
)
}

/// Display the build results in a pretty formatted JSON string.
pub fn serialize_json(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(self)?)
}
}
15 changes: 15 additions & 0 deletions crates/cargo-contract/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ use self::cmd::{
InstantiateCommand,
RemoveCommand,
UploadCommand,
VerifyCommand,
};
use cmd::encode::EncodeCommand;
use contract_build::{
Expand Down Expand Up @@ -136,6 +137,10 @@ enum Command {
/// Display information about a contract
#[clap(name = "info")]
Info(InfoCommand),
/// Verifies that a given contract binary matches the build result of the specified
/// workspace.
#[clap(name = "verify")]
Verify(VerifyCommand),
}

fn main() {
Expand Down Expand Up @@ -199,6 +204,16 @@ fn exec(cmd: Command) -> Result<()> {
.map_err(|err| map_extrinsic_err(err, remove.is_json()))
}
Command::Info(info) => info.run().map_err(format_err),
Command::Verify(verify) => {
let result = verify.run().map_err(format_err)?;

if result.output_json {
println!("{}", result.serialize_json()?)
} else if result.verbosity.is_verbose() {
println!("{}", result.display())
}
Ok(())
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/metadata/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ impl Source {
}

/// The bytes of the compiled Wasm smart contract.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct SourceWasm(
#[serde(
serialize_with = "byte_str::serialize_as_byte_str",
Expand Down