Skip to content

Commit

Permalink
Fixes to update fuels-rs on small values as single bytes (FuelLabs#5264)
Browse files Browse the repository at this point in the history
## Description

This PR contains some necessary fixes to enable this
FuelLabs/fuels-rs#1163 to be merged.

1 - It guarantees that when the env var `FORC_IMPLICIT_STD_GIT_BRANCH`
is used, no `tag` or `rev` is also used;
2 - It removes all warnings from the sway std-lib;
3 - It fixes reading predicates witness when it is only one byte.


## Checklist

- [ ] I have linked to any relevant issues.
- [ ] I have commented my code, particularly in hard-to-understand
areas.
- [ ] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] I have added tests that prove my fix is effective or that my
feature works.
- [ ] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [ ] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [ ] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: hal3e <[email protected]>
Co-authored-by: IGI-111 <[email protected]>
  • Loading branch information
3 people authored Nov 17, 2023
1 parent b4df674 commit 1c310f3
Show file tree
Hide file tree
Showing 58 changed files with 1,079 additions and 780 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ concurrency:
env:
CARGO_TERM_COLOR: always
REGISTRY: ghcr.io
RUST_VERSION: 1.72.0
RUST_VERSION: 1.72.1
NIGHTLY_RUST_VERSION: nightly-2023-08-27

jobs:
Expand Down
16 changes: 8 additions & 8 deletions forc-pkg/src/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -780,22 +780,22 @@ fn implicit_std_dep() -> Dependency {
.unwrap_or_else(|| format!("v{}", env!("CARGO_PKG_VERSION")));
const SWAY_GIT_REPO_URL: &str = "https://github.com/fuellabs/sway";

fn rev_from_build_metadata(build_metadata: &str) -> Option<String> {
// Nightlies are in the format v<version>+nightly.<date>.<hash>
build_metadata.split('.').last().map(|r| r.to_string())
}
// only use tag/rev if the branch is None
let branch = std::env::var("FORC_IMPLICIT_STD_GIT_BRANCH").ok();
let tag = branch.as_ref().map_or_else(|| Some(tag), |_| None);

let mut det = DependencyDetails {
git: std::env::var("FORC_IMPLICIT_STD_GIT")
.ok()
.or_else(|| Some(SWAY_GIT_REPO_URL.to_string())),
tag: Some(tag),
branch: std::env::var("FORC_IMPLICIT_STD_GIT_BRANCH").ok(),
tag,
branch,
..Default::default()
};

if let Some((_, build_metadata)) = det.tag.as_ref().unwrap().split_once('+') {
let rev = rev_from_build_metadata(build_metadata);
if let Some((_, build_metadata)) = det.tag.as_ref().and_then(|tag| tag.split_once('+')) {
// Nightlies are in the format v<version>+nightly.<date>.<hash>
let rev = build_metadata.split('.').last().map(|r| r.to_string());

// If some revision is available and parsed from the 'nightly' build metadata,
// we always prefer the revision over the tag.
Expand Down
6 changes: 3 additions & 3 deletions sway-lib-std/src/ecr.sw
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ fn test_revert_ec_recover_r1() {
let lo = 0x44ac566bd156b4fc71a4a4cb2655d3da360c695edb27dc3b64d621e122fea23d;
let msg_hash = 0x1e45523606c96c98ba970ff7cf9511fab8b25e1bcd52ced30b81df1e4a9c4323;
let signature: B512 = B512::from((hi, lo));
let public_key = ec_recover_r1(signature, msg_hash).unwrap();
let _ = ec_recover_r1(signature, msg_hash).unwrap();
}

#[test]
Expand All @@ -301,7 +301,7 @@ fn test_revert_ec_recover_address_r1() {
let lo = 0x44ac566bd156b4fc71a4a4cb2655d3dd360c695edb17dc3b64d611e122fea23d;
let msg_hash = 0xee45573606c96c98ba970ff7cf9511f1b8b25e6bcd52ced30b89df1e4a9c4323;
let signature: B512 = B512::from((hi, lo));
let result_address = ec_recover_address_r1(signature, msg_hash).unwrap();
let _ = ec_recover_address_r1(signature, msg_hash).unwrap();
}

#[test]
Expand Down Expand Up @@ -333,5 +333,5 @@ fn test_revert_ed_verify() {
let hi = ZERO_B256;
let lo = 0xf5084560039486d3462dd65a40c80a74709b2f06d450ffc5dc00345c6b2cdd00;
let signature: B512 = B512::from((hi, lo));
let verfied = ed_verify(pub_key, signature, msg_hash).unwrap();
let _ = ed_verify(pub_key, signature, msg_hash).unwrap();
}
6 changes: 5 additions & 1 deletion sway-lib-std/src/tx.sw
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,11 @@ pub fn tx_witness_data_length(index: u64) -> u64 {
/// }
/// ```
pub fn tx_witness_data<T>(index: u64) -> T {
__gtf::<raw_ptr>(index, GTF_WITNESS_DATA).read::<T>()
if __size_of::<T>() == 1 {
__gtf::<raw_ptr>(index, GTF_WITNESS_DATA).add::<u8>(7).read::<T>()
} else {
__gtf::<raw_ptr>(index, GTF_WITNESS_DATA).read::<T>()
}
}

/// Get the transaction receipts root.
Expand Down
12 changes: 6 additions & 6 deletions sway-lib-std/src/u256.sw
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ impl U256 {
///
/// assert(init_one == one_u256);
/// ```
#[allow(deprecated)]
pub fn one() -> Self {
Self {
a: 0,
Expand Down Expand Up @@ -685,9 +686,9 @@ impl Power for U256 {
/// # Panics
///
/// Panics if the result overflows the type.
#[allow(deprecated)]
fn pow(self, exponent: u32) -> Self {
let one = U256::from((0, 0, 0, 1));
let two = U256::from((0, 0, 0, 2));

if exponent == 0 {
return one;
Expand All @@ -709,12 +710,8 @@ impl Power for U256 {
}
}


fn is_even(x: U256) -> bool {
x.low_u64() & 1 == 0
}

#[test]
#[allow(deprecated)]
fn test_five_pow_two_u256() {
let five = U256::from((0, 0, 0, 5));

Expand All @@ -726,6 +723,7 @@ fn test_five_pow_two_u256() {
}

#[test]
#[allow(deprecated)]
fn test_five_pow_three_u256() {
let five = U256::from((0, 0, 0, 5));

Expand All @@ -737,6 +735,7 @@ fn test_five_pow_three_u256() {
}

#[test]
#[allow(deprecated)]
fn test_five_pow_28_u256() {
let five = U256::from((0, 0, 0, 5));

Expand All @@ -748,6 +747,7 @@ fn test_five_pow_28_u256() {
}

#[test]
#[allow(deprecated)]
fn test_is_zero() {
let zero_u256 = U256::new();
assert(zero_u256.is_zero());
Expand Down
17 changes: 13 additions & 4 deletions test/src/e2e_vm_tests/harness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ pub(crate) enum VMExecutionResult {
pub(crate) fn runs_in_vm(
script: BuiltPackage,
script_data: Option<Vec<u8>>,
witness_data: Option<Vec<Vec<u8>>>,
) -> Result<VMExecutionResult> {
match script.descriptor.target {
BuildTarget::Fuel => {
Expand All @@ -152,8 +153,9 @@ pub(crate) fn runs_in_vm(
..ConsensusParameters::DEFAULT
};

let tx = TransactionBuilder::script(script.bytecode.bytes, script_data)
.with_params(params)
let mut tx = TransactionBuilder::script(script.bytecode.bytes, script_data);

tx.with_params(params)
.add_unsigned_coin_input(
rng.gen(),
rng.gen(),
Expand All @@ -163,8 +165,15 @@ pub(crate) fn runs_in_vm(
0u32.into(),
)
.gas_limit(fuel_tx::ConsensusParameters::DEFAULT.max_gas_per_tx)
.maturity(maturity)
.finalize_checked(block_height, &GasCosts::default());
.maturity(maturity);

if let Some(witnesses) = witness_data {
for witness in witnesses {
tx.add_witness(witness.into());
}
}

let tx = tx.finalize_checked(block_height, &GasCosts::default());

let mut i = Interpreter::with_storage(storage, Default::default(), GasCosts::default());
let transition = i.transact(tx)?;
Expand Down
37 changes: 36 additions & 1 deletion test/src/e2e_vm_tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ struct TestDescription {
name: String,
category: TestCategory,
script_data: Option<Vec<u8>>,
witness_data: Option<Vec<Vec<u8>>>,
expected_result: Option<TestResult>,
expected_warnings: u32,
contract_paths: Vec<String>,
Expand Down Expand Up @@ -105,6 +106,7 @@ impl TestContext {
name,
category,
script_data,
witness_data,
expected_result,
expected_warnings,
contract_paths,
Expand Down Expand Up @@ -149,7 +151,7 @@ impl TestContext {
)));
}

let result = harness::runs_in_vm(compiled.clone(), script_data)?;
let result = harness::runs_in_vm(compiled.clone(), script_data, witness_data)?;
let result = match result {
harness::VMExecutionResult::Fuel(state, receipts) => {
if verbose {
Expand Down Expand Up @@ -640,6 +642,38 @@ fn parse_test_toml(path: &Path) -> Result<TestDescription> {
| TestCategory::Disabled => None,
};

let witness_data = match &category {
TestCategory::Runs | TestCategory::RunsWithContract => {
match toml_content.get("witness_data") {
Some(toml::Value::Array(items)) => {
let mut data = vec![];

for item in items {
let decoded = item
.as_str()
.ok_or_else(|| anyhow!("witness data should be a hex string"))
.and_then(|x| {
hex::decode(x).map_err(|e| {
anyhow!("Invalid hex value for 'script_data': {}", e)
})
})?;
data.push(decoded);
}

Some(data)
}
Some(_) => {
bail!("Expected 'script_data' to be a hex string.");
}
_ => None,
}
}
TestCategory::Compiles
| TestCategory::FailsToCompile
| TestCategory::UnitTestsPass
| TestCategory::Disabled => None,
};

let expected_result = match &category {
TestCategory::Runs | TestCategory::RunsWithContract => {
Some(get_expected_result(&toml_content)?)
Expand Down Expand Up @@ -720,6 +754,7 @@ fn parse_test_toml(path: &Path) -> Result<TestDescription> {
name,
category,
script_data,
witness_data,
expected_result,
expected_warnings,
contract_paths,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
[[package]]
name = 'gtf_intrinsic'
source = 'member'
name = "core"
source = "path+from-root-AC247AEA3D39B916"

[[package]]
name = "gtf_intrinsic"
source = "member"
dependencies = ["std"]

[[package]]
name = "std"
source = "git+https://github.com/fuellabs/sway?tag=v0.47.0#34265301c6037d51444899a99df1cfc563df6016"
dependencies = ["core"]
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
[project]
authors = ["Fuel Labs <[email protected]>"]
entry = "main.sw"
implicit-std = false
license = "Apache-2.0"
name = "gtf_intrinsic"

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,33 +15,10 @@
"loggedTypes": [],
"messagesTypes": [],
"types": [
{
"components": [
{
"name": "__tuple_element",
"type": 2,
"typeArguments": null
},
{
"name": "__tuple_element",
"type": 1,
"typeArguments": null
}
],
"type": "(_, _)",
"typeId": 0,
"typeParameters": null
},
{
"components": null,
"type": "b256",
"typeId": 1,
"typeParameters": null
},
{
"components": null,
"type": "u64",
"typeId": 2,
"typeId": 0,
"typeParameters": null
}
]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
script;

const SOME_TX_FIELD = 0x42;
const SOME_OTHER_TX_FIELD = 0x77;
use std::tx::*;

fn main() -> (u64, b256) {
// Test expected to compile but revert because `fuel-core` does not support `gtf` yet.
let u64_field = __gtf::<u64>(1, SOME_TX_FIELD);
let b256_field = __gtf::<b256>(2, SOME_OTHER_TX_FIELD);
(u64_field, b256_field)
fn main() -> u64 {
assert(tx_witnesses_count() == 3);
assert(tx_witness_data::<u8>(1) == 1);
assert(tx_witness_data::<u64>(2) == 1234);
0
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
category = "run"
expected_result = { action = "revert", value = 0 }
expected_result = { action = "return", value = 0 }
validate_abi = true
witness_data = [ "0000000000000001", "00000000000004D2" ]
Loading

0 comments on commit 1c310f3

Please sign in to comment.